From cfbdb43d2cadd40aa87338d41548e4bf89e146e6 Mon Sep 17 00:00:00 2001 From: Tobias Markmann Date: Thu, 31 Mar 2016 16:57:35 +0200 Subject: Convert tabs to 4 spaces for all source files Removed trailing spaces and whitespace on empty lines in the process. Changed CheckTabs.py tool to disallow hard tabs in source files. Test-Information: Manually checked 30 random files that the conversion worked as expected. Change-Id: I874f99d617bd3d2bb55f02d58f22f58f9b094480 diff --git a/BuildTools/CheckTabs.py b/BuildTools/CheckTabs.py index e2029b0..f0ec0ab 100755 --- a/BuildTools/CheckTabs.py +++ b/BuildTools/CheckTabs.py @@ -5,27 +5,15 @@ import os, sys foundExpandedTabs = False filename = sys.argv[1] -if (filename.endswith(".cpp") or filename.endswith(".h") or filename.endswith(".py") or filename.endswith("SConscript") or filename.endswith("SConscript.boot") or filename.endswith("SConstruct")) and not "3rdParty" in filename : - file = open(filename, "r") - contents = [] - contentsChanged = False - for line in file.readlines() : - newline = "" - previousChar = None - pastInitialSpace = False - for char in line : - if not pastInitialSpace : - if char == ' ' and previousChar == ' ' : - contentsChanged = True - previousChar = '\t' - continue - pastInitialSpace = (char != ' ') - if previousChar : - newline += previousChar - previousChar = char - if previousChar : - newline += previousChar - contents.append(newline) - file.close() - if contentsChanged : - sys.exit(-1) +if (filename.endswith(".cpp") or filename.endswith(".h") or filename.endswith(".c") or filename.endswith(".mm") or filename.endswith(".ipp") or filename.endswith(".hpp") or filename.endswith(".py") or filename.endswith("SConscript") or filename.endswith("SConscript.boot") or filename.endswith("SConstruct")) and not "3rdParty" in filename : + file = open(filename, "r") + contents = [] + contentsChanged = False + for line in file.readlines() : + if "\t" in line: + print("File %s contains hard tabs. This is not allowed." % filename) + file.close() + sys.exit(-1) + file.close() + if contentsChanged : + sys.exit(-1) diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp index 912ba07..9a7301a 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot0x.cpp @@ -9,23 +9,23 @@ using namespace Swift; int main(int, char**) { - // Set up the event loop and network classes - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + // Set up the event loop and network classes + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - Client client("echobot@wonderland.lit", "mypass", &networkFactories); - client.setAlwaysTrustCertificates(); - client.onConnected.connect([&] { - std::cout << "Connected" << std::endl; - }); - client.onMessageReceived.connect([&] (Message::ref message) { - message->setTo(message->getFrom()); - message->setFrom(JID()); - client.sendMessage(message); - }); - client.connect(); + Client client("echobot@wonderland.lit", "mypass", &networkFactories); + client.setAlwaysTrustCertificates(); + client.onConnected.connect([&] { + std::cout << "Connected" << std::endl; + }); + client.onMessageReceived.connect([&] (Message::ref message) { + message->setTo(message->getFrom()); + message->setFrom(JID()); + client.sendMessage(message); + }); + client.connect(); - eventLoop.run(); + eventLoop.run(); - return 0; + return 0; } diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp index 15d1a77..6e04eee 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot1.cpp @@ -9,14 +9,14 @@ using namespace Swift; int main(int, char**) { - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - Client client("echobot@wonderland.lit", "mypass", &networkFactories); - client.setAlwaysTrustCertificates(); - client.connect(); + Client client("echobot@wonderland.lit", "mypass", &networkFactories); + client.setAlwaysTrustCertificates(); + client.connect(); - eventLoop.run(); + eventLoop.run(); - return 0; + return 0; } diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp index 1cec06c..d928db8 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot2.cpp @@ -19,28 +19,28 @@ void handleConnected(); void handleMessageReceived(Message::ref message); int main(int, char**) { - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - client = new Client("echobot@wonderland.lit", "mypass", &networkFactories); - client->setAlwaysTrustCertificates(); - client->onConnected.connect(&handleConnected); - client->onMessageReceived.connect(bind(&handleMessageReceived, _1)); - client->connect(); + client = new Client("echobot@wonderland.lit", "mypass", &networkFactories); + client->setAlwaysTrustCertificates(); + client->onConnected.connect(&handleConnected); + client->onMessageReceived.connect(bind(&handleMessageReceived, _1)); + client->connect(); - eventLoop.run(); + eventLoop.run(); - delete client; - return 0; + delete client; + return 0; } void handleConnected() { - std::cout << "Connected" << std::endl; + std::cout << "Connected" << std::endl; } void handleMessageReceived(Message::ref message) { - // Echo back the incoming message - message->setTo(message->getFrom()); - message->setFrom(JID()); - client->sendMessage(message); + // Echo back the incoming message + message->setTo(message->getFrom()); + message->setFrom(JID()); + client->sendMessage(message); } diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp index 4cba31f..470753d 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot3.cpp @@ -14,45 +14,45 @@ using namespace Swift; using namespace boost; class EchoBot { - public: - EchoBot(NetworkFactories* networkFactories) { - client = new Client("echobot@wonderland.lit", "mypass", networkFactories); - client->setAlwaysTrustCertificates(); - client->onConnected.connect(bind(&EchoBot::handleConnected, this)); - client->onMessageReceived.connect( - bind(&EchoBot::handleMessageReceived, this, _1)); - tracer = new ClientXMLTracer(client); - client->connect(); - } - - ~EchoBot() { - delete tracer; - delete client; - } - - private: - void handleConnected() { - std::cout << "Connected" << std::endl; - } - - void handleMessageReceived(Message::ref message) { - // Echo back the incoming message - message->setTo(message->getFrom()); - message->setFrom(JID()); - client->sendMessage(message); - } - - private: - Client* client; - ClientXMLTracer* tracer; + public: + EchoBot(NetworkFactories* networkFactories) { + client = new Client("echobot@wonderland.lit", "mypass", networkFactories); + client->setAlwaysTrustCertificates(); + client->onConnected.connect(bind(&EchoBot::handleConnected, this)); + client->onMessageReceived.connect( + bind(&EchoBot::handleMessageReceived, this, _1)); + tracer = new ClientXMLTracer(client); + client->connect(); + } + + ~EchoBot() { + delete tracer; + delete client; + } + + private: + void handleConnected() { + std::cout << "Connected" << std::endl; + } + + void handleMessageReceived(Message::ref message) { + // Echo back the incoming message + message->setTo(message->getFrom()); + message->setFrom(JID()); + client->sendMessage(message); + } + + private: + Client* client; + ClientXMLTracer* tracer; }; int main(int, char**) { - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - EchoBot bot(&networkFactories); + EchoBot bot(&networkFactories); - eventLoop.run(); - return 0; + eventLoop.run(); + return 0; } diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp index b5537c9..9ab7864 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot4.cpp @@ -15,80 +15,80 @@ using namespace Swift; using namespace boost; //... class EchoBot { - public: - EchoBot(NetworkFactories* networkFactories) { - //... - client = new Client("echobot@wonderland.lit", "mypass", networkFactories); - client->setAlwaysTrustCertificates(); - client->onConnected.connect(bind(&EchoBot::handleConnected, this)); - client->onMessageReceived.connect( - bind(&EchoBot::handleMessageReceived, this, _1)); - //... - client->onPresenceReceived.connect( - bind(&EchoBot::handlePresenceReceived, this, _1)); - //... - tracer = new ClientXMLTracer(client); - client->connect(); - //... - } + public: + EchoBot(NetworkFactories* networkFactories) { + //... + client = new Client("echobot@wonderland.lit", "mypass", networkFactories); + client->setAlwaysTrustCertificates(); + client->onConnected.connect(bind(&EchoBot::handleConnected, this)); + client->onMessageReceived.connect( + bind(&EchoBot::handleMessageReceived, this, _1)); + //... + client->onPresenceReceived.connect( + bind(&EchoBot::handlePresenceReceived, this, _1)); + //... + tracer = new ClientXMLTracer(client); + client->connect(); + //... + } - //... - ~EchoBot() { - delete tracer; - delete client; - } - - private: - //... - void handlePresenceReceived(Presence::ref presence) { - // Automatically approve subscription requests - if (presence->getType() == Presence::Subscribe) { - Presence::ref response = Presence::create(); - response->setTo(presence->getFrom()); - response->setType(Presence::Subscribed); - client->sendPresence(response); - } - } + //... + ~EchoBot() { + delete tracer; + delete client; + } - void handleConnected() { - // Request the roster - GetRosterRequest::ref rosterRequest = - GetRosterRequest::create(client->getIQRouter()); - rosterRequest->onResponse.connect( - bind(&EchoBot::handleRosterReceived, this, _2)); - rosterRequest->send(); - } + private: + //... + void handlePresenceReceived(Presence::ref presence) { + // Automatically approve subscription requests + if (presence->getType() == Presence::Subscribe) { + Presence::ref response = Presence::create(); + response->setTo(presence->getFrom()); + response->setType(Presence::Subscribed); + client->sendPresence(response); + } + } - void handleRosterReceived(ErrorPayload::ref error) { - if (error) { - std::cerr << "Error receiving roster. Continuing anyway."; - } - // Send initial available presence - client->sendPresence(Presence::create("Send me a message")); - } - //... - - void handleMessageReceived(Message::ref message) { - // Echo back the incoming message - message->setTo(message->getFrom()); - message->setFrom(JID()); - client->sendMessage(message); - } + void handleConnected() { + // Request the roster + GetRosterRequest::ref rosterRequest = + GetRosterRequest::create(client->getIQRouter()); + rosterRequest->onResponse.connect( + bind(&EchoBot::handleRosterReceived, this, _2)); + rosterRequest->send(); + } - private: - Client* client; - ClientXMLTracer* tracer; - //... + void handleRosterReceived(ErrorPayload::ref error) { + if (error) { + std::cerr << "Error receiving roster. Continuing anyway."; + } + // Send initial available presence + client->sendPresence(Presence::create("Send me a message")); + } + //... + + void handleMessageReceived(Message::ref message) { + // Echo back the incoming message + message->setTo(message->getFrom()); + message->setFrom(JID()); + client->sendMessage(message); + } + + private: + Client* client; + ClientXMLTracer* tracer; + //... }; //... int main(int, char**) { - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - EchoBot bot(&networkFactories); + EchoBot bot(&networkFactories); - eventLoop.run(); - return 0; + eventLoop.run(); + return 0; } //... diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp index 811887e..3475a6c 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot5.cpp @@ -15,88 +15,88 @@ using namespace Swift; using namespace boost; //... class EchoBot { - public: - EchoBot(NetworkFactories* networkFactories) { - //... - client = new Client("echobot@wonderland.lit", "mypass", networkFactories); - client->setAlwaysTrustCertificates(); - client->onConnected.connect(bind(&EchoBot::handleConnected, this)); - client->onMessageReceived.connect( - bind(&EchoBot::handleMessageReceived, this, _1)); - client->onPresenceReceived.connect( - bind(&EchoBot::handlePresenceReceived, this, _1)); - tracer = new ClientXMLTracer(client); - //... - softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter()); - softwareVersionResponder->setVersion("EchoBot", "1.0"); - softwareVersionResponder->start(); - //... - client->connect(); - //... - } + public: + EchoBot(NetworkFactories* networkFactories) { + //... + client = new Client("echobot@wonderland.lit", "mypass", networkFactories); + client->setAlwaysTrustCertificates(); + client->onConnected.connect(bind(&EchoBot::handleConnected, this)); + client->onMessageReceived.connect( + bind(&EchoBot::handleMessageReceived, this, _1)); + client->onPresenceReceived.connect( + bind(&EchoBot::handlePresenceReceived, this, _1)); + tracer = new ClientXMLTracer(client); + //... + softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter()); + softwareVersionResponder->setVersion("EchoBot", "1.0"); + softwareVersionResponder->start(); + //... + client->connect(); + //... + } - ~EchoBot() { - softwareVersionResponder->stop(); - delete softwareVersionResponder; - //... - delete tracer; - delete client; - //... - } - //... - - private: - void handlePresenceReceived(Presence::ref presence) { - // Automatically approve subscription requests - if (presence->getType() == Presence::Subscribe) { - Presence::ref response = Presence::create(); - response->setTo(presence->getFrom()); - response->setType(Presence::Subscribed); - client->sendPresence(response); - } - } + ~EchoBot() { + softwareVersionResponder->stop(); + delete softwareVersionResponder; + //... + delete tracer; + delete client; + //... + } + //... - void handleConnected() { - // Request the roster - GetRosterRequest::ref rosterRequest = - GetRosterRequest::create(client->getIQRouter()); - rosterRequest->onResponse.connect( - bind(&EchoBot::handleRosterReceived, this, _2)); - rosterRequest->send(); - } + private: + void handlePresenceReceived(Presence::ref presence) { + // Automatically approve subscription requests + if (presence->getType() == Presence::Subscribe) { + Presence::ref response = Presence::create(); + response->setTo(presence->getFrom()); + response->setType(Presence::Subscribed); + client->sendPresence(response); + } + } - void handleRosterReceived(ErrorPayload::ref error) { - if (error) { - std::cerr << "Error receiving roster. Continuing anyway."; - } - // Send initial available presence - client->sendPresence(Presence::create("Send me a message")); - } - - void handleMessageReceived(Message::ref message) { - // Echo back the incoming message - message->setTo(message->getFrom()); - message->setFrom(JID()); - client->sendMessage(message); - } + void handleConnected() { + // Request the roster + GetRosterRequest::ref rosterRequest = + GetRosterRequest::create(client->getIQRouter()); + rosterRequest->onResponse.connect( + bind(&EchoBot::handleRosterReceived, this, _2)); + rosterRequest->send(); + } - //... - private: - //... - Client* client; - ClientXMLTracer* tracer; - //... - SoftwareVersionResponder* softwareVersionResponder; + void handleRosterReceived(ErrorPayload::ref error) { + if (error) { + std::cerr << "Error receiving roster. Continuing anyway."; + } + // Send initial available presence + client->sendPresence(Presence::create("Send me a message")); + } + + void handleMessageReceived(Message::ref message) { + // Echo back the incoming message + message->setTo(message->getFrom()); + message->setFrom(JID()); + client->sendMessage(message); + } + + //... + private: + //... + Client* client; + ClientXMLTracer* tracer; + //... + SoftwareVersionResponder* softwareVersionResponder; }; //... int main(int, char**) { - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - EchoBot bot(&networkFactories); + EchoBot bot(&networkFactories); - eventLoop.run(); - return 0; + eventLoop.run(); + return 0; } //... diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp index b3239c8..b1a1c37 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoBot6.cpp @@ -20,104 +20,104 @@ using namespace boost; #include "EchoPayloadSerializer.h" class EchoBot { - public: - EchoBot(NetworkFactories* networkFactories) { - //... - client = new Client("echobot@wonderland.lit", "mypass", networkFactories); - client->setAlwaysTrustCertificates(); - client->onConnected.connect(bind(&EchoBot::handleConnected, this)); - client->onMessageReceived.connect( - bind(&EchoBot::handleMessageReceived, this, _1)); - client->onPresenceReceived.connect( - bind(&EchoBot::handlePresenceReceived, this, _1)); - tracer = new ClientXMLTracer(client); + public: + EchoBot(NetworkFactories* networkFactories) { + //... + client = new Client("echobot@wonderland.lit", "mypass", networkFactories); + client->setAlwaysTrustCertificates(); + client->onConnected.connect(bind(&EchoBot::handleConnected, this)); + client->onMessageReceived.connect( + bind(&EchoBot::handleMessageReceived, this, _1)); + client->onPresenceReceived.connect( + bind(&EchoBot::handlePresenceReceived, this, _1)); + tracer = new ClientXMLTracer(client); - softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter()); - softwareVersionResponder->setVersion("EchoBot", "1.0"); - softwareVersionResponder->start(); - //... - client->addPayloadParserFactory(&echoPayloadParserFactory); - client->addPayloadSerializer(&echoPayloadSerializer); - //... - client->connect(); - //... - } + softwareVersionResponder = new SoftwareVersionResponder(client->getIQRouter()); + softwareVersionResponder->setVersion("EchoBot", "1.0"); + softwareVersionResponder->start(); + //... + client->addPayloadParserFactory(&echoPayloadParserFactory); + client->addPayloadSerializer(&echoPayloadSerializer); + //... + client->connect(); + //... + } - ~EchoBot() { - client->removePayloadSerializer(&echoPayloadSerializer); - client->removePayloadParserFactory(&echoPayloadParserFactory); - //... - softwareVersionResponder->stop(); - delete softwareVersionResponder; - delete tracer; - delete client; - //... - } - //... - - private: - void handlePresenceReceived(Presence::ref presence) { - // Automatically approve subscription requests - if (presence->getType() == Presence::Subscribe) { - Presence::ref response = Presence::create(); - response->setTo(presence->getFrom()); - response->setType(Presence::Subscribed); - client->sendPresence(response); - } - } + ~EchoBot() { + client->removePayloadSerializer(&echoPayloadSerializer); + client->removePayloadParserFactory(&echoPayloadParserFactory); + //... + softwareVersionResponder->stop(); + delete softwareVersionResponder; + delete tracer; + delete client; + //... + } + //... - void handleConnected() { - // Request the roster - GetRosterRequest::ref rosterRequest = - GetRosterRequest::create(client->getIQRouter()); - rosterRequest->onResponse.connect( - bind(&EchoBot::handleRosterReceived, this, _2)); - rosterRequest->send(); - } + private: + void handlePresenceReceived(Presence::ref presence) { + // Automatically approve subscription requests + if (presence->getType() == Presence::Subscribe) { + Presence::ref response = Presence::create(); + response->setTo(presence->getFrom()); + response->setType(Presence::Subscribed); + client->sendPresence(response); + } + } - void handleRosterReceived(ErrorPayload::ref error) { - if (error) { - std::cerr << "Error receiving roster. Continuing anyway."; - } - // Send initial available presence - client->sendPresence(Presence::create("Send me a message")); - } + void handleConnected() { + // Request the roster + GetRosterRequest::ref rosterRequest = + GetRosterRequest::create(client->getIQRouter()); + rosterRequest->onResponse.connect( + bind(&EchoBot::handleRosterReceived, this, _2)); + rosterRequest->send(); + } - //... - void handleMessageReceived(Message::ref message) { - //... - // Echo back the incoming message - message->setTo(message->getFrom()); - message->setFrom(JID()); - //... - if (!message->getPayload()) { - boost::shared_ptr echoPayload = boost::make_shared(); - echoPayload->setMessage("This is an echoed message"); - message->addPayload(echoPayload); - client->sendMessage(message); - } - } - //... + void handleRosterReceived(ErrorPayload::ref error) { + if (error) { + std::cerr << "Error receiving roster. Continuing anyway."; + } + // Send initial available presence + client->sendPresence(Presence::create("Send me a message")); + } - //... - private: - //... - Client* client; - ClientXMLTracer* tracer; - SoftwareVersionResponder* softwareVersionResponder; - //... - EchoPayloadParserFactory echoPayloadParserFactory; - EchoPayloadSerializer echoPayloadSerializer; + //... + void handleMessageReceived(Message::ref message) { + //... + // Echo back the incoming message + message->setTo(message->getFrom()); + message->setFrom(JID()); + //... + if (!message->getPayload()) { + boost::shared_ptr echoPayload = boost::make_shared(); + echoPayload->setMessage("This is an echoed message"); + message->addPayload(echoPayload); + client->sendMessage(message); + } + } + //... + + //... + private: + //... + Client* client; + ClientXMLTracer* tracer; + SoftwareVersionResponder* softwareVersionResponder; + //... + EchoPayloadParserFactory echoPayloadParserFactory; + EchoPayloadSerializer echoPayloadSerializer; }; //... int main(int, char**) { - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - EchoBot bot(&networkFactories); + EchoBot bot(&networkFactories); - eventLoop.run(); - return 0; + eventLoop.run(); + return 0; } //... diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp index c827b94..16d7e4e 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoComponent.cpp @@ -14,56 +14,56 @@ using namespace Swift; using namespace boost; class EchoComponent { - public: - EchoComponent(NetworkFactories* networkFactories) : jid("echo.wonderland.lit") { - component = new Component(jid, "EchoSecret", networkFactories); - component->onConnected.connect(bind(&EchoComponent::handleConnected, this)); - component->onMessageReceived.connect( - bind(&EchoComponent::handleMessageReceived, this, _1)); - component->onPresenceReceived.connect( - bind(&EchoComponent::handlePresenceReceived, this, _1)); - tracer = new ComponentXMLTracer(component); - component->connect("wonderland.lit", 5347); - } + public: + EchoComponent(NetworkFactories* networkFactories) : jid("echo.wonderland.lit") { + component = new Component(jid, "EchoSecret", networkFactories); + component->onConnected.connect(bind(&EchoComponent::handleConnected, this)); + component->onMessageReceived.connect( + bind(&EchoComponent::handleMessageReceived, this, _1)); + component->onPresenceReceived.connect( + bind(&EchoComponent::handlePresenceReceived, this, _1)); + tracer = new ComponentXMLTracer(component); + component->connect("wonderland.lit", 5347); + } - ~EchoComponent() { - delete tracer; - delete component; - } - - private: - void handlePresenceReceived(Presence::ref presence) { - // Automatically approve subscription requests - if (presence->getType() == Presence::Subscribe) { - Presence::ref response = Presence::create(); - response->setTo(presence->getFrom()); - response->setType(Presence::Subscribed); - component->sendPresence(response); - } - } + ~EchoComponent() { + delete tracer; + delete component; + } - void handleConnected() { - } + private: + void handlePresenceReceived(Presence::ref presence) { + // Automatically approve subscription requests + if (presence->getType() == Presence::Subscribe) { + Presence::ref response = Presence::create(); + response->setTo(presence->getFrom()); + response->setType(Presence::Subscribed); + component->sendPresence(response); + } + } - void handleMessageReceived(Message::ref message) { - // Echo back the incoming message - message->setTo(message->getFrom()); - message->setFrom(jid); - component->sendMessage(message); - } + void handleConnected() { + } - private: - JID jid; - Component* component; - ComponentXMLTracer* tracer; + void handleMessageReceived(Message::ref message) { + // Echo back the incoming message + message->setTo(message->getFrom()); + message->setFrom(jid); + component->sendMessage(message); + } + + private: + JID jid; + Component* component; + ComponentXMLTracer* tracer; }; int main(int, char**) { - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories(&eventLoop); + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories(&eventLoop); - EchoComponent bot(&networkFactories); + EchoComponent bot(&networkFactories); - eventLoop.run(); - return 0; + eventLoop.run(); + return 0; } diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h index c93b78b..1e5fc98 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayload.h @@ -10,17 +10,17 @@ //... class EchoPayload : public Swift::Payload { - public: - EchoPayload() {} + public: + EchoPayload() {} - const std::string& getMessage() const { - return message; - } + const std::string& getMessage() const { + return message; + } - void setMessage(const std::string& message) { - this->message = message; - } + void setMessage(const std::string& message) { + this->message = message; + } - private: - std::string message; + private: + std::string message; }; diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h index 9d66204..48d08bd 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadParserFactory.h @@ -10,32 +10,32 @@ #include "EchoPayload.h" class EchoPayloadParser : public Swift::GenericPayloadParser { - public: - EchoPayloadParser() : currentDepth(0) {} - - void handleStartElement( - const std::string& /* element */, const std::string& /* ns */, const AttributeMap&) { - currentDepth++; - } - - void handleEndElement(const std::string& /* element */, const std::string& /* ns */) { - currentDepth--; - if (currentDepth == 0) { - getPayloadInternal()->setMessage(currentText); - } - } - - void handleCharacterData(const std::string& data) { - currentText += data; - } - - private: - int currentDepth; - std::string currentText; + public: + EchoPayloadParser() : currentDepth(0) {} + + void handleStartElement( + const std::string& /* element */, const std::string& /* ns */, const AttributeMap&) { + currentDepth++; + } + + void handleEndElement(const std::string& /* element */, const std::string& /* ns */) { + currentDepth--; + if (currentDepth == 0) { + getPayloadInternal()->setMessage(currentText); + } + } + + void handleCharacterData(const std::string& data) { + currentText += data; + } + + private: + int currentDepth; + std::string currentText; }; class EchoPayloadParserFactory : public Swift::GenericPayloadParserFactory { - public: - EchoPayloadParserFactory() : - GenericPayloadParserFactory("echo", "http://swift.im/echo") {} + public: + EchoPayloadParserFactory() : + GenericPayloadParserFactory("echo", "http://swift.im/echo") {} }; diff --git a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h index abc4760..91440d0 100644 --- a/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h +++ b/Documentation/SwiftenDevelopersGuide/Examples/EchoBot/EchoPayloadSerializer.h @@ -10,10 +10,10 @@ #include "EchoPayload.h" class EchoPayloadSerializer : public Swift::GenericPayloadSerializer { - public: - std::string serializePayload(boost::shared_ptr payload) const { - XMLElement element("echo", "http://swift.im/protocol/echo"); - element.addNode(XMLTextNode::ref(new XMLTextNode(payload->getMessage()))); - return element.serialize(); - } + public: + std::string serializePayload(boost::shared_ptr payload) const { + XMLElement element("echo", "http://swift.im/protocol/echo"); + element.addNode(XMLTextNode::ref(new XMLTextNode(payload->getMessage()))); + return element.serialize(); + } }; diff --git a/Limber/Server/ServerFromClientSession.cpp b/Limber/Server/ServerFromClientSession.cpp index ab596a1..e8d0769 100644 --- a/Limber/Server/ServerFromClientSession.cpp +++ b/Limber/Server/ServerFromClientSession.cpp @@ -26,95 +26,95 @@ namespace Swift { ServerFromClientSession::ServerFromClientSession( - const std::string& id, - boost::shared_ptr connection, - PayloadParserFactoryCollection* payloadParserFactories, - PayloadSerializerCollection* payloadSerializers, - XMLParserFactory* xmlParserFactory, - UserRegistry* userRegistry) : - Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory), - id_(id), - userRegistry_(userRegistry), - authenticated_(false), - initialized(false), - allowSASLEXTERNAL(false) { + const std::string& id, + boost::shared_ptr connection, + PayloadParserFactoryCollection* payloadParserFactories, + PayloadSerializerCollection* payloadSerializers, + XMLParserFactory* xmlParserFactory, + UserRegistry* userRegistry) : + Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory), + id_(id), + userRegistry_(userRegistry), + authenticated_(false), + initialized(false), + allowSASLEXTERNAL(false) { } void ServerFromClientSession::handleElement(boost::shared_ptr element) { - if (isInitialized()) { - onElementReceived(element); - } - else { - if (AuthRequest* authRequest = dynamic_cast(element.get())) { - if (authRequest->getMechanism() == "PLAIN" || (allowSASLEXTERNAL && authRequest->getMechanism() == "EXTERNAL")) { - if (authRequest->getMechanism() == "EXTERNAL") { - getXMPPLayer()->writeElement(boost::make_shared()); - authenticated_ = true; - getXMPPLayer()->resetParser(); - } - else { - PLAINMessage plainMessage(authRequest->getMessage() ? *authRequest->getMessage() : createSafeByteArray("")); - if (userRegistry_->isValidUserPassword(JID(plainMessage.getAuthenticationID(), getLocalJID().getDomain()), plainMessage.getPassword())) { - getXMPPLayer()->writeElement(boost::make_shared()); - user_ = plainMessage.getAuthenticationID(); - authenticated_ = true; - getXMPPLayer()->resetParser(); - } - else { - getXMPPLayer()->writeElement(boost::shared_ptr(new AuthFailure)); - finishSession(AuthenticationFailedError); - } - } - } - else { - getXMPPLayer()->writeElement(boost::shared_ptr(new AuthFailure)); - finishSession(NoSupportedAuthMechanismsError); - } - } - else if (IQ* iq = dynamic_cast(element.get())) { - if (boost::shared_ptr resourceBind = iq->getPayload()) { - setRemoteJID(JID(user_, getLocalJID().getDomain(), resourceBind->getResource())); - boost::shared_ptr resultResourceBind(new ResourceBind()); - resultResourceBind->setJID(getRemoteJID()); - getXMPPLayer()->writeElement(IQ::createResult(JID(), iq->getID(), resultResourceBind)); - } - else if (iq->getPayload()) { - getXMPPLayer()->writeElement(IQ::createResult(getRemoteJID(), iq->getID())); - setInitialized(); - } - } - } + if (isInitialized()) { + onElementReceived(element); + } + else { + if (AuthRequest* authRequest = dynamic_cast(element.get())) { + if (authRequest->getMechanism() == "PLAIN" || (allowSASLEXTERNAL && authRequest->getMechanism() == "EXTERNAL")) { + if (authRequest->getMechanism() == "EXTERNAL") { + getXMPPLayer()->writeElement(boost::make_shared()); + authenticated_ = true; + getXMPPLayer()->resetParser(); + } + else { + PLAINMessage plainMessage(authRequest->getMessage() ? *authRequest->getMessage() : createSafeByteArray("")); + if (userRegistry_->isValidUserPassword(JID(plainMessage.getAuthenticationID(), getLocalJID().getDomain()), plainMessage.getPassword())) { + getXMPPLayer()->writeElement(boost::make_shared()); + user_ = plainMessage.getAuthenticationID(); + authenticated_ = true; + getXMPPLayer()->resetParser(); + } + else { + getXMPPLayer()->writeElement(boost::shared_ptr(new AuthFailure)); + finishSession(AuthenticationFailedError); + } + } + } + else { + getXMPPLayer()->writeElement(boost::shared_ptr(new AuthFailure)); + finishSession(NoSupportedAuthMechanismsError); + } + } + else if (IQ* iq = dynamic_cast(element.get())) { + if (boost::shared_ptr resourceBind = iq->getPayload()) { + setRemoteJID(JID(user_, getLocalJID().getDomain(), resourceBind->getResource())); + boost::shared_ptr resultResourceBind(new ResourceBind()); + resultResourceBind->setJID(getRemoteJID()); + getXMPPLayer()->writeElement(IQ::createResult(JID(), iq->getID(), resultResourceBind)); + } + else if (iq->getPayload()) { + getXMPPLayer()->writeElement(IQ::createResult(getRemoteJID(), iq->getID())); + setInitialized(); + } + } + } } void ServerFromClientSession::handleStreamStart(const ProtocolHeader& incomingHeader) { - setLocalJID(JID("", incomingHeader.getTo())); - ProtocolHeader header; - header.setFrom(incomingHeader.getTo()); - header.setID(id_); - getXMPPLayer()->writeHeader(header); + setLocalJID(JID("", incomingHeader.getTo())); + ProtocolHeader header; + header.setFrom(incomingHeader.getTo()); + header.setID(id_); + getXMPPLayer()->writeHeader(header); - boost::shared_ptr features(new StreamFeatures()); - if (!authenticated_) { - features->addAuthenticationMechanism("PLAIN"); - if (allowSASLEXTERNAL) { - features->addAuthenticationMechanism("EXTERNAL"); - } - } - else { - features->setHasResourceBind(); - features->setHasSession(); - } - getXMPPLayer()->writeElement(features); + boost::shared_ptr features(new StreamFeatures()); + if (!authenticated_) { + features->addAuthenticationMechanism("PLAIN"); + if (allowSASLEXTERNAL) { + features->addAuthenticationMechanism("EXTERNAL"); + } + } + else { + features->setHasResourceBind(); + features->setHasSession(); + } + getXMPPLayer()->writeElement(features); } void ServerFromClientSession::setInitialized() { - initialized = true; - onSessionStarted(); + initialized = true; + onSessionStarted(); } void ServerFromClientSession::setAllowSASLEXTERNAL() { - allowSASLEXTERNAL = true; + allowSASLEXTERNAL = true; } } diff --git a/Limber/Server/ServerFromClientSession.h b/Limber/Server/ServerFromClientSession.h index 7d6907c..34d4f18 100644 --- a/Limber/Server/ServerFromClientSession.h +++ b/Limber/Server/ServerFromClientSession.h @@ -18,46 +18,46 @@ #include namespace Swift { - class ProtocolHeader; - class ToplevelElement; - class Stanza; - class PayloadParserFactoryCollection; - class PayloadSerializerCollection; - class StreamStack; - class UserRegistry; - class XMPPLayer; - class ConnectionLayer; - class Connection; - class XMLParserFactory; - - class ServerFromClientSession : public Session { - public: - ServerFromClientSession( - const std::string& id, - boost::shared_ptr connection, - PayloadParserFactoryCollection* payloadParserFactories, - PayloadSerializerCollection* payloadSerializers, - XMLParserFactory* xmlParserFactory, - UserRegistry* userRegistry); - - boost::signal onSessionStarted; - void setAllowSASLEXTERNAL(); - - private: - void handleElement(boost::shared_ptr); - void handleStreamStart(const ProtocolHeader& header); - - void setInitialized(); - bool isInitialized() const { - return initialized; - } - - private: - std::string id_; - UserRegistry* userRegistry_; - bool authenticated_; - bool initialized; - bool allowSASLEXTERNAL; - std::string user_; - }; + class ProtocolHeader; + class ToplevelElement; + class Stanza; + class PayloadParserFactoryCollection; + class PayloadSerializerCollection; + class StreamStack; + class UserRegistry; + class XMPPLayer; + class ConnectionLayer; + class Connection; + class XMLParserFactory; + + class ServerFromClientSession : public Session { + public: + ServerFromClientSession( + const std::string& id, + boost::shared_ptr connection, + PayloadParserFactoryCollection* payloadParserFactories, + PayloadSerializerCollection* payloadSerializers, + XMLParserFactory* xmlParserFactory, + UserRegistry* userRegistry); + + boost::signal onSessionStarted; + void setAllowSASLEXTERNAL(); + + private: + void handleElement(boost::shared_ptr); + void handleStreamStart(const ProtocolHeader& header); + + void setInitialized(); + bool isInitialized() const { + return initialized; + } + + private: + std::string id_; + UserRegistry* userRegistry_; + bool authenticated_; + bool initialized; + bool allowSASLEXTERNAL; + std::string user_; + }; } diff --git a/Limber/Server/ServerSession.h b/Limber/Server/ServerSession.h index 4296e16..9b784ac 100644 --- a/Limber/Server/ServerSession.h +++ b/Limber/Server/ServerSession.h @@ -11,13 +11,13 @@ #include namespace Swift { - class ServerSession { - public: - virtual ~ServerSession(); + class ServerSession { + public: + virtual ~ServerSession(); - virtual const JID& getJID() const = 0; - virtual int getPriority() const = 0; + virtual const JID& getJID() const = 0; + virtual int getPriority() const = 0; - virtual void sendStanza(boost::shared_ptr) = 0; - }; + virtual void sendStanza(boost::shared_ptr) = 0; + }; } diff --git a/Limber/Server/ServerStanzaRouter.cpp b/Limber/Server/ServerStanzaRouter.cpp index d0896a0..3ab88e1 100644 --- a/Limber/Server/ServerStanzaRouter.cpp +++ b/Limber/Server/ServerStanzaRouter.cpp @@ -16,61 +16,61 @@ namespace Swift { namespace { - struct PriorityLessThan { - bool operator()(const ServerSession* s1, const ServerSession* s2) const { - return s1->getPriority() < s2->getPriority(); - } - }; + struct PriorityLessThan { + bool operator()(const ServerSession* s1, const ServerSession* s2) const { + return s1->getPriority() < s2->getPriority(); + } + }; - struct HasJID { - HasJID(const JID& jid) : jid(jid) {} - bool operator()(const ServerSession* session) const { - return session->getJID().equals(jid, JID::WithResource); - } - JID jid; - }; + struct HasJID { + HasJID(const JID& jid) : jid(jid) {} + bool operator()(const ServerSession* session) const { + return session->getJID().equals(jid, JID::WithResource); + } + JID jid; + }; } ServerStanzaRouter::ServerStanzaRouter() { } bool ServerStanzaRouter::routeStanza(boost::shared_ptr stanza) { - JID to = stanza->getTo(); - assert(to.isValid()); + JID to = stanza->getTo(); + assert(to.isValid()); - // For a full JID, first try to route to a session with the full JID - if (!to.isBare()) { - std::vector::const_iterator i = std::find_if(clientSessions_.begin(), clientSessions_.end(), HasJID(to)); - if (i != clientSessions_.end()) { - (*i)->sendStanza(stanza); - return true; - } - } + // For a full JID, first try to route to a session with the full JID + if (!to.isBare()) { + std::vector::const_iterator i = std::find_if(clientSessions_.begin(), clientSessions_.end(), HasJID(to)); + if (i != clientSessions_.end()) { + (*i)->sendStanza(stanza); + return true; + } + } - // Look for candidate sessions - to = to.toBare(); - std::vector candidateSessions; - for (std::vector::const_iterator i = clientSessions_.begin(); i != clientSessions_.end(); ++i) { - if ((*i)->getJID().equals(to, JID::WithoutResource) && (*i)->getPriority() >= 0) { - candidateSessions.push_back(*i); - } - } - if (candidateSessions.empty()) { - return false; - } + // Look for candidate sessions + to = to.toBare(); + std::vector candidateSessions; + for (std::vector::const_iterator i = clientSessions_.begin(); i != clientSessions_.end(); ++i) { + if ((*i)->getJID().equals(to, JID::WithoutResource) && (*i)->getPriority() >= 0) { + candidateSessions.push_back(*i); + } + } + if (candidateSessions.empty()) { + return false; + } - // Find the session with the highest priority - std::vector::const_iterator i = std::max_element(clientSessions_.begin(), clientSessions_.end(), PriorityLessThan()); - (*i)->sendStanza(stanza); - return true; + // Find the session with the highest priority + std::vector::const_iterator i = std::max_element(clientSessions_.begin(), clientSessions_.end(), PriorityLessThan()); + (*i)->sendStanza(stanza); + return true; } void ServerStanzaRouter::addClientSession(ServerSession* clientSession) { - clientSessions_.push_back(clientSession); + clientSessions_.push_back(clientSession); } void ServerStanzaRouter::removeClientSession(ServerSession* clientSession) { - erase(clientSessions_, clientSession); + erase(clientSessions_, clientSession); } } diff --git a/Limber/Server/ServerStanzaRouter.h b/Limber/Server/ServerStanzaRouter.h index a9cc494..174f509 100644 --- a/Limber/Server/ServerStanzaRouter.h +++ b/Limber/Server/ServerStanzaRouter.h @@ -14,18 +14,18 @@ #include namespace Swift { - class ServerSession; + class ServerSession; - class ServerStanzaRouter { - public: - ServerStanzaRouter(); + class ServerStanzaRouter { + public: + ServerStanzaRouter(); - bool routeStanza(boost::shared_ptr); + bool routeStanza(boost::shared_ptr); - void addClientSession(ServerSession*); - void removeClientSession(ServerSession*); + void addClientSession(ServerSession*); + void removeClientSession(ServerSession*); - private: - std::vector clientSessions_; - }; + private: + std::vector clientSessions_; + }; } diff --git a/Limber/Server/SimpleUserRegistry.cpp b/Limber/Server/SimpleUserRegistry.cpp index dd6c112..4f39030 100644 --- a/Limber/Server/SimpleUserRegistry.cpp +++ b/Limber/Server/SimpleUserRegistry.cpp @@ -12,12 +12,12 @@ SimpleUserRegistry::SimpleUserRegistry() { } bool SimpleUserRegistry::isValidUserPassword(const JID& user, const SafeByteArray& password) const { - std::map::const_iterator i = users.find(user); - return i != users.end() ? i->second == password : false; + std::map::const_iterator i = users.find(user); + return i != users.end() ? i->second == password : false; } void SimpleUserRegistry::addUser(const JID& user, const std::string& password) { - users.insert(std::make_pair(user, createSafeByteArray(password))); + users.insert(std::make_pair(user, createSafeByteArray(password))); } } diff --git a/Limber/Server/SimpleUserRegistry.h b/Limber/Server/SimpleUserRegistry.h index 8287a14..9963b2c 100644 --- a/Limber/Server/SimpleUserRegistry.h +++ b/Limber/Server/SimpleUserRegistry.h @@ -14,16 +14,16 @@ #include namespace Swift { - - class SimpleUserRegistry : public UserRegistry { - public: - SimpleUserRegistry(); - virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const; - void addUser(const JID& user, const std::string& password); + class SimpleUserRegistry : public UserRegistry { + public: + SimpleUserRegistry(); - private: - std::map users; - }; + virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const; + void addUser(const JID& user, const std::string& password); + + private: + std::map users; + }; } diff --git a/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp b/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp index 2e7293b..a234038 100644 --- a/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp +++ b/Limber/Server/UnitTest/ServerStanzaRouterTest.cpp @@ -15,137 +15,137 @@ using namespace Swift; class ServerStanzaRouterTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ServerStanzaRouterTest); - CPPUNIT_TEST(testRouteStanza_FullJID); - CPPUNIT_TEST(testRouteStanza_FullJIDWithNegativePriority); - CPPUNIT_TEST(testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession); - CPPUNIT_TEST(testRouteStanza_BareJIDWithoutMatchingSession); - CPPUNIT_TEST(testRouteStanza_BareJIDWithMultipleSessions); - CPPUNIT_TEST(testRouteStanza_BareJIDWithOnlyNegativePriorities); - CPPUNIT_TEST(testRouteStanza_BareJIDWithChangingPresence); - CPPUNIT_TEST_SUITE_END(); - - public: - ServerStanzaRouterTest() {} - - void setUp() { - } - - void tearDown() { - } - - void testRouteStanza_FullJID() { - ServerStanzaRouter testling; - MockServerSession session1(JID("foo@bar.com/Bla"), 0); - testling.addClientSession(&session1); - MockServerSession session2(JID("foo@bar.com/Baz"), 0); - testling.addClientSession(&session2); - - bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz")); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(0, static_cast(session1.sentStanzas.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(session2.sentStanzas.size())); - } - - void testRouteStanza_FullJIDWithNegativePriority() { - ServerStanzaRouter testling; - MockServerSession session1(JID("foo@bar.com/Bla"), -1); - testling.addClientSession(&session1); - MockServerSession session2(JID("foo@bar.com/Baz"), 0); - testling.addClientSession(&session2); - - bool result = testling.routeStanza(createMessageTo("foo@bar.com/Bla")); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(1, static_cast(session1.sentStanzas.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast(session2.sentStanzas.size())); - } - - void testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession() { - ServerStanzaRouter testling; - MockServerSession session(JID("foo@bar.com/Bla"), 0); - testling.addClientSession(&session); - - bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz")); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(1, static_cast(session.sentStanzas.size())); - } - - void testRouteStanza_BareJIDWithoutMatchingSession() { - ServerStanzaRouter testling; - - bool result = testling.routeStanza(createMessageTo("foo@bar.com")); - - CPPUNIT_ASSERT(!result); - } - - void testRouteStanza_BareJIDWithMultipleSessions() { - ServerStanzaRouter testling; - MockServerSession session1(JID("foo@bar.com/Bla"), 1); - testling.addClientSession(&session1); - MockServerSession session2(JID("foo@bar.com/Baz"), 8); - testling.addClientSession(&session2); - MockServerSession session3(JID("foo@bar.com/Bar"), 5); - testling.addClientSession(&session3); - - bool result = testling.routeStanza(createMessageTo("foo@bar.com")); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(0, static_cast(session1.sentStanzas.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(session2.sentStanzas.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast(session3.sentStanzas.size())); - } - - void testRouteStanza_BareJIDWithOnlyNegativePriorities() { - ServerStanzaRouter testling; - MockServerSession session(JID("foo@bar.com/Bla"), -1); - testling.addClientSession(&session); - - bool result = testling.routeStanza(createMessageTo("foo@bar.com")); - - CPPUNIT_ASSERT(!result); - } - - void testRouteStanza_BareJIDWithChangingPresence() { - ServerStanzaRouter testling; - MockServerSession session1(JID("foo@bar.com/Baz"), 8); - testling.addClientSession(&session1); - MockServerSession session2(JID("foo@bar.com/Bar"), 5); - testling.addClientSession(&session2); - - session1.priority = 3; - session2.priority = 4; - bool result = testling.routeStanza(createMessageTo("foo@bar.com")); - - CPPUNIT_ASSERT(result); - CPPUNIT_ASSERT_EQUAL(0, static_cast(session1.sentStanzas.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(session2.sentStanzas.size())); - } - - private: - boost::shared_ptr createMessageTo(const std::string& recipient) { - boost::shared_ptr message(new Message()); - message->setTo(JID(recipient)); - return message; - } - - class MockServerSession : public ServerSession { - public: - MockServerSession(const JID& jid, int priority) : jid(jid), priority(priority) {} - - virtual const JID& getJID() const { return jid; } - virtual int getPriority() const { return priority; } - - virtual void sendStanza(boost::shared_ptr stanza) { - sentStanzas.push_back(stanza); - } - - JID jid; - int priority; - std::vector< boost::shared_ptr > sentStanzas; - }; + CPPUNIT_TEST_SUITE(ServerStanzaRouterTest); + CPPUNIT_TEST(testRouteStanza_FullJID); + CPPUNIT_TEST(testRouteStanza_FullJIDWithNegativePriority); + CPPUNIT_TEST(testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession); + CPPUNIT_TEST(testRouteStanza_BareJIDWithoutMatchingSession); + CPPUNIT_TEST(testRouteStanza_BareJIDWithMultipleSessions); + CPPUNIT_TEST(testRouteStanza_BareJIDWithOnlyNegativePriorities); + CPPUNIT_TEST(testRouteStanza_BareJIDWithChangingPresence); + CPPUNIT_TEST_SUITE_END(); + + public: + ServerStanzaRouterTest() {} + + void setUp() { + } + + void tearDown() { + } + + void testRouteStanza_FullJID() { + ServerStanzaRouter testling; + MockServerSession session1(JID("foo@bar.com/Bla"), 0); + testling.addClientSession(&session1); + MockServerSession session2(JID("foo@bar.com/Baz"), 0); + testling.addClientSession(&session2); + + bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz")); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(0, static_cast(session1.sentStanzas.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(session2.sentStanzas.size())); + } + + void testRouteStanza_FullJIDWithNegativePriority() { + ServerStanzaRouter testling; + MockServerSession session1(JID("foo@bar.com/Bla"), -1); + testling.addClientSession(&session1); + MockServerSession session2(JID("foo@bar.com/Baz"), 0); + testling.addClientSession(&session2); + + bool result = testling.routeStanza(createMessageTo("foo@bar.com/Bla")); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(1, static_cast(session1.sentStanzas.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast(session2.sentStanzas.size())); + } + + void testRouteStanza_FullJIDWithOnlyBareJIDMatchingSession() { + ServerStanzaRouter testling; + MockServerSession session(JID("foo@bar.com/Bla"), 0); + testling.addClientSession(&session); + + bool result = testling.routeStanza(createMessageTo("foo@bar.com/Baz")); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(1, static_cast(session.sentStanzas.size())); + } + + void testRouteStanza_BareJIDWithoutMatchingSession() { + ServerStanzaRouter testling; + + bool result = testling.routeStanza(createMessageTo("foo@bar.com")); + + CPPUNIT_ASSERT(!result); + } + + void testRouteStanza_BareJIDWithMultipleSessions() { + ServerStanzaRouter testling; + MockServerSession session1(JID("foo@bar.com/Bla"), 1); + testling.addClientSession(&session1); + MockServerSession session2(JID("foo@bar.com/Baz"), 8); + testling.addClientSession(&session2); + MockServerSession session3(JID("foo@bar.com/Bar"), 5); + testling.addClientSession(&session3); + + bool result = testling.routeStanza(createMessageTo("foo@bar.com")); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(0, static_cast(session1.sentStanzas.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(session2.sentStanzas.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast(session3.sentStanzas.size())); + } + + void testRouteStanza_BareJIDWithOnlyNegativePriorities() { + ServerStanzaRouter testling; + MockServerSession session(JID("foo@bar.com/Bla"), -1); + testling.addClientSession(&session); + + bool result = testling.routeStanza(createMessageTo("foo@bar.com")); + + CPPUNIT_ASSERT(!result); + } + + void testRouteStanza_BareJIDWithChangingPresence() { + ServerStanzaRouter testling; + MockServerSession session1(JID("foo@bar.com/Baz"), 8); + testling.addClientSession(&session1); + MockServerSession session2(JID("foo@bar.com/Bar"), 5); + testling.addClientSession(&session2); + + session1.priority = 3; + session2.priority = 4; + bool result = testling.routeStanza(createMessageTo("foo@bar.com")); + + CPPUNIT_ASSERT(result); + CPPUNIT_ASSERT_EQUAL(0, static_cast(session1.sentStanzas.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(session2.sentStanzas.size())); + } + + private: + boost::shared_ptr createMessageTo(const std::string& recipient) { + boost::shared_ptr message(new Message()); + message->setTo(JID(recipient)); + return message; + } + + class MockServerSession : public ServerSession { + public: + MockServerSession(const JID& jid, int priority) : jid(jid), priority(priority) {} + + virtual const JID& getJID() const { return jid; } + virtual int getPriority() const { return priority; } + + virtual void sendStanza(boost::shared_ptr stanza) { + sentStanzas.push_back(stanza); + } + + JID jid; + int priority; + std::vector< boost::shared_ptr > sentStanzas; + }; }; CPPUNIT_TEST_SUITE_REGISTRATION(ServerStanzaRouterTest); diff --git a/Limber/Server/UserRegistry.h b/Limber/Server/UserRegistry.h index 812b218..98b3e99 100644 --- a/Limber/Server/UserRegistry.h +++ b/Limber/Server/UserRegistry.h @@ -11,12 +11,12 @@ #include namespace Swift { - class JID; + class JID; - class UserRegistry { - public: - virtual ~UserRegistry(); + class UserRegistry { + public: + virtual ~UserRegistry(); - virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const = 0; - }; + virtual bool isValidUserPassword(const JID& user, const SafeByteArray& password) const = 0; + }; } diff --git a/Limber/main.cpp b/Limber/main.cpp index e4bac77..52f9347 100644 --- a/Limber/main.cpp +++ b/Limber/main.cpp @@ -31,76 +31,76 @@ using namespace Swift; class Server { - public: - Server(UserRegistry* userRegistry, EventLoop* eventLoop) : userRegistry_(userRegistry) { - serverFromClientConnectionServer_ = BoostConnectionServer::create(5222, boostIOServiceThread_.getIOService(), eventLoop); - serverFromClientConnectionServer_->onNewConnection.connect(boost::bind(&Server::handleNewConnection, this, _1)); - serverFromClientConnectionServer_->start(); - } + public: + Server(UserRegistry* userRegistry, EventLoop* eventLoop) : userRegistry_(userRegistry) { + serverFromClientConnectionServer_ = BoostConnectionServer::create(5222, boostIOServiceThread_.getIOService(), eventLoop); + serverFromClientConnectionServer_->onNewConnection.connect(boost::bind(&Server::handleNewConnection, this, _1)); + serverFromClientConnectionServer_->start(); + } - private: - void handleNewConnection(boost::shared_ptr c) { - boost::shared_ptr session(new ServerFromClientSession(idGenerator_.generateID(), c, &payloadParserFactories_, &payloadSerializers_, &xmlParserFactory, userRegistry_)); - serverFromClientSessions_.push_back(session); - session->onElementReceived.connect(boost::bind(&Server::handleElementReceived, this, _1, session)); - session->onSessionFinished.connect(boost::bind(&Server::handleSessionFinished, this, session)); - session->startSession(); - } + private: + void handleNewConnection(boost::shared_ptr c) { + boost::shared_ptr session(new ServerFromClientSession(idGenerator_.generateID(), c, &payloadParserFactories_, &payloadSerializers_, &xmlParserFactory, userRegistry_)); + serverFromClientSessions_.push_back(session); + session->onElementReceived.connect(boost::bind(&Server::handleElementReceived, this, _1, session)); + session->onSessionFinished.connect(boost::bind(&Server::handleSessionFinished, this, session)); + session->startSession(); + } - void handleSessionFinished(boost::shared_ptr session) { - serverFromClientSessions_.erase(std::remove(serverFromClientSessions_.begin(), serverFromClientSessions_.end(), session), serverFromClientSessions_.end()); - } + void handleSessionFinished(boost::shared_ptr session) { + serverFromClientSessions_.erase(std::remove(serverFromClientSessions_.begin(), serverFromClientSessions_.end(), session), serverFromClientSessions_.end()); + } - void handleElementReceived(boost::shared_ptr element, boost::shared_ptr session) { - boost::shared_ptr stanza(boost::dynamic_pointer_cast(element)); - if (!stanza) { - return; - } - stanza->setFrom(session->getRemoteJID()); - if (!stanza->getTo().isValid()) { - stanza->setTo(JID(session->getLocalJID())); - } - if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) { - if (boost::shared_ptr iq = boost::dynamic_pointer_cast(stanza)) { - if (iq->getPayload()) { - session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), boost::make_shared())); - } - if (iq->getPayload()) { - if (iq->getType() == IQ::Get) { - boost::shared_ptr vcard(new VCard()); - vcard->setNickname(iq->getFrom().getNode()); - session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vcard)); - } - else { - session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel)); - } - } - else { - session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel)); - } - } - } - } + void handleElementReceived(boost::shared_ptr element, boost::shared_ptr session) { + boost::shared_ptr stanza(boost::dynamic_pointer_cast(element)); + if (!stanza) { + return; + } + stanza->setFrom(session->getRemoteJID()); + if (!stanza->getTo().isValid()) { + stanza->setTo(JID(session->getLocalJID())); + } + if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) { + if (boost::shared_ptr iq = boost::dynamic_pointer_cast(stanza)) { + if (iq->getPayload()) { + session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), boost::make_shared())); + } + if (iq->getPayload()) { + if (iq->getType() == IQ::Get) { + boost::shared_ptr vcard(new VCard()); + vcard->setNickname(iq->getFrom().getNode()); + session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vcard)); + } + else { + session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel)); + } + } + else { + session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel)); + } + } + } + } - private: - IDGenerator idGenerator_; - PlatformXMLParserFactory xmlParserFactory; - UserRegistry* userRegistry_; - BoostIOServiceThread boostIOServiceThread_; - boost::shared_ptr serverFromClientConnectionServer_; - std::vector< boost::shared_ptr > serverFromClientSessions_; - FullPayloadParserFactoryCollection payloadParserFactories_; - FullPayloadSerializerCollection payloadSerializers_; + private: + IDGenerator idGenerator_; + PlatformXMLParserFactory xmlParserFactory; + UserRegistry* userRegistry_; + BoostIOServiceThread boostIOServiceThread_; + boost::shared_ptr serverFromClientConnectionServer_; + std::vector< boost::shared_ptr > serverFromClientSessions_; + FullPayloadParserFactoryCollection payloadParserFactories_; + FullPayloadSerializerCollection payloadSerializers_; }; int main() { - SimpleEventLoop eventLoop; - SimpleUserRegistry userRegistry; - userRegistry.addUser(JID("remko@localhost"), "remko"); - userRegistry.addUser(JID("kevin@localhost"), "kevin"); - userRegistry.addUser(JID("remko@limber.swift.im"), "remko"); - userRegistry.addUser(JID("kevin@limber.swift.im"), "kevin"); - Server server(&userRegistry, &eventLoop); - eventLoop.run(); - return 0; + SimpleEventLoop eventLoop; + SimpleUserRegistry userRegistry; + userRegistry.addUser(JID("remko@localhost"), "remko"); + userRegistry.addUser(JID("kevin@localhost"), "kevin"); + userRegistry.addUser(JID("remko@limber.swift.im"), "remko"); + userRegistry.addUser(JID("kevin@limber.swift.im"), "kevin"); + Server server(&userRegistry, &eventLoop); + eventLoop.run(); + return 0; } diff --git a/QA/Checker/IO.cpp b/QA/Checker/IO.cpp index ad9f877..d8fcc96 100644 --- a/QA/Checker/IO.cpp +++ b/QA/Checker/IO.cpp @@ -10,56 +10,56 @@ #include std::ostream& operator<<(std::ostream& os, const Swift::ByteArray& s) { - std::ios::fmtflags oldFlags = os.flags(); - os << std::hex; - for (Swift::ByteArray::const_iterator i = s.begin(); i != s.end(); ++i) { - if (*i >= 32 && *i < 127) { - os << *i; - } - else { - os << "\\x" << static_cast(static_cast(*i)); - } - } - os << std::endl; - os.flags(oldFlags); - return os; + std::ios::fmtflags oldFlags = os.flags(); + os << std::hex; + for (Swift::ByteArray::const_iterator i = s.begin(); i != s.end(); ++i) { + if (*i >= 32 && *i < 127) { + os << *i; + } + else { + os << "\\x" << static_cast(static_cast(*i)); + } + } + os << std::endl; + os.flags(oldFlags); + return os; } std::ostream& operator<<(std::ostream& os, const Swift::SafeByteArray& s) { - std::ios::fmtflags oldFlags = os.flags(); - os << std::hex; - for (Swift::SafeByteArray::const_iterator i = s.begin(); i != s.end(); ++i) { - if (*i >= 32 && *i < 127) { - os << *i; - } - else { - os << "\\x" << static_cast(static_cast(*i)); - } - } - os << std::endl; - os.flags(oldFlags); - return os; + std::ios::fmtflags oldFlags = os.flags(); + os << std::hex; + for (Swift::SafeByteArray::const_iterator i = s.begin(); i != s.end(); ++i) { + if (*i >= 32 && *i < 127) { + os << *i; + } + else { + os << "\\x" << static_cast(static_cast(*i)); + } + } + os << std::endl; + os.flags(oldFlags); + return os; } std::ostream& operator<<(std::ostream& os, const std::vector& s) { - for (std::vector::const_iterator i = s.begin(); i != s.end(); ++i) { - os << *i << " "; - } - os << std::endl; - return os; + for (std::vector::const_iterator i = s.begin(); i != s.end(); ++i) { + os << *i << " "; + } + os << std::endl; + return os; } std::ostream& operator<<(std::ostream& os, const std::vector& s) { - for (std::vector::const_iterator i = s.begin(); i != s.end(); ++i) { - os << *i << " "; - } - os << std::endl; - return os; + for (std::vector::const_iterator i = s.begin(); i != s.end(); ++i) { + os << *i << " "; + } + os << std::endl; + return os; } bool operator==(const Swift::ByteArray& a, const Swift::ByteArray& b) { - if (a.size() != b.size()) { - return false; - } - return std::equal(a.begin(), a.end(), b.begin()); + if (a.size() != b.size()) { + return false; + } + return std::equal(a.begin(), a.end(), b.begin()); } diff --git a/QA/Checker/checker.cpp b/QA/Checker/checker.cpp index 9cae75a..f1186cc 100644 --- a/QA/Checker/checker.cpp +++ b/QA/Checker/checker.cpp @@ -17,71 +17,71 @@ #include int main(int argc, char* argv[]) { - bool verbose = false; - bool outputXML = false; + bool verbose = false; + bool outputXML = false; - Swift::Log::setLogLevel(Swift::Log::error); + Swift::Log::setLogLevel(Swift::Log::error); - // Parse parameters - std::vector testsToRun; - for (int i = 1; i < argc; ++i) { - std::string param(argv[i]); - if (param == "--verbose") { - verbose = true; - } - else if (param == "--xml") { - outputXML = true; - } - else if (param == "--debug") { - Swift::Log::setLogLevel(Swift::Log::debug); - } - else { - testsToRun.push_back(param); - } - } - if (testsToRun.empty()) { - testsToRun.push_back(""); - } + // Parse parameters + std::vector testsToRun; + for (int i = 1; i < argc; ++i) { + std::string param(argv[i]); + if (param == "--verbose") { + verbose = true; + } + else if (param == "--xml") { + outputXML = true; + } + else if (param == "--debug") { + Swift::Log::setLogLevel(Swift::Log::debug); + } + else { + testsToRun.push_back(param); + } + } + if (testsToRun.empty()) { + testsToRun.push_back(""); + } - // Set up the listeners - CppUnit::TestResult controller; + // Set up the listeners + CppUnit::TestResult controller; - CppUnit::TestResultCollector result; - controller.addListener(&result); + CppUnit::TestResultCollector result; + controller.addListener(&result); - CppUnit::TextTestProgressListener progressListener; - CppUnit::BriefTestProgressListener verboseListener; - if (!outputXML) { - if (verbose) { - controller.addListener(&verboseListener); - } - else { - controller.addListener(&progressListener); - } - } + CppUnit::TextTestProgressListener progressListener; + CppUnit::BriefTestProgressListener verboseListener; + if (!outputXML) { + if (verbose) { + controller.addListener(&verboseListener); + } + else { + controller.addListener(&progressListener); + } + } - // Run the tests - CppUnit::TestRunner runner; - runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); - for (std::vector::const_iterator i = testsToRun.begin(); i != testsToRun.end(); ++i) { - try { - runner.run(controller, *i); - } - catch (const std::exception& e) { - std::cerr << "Error: " << e.what() << std::endl; - return -1; - } - } + // Run the tests + CppUnit::TestRunner runner; + runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest()); + for (std::vector::const_iterator i = testsToRun.begin(); i != testsToRun.end(); ++i) { + try { + runner.run(controller, *i); + } + catch (const std::exception& e) { + std::cerr << "Error: " << e.what() << std::endl; + return -1; + } + } - // Output the results - if (outputXML) { - CppUnit::XmlOutputter outputter(&result, std::cout); - outputter.write(); - } - else { - CppUnit::TextOutputter outputter(&result, std::cerr); - outputter.write(); - } + // Output the results + if (outputXML) { + CppUnit::XmlOutputter outputter(&result, std::cout); + outputter.write(); + } + else { + CppUnit::TextOutputter outputter(&result, std::cerr); + outputter.write(); + } - return result.wasSuccessful() ? 0 : 1; + return result.wasSuccessful() ? 0 : 1; } diff --git a/QA/UnitTest/template/FooTest.cpp b/QA/UnitTest/template/FooTest.cpp index 854c24a..adddb5b 100644 --- a/QA/UnitTest/template/FooTest.cpp +++ b/QA/UnitTest/template/FooTest.cpp @@ -10,19 +10,19 @@ using namespace Swift; class FooTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(FooTest); - CPPUNIT_TEST(testBar); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(FooTest); + CPPUNIT_TEST(testBar); + CPPUNIT_TEST_SUITE_END(); - public: - void setUp() { - } + public: + void setUp() { + } - void tearDown() { - } + void tearDown() { + } - void testBar() { - } + void testBar() { + } }; CPPUNIT_TEST_SUITE_REGISTRATION(FooTest); diff --git a/Slimber/CLI/DummyMenulet.h b/Slimber/CLI/DummyMenulet.h index 22d4b36..4b37df6 100644 --- a/Slimber/CLI/DummyMenulet.h +++ b/Slimber/CLI/DummyMenulet.h @@ -9,28 +9,28 @@ #include class DummyMenulet : public Menulet { - public: - DummyMenulet() { - } + public: + DummyMenulet() { + } - void clear() { - } + void clear() { + } - void addItem(const std::string&, const std::string&) { - } + void addItem(const std::string&, const std::string&) { + } - void addAboutItem() { - } + void addAboutItem() { + } - void addRestartItem() { - } + void addRestartItem() { + } - void addExitItem() { - } + void addExitItem() { + } - void addSeparator() { - } + void addSeparator() { + } - void setIcon(const std::string&) { - } + void setIcon(const std::string&) { + } }; diff --git a/Slimber/CLI/main.cpp b/Slimber/CLI/main.cpp index 9084a60..26f88d0 100644 --- a/Slimber/CLI/main.cpp +++ b/Slimber/CLI/main.cpp @@ -12,11 +12,11 @@ using namespace Swift; int main() { - SimpleEventLoop eventLoop; - - DummyMenulet menulet; - MainController controller(&menulet, &eventLoop); + SimpleEventLoop eventLoop; - eventLoop.run(); - return 0; + DummyMenulet menulet; + MainController controller(&menulet, &eventLoop); + + eventLoop.run(); + return 0; } diff --git a/Slimber/Cocoa/CocoaController.mm b/Slimber/Cocoa/CocoaController.mm index 1d2ef5c..7d17948 100644 --- a/Slimber/Cocoa/CocoaController.mm +++ b/Slimber/Cocoa/CocoaController.mm @@ -11,19 +11,19 @@ #include @implementation CocoaController { - CocoaMenulet* menulet; - MainController* main; + CocoaMenulet* menulet; + MainController* main; } - (void) dealloc { - delete main; - delete menulet; - [super dealloc]; + delete main; + delete menulet; + [super dealloc]; } - (void) awakeFromNib { - menulet = new CocoaMenulet(); - main = new MainController(menulet, eventLoop); + menulet = new CocoaMenulet(); + main = new MainController(menulet, eventLoop); } @end diff --git a/Slimber/Cocoa/CocoaMenulet.h b/Slimber/Cocoa/CocoaMenulet.h index c31f15c..0dc06f5 100644 --- a/Slimber/Cocoa/CocoaMenulet.h +++ b/Slimber/Cocoa/CocoaMenulet.h @@ -13,21 +13,21 @@ #include class CocoaMenulet : public Menulet { - public: - CocoaMenulet(); - virtual ~CocoaMenulet(); - - private: - virtual void clear(); - virtual void addItem(const std::string& name, const std::string& icon); - virtual void addSeparator(); - void setIcon(const std::string& icon); - virtual void addAboutItem(); - virtual void addRestartItem(); - virtual void addExitItem(); - - private: - NSStatusItem* statusItem; - NSMenu* menu; - CocoaAction* restartAction; + public: + CocoaMenulet(); + virtual ~CocoaMenulet(); + + private: + virtual void clear(); + virtual void addItem(const std::string& name, const std::string& icon); + virtual void addSeparator(); + void setIcon(const std::string& icon); + virtual void addAboutItem(); + virtual void addRestartItem(); + virtual void addExitItem(); + + private: + NSStatusItem* statusItem; + NSMenu* menu; + CocoaAction* restartAction; }; diff --git a/Slimber/Cocoa/CocoaMenulet.mm b/Slimber/Cocoa/CocoaMenulet.mm index f62da80..98042d7 100644 --- a/Slimber/Cocoa/CocoaMenulet.mm +++ b/Slimber/Cocoa/CocoaMenulet.mm @@ -11,72 +11,72 @@ #include CocoaMenulet::CocoaMenulet() { - restartAction = [[CocoaAction alloc] initWithFunction: - new boost::function(boost::ref(onRestartClicked))]; - menu = [[NSMenu alloc] init]; + restartAction = [[CocoaAction alloc] initWithFunction: + new boost::function(boost::ref(onRestartClicked))]; + menu = [[NSMenu alloc] init]; - statusItem = [[[NSStatusBar systemStatusBar] - statusItemWithLength: NSVariableStatusItemLength] retain]; - [statusItem setHighlightMode: YES]; - [statusItem setEnabled: YES]; - [statusItem setToolTip: @"Slimber"]; - [statusItem setMenu: menu]; + statusItem = [[[NSStatusBar systemStatusBar] + statusItemWithLength: NSVariableStatusItemLength] retain]; + [statusItem setHighlightMode: YES]; + [statusItem setEnabled: YES]; + [statusItem setToolTip: @"Slimber"]; + [statusItem setMenu: menu]; } CocoaMenulet::~CocoaMenulet() { - [statusItem release]; - [menu release]; - [restartAction release]; + [statusItem release]; + [menu release]; + [restartAction release]; } void CocoaMenulet::setIcon(const std::string& icon) { - NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"]; - NSImage* image = [[NSImage alloc] initWithContentsOfFile: path]; - [statusItem setImage: image]; - [image release]; + NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"]; + NSImage* image = [[NSImage alloc] initWithContentsOfFile: path]; + [statusItem setImage: image]; + [image release]; } void CocoaMenulet::clear() { - while ([menu numberOfItems] > 0) { - [menu removeItemAtIndex: 0]; - } + while ([menu numberOfItems] > 0) { + [menu removeItemAtIndex: 0]; + } } void CocoaMenulet::addItem(const std::string& name, const std::string& icon) { - NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: std2NSString(name) - action: NULL keyEquivalent: @""]; - if (!icon.empty()) { - NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"]; - NSImage* image = [[NSImage alloc] initWithContentsOfFile: path]; - [item setImage: image]; - [image release]; - } - [menu addItem: item]; - [item release]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: std2NSString(name) + action: NULL keyEquivalent: @""]; + if (!icon.empty()) { + NSString* path = [[NSBundle mainBundle] pathForResource: std2NSString(icon) ofType:@"png"]; + NSImage* image = [[NSImage alloc] initWithContentsOfFile: path]; + [item setImage: image]; + [image release]; + } + [menu addItem: item]; + [item release]; } void CocoaMenulet::addAboutItem() { - NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"About Slimber" action: @selector(orderFrontStandardAboutPanel:) keyEquivalent: @""]; - [item setTarget: [NSApplication sharedApplication]]; - [menu addItem: item]; - [item release]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"About Slimber" action: @selector(orderFrontStandardAboutPanel:) keyEquivalent: @""]; + [item setTarget: [NSApplication sharedApplication]]; + [menu addItem: item]; + [item release]; } void CocoaMenulet::addRestartItem() { - NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: - @"Restart" action: @selector(doAction:) keyEquivalent: @""]; - [item setTarget: restartAction]; - [menu addItem: item]; - [item release]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: + @"Restart" action: @selector(doAction:) keyEquivalent: @""]; + [item setTarget: restartAction]; + [menu addItem: item]; + [item release]; } void CocoaMenulet::addExitItem() { - NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"Exit" action: @selector(terminate:) keyEquivalent: @""]; - [item setTarget: [NSApplication sharedApplication]]; - [menu addItem: item]; - [item release]; + NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"Exit" action: @selector(terminate:) keyEquivalent: @""]; + [item setTarget: [NSApplication sharedApplication]]; + [menu addItem: item]; + [item release]; } void CocoaMenulet::addSeparator() { - [menu addItem: [NSMenuItem separatorItem]]; + [menu addItem: [NSMenuItem separatorItem]]; } diff --git a/Slimber/Cocoa/main.mm b/Slimber/Cocoa/main.mm index 41678f1..c5495af 100644 --- a/Slimber/Cocoa/main.mm +++ b/Slimber/Cocoa/main.mm @@ -13,8 +13,8 @@ Swift::CocoaEventLoop* eventLoop; int main(int argc, char *argv[]) { - eventLoop = new Swift::CocoaEventLoop(); - int result = NSApplicationMain(argc, const_cast(argv)); - delete eventLoop; - return result; + eventLoop = new Swift::CocoaEventLoop(); + int result = NSApplicationMain(argc, const_cast(argv)); + delete eventLoop; + return result; } diff --git a/Slimber/FileVCardCollection.cpp b/Slimber/FileVCardCollection.cpp index 33e20c9..af8d57d 100644 --- a/Slimber/FileVCardCollection.cpp +++ b/Slimber/FileVCardCollection.cpp @@ -21,24 +21,24 @@ FileVCardCollection::FileVCardCollection(boost::filesystem::path dir) : vcardsPa } boost::shared_ptr FileVCardCollection::getOwnVCard() const { - if (boost::filesystem::exists(vcardsPath / std::string("vcard.xml"))) { - ByteArray data; - readByteArrayFromFile(data, boost::filesystem::path(vcardsPath / std::string("vcard.xml")).string()); - - VCardParser parser; - PayloadParserTester tester(&parser); - tester.parse(byteArrayToString(data)); - return boost::dynamic_pointer_cast(parser.getPayload()); - } - else { - return boost::make_shared(); - } + if (boost::filesystem::exists(vcardsPath / std::string("vcard.xml"))) { + ByteArray data; + readByteArrayFromFile(data, boost::filesystem::path(vcardsPath / std::string("vcard.xml")).string()); + + VCardParser parser; + PayloadParserTester tester(&parser); + tester.parse(byteArrayToString(data)); + return boost::dynamic_pointer_cast(parser.getPayload()); + } + else { + return boost::make_shared(); + } } void FileVCardCollection::setOwnVCard(boost::shared_ptr v) { - boost::filesystem::ofstream file(vcardsPath / std::string("vcard.xml")); - file << VCardSerializer().serializePayload(v); - file.close(); + boost::filesystem::ofstream file(vcardsPath / std::string("vcard.xml")); + file << VCardSerializer().serializePayload(v); + file.close(); } } diff --git a/Slimber/FileVCardCollection.h b/Slimber/FileVCardCollection.h index 40f3e53..c05c4f4 100644 --- a/Slimber/FileVCardCollection.h +++ b/Slimber/FileVCardCollection.h @@ -12,14 +12,14 @@ #include namespace Swift { - class FileVCardCollection : public VCardCollection { - public: - FileVCardCollection(boost::filesystem::path dir); + class FileVCardCollection : public VCardCollection { + public: + FileVCardCollection(boost::filesystem::path dir); - boost::shared_ptr getOwnVCard() const; - void setOwnVCard(boost::shared_ptr vcard); + boost::shared_ptr getOwnVCard() const; + void setOwnVCard(boost::shared_ptr vcard); - private: - boost::filesystem::path vcardsPath; - }; + private: + boost::filesystem::path vcardsPath; + }; } diff --git a/Slimber/LinkLocalPresenceManager.cpp b/Slimber/LinkLocalPresenceManager.cpp index 786f3a8..200e98f 100644 --- a/Slimber/LinkLocalPresenceManager.cpp +++ b/Slimber/LinkLocalPresenceManager.cpp @@ -16,54 +16,54 @@ namespace Swift { LinkLocalPresenceManager::LinkLocalPresenceManager(LinkLocalServiceBrowser* browser) : browser(browser) { - browser->onServiceAdded.connect( - boost::bind(&LinkLocalPresenceManager::handleServiceAdded, this, _1)); - browser->onServiceChanged.connect( - boost::bind(&LinkLocalPresenceManager::handleServiceChanged, this, _1)); - browser->onServiceRemoved.connect( - boost::bind(&LinkLocalPresenceManager::handleServiceRemoved, this, _1)); + browser->onServiceAdded.connect( + boost::bind(&LinkLocalPresenceManager::handleServiceAdded, this, _1)); + browser->onServiceChanged.connect( + boost::bind(&LinkLocalPresenceManager::handleServiceChanged, this, _1)); + browser->onServiceRemoved.connect( + boost::bind(&LinkLocalPresenceManager::handleServiceRemoved, this, _1)); } boost::optional LinkLocalPresenceManager::getServiceForJID(const JID& j) const { - foreach(const LinkLocalService& service, browser->getServices()) { - if (service.getJID() == j) { - return service; - } - } - return boost::optional(); + foreach(const LinkLocalService& service, browser->getServices()) { + if (service.getJID() == j) { + return service; + } + } + return boost::optional(); } void LinkLocalPresenceManager::handleServiceAdded(const LinkLocalService& service) { - boost::shared_ptr roster(new RosterPayload()); - roster->addItem(getRosterItem(service)); - onRosterChanged(roster); - onPresenceChanged(getPresence(service)); + boost::shared_ptr roster(new RosterPayload()); + roster->addItem(getRosterItem(service)); + onRosterChanged(roster); + onPresenceChanged(getPresence(service)); } void LinkLocalPresenceManager::handleServiceChanged(const LinkLocalService& service) { - onPresenceChanged(getPresence(service)); + onPresenceChanged(getPresence(service)); } void LinkLocalPresenceManager::handleServiceRemoved(const LinkLocalService& service) { - boost::shared_ptr roster(new RosterPayload()); - roster->addItem(RosterItemPayload(service.getJID(), "", RosterItemPayload::Remove)); - onRosterChanged(roster); + boost::shared_ptr roster(new RosterPayload()); + roster->addItem(RosterItemPayload(service.getJID(), "", RosterItemPayload::Remove)); + onRosterChanged(roster); } boost::shared_ptr LinkLocalPresenceManager::getRoster() const { - boost::shared_ptr roster(new RosterPayload()); - foreach(const LinkLocalService& service, browser->getServices()) { - roster->addItem(getRosterItem(service)); - } - return roster; + boost::shared_ptr roster(new RosterPayload()); + foreach(const LinkLocalService& service, browser->getServices()) { + roster->addItem(getRosterItem(service)); + } + return roster; } std::vector > LinkLocalPresenceManager::getAllPresence() const { - std::vector > result; - foreach(const LinkLocalService& service, browser->getServices()) { - result.push_back(getPresence(service)); - } - return result; + std::vector > result; + foreach(const LinkLocalService& service, browser->getServices()) { + result.push_back(getPresence(service)); + } + return result; } RosterItemPayload LinkLocalPresenceManager::getRosterItem(const LinkLocalService& service) const { @@ -71,39 +71,39 @@ RosterItemPayload LinkLocalPresenceManager::getRosterItem(const LinkLocalService } std::string LinkLocalPresenceManager::getRosterName(const LinkLocalService& service) const { - LinkLocalServiceInfo info = service.getInfo(); - if (!info.getNick().empty()) { - return info.getNick(); - } - else if (!info.getFirstName().empty()) { - std::string result = info.getFirstName(); - if (!info.getLastName().empty()) { - result += " " + info.getLastName(); - } - return result; - } - else if (!info.getLastName().empty()) { - return info.getLastName(); - } - return ""; + LinkLocalServiceInfo info = service.getInfo(); + if (!info.getNick().empty()) { + return info.getNick(); + } + else if (!info.getFirstName().empty()) { + std::string result = info.getFirstName(); + if (!info.getLastName().empty()) { + result += " " + info.getLastName(); + } + return result; + } + else if (!info.getLastName().empty()) { + return info.getLastName(); + } + return ""; } boost::shared_ptr LinkLocalPresenceManager::getPresence(const LinkLocalService& service) const { - boost::shared_ptr presence(new Presence()); - presence->setFrom(service.getJID()); - switch (service.getInfo().getStatus()) { - case LinkLocalServiceInfo::Available: - presence->setShow(StatusShow::Online); - break; - case LinkLocalServiceInfo::Away: - presence->setShow(StatusShow::Away); - break; - case LinkLocalServiceInfo::DND: - presence->setShow(StatusShow::DND); - break; - } - presence->setStatus(service.getInfo().getMessage()); - return presence; + boost::shared_ptr presence(new Presence()); + presence->setFrom(service.getJID()); + switch (service.getInfo().getStatus()) { + case LinkLocalServiceInfo::Available: + presence->setShow(StatusShow::Online); + break; + case LinkLocalServiceInfo::Away: + presence->setShow(StatusShow::Away); + break; + case LinkLocalServiceInfo::DND: + presence->setShow(StatusShow::DND); + break; + } + presence->setStatus(service.getInfo().getMessage()); + return presence; } } diff --git a/Slimber/LinkLocalPresenceManager.h b/Slimber/LinkLocalPresenceManager.h index 1f27e50..83df624 100644 --- a/Slimber/LinkLocalPresenceManager.h +++ b/Slimber/LinkLocalPresenceManager.h @@ -15,33 +15,33 @@ #include namespace Swift { - class LinkLocalService; - class LinkLocalServiceBrowser; - class RosterPayload; - class Presence; + class LinkLocalService; + class LinkLocalServiceBrowser; + class RosterPayload; + class Presence; - class LinkLocalPresenceManager : public boost::bsignals::trackable { - public: - LinkLocalPresenceManager(LinkLocalServiceBrowser*); + class LinkLocalPresenceManager : public boost::bsignals::trackable { + public: + LinkLocalPresenceManager(LinkLocalServiceBrowser*); - boost::shared_ptr getRoster() const; - std::vector > getAllPresence() const; + boost::shared_ptr getRoster() const; + std::vector > getAllPresence() const; - boost::optional getServiceForJID(const JID&) const; + boost::optional getServiceForJID(const JID&) const; - boost::signal)> onRosterChanged; - boost::signal)> onPresenceChanged; + boost::signal)> onRosterChanged; + boost::signal)> onPresenceChanged; - private: - void handleServiceAdded(const LinkLocalService&); - void handleServiceChanged(const LinkLocalService&); - void handleServiceRemoved(const LinkLocalService&); + private: + void handleServiceAdded(const LinkLocalService&); + void handleServiceChanged(const LinkLocalService&); + void handleServiceRemoved(const LinkLocalService&); - RosterItemPayload getRosterItem(const LinkLocalService& service) const; - std::string getRosterName(const LinkLocalService& service) const; - boost::shared_ptr getPresence(const LinkLocalService& service) const; + RosterItemPayload getRosterItem(const LinkLocalService& service) const; + std::string getRosterName(const LinkLocalService& service) const; + boost::shared_ptr getPresence(const LinkLocalService& service) const; - private: - LinkLocalServiceBrowser* browser; - }; + private: + LinkLocalServiceBrowser* browser; + }; } diff --git a/Slimber/MainController.cpp b/Slimber/MainController.cpp index 85c8f4b..90a1b94 100644 --- a/Slimber/MainController.cpp +++ b/Slimber/MainController.cpp @@ -26,105 +26,105 @@ using namespace Swift; MainController::MainController(Menulet* menulet, EventLoop* eventLoop) { - dnsSDQuerier = PlatformDNSSDQuerierFactory(eventLoop).createQuerier(); - assert(dnsSDQuerier); + dnsSDQuerier = PlatformDNSSDQuerierFactory(eventLoop).createQuerier(); + assert(dnsSDQuerier); - linkLocalServiceBrowser = new LinkLocalServiceBrowser(dnsSDQuerier); - linkLocalServiceBrowser->onServiceAdded.connect( - boost::bind(&MainController::handleServicesChanged, this)); - linkLocalServiceBrowser->onServiceRemoved.connect( - boost::bind(&MainController::handleServicesChanged, this)); - linkLocalServiceBrowser->onServiceChanged.connect( - boost::bind(&MainController::handleServicesChanged, this)); + linkLocalServiceBrowser = new LinkLocalServiceBrowser(dnsSDQuerier); + linkLocalServiceBrowser->onServiceAdded.connect( + boost::bind(&MainController::handleServicesChanged, this)); + linkLocalServiceBrowser->onServiceRemoved.connect( + boost::bind(&MainController::handleServicesChanged, this)); + linkLocalServiceBrowser->onServiceChanged.connect( + boost::bind(&MainController::handleServicesChanged, this)); - vCardCollection = new FileVCardCollection( - PlatformApplicationPathProvider("Slimber").getDataDir()); + vCardCollection = new FileVCardCollection( + PlatformApplicationPathProvider("Slimber").getDataDir()); - server = new Server(5222, 5562, linkLocalServiceBrowser, vCardCollection, eventLoop); - server->onStopped.connect( - boost::bind(&MainController::handleServerStopped, this, _1)); - server->onSelfConnected.connect( - boost::bind(&MainController::handleSelfConnected, this, _1)); + server = new Server(5222, 5562, linkLocalServiceBrowser, vCardCollection, eventLoop); + server->onStopped.connect( + boost::bind(&MainController::handleServerStopped, this, _1)); + server->onSelfConnected.connect( + boost::bind(&MainController::handleSelfConnected, this, _1)); - menuletController = new MenuletController(menulet); - menuletController->onRestartRequested.connect(boost::bind( - &MainController::handleRestartRequested, this)); + menuletController = new MenuletController(menulet); + menuletController->onRestartRequested.connect(boost::bind( + &MainController::handleRestartRequested, this)); - start(); + start(); } MainController::~MainController() { - delete server; - delete menuletController; - delete vCardCollection; - linkLocalServiceBrowser->stop(); - delete linkLocalServiceBrowser; - dnsSDQuerier->stop(); + delete server; + delete menuletController; + delete vCardCollection; + linkLocalServiceBrowser->stop(); + delete linkLocalServiceBrowser; + dnsSDQuerier->stop(); } void MainController::start() { - dnsSDQuerier->start(); - linkLocalServiceBrowser->start(); + dnsSDQuerier->start(); + linkLocalServiceBrowser->start(); - handleSelfConnected(false); - handleServicesChanged(); + handleSelfConnected(false); + handleServicesChanged(); - server->start(); + server->start(); } void MainController::stop() { - server->stop(); - linkLocalServiceBrowser->stop(); - dnsSDQuerier->stop(); + server->stop(); + linkLocalServiceBrowser->stop(); + dnsSDQuerier->stop(); } void MainController::handleSelfConnected(bool b) { - if (b) { - menuletController->setXMPPStatus("You are logged in", MenuletController::Online); - } - else { - menuletController->setXMPPStatus("You are not logged in", MenuletController::Offline); - } + if (b) { + menuletController->setXMPPStatus("You are logged in", MenuletController::Online); + } + else { + menuletController->setXMPPStatus("You are not logged in", MenuletController::Offline); + } } void MainController::handleServicesChanged() { - std::vector names; - foreach(const LinkLocalService& service, linkLocalServiceBrowser->getServices()) { - std::string description = service.getDescription(); - if (description != service.getName()) { - description += " (" + service.getName() + ")"; - } - names.push_back(description); - } - menuletController->setUserNames(names); + std::vector names; + foreach(const LinkLocalService& service, linkLocalServiceBrowser->getServices()) { + std::string description = service.getDescription(); + if (description != service.getName()) { + description += " (" + service.getName() + ")"; + } + names.push_back(description); + } + menuletController->setUserNames(names); } void MainController::handleServerStopped(boost::optional error) { - if (error) { - std::string message; - switch (error->getType()) { - case ServerError::C2SPortConflict: - message = std::string("Error: Port ") + boost::lexical_cast(server->getClientToServerPort()) + std::string(" in use"); - break; - case ServerError::C2SError: - message = std::string("Local connection server error"); - break; - case ServerError::LinkLocalPortConflict: - message = std::string("Error: Port ") + boost::lexical_cast(server->getLinkLocalPort()) + std::string(" in use"); - break; - case ServerError::LinkLocalError: - message = std::string("External connection server error"); - break; - } - menuletController->setXMPPStatus(message, MenuletController::Offline); - } - else { - menuletController->setXMPPStatus("XMPP Server Not Running", MenuletController::Offline); - } + if (error) { + std::string message; + switch (error->getType()) { + case ServerError::C2SPortConflict: + message = std::string("Error: Port ") + boost::lexical_cast(server->getClientToServerPort()) + std::string(" in use"); + break; + case ServerError::C2SError: + message = std::string("Local connection server error"); + break; + case ServerError::LinkLocalPortConflict: + message = std::string("Error: Port ") + boost::lexical_cast(server->getLinkLocalPort()) + std::string(" in use"); + break; + case ServerError::LinkLocalError: + message = std::string("External connection server error"); + break; + } + menuletController->setXMPPStatus(message, MenuletController::Offline); + } + else { + menuletController->setXMPPStatus("XMPP Server Not Running", MenuletController::Offline); + } } void MainController::handleRestartRequested() { - stop(); - start(); + stop(); + start(); } diff --git a/Slimber/MainController.h b/Slimber/MainController.h index 5f28c31..8f4e981 100644 --- a/Slimber/MainController.h +++ b/Slimber/MainController.h @@ -12,34 +12,34 @@ #include namespace Swift { - class DNSSDQuerier; - class LinkLocalServiceBrowser; - class VCardCollection; - class Server; - class EventLoop; + class DNSSDQuerier; + class LinkLocalServiceBrowser; + class VCardCollection; + class Server; + class EventLoop; } class MenuletController; class Menulet; class MainController { - public: - MainController(Menulet* menulet, Swift::EventLoop* eventLoop); - virtual ~MainController(); - - private: - void handleSelfConnected(bool b); - void handleServicesChanged(); - void handleServerStopped(boost::optional error); - void handleRestartRequested(); - - void start(); - void stop(); - - private: - boost::shared_ptr dnsSDQuerier; - Swift::LinkLocalServiceBrowser* linkLocalServiceBrowser; - Swift::VCardCollection* vCardCollection; - Swift::Server* server; - MenuletController* menuletController; + public: + MainController(Menulet* menulet, Swift::EventLoop* eventLoop); + virtual ~MainController(); + + private: + void handleSelfConnected(bool b); + void handleServicesChanged(); + void handleServerStopped(boost::optional error); + void handleRestartRequested(); + + void start(); + void stop(); + + private: + boost::shared_ptr dnsSDQuerier; + Swift::LinkLocalServiceBrowser* linkLocalServiceBrowser; + Swift::VCardCollection* vCardCollection; + Swift::Server* server; + MenuletController* menuletController; }; diff --git a/Slimber/Menulet.h b/Slimber/Menulet.h index cd4b4d9..4f2e33f 100644 --- a/Slimber/Menulet.h +++ b/Slimber/Menulet.h @@ -11,16 +11,16 @@ #include class Menulet { - public: - virtual ~Menulet(); + public: + virtual ~Menulet(); - virtual void clear() = 0; - virtual void addItem(const std::string& name, const std::string& icon = std::string()) = 0; - virtual void addAboutItem() = 0; - virtual void addRestartItem() = 0; - virtual void addExitItem() = 0; - virtual void addSeparator() = 0; - virtual void setIcon(const std::string&) = 0; + virtual void clear() = 0; + virtual void addItem(const std::string& name, const std::string& icon = std::string()) = 0; + virtual void addAboutItem() = 0; + virtual void addRestartItem() = 0; + virtual void addExitItem() = 0; + virtual void addSeparator() = 0; + virtual void setIcon(const std::string&) = 0; - boost::signal onRestartClicked; + boost::signal onRestartClicked; }; diff --git a/Slimber/MenuletController.cpp b/Slimber/MenuletController.cpp index c09d35f..5868128 100644 --- a/Slimber/MenuletController.cpp +++ b/Slimber/MenuletController.cpp @@ -13,44 +13,44 @@ #include -MenuletController::MenuletController(Menulet* menulet) : - menulet(menulet), xmppStatus(Offline) { - menulet->onRestartClicked.connect(boost::ref(onRestartRequested)); - update(); +MenuletController::MenuletController(Menulet* menulet) : + menulet(menulet), xmppStatus(Offline) { + menulet->onRestartClicked.connect(boost::ref(onRestartRequested)); + update(); } MenuletController::~MenuletController() { } void MenuletController::setXMPPStatus(const std::string& message, Status status) { - xmppStatus = status; - xmppStatusMessage = message; - update(); + xmppStatus = status; + xmppStatusMessage = message; + update(); } void MenuletController::setUserNames(const std::vector& users) { - linkLocalUsers = users; - update(); + linkLocalUsers = users; + update(); } void MenuletController::update() { - menulet->clear(); - if (linkLocalUsers.empty()) { - menulet->setIcon("UsersOffline"); - menulet->addItem("No online users"); - } - else { - menulet->setIcon("UsersOnline"); - menulet->addItem("Online users:"); - foreach(const std::string& user, linkLocalUsers) { - menulet->addItem(std::string(" ") + user); - } - } - menulet->addSeparator(); - menulet->addItem(xmppStatusMessage, (xmppStatus == Online ? "Online" : "Offline")); - menulet->addSeparator(); - menulet->addAboutItem(); - menulet->addSeparator(); - menulet->addRestartItem(); - menulet->addExitItem(); + menulet->clear(); + if (linkLocalUsers.empty()) { + menulet->setIcon("UsersOffline"); + menulet->addItem("No online users"); + } + else { + menulet->setIcon("UsersOnline"); + menulet->addItem("Online users:"); + foreach(const std::string& user, linkLocalUsers) { + menulet->addItem(std::string(" ") + user); + } + } + menulet->addSeparator(); + menulet->addItem(xmppStatusMessage, (xmppStatus == Online ? "Online" : "Offline")); + menulet->addSeparator(); + menulet->addAboutItem(); + menulet->addSeparator(); + menulet->addRestartItem(); + menulet->addExitItem(); } diff --git a/Slimber/MenuletController.h b/Slimber/MenuletController.h index 46dc41f..210eac2 100644 --- a/Slimber/MenuletController.h +++ b/Slimber/MenuletController.h @@ -14,26 +14,26 @@ class Menulet; class MenuletController { - public: - enum Status { - Online, - Offline - }; - - MenuletController(Menulet*); - virtual ~MenuletController(); - - void setXMPPStatus(const std::string& message, Status status); - void setUserNames(const std::vector&); - - boost::signal onRestartRequested; - - private: - void update(); - - private: - Menulet* menulet; - Status xmppStatus; - std::string xmppStatusMessage; - std::vector linkLocalUsers; + public: + enum Status { + Online, + Offline + }; + + MenuletController(Menulet*); + virtual ~MenuletController(); + + void setXMPPStatus(const std::string& message, Status status); + void setUserNames(const std::vector&); + + boost::signal onRestartRequested; + + private: + void update(); + + private: + Menulet* menulet; + Status xmppStatus; + std::string xmppStatusMessage; + std::vector linkLocalUsers; }; diff --git a/Slimber/Qt/QtAboutDialog.cpp b/Slimber/Qt/QtAboutDialog.cpp index 7fcd2ca..301661e 100644 --- a/Slimber/Qt/QtAboutDialog.cpp +++ b/Slimber/Qt/QtAboutDialog.cpp @@ -12,26 +12,26 @@ #include QtAboutDialog::QtAboutDialog() { - setAttribute(Qt::WA_DeleteOnClose); - setWindowTitle("About Slimber"); - - QVBoxLayout* layout = new QVBoxLayout(this); - - QLabel* iconLabel = new QLabel(this); - iconLabel->setPixmap(QPixmap(":/icons/Icon-128.png")); - iconLabel->setAlignment(Qt::AlignHCenter); - layout->addWidget(iconLabel); - - QLabel* appNameLabel = new QLabel("
" + QCoreApplication::applicationName() + "
", this); - layout->addWidget(appNameLabel); - - QLabel* versionLabel = new QLabel(QString("
Version ") + QCoreApplication::applicationVersion() + "
", this); - layout->addWidget(versionLabel); - QString buildString = QString("
Built with: Qt version ") + QT_VERSION_STR; - buildString += QString("
Running with Qt version ") + qVersion(); - buildString += "
"; - QLabel* buildLabel = new QLabel(buildString, this); - layout->addWidget(buildLabel); - - setFixedSize(minimumSizeHint()); + setAttribute(Qt::WA_DeleteOnClose); + setWindowTitle("About Slimber"); + + QVBoxLayout* layout = new QVBoxLayout(this); + + QLabel* iconLabel = new QLabel(this); + iconLabel->setPixmap(QPixmap(":/icons/Icon-128.png")); + iconLabel->setAlignment(Qt::AlignHCenter); + layout->addWidget(iconLabel); + + QLabel* appNameLabel = new QLabel("
" + QCoreApplication::applicationName() + "
", this); + layout->addWidget(appNameLabel); + + QLabel* versionLabel = new QLabel(QString("
Version ") + QCoreApplication::applicationVersion() + "
", this); + layout->addWidget(versionLabel); + QString buildString = QString("
Built with: Qt version ") + QT_VERSION_STR; + buildString += QString("
Running with Qt version ") + qVersion(); + buildString += "
"; + QLabel* buildLabel = new QLabel(buildString, this); + layout->addWidget(buildLabel); + + setFixedSize(minimumSizeHint()); } diff --git a/Slimber/Qt/QtAboutDialog.h b/Slimber/Qt/QtAboutDialog.h index d19d209..1f14ebe 100644 --- a/Slimber/Qt/QtAboutDialog.h +++ b/Slimber/Qt/QtAboutDialog.h @@ -9,6 +9,6 @@ #include class QtAboutDialog : public QDialog { - public: - QtAboutDialog(); + public: + QtAboutDialog(); }; diff --git a/Slimber/Qt/QtMenulet.h b/Slimber/Qt/QtMenulet.h index 1aed329..fa17d21 100644 --- a/Slimber/Qt/QtMenulet.h +++ b/Slimber/Qt/QtMenulet.h @@ -18,65 +18,65 @@ #include class QtMenulet : public QObject, public Menulet { - Q_OBJECT - public: - QtMenulet() { - trayIcon.setIcon(QPixmap(":/icons/UsersOffline.png")); - trayIcon.setContextMenu(&menu); - trayIcon.show(); - } + Q_OBJECT + public: + QtMenulet() { + trayIcon.setIcon(QPixmap(":/icons/UsersOffline.png")); + trayIcon.setContextMenu(&menu); + trayIcon.show(); + } - void clear() { - menu.clear(); - } + void clear() { + menu.clear(); + } - void addItem(const std::string& name, const std::string& icon) { - menu.addAction(getIcon(icon), QString::fromUtf8(name.c_str())); - } + void addItem(const std::string& name, const std::string& icon) { + menu.addAction(getIcon(icon), QString::fromUtf8(name.c_str())); + } - void addAboutItem() { - menu.addAction("About", this, SLOT(showAboutDialog())); - } + void addAboutItem() { + menu.addAction("About", this, SLOT(showAboutDialog())); + } - void addRestartItem() { - menu.addAction("Restart", this, SLOT(restart())); - } + void addRestartItem() { + menu.addAction("Restart", this, SLOT(restart())); + } - void addExitItem() { - menu.addAction("Exit", qApp, SLOT(quit())); - } + void addExitItem() { + menu.addAction("Exit", qApp, SLOT(quit())); + } - void addSeparator() { - menu.addSeparator(); - } + void addSeparator() { + menu.addSeparator(); + } - void setIcon(const std::string& icon) { - trayIcon.setIcon(getIcon(icon)); - } + void setIcon(const std::string& icon) { + trayIcon.setIcon(getIcon(icon)); + } - private: - QPixmap getIcon(const std::string& name) { - return QPixmap(":/icons/" + QString::fromUtf8(name.c_str()) + ".png"); - } + private: + QPixmap getIcon(const std::string& name) { + return QPixmap(":/icons/" + QString::fromUtf8(name.c_str()) + ".png"); + } - private slots: - void showAboutDialog() { - if (aboutDialog) { - aboutDialog->raise(); - aboutDialog->activateWindow(); - } - else { - aboutDialog = new QtAboutDialog(); - aboutDialog->show(); - } - } + private slots: + void showAboutDialog() { + if (aboutDialog) { + aboutDialog->raise(); + aboutDialog->activateWindow(); + } + else { + aboutDialog = new QtAboutDialog(); + aboutDialog->show(); + } + } - void restart() { - onRestartClicked(); - } + void restart() { + onRestartClicked(); + } - private: - QMenu menu; - QSystemTrayIcon trayIcon; - QPointer aboutDialog; + private: + QMenu menu; + QSystemTrayIcon trayIcon; + QPointer aboutDialog; }; diff --git a/Slimber/Qt/main.cpp b/Slimber/Qt/main.cpp index 69a8b6e..8fbfbb6 100644 --- a/Slimber/Qt/main.cpp +++ b/Slimber/Qt/main.cpp @@ -16,21 +16,21 @@ #include int main(int argc, char* argv[]) { - QApplication app(argc, argv); - Swift::QtEventLoop eventLoop; + QApplication app(argc, argv); + Swift::QtEventLoop eventLoop; - QCoreApplication::setApplicationName("Slimber"); - QCoreApplication::setApplicationVersion(QString(buildVersion)); + QCoreApplication::setApplicationName("Slimber"); + QCoreApplication::setApplicationVersion(QString(buildVersion)); - if (!QSystemTrayIcon::isSystemTrayAvailable()) { + if (!QSystemTrayIcon::isSystemTrayAvailable()) { QMessageBox::critical(0, QObject::tr("Systray"), QObject::tr("No system tray")); - return 1; - } + return 1; + } - app.setQuitOnLastWindowClosed(false); + app.setQuitOnLastWindowClosed(false); - QtMenulet menulet; - MainController controller(&menulet, &eventLoop); + QtMenulet menulet; + MainController controller(&menulet, &eventLoop); - return app.exec(); + return app.exec(); } diff --git a/Slimber/Server.cpp b/Slimber/Server.cpp index 79dc22d..c69c75d 100644 --- a/Slimber/Server.cpp +++ b/Slimber/Server.cpp @@ -39,401 +39,401 @@ namespace Swift { Server::Server( - int clientConnectionPort, - int linkLocalConnectionPort, - LinkLocalServiceBrowser* linkLocalServiceBrowser, - VCardCollection* vCardCollection, - EventLoop* eventLoop) : - linkLocalServiceRegistered(false), - rosterRequested(false), - clientConnectionPort(clientConnectionPort), - linkLocalConnectionPort(linkLocalConnectionPort), - linkLocalServiceBrowser(linkLocalServiceBrowser), - vCardCollection(vCardCollection), - eventLoop(eventLoop), - presenceManager(NULL), - stopping(false) { - linkLocalServiceBrowser->onServiceRegistered.connect( - boost::bind(&Server::handleServiceRegistered, this, _1)); + int clientConnectionPort, + int linkLocalConnectionPort, + LinkLocalServiceBrowser* linkLocalServiceBrowser, + VCardCollection* vCardCollection, + EventLoop* eventLoop) : + linkLocalServiceRegistered(false), + rosterRequested(false), + clientConnectionPort(clientConnectionPort), + linkLocalConnectionPort(linkLocalConnectionPort), + linkLocalServiceBrowser(linkLocalServiceBrowser), + vCardCollection(vCardCollection), + eventLoop(eventLoop), + presenceManager(NULL), + stopping(false) { + linkLocalServiceBrowser->onServiceRegistered.connect( + boost::bind(&Server::handleServiceRegistered, this, _1)); } Server::~Server() { - stop(); + stop(); } void Server::start() { - assert(!serverFromClientConnectionServer); - serverFromClientConnectionServer = BoostConnectionServer::create( - clientConnectionPort, boostIOServiceThread.getIOService(), eventLoop); - serverFromClientConnectionServerSignalConnections.push_back( - serverFromClientConnectionServer->onNewConnection.connect( - boost::bind(&Server::handleNewClientConnection, this, _1))); - serverFromClientConnectionServerSignalConnections.push_back( - serverFromClientConnectionServer->onStopped.connect( - boost::bind(&Server::handleClientConnectionServerStopped, this, _1))); - - assert(!serverFromNetworkConnectionServer); - serverFromNetworkConnectionServer = BoostConnectionServer::create( - linkLocalConnectionPort, boostIOServiceThread.getIOService(), eventLoop); - serverFromNetworkConnectionServerSignalConnections.push_back( - serverFromNetworkConnectionServer->onNewConnection.connect( - boost::bind(&Server::handleNewLinkLocalConnection, this, _1))); - serverFromNetworkConnectionServerSignalConnections.push_back( - serverFromNetworkConnectionServer->onStopped.connect( - boost::bind(&Server::handleLinkLocalConnectionServerStopped, this, _1))); - - assert(!presenceManager); - presenceManager = new LinkLocalPresenceManager(linkLocalServiceBrowser); - presenceManager->onRosterChanged.connect( - boost::bind(&Server::handleRosterChanged, this, _1)); - presenceManager->onPresenceChanged.connect( - boost::bind(&Server::handlePresenceChanged, this, _1)); - - serverFromClientConnectionServer->start(); - serverFromNetworkConnectionServer->start(); + assert(!serverFromClientConnectionServer); + serverFromClientConnectionServer = BoostConnectionServer::create( + clientConnectionPort, boostIOServiceThread.getIOService(), eventLoop); + serverFromClientConnectionServerSignalConnections.push_back( + serverFromClientConnectionServer->onNewConnection.connect( + boost::bind(&Server::handleNewClientConnection, this, _1))); + serverFromClientConnectionServerSignalConnections.push_back( + serverFromClientConnectionServer->onStopped.connect( + boost::bind(&Server::handleClientConnectionServerStopped, this, _1))); + + assert(!serverFromNetworkConnectionServer); + serverFromNetworkConnectionServer = BoostConnectionServer::create( + linkLocalConnectionPort, boostIOServiceThread.getIOService(), eventLoop); + serverFromNetworkConnectionServerSignalConnections.push_back( + serverFromNetworkConnectionServer->onNewConnection.connect( + boost::bind(&Server::handleNewLinkLocalConnection, this, _1))); + serverFromNetworkConnectionServerSignalConnections.push_back( + serverFromNetworkConnectionServer->onStopped.connect( + boost::bind(&Server::handleLinkLocalConnectionServerStopped, this, _1))); + + assert(!presenceManager); + presenceManager = new LinkLocalPresenceManager(linkLocalServiceBrowser); + presenceManager->onRosterChanged.connect( + boost::bind(&Server::handleRosterChanged, this, _1)); + presenceManager->onPresenceChanged.connect( + boost::bind(&Server::handlePresenceChanged, this, _1)); + + serverFromClientConnectionServer->start(); + serverFromNetworkConnectionServer->start(); } void Server::stop() { - stop(boost::optional()); + stop(boost::optional()); } void Server::stop(boost::optional e) { - if (stopping) { - return; - } - - stopping = true; - - delete presenceManager; - presenceManager = NULL; - - if (serverFromClientSession) { - serverFromClientSession->finishSession(); - } - serverFromClientSession.reset(); - foreach(boost::shared_ptr session, linkLocalSessions) { - session->finishSession(); - } - linkLocalSessions.clear(); - foreach(boost::shared_ptr connector, connectors) { - connector->cancel(); - } - connectors.clear(); - tracers.clear(); - - if (serverFromNetworkConnectionServer) { - serverFromNetworkConnectionServer->stop(); - foreach(boost::bsignals::connection& connection, serverFromNetworkConnectionServerSignalConnections) { - connection.disconnect(); - } - serverFromNetworkConnectionServerSignalConnections.clear(); - serverFromNetworkConnectionServer.reset(); - } - if (serverFromClientConnectionServer) { - serverFromClientConnectionServer->stop(); - foreach(boost::bsignals::connection& connection, serverFromClientConnectionServerSignalConnections) { - connection.disconnect(); - } - serverFromClientConnectionServerSignalConnections.clear(); - serverFromClientConnectionServer.reset(); - } - - stopping = false; - onStopped(e); + if (stopping) { + return; + } + + stopping = true; + + delete presenceManager; + presenceManager = NULL; + + if (serverFromClientSession) { + serverFromClientSession->finishSession(); + } + serverFromClientSession.reset(); + foreach(boost::shared_ptr session, linkLocalSessions) { + session->finishSession(); + } + linkLocalSessions.clear(); + foreach(boost::shared_ptr connector, connectors) { + connector->cancel(); + } + connectors.clear(); + tracers.clear(); + + if (serverFromNetworkConnectionServer) { + serverFromNetworkConnectionServer->stop(); + foreach(boost::bsignals::connection& connection, serverFromNetworkConnectionServerSignalConnections) { + connection.disconnect(); + } + serverFromNetworkConnectionServerSignalConnections.clear(); + serverFromNetworkConnectionServer.reset(); + } + if (serverFromClientConnectionServer) { + serverFromClientConnectionServer->stop(); + foreach(boost::bsignals::connection& connection, serverFromClientConnectionServerSignalConnections) { + connection.disconnect(); + } + serverFromClientConnectionServerSignalConnections.clear(); + serverFromClientConnectionServer.reset(); + } + + stopping = false; + onStopped(e); } void Server::handleNewClientConnection(boost::shared_ptr connection) { - if (serverFromClientSession) { - connection->disconnect(); - } - serverFromClientSession = boost::shared_ptr( - new ServerFromClientSession(idGenerator.generateID(), connection, - &payloadParserFactories, &payloadSerializers, &xmlParserFactory, &userRegistry)); - serverFromClientSession->setAllowSASLEXTERNAL(); - serverFromClientSession->onSessionStarted.connect( - boost::bind(&Server::handleSessionStarted, this)); - serverFromClientSession->onElementReceived.connect( - boost::bind(&Server::handleElementReceived, this, _1, - serverFromClientSession)); - serverFromClientSession->onSessionFinished.connect( - boost::bind(&Server::handleSessionFinished, this, - serverFromClientSession)); - //tracers.push_back(boost::shared_ptr( - // new SessionTracer(serverFromClientSession))); - serverFromClientSession->startSession(); + if (serverFromClientSession) { + connection->disconnect(); + } + serverFromClientSession = boost::shared_ptr( + new ServerFromClientSession(idGenerator.generateID(), connection, + &payloadParserFactories, &payloadSerializers, &xmlParserFactory, &userRegistry)); + serverFromClientSession->setAllowSASLEXTERNAL(); + serverFromClientSession->onSessionStarted.connect( + boost::bind(&Server::handleSessionStarted, this)); + serverFromClientSession->onElementReceived.connect( + boost::bind(&Server::handleElementReceived, this, _1, + serverFromClientSession)); + serverFromClientSession->onSessionFinished.connect( + boost::bind(&Server::handleSessionFinished, this, + serverFromClientSession)); + //tracers.push_back(boost::shared_ptr( + // new SessionTracer(serverFromClientSession))); + serverFromClientSession->startSession(); } void Server::handleSessionStarted() { - onSelfConnected(true); + onSelfConnected(true); } void Server::handleSessionFinished(boost::shared_ptr) { - serverFromClientSession.reset(); - unregisterService(); - selfJID = JID(); - rosterRequested = false; - onSelfConnected(false); - lastPresence.reset(); + serverFromClientSession.reset(); + unregisterService(); + selfJID = JID(); + rosterRequested = false; + onSelfConnected(false); + lastPresence.reset(); } void Server::unregisterService() { - if (linkLocalServiceRegistered) { - linkLocalServiceRegistered = false; - linkLocalServiceBrowser->unregisterService(); - } + if (linkLocalServiceRegistered) { + linkLocalServiceRegistered = false; + linkLocalServiceBrowser->unregisterService(); + } } void Server::handleElementReceived(boost::shared_ptr element, boost::shared_ptr session) { - boost::shared_ptr stanza = boost::dynamic_pointer_cast(element); - if (!stanza) { - return; - } - - stanza->setFrom(session->getRemoteJID()); - if (!stanza->getTo().isValid()) { - stanza->setTo(session->getLocalJID()); - } - - if (boost::shared_ptr presence = boost::dynamic_pointer_cast(stanza)) { - if (presence->getType() == Presence::Available) { - if (!linkLocalServiceRegistered) { - linkLocalServiceRegistered = true; - linkLocalServiceBrowser->registerService( - session->getRemoteJID().toBare().toString(), - linkLocalConnectionPort, getLinkLocalServiceInfo(presence)); - } - else { - linkLocalServiceBrowser->updateService( - getLinkLocalServiceInfo(presence)); - } - lastPresence = presence; - } - else { - unregisterService(); - } - } - else if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) { - if (boost::shared_ptr iq = boost::dynamic_pointer_cast(stanza)) { - if (iq->getPayload()) { - if (iq->getType() == IQ::Get) { - session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), presenceManager->getRoster())); - rosterRequested = true; - foreach(const boost::shared_ptr presence, presenceManager->getAllPresence()) { - session->sendElement(presence); - } - } - else { - session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel)); - } - } - if (boost::shared_ptr vcard = iq->getPayload()) { - if (iq->getType() == IQ::Get) { - session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vCardCollection->getOwnVCard())); - } - else { - vCardCollection->setOwnVCard(vcard); - session->sendElement(IQ::createResult(iq->getFrom(), iq->getID())); - if (lastPresence) { - linkLocalServiceBrowser->updateService(getLinkLocalServiceInfo(lastPresence)); - } - } - } - else { - session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel)); - } - } - } - else { - JID toJID = stanza->getTo(); - boost::shared_ptr outgoingSession = - getLinkLocalSessionForJID(toJID); - if (outgoingSession) { - outgoingSession->sendElement(stanza); - } - else { - boost::optional service = - presenceManager->getServiceForJID(toJID); - if (service) { - boost::shared_ptr connector = - getLinkLocalConnectorForJID(toJID); - if (!connector) { - connector = boost::shared_ptr( - new LinkLocalConnector( - *service, - linkLocalServiceBrowser->getQuerier(), - BoostConnection::create(boostIOServiceThread.getIOService(), eventLoop))); - connector->onConnectFinished.connect( - boost::bind(&Server::handleConnectFinished, this, connector, _1)); - connectors.push_back(connector); - connector->connect(); - } - connector->queueElement(element); - } - else { - session->sendElement(IQ::createError( - stanza->getFrom(), stanza->getID(), - ErrorPayload::RecipientUnavailable, ErrorPayload::Wait)); - } - } - } + boost::shared_ptr stanza = boost::dynamic_pointer_cast(element); + if (!stanza) { + return; + } + + stanza->setFrom(session->getRemoteJID()); + if (!stanza->getTo().isValid()) { + stanza->setTo(session->getLocalJID()); + } + + if (boost::shared_ptr presence = boost::dynamic_pointer_cast(stanza)) { + if (presence->getType() == Presence::Available) { + if (!linkLocalServiceRegistered) { + linkLocalServiceRegistered = true; + linkLocalServiceBrowser->registerService( + session->getRemoteJID().toBare().toString(), + linkLocalConnectionPort, getLinkLocalServiceInfo(presence)); + } + else { + linkLocalServiceBrowser->updateService( + getLinkLocalServiceInfo(presence)); + } + lastPresence = presence; + } + else { + unregisterService(); + } + } + else if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) { + if (boost::shared_ptr iq = boost::dynamic_pointer_cast(stanza)) { + if (iq->getPayload()) { + if (iq->getType() == IQ::Get) { + session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), presenceManager->getRoster())); + rosterRequested = true; + foreach(const boost::shared_ptr presence, presenceManager->getAllPresence()) { + session->sendElement(presence); + } + } + else { + session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel)); + } + } + if (boost::shared_ptr vcard = iq->getPayload()) { + if (iq->getType() == IQ::Get) { + session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vCardCollection->getOwnVCard())); + } + else { + vCardCollection->setOwnVCard(vcard); + session->sendElement(IQ::createResult(iq->getFrom(), iq->getID())); + if (lastPresence) { + linkLocalServiceBrowser->updateService(getLinkLocalServiceInfo(lastPresence)); + } + } + } + else { + session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel)); + } + } + } + else { + JID toJID = stanza->getTo(); + boost::shared_ptr outgoingSession = + getLinkLocalSessionForJID(toJID); + if (outgoingSession) { + outgoingSession->sendElement(stanza); + } + else { + boost::optional service = + presenceManager->getServiceForJID(toJID); + if (service) { + boost::shared_ptr connector = + getLinkLocalConnectorForJID(toJID); + if (!connector) { + connector = boost::shared_ptr( + new LinkLocalConnector( + *service, + linkLocalServiceBrowser->getQuerier(), + BoostConnection::create(boostIOServiceThread.getIOService(), eventLoop))); + connector->onConnectFinished.connect( + boost::bind(&Server::handleConnectFinished, this, connector, _1)); + connectors.push_back(connector); + connector->connect(); + } + connector->queueElement(element); + } + else { + session->sendElement(IQ::createError( + stanza->getFrom(), stanza->getID(), + ErrorPayload::RecipientUnavailable, ErrorPayload::Wait)); + } + } + } } void Server::handleNewLinkLocalConnection(boost::shared_ptr connection) { - boost::shared_ptr session( - new IncomingLinkLocalSession( - selfJID, connection, - &payloadParserFactories, &payloadSerializers, &xmlParserFactory)); - registerLinkLocalSession(session); + boost::shared_ptr session( + new IncomingLinkLocalSession( + selfJID, connection, + &payloadParserFactories, &payloadSerializers, &xmlParserFactory)); + registerLinkLocalSession(session); } void Server::handleLinkLocalSessionFinished(boost::shared_ptr session) { - //std::cout << "Link local session from " << session->getRemoteJID() << " ended" << std::endl; - linkLocalSessions.erase( - std::remove(linkLocalSessions.begin(), linkLocalSessions.end(), session), - linkLocalSessions.end()); + //std::cout << "Link local session from " << session->getRemoteJID() << " ended" << std::endl; + linkLocalSessions.erase( + std::remove(linkLocalSessions.begin(), linkLocalSessions.end(), session), + linkLocalSessions.end()); } void Server::handleLinkLocalElementReceived(boost::shared_ptr element, boost::shared_ptr session) { - if (boost::shared_ptr stanza = boost::dynamic_pointer_cast(element)) { - JID fromJID = session->getRemoteJID(); - if (!presenceManager->getServiceForJID(fromJID.toBare())) { - return; // TODO: Send error back - } - stanza->setFrom(fromJID); - serverFromClientSession->sendElement(stanza); - } + if (boost::shared_ptr stanza = boost::dynamic_pointer_cast(element)) { + JID fromJID = session->getRemoteJID(); + if (!presenceManager->getServiceForJID(fromJID.toBare())) { + return; // TODO: Send error back + } + stanza->setFrom(fromJID); + serverFromClientSession->sendElement(stanza); + } } void Server::handleConnectFinished(boost::shared_ptr connector, bool error) { - if (error) { - std::cerr << "Error connecting" << std::endl; - // TODO: Send back queued stanzas - } - else { - boost::shared_ptr outgoingSession( - new OutgoingLinkLocalSession( - selfJID, connector->getService().getJID(), connector->getConnection(), - &payloadParserFactories, &payloadSerializers, &xmlParserFactory)); - foreach(const boost::shared_ptr element, connector->getQueuedElements()) { - outgoingSession->queueElement(element); - } - registerLinkLocalSession(outgoingSession); - } - connectors.erase(std::remove(connectors.begin(), connectors.end(), connector), connectors.end()); + if (error) { + std::cerr << "Error connecting" << std::endl; + // TODO: Send back queued stanzas + } + else { + boost::shared_ptr outgoingSession( + new OutgoingLinkLocalSession( + selfJID, connector->getService().getJID(), connector->getConnection(), + &payloadParserFactories, &payloadSerializers, &xmlParserFactory)); + foreach(const boost::shared_ptr element, connector->getQueuedElements()) { + outgoingSession->queueElement(element); + } + registerLinkLocalSession(outgoingSession); + } + connectors.erase(std::remove(connectors.begin(), connectors.end(), connector), connectors.end()); } void Server::registerLinkLocalSession(boost::shared_ptr session) { - session->onSessionFinished.connect( - boost::bind(&Server::handleLinkLocalSessionFinished, this, session)); - session->onElementReceived.connect( - boost::bind(&Server::handleLinkLocalElementReceived, this, _1, session)); - linkLocalSessions.push_back(session); - //tracers.push_back(boost::make_shared(session)); - session->startSession(); + session->onSessionFinished.connect( + boost::bind(&Server::handleLinkLocalSessionFinished, this, session)); + session->onElementReceived.connect( + boost::bind(&Server::handleLinkLocalElementReceived, this, _1, session)); + linkLocalSessions.push_back(session); + //tracers.push_back(boost::make_shared(session)); + session->startSession(); } boost::shared_ptr Server::getLinkLocalSessionForJID(const JID& jid) { - foreach(const boost::shared_ptr session, linkLocalSessions) { - if (session->getRemoteJID() == jid) { - return session; - } - } - return boost::shared_ptr(); + foreach(const boost::shared_ptr session, linkLocalSessions) { + if (session->getRemoteJID() == jid) { + return session; + } + } + return boost::shared_ptr(); } boost::shared_ptr Server::getLinkLocalConnectorForJID(const JID& jid) { - foreach(const boost::shared_ptr connector, connectors) { - if (connector->getService().getJID() == jid) { - return connector; - } - } - return boost::shared_ptr(); + foreach(const boost::shared_ptr connector, connectors) { + if (connector->getService().getJID() == jid) { + return connector; + } + } + return boost::shared_ptr(); } void Server::handleServiceRegistered(const DNSSDServiceID& service) { - selfJID = JID(service.getName()); + selfJID = JID(service.getName()); } void Server::handleRosterChanged(boost::shared_ptr roster) { - if (rosterRequested) { - assert(serverFromClientSession); - boost::shared_ptr iq = IQ::createRequest( - IQ::Set, serverFromClientSession->getRemoteJID(), - idGenerator.generateID(), roster); - iq->setFrom(serverFromClientSession->getRemoteJID().toBare()); - serverFromClientSession->sendElement(iq); - } + if (rosterRequested) { + assert(serverFromClientSession); + boost::shared_ptr iq = IQ::createRequest( + IQ::Set, serverFromClientSession->getRemoteJID(), + idGenerator.generateID(), roster); + iq->setFrom(serverFromClientSession->getRemoteJID().toBare()); + serverFromClientSession->sendElement(iq); + } } void Server::handlePresenceChanged(boost::shared_ptr presence) { - if (rosterRequested) { - serverFromClientSession->sendElement(presence); - } + if (rosterRequested) { + serverFromClientSession->sendElement(presence); + } } void Server::handleClientConnectionServerStopped(boost::optional e) { - if (e) { - if (*e == BoostConnectionServer::Conflict) { - stop(ServerError(ServerError::C2SPortConflict)); - } - else { - stop(ServerError(ServerError::C2SError)); - } - } - else { - stop(); - } + if (e) { + if (*e == BoostConnectionServer::Conflict) { + stop(ServerError(ServerError::C2SPortConflict)); + } + else { + stop(ServerError(ServerError::C2SError)); + } + } + else { + stop(); + } } void Server::handleLinkLocalConnectionServerStopped(boost::optional e) { - if (e) { - if (*e == BoostConnectionServer::Conflict) { - stop(ServerError(ServerError::LinkLocalPortConflict)); - } - else { - stop(ServerError(ServerError::LinkLocalError)); - } - } - else { - stop(); - } + if (e) { + if (*e == BoostConnectionServer::Conflict) { + stop(ServerError(ServerError::LinkLocalPortConflict)); + } + else { + stop(ServerError(ServerError::LinkLocalError)); + } + } + else { + stop(); + } } LinkLocalServiceInfo Server::getLinkLocalServiceInfo(boost::shared_ptr presence) { - LinkLocalServiceInfo info; - boost::shared_ptr vcard = vCardCollection->getOwnVCard(); - if (!vcard->getFamilyName().empty() || !vcard->getGivenName().empty()) { - info.setFirstName(vcard->getGivenName()); - info.setLastName(vcard->getFamilyName()); - } - else if (!vcard->getFullName().empty()) { - std::pair p = String::getSplittedAtFirst(vcard->getFullName(), ' '); - info.setFirstName(p.first); - info.setLastName(p.second); - } - if (!vcard->getNickname().empty()) { - info.setNick(vcard->getNickname()); - } - if (!vcard->getPreferredEMailAddress().address.empty()) { - info.setEMail(vcard->getPreferredEMailAddress().address); - } - info.setMessage(presence->getStatus()); - switch (presence->getShow()) { - case StatusShow::Online: - case StatusShow::None: - case StatusShow::FFC: - info.setStatus(LinkLocalServiceInfo::Available); - break; - case StatusShow::Away: - case StatusShow::XA: - info.setStatus(LinkLocalServiceInfo::Away); - break; - case StatusShow::DND: - info.setStatus(LinkLocalServiceInfo::DND); - break; - } - info.setPort(linkLocalConnectionPort); - return info; + LinkLocalServiceInfo info; + boost::shared_ptr vcard = vCardCollection->getOwnVCard(); + if (!vcard->getFamilyName().empty() || !vcard->getGivenName().empty()) { + info.setFirstName(vcard->getGivenName()); + info.setLastName(vcard->getFamilyName()); + } + else if (!vcard->getFullName().empty()) { + std::pair p = String::getSplittedAtFirst(vcard->getFullName(), ' '); + info.setFirstName(p.first); + info.setLastName(p.second); + } + if (!vcard->getNickname().empty()) { + info.setNick(vcard->getNickname()); + } + if (!vcard->getPreferredEMailAddress().address.empty()) { + info.setEMail(vcard->getPreferredEMailAddress().address); + } + info.setMessage(presence->getStatus()); + switch (presence->getShow()) { + case StatusShow::Online: + case StatusShow::None: + case StatusShow::FFC: + info.setStatus(LinkLocalServiceInfo::Available); + break; + case StatusShow::Away: + case StatusShow::XA: + info.setStatus(LinkLocalServiceInfo::Away); + break; + case StatusShow::DND: + info.setStatus(LinkLocalServiceInfo::DND); + break; + } + info.setPort(linkLocalConnectionPort); + return info; } } diff --git a/Slimber/Server.h b/Slimber/Server.h index a87381c..7037cdb 100644 --- a/Slimber/Server.h +++ b/Slimber/Server.h @@ -26,101 +26,101 @@ #include namespace Swift { - class DNSSDServiceID; - - class VCardCollection; - class LinkLocalConnector; - class LinkLocalServiceBrowser; - class LinkLocalPresenceManager; - class BoostConnectionServer; - class SessionTracer; - class RosterPayload; - class Presence; - class EventLoop; - - class Server { - public: - Server( - int clientConnectionPort, - int linkLocalConnectionPort, - LinkLocalServiceBrowser* browser, - VCardCollection* vCardCollection, - EventLoop* eventLoop); - ~Server(); - - void start(); - void stop(); - - int getLinkLocalPort() const { - return linkLocalConnectionPort; - } - - int getClientToServerPort() const { - return clientConnectionPort; - } - - boost::signal onSelfConnected; - boost::signal)> onStopped; - - private: - void stop(boost::optional); - - void handleNewClientConnection(boost::shared_ptr c); - void handleSessionStarted(); - void handleSessionFinished(boost::shared_ptr); - void handleElementReceived(boost::shared_ptr element, boost::shared_ptr session); - void handleRosterChanged(boost::shared_ptr roster); - void handlePresenceChanged(boost::shared_ptr presence); - void handleServiceRegistered(const DNSSDServiceID& service); - void handleNewLinkLocalConnection(boost::shared_ptr connection); - void handleLinkLocalSessionFinished(boost::shared_ptr session); - void handleLinkLocalElementReceived(boost::shared_ptr element, boost::shared_ptr session); - void handleConnectFinished(boost::shared_ptr connector, bool error); - void handleClientConnectionServerStopped( - boost::optional); - void handleLinkLocalConnectionServerStopped( - boost::optional); - boost::shared_ptr getLinkLocalSessionForJID(const JID& jid); - boost::shared_ptr getLinkLocalConnectorForJID(const JID& jid); - void registerLinkLocalSession(boost::shared_ptr session); - void unregisterService(); - LinkLocalServiceInfo getLinkLocalServiceInfo(boost::shared_ptr presence); - - private: - class DummyUserRegistry : public UserRegistry { - public: - DummyUserRegistry() {} - - virtual bool isValidUserPassword(const JID&, const SafeByteArray&) const { - return true; - } - }; - - private: - IDGenerator idGenerator; - FullPayloadParserFactoryCollection payloadParserFactories; - FullPayloadSerializerCollection payloadSerializers; - BoostIOServiceThread boostIOServiceThread; - DummyUserRegistry userRegistry; - PlatformXMLParserFactory xmlParserFactory; - bool linkLocalServiceRegistered; - bool rosterRequested; - int clientConnectionPort; - int linkLocalConnectionPort; - LinkLocalServiceBrowser* linkLocalServiceBrowser; - VCardCollection* vCardCollection; - EventLoop* eventLoop; - LinkLocalPresenceManager* presenceManager; - bool stopping; - boost::shared_ptr serverFromClientConnectionServer; - std::vector serverFromClientConnectionServerSignalConnections; - boost::shared_ptr serverFromClientSession; - boost::shared_ptr lastPresence; - JID selfJID; - boost::shared_ptr serverFromNetworkConnectionServer; - std::vector serverFromNetworkConnectionServerSignalConnections; - std::vector< boost::shared_ptr > linkLocalSessions; - std::vector< boost::shared_ptr > connectors; - std::vector< boost::shared_ptr > tracers; - }; + class DNSSDServiceID; + + class VCardCollection; + class LinkLocalConnector; + class LinkLocalServiceBrowser; + class LinkLocalPresenceManager; + class BoostConnectionServer; + class SessionTracer; + class RosterPayload; + class Presence; + class EventLoop; + + class Server { + public: + Server( + int clientConnectionPort, + int linkLocalConnectionPort, + LinkLocalServiceBrowser* browser, + VCardCollection* vCardCollection, + EventLoop* eventLoop); + ~Server(); + + void start(); + void stop(); + + int getLinkLocalPort() const { + return linkLocalConnectionPort; + } + + int getClientToServerPort() const { + return clientConnectionPort; + } + + boost::signal onSelfConnected; + boost::signal)> onStopped; + + private: + void stop(boost::optional); + + void handleNewClientConnection(boost::shared_ptr c); + void handleSessionStarted(); + void handleSessionFinished(boost::shared_ptr); + void handleElementReceived(boost::shared_ptr element, boost::shared_ptr session); + void handleRosterChanged(boost::shared_ptr roster); + void handlePresenceChanged(boost::shared_ptr presence); + void handleServiceRegistered(const DNSSDServiceID& service); + void handleNewLinkLocalConnection(boost::shared_ptr connection); + void handleLinkLocalSessionFinished(boost::shared_ptr session); + void handleLinkLocalElementReceived(boost::shared_ptr element, boost::shared_ptr session); + void handleConnectFinished(boost::shared_ptr connector, bool error); + void handleClientConnectionServerStopped( + boost::optional); + void handleLinkLocalConnectionServerStopped( + boost::optional); + boost::shared_ptr getLinkLocalSessionForJID(const JID& jid); + boost::shared_ptr getLinkLocalConnectorForJID(const JID& jid); + void registerLinkLocalSession(boost::shared_ptr session); + void unregisterService(); + LinkLocalServiceInfo getLinkLocalServiceInfo(boost::shared_ptr presence); + + private: + class DummyUserRegistry : public UserRegistry { + public: + DummyUserRegistry() {} + + virtual bool isValidUserPassword(const JID&, const SafeByteArray&) const { + return true; + } + }; + + private: + IDGenerator idGenerator; + FullPayloadParserFactoryCollection payloadParserFactories; + FullPayloadSerializerCollection payloadSerializers; + BoostIOServiceThread boostIOServiceThread; + DummyUserRegistry userRegistry; + PlatformXMLParserFactory xmlParserFactory; + bool linkLocalServiceRegistered; + bool rosterRequested; + int clientConnectionPort; + int linkLocalConnectionPort; + LinkLocalServiceBrowser* linkLocalServiceBrowser; + VCardCollection* vCardCollection; + EventLoop* eventLoop; + LinkLocalPresenceManager* presenceManager; + bool stopping; + boost::shared_ptr serverFromClientConnectionServer; + std::vector serverFromClientConnectionServerSignalConnections; + boost::shared_ptr serverFromClientSession; + boost::shared_ptr lastPresence; + JID selfJID; + boost::shared_ptr serverFromNetworkConnectionServer; + std::vector serverFromNetworkConnectionServerSignalConnections; + std::vector< boost::shared_ptr > linkLocalSessions; + std::vector< boost::shared_ptr > connectors; + std::vector< boost::shared_ptr > tracers; + }; } diff --git a/Slimber/ServerError.h b/Slimber/ServerError.h index b8cb0a5..93b6a3f 100644 --- a/Slimber/ServerError.h +++ b/Slimber/ServerError.h @@ -9,29 +9,29 @@ #include namespace Swift { - class ServerError { - public: - enum Type { - C2SPortConflict, - C2SError, - LinkLocalPortConflict, - LinkLocalError - }; + class ServerError { + public: + enum Type { + C2SPortConflict, + C2SError, + LinkLocalPortConflict, + LinkLocalError + }; - ServerError(Type type, const std::string& message = std::string()) : - type(type), message(message) { - } + ServerError(Type type, const std::string& message = std::string()) : + type(type), message(message) { + } - Type getType() const { - return type; - } + Type getType() const { + return type; + } - const std::string& getMessage() const { - return message; - } + const std::string& getMessage() const { + return message; + } - private: - Type type; - std::string message; - }; + private: + Type type; + std::string message; + }; } diff --git a/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp b/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp index 2681c1a..45bc2aa 100644 --- a/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp +++ b/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp @@ -26,239 +26,239 @@ using namespace Swift; class LinkLocalPresenceManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LinkLocalPresenceManagerTest); - CPPUNIT_TEST(testConstructor); - CPPUNIT_TEST(testServiceAdded); - CPPUNIT_TEST(testServiceRemoved); - CPPUNIT_TEST(testServiceChanged); - CPPUNIT_TEST(testGetRoster); - CPPUNIT_TEST(testGetAllPresence); - CPPUNIT_TEST(testGetRoster_InfoWithNick); - CPPUNIT_TEST(testGetRoster_InfoWithFirstName); - CPPUNIT_TEST(testGetRoster_InfoWithLastName); - CPPUNIT_TEST(testGetRoster_InfoWithFirstAndLastName); - CPPUNIT_TEST(testGetRoster_NoInfo); - CPPUNIT_TEST(testGetServiceForJID); - CPPUNIT_TEST(testGetServiceForJID_NoMatch); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - eventLoop = new DummyEventLoop(); - querier = boost::make_shared("wonderland.lit", eventLoop); - browser = new LinkLocalServiceBrowser(querier); - browser->start(); - } - - void tearDown() { - browser->stop(); - delete browser; - delete eventLoop; - } - - void testConstructor() { - addService("alice@wonderland"); - addService("rabbit@teaparty"); - boost::shared_ptr testling(createTestling()); - - CPPUNIT_ASSERT_EQUAL(2, static_cast(testling->getRoster()->getItems().size())); - CPPUNIT_ASSERT_EQUAL(2, static_cast(testling->getAllPresence().size())); - } - - void testServiceAdded() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland", "Alice"); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges[0]->getItems().size())); - boost::optional item = rosterChanges[0]->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT(item); - CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName()); - CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription()); - CPPUNIT_ASSERT_EQUAL(1, static_cast(presenceChanges.size())); - CPPUNIT_ASSERT(StatusShow::Online == presenceChanges[0]->getShow()); - CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[0]->getFrom()); - } - - void testServiceRemoved() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland"); - removeService("alice@wonderland"); - - CPPUNIT_ASSERT_EQUAL(2, static_cast(rosterChanges.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges[1]->getItems().size())); - boost::optional item = rosterChanges[1]->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT(item); - CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Remove, item->getSubscription()); - } - - void testServiceChanged() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland"); - updateServicePresence("alice@wonderland", LinkLocalServiceInfo::Away, "I'm Away"); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges.size())); - CPPUNIT_ASSERT_EQUAL(2, static_cast(presenceChanges.size())); - CPPUNIT_ASSERT(StatusShow::Away == presenceChanges[1]->getShow()); - CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[1]->getFrom()); - CPPUNIT_ASSERT_EQUAL(std::string("I'm Away"), presenceChanges[1]->getStatus()); - } - - void testGetAllPresence() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland"); - addService("rabbit@teaparty"); - updateServicePresence("rabbit@teaparty", LinkLocalServiceInfo::Away, "Partying"); - - std::vector > presences = testling->getAllPresence(); - CPPUNIT_ASSERT_EQUAL(2, static_cast(presences.size())); - // The order doesn't matter - CPPUNIT_ASSERT(JID("rabbit@teaparty") == presences[0]->getFrom()); - CPPUNIT_ASSERT(StatusShow::Away == presences[0]->getShow()); - CPPUNIT_ASSERT(JID("alice@wonderland") == presences[1]->getFrom()); - CPPUNIT_ASSERT(StatusShow::Online == presences[1]->getShow()); - } - - void testGetRoster() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland", "Alice"); - addService("rabbit@teaparty", "Rabbit"); - - boost::shared_ptr roster = testling->getRoster(); - CPPUNIT_ASSERT_EQUAL(2, static_cast(roster->getItems().size())); - boost::optional item; - item = roster->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT(item); - CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName()); - CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription()); - item = roster->getItem(JID("rabbit@teaparty")); - CPPUNIT_ASSERT(item); - CPPUNIT_ASSERT_EQUAL(std::string("Rabbit"), item->getName()); - CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription()); - } - - void testGetRoster_InfoWithNick() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland", "Alice", "Alice In", "Wonderland"); - - boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName()); - } - - void testGetRoster_InfoWithFirstName() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland", "", "Alice In", ""); - - boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), item->getName()); - } - - void testGetRoster_InfoWithLastName() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland", "", "", "Wonderland"); - - boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), item->getName()); - } - - void testGetRoster_InfoWithFirstAndLastName() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland", "", "Alice In", "Wonderland"); - - boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), item->getName()); - } - - void testGetRoster_NoInfo() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland"); - - boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); - CPPUNIT_ASSERT_EQUAL(std::string(""), item->getName()); - } - - void testGetServiceForJID() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland"); - addService("rabbit@teaparty"); - addService("queen@garden"); - - boost::optional service = testling->getServiceForJID(JID("rabbit@teaparty")); - CPPUNIT_ASSERT(service); - CPPUNIT_ASSERT_EQUAL(std::string("rabbit@teaparty"), service->getID().getName()); - } - - void testGetServiceForJID_NoMatch() { - boost::shared_ptr testling(createTestling()); - - addService("alice@wonderland"); - addService("queen@garden"); - - CPPUNIT_ASSERT(!testling->getServiceForJID(JID("rabbit@teaparty"))); - } - - private: - boost::shared_ptr createTestling() { - boost::shared_ptr testling( - new LinkLocalPresenceManager(browser)); - testling->onRosterChanged.connect(boost::bind( - &LinkLocalPresenceManagerTest::handleRosterChanged, this, _1)); - testling->onPresenceChanged.connect(boost::bind( - &LinkLocalPresenceManagerTest::handlePresenceChanged, this, _1)); - return testling; - } - - void addService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) { - DNSSDServiceID service(name, "local."); - LinkLocalServiceInfo info; - info.setFirstName(firstName); - info.setLastName(lastName); - info.setNick(nickName); - querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord())); - querier->addService(service); - eventLoop->processEvents(); - } - - void removeService(const std::string& name) { - DNSSDServiceID service(name, "local."); - querier->removeService(DNSSDServiceID(name, "local.")); - eventLoop->processEvents(); - } - - void updateServicePresence(const std::string& name, LinkLocalServiceInfo::Status status, const std::string& message) { - DNSSDServiceID service(name, "local."); - LinkLocalServiceInfo info; - info.setStatus(status); - info.setMessage(message); - querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord())); - eventLoop->processEvents(); - } - - void handleRosterChanged(boost::shared_ptr payload) { - rosterChanges.push_back(payload); - } - - void handlePresenceChanged(boost::shared_ptr presence) { - presenceChanges.push_back(presence); - } - - private: - DummyEventLoop* eventLoop; - boost::shared_ptr querier; - LinkLocalServiceBrowser* browser; - std::vector< boost::shared_ptr > rosterChanges; - std::vector< boost::shared_ptr > presenceChanges; + CPPUNIT_TEST_SUITE(LinkLocalPresenceManagerTest); + CPPUNIT_TEST(testConstructor); + CPPUNIT_TEST(testServiceAdded); + CPPUNIT_TEST(testServiceRemoved); + CPPUNIT_TEST(testServiceChanged); + CPPUNIT_TEST(testGetRoster); + CPPUNIT_TEST(testGetAllPresence); + CPPUNIT_TEST(testGetRoster_InfoWithNick); + CPPUNIT_TEST(testGetRoster_InfoWithFirstName); + CPPUNIT_TEST(testGetRoster_InfoWithLastName); + CPPUNIT_TEST(testGetRoster_InfoWithFirstAndLastName); + CPPUNIT_TEST(testGetRoster_NoInfo); + CPPUNIT_TEST(testGetServiceForJID); + CPPUNIT_TEST(testGetServiceForJID_NoMatch); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + eventLoop = new DummyEventLoop(); + querier = boost::make_shared("wonderland.lit", eventLoop); + browser = new LinkLocalServiceBrowser(querier); + browser->start(); + } + + void tearDown() { + browser->stop(); + delete browser; + delete eventLoop; + } + + void testConstructor() { + addService("alice@wonderland"); + addService("rabbit@teaparty"); + boost::shared_ptr testling(createTestling()); + + CPPUNIT_ASSERT_EQUAL(2, static_cast(testling->getRoster()->getItems().size())); + CPPUNIT_ASSERT_EQUAL(2, static_cast(testling->getAllPresence().size())); + } + + void testServiceAdded() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland", "Alice"); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges[0]->getItems().size())); + boost::optional item = rosterChanges[0]->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT(item); + CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName()); + CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription()); + CPPUNIT_ASSERT_EQUAL(1, static_cast(presenceChanges.size())); + CPPUNIT_ASSERT(StatusShow::Online == presenceChanges[0]->getShow()); + CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[0]->getFrom()); + } + + void testServiceRemoved() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland"); + removeService("alice@wonderland"); + + CPPUNIT_ASSERT_EQUAL(2, static_cast(rosterChanges.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges[1]->getItems().size())); + boost::optional item = rosterChanges[1]->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT(item); + CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Remove, item->getSubscription()); + } + + void testServiceChanged() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland"); + updateServicePresence("alice@wonderland", LinkLocalServiceInfo::Away, "I'm Away"); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(rosterChanges.size())); + CPPUNIT_ASSERT_EQUAL(2, static_cast(presenceChanges.size())); + CPPUNIT_ASSERT(StatusShow::Away == presenceChanges[1]->getShow()); + CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[1]->getFrom()); + CPPUNIT_ASSERT_EQUAL(std::string("I'm Away"), presenceChanges[1]->getStatus()); + } + + void testGetAllPresence() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland"); + addService("rabbit@teaparty"); + updateServicePresence("rabbit@teaparty", LinkLocalServiceInfo::Away, "Partying"); + + std::vector > presences = testling->getAllPresence(); + CPPUNIT_ASSERT_EQUAL(2, static_cast(presences.size())); + // The order doesn't matter + CPPUNIT_ASSERT(JID("rabbit@teaparty") == presences[0]->getFrom()); + CPPUNIT_ASSERT(StatusShow::Away == presences[0]->getShow()); + CPPUNIT_ASSERT(JID("alice@wonderland") == presences[1]->getFrom()); + CPPUNIT_ASSERT(StatusShow::Online == presences[1]->getShow()); + } + + void testGetRoster() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland", "Alice"); + addService("rabbit@teaparty", "Rabbit"); + + boost::shared_ptr roster = testling->getRoster(); + CPPUNIT_ASSERT_EQUAL(2, static_cast(roster->getItems().size())); + boost::optional item; + item = roster->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT(item); + CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName()); + CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription()); + item = roster->getItem(JID("rabbit@teaparty")); + CPPUNIT_ASSERT(item); + CPPUNIT_ASSERT_EQUAL(std::string("Rabbit"), item->getName()); + CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription()); + } + + void testGetRoster_InfoWithNick() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland", "Alice", "Alice In", "Wonderland"); + + boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName()); + } + + void testGetRoster_InfoWithFirstName() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland", "", "Alice In", ""); + + boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT_EQUAL(std::string("Alice In"), item->getName()); + } + + void testGetRoster_InfoWithLastName() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland", "", "", "Wonderland"); + + boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT_EQUAL(std::string("Wonderland"), item->getName()); + } + + void testGetRoster_InfoWithFirstAndLastName() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland", "", "Alice In", "Wonderland"); + + boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT_EQUAL(std::string("Alice In Wonderland"), item->getName()); + } + + void testGetRoster_NoInfo() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland"); + + boost::optional item = testling->getRoster()->getItem(JID("alice@wonderland")); + CPPUNIT_ASSERT_EQUAL(std::string(""), item->getName()); + } + + void testGetServiceForJID() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland"); + addService("rabbit@teaparty"); + addService("queen@garden"); + + boost::optional service = testling->getServiceForJID(JID("rabbit@teaparty")); + CPPUNIT_ASSERT(service); + CPPUNIT_ASSERT_EQUAL(std::string("rabbit@teaparty"), service->getID().getName()); + } + + void testGetServiceForJID_NoMatch() { + boost::shared_ptr testling(createTestling()); + + addService("alice@wonderland"); + addService("queen@garden"); + + CPPUNIT_ASSERT(!testling->getServiceForJID(JID("rabbit@teaparty"))); + } + + private: + boost::shared_ptr createTestling() { + boost::shared_ptr testling( + new LinkLocalPresenceManager(browser)); + testling->onRosterChanged.connect(boost::bind( + &LinkLocalPresenceManagerTest::handleRosterChanged, this, _1)); + testling->onPresenceChanged.connect(boost::bind( + &LinkLocalPresenceManagerTest::handlePresenceChanged, this, _1)); + return testling; + } + + void addService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) { + DNSSDServiceID service(name, "local."); + LinkLocalServiceInfo info; + info.setFirstName(firstName); + info.setLastName(lastName); + info.setNick(nickName); + querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord())); + querier->addService(service); + eventLoop->processEvents(); + } + + void removeService(const std::string& name) { + DNSSDServiceID service(name, "local."); + querier->removeService(DNSSDServiceID(name, "local.")); + eventLoop->processEvents(); + } + + void updateServicePresence(const std::string& name, LinkLocalServiceInfo::Status status, const std::string& message) { + DNSSDServiceID service(name, "local."); + LinkLocalServiceInfo info; + info.setStatus(status); + info.setMessage(message); + querier->setServiceInfo(service, DNSSDResolveServiceQuery::Result(name + "._presence._tcp.local", "rabbithole.local", 1234, info.toTXTRecord())); + eventLoop->processEvents(); + } + + void handleRosterChanged(boost::shared_ptr payload) { + rosterChanges.push_back(payload); + } + + void handlePresenceChanged(boost::shared_ptr presence) { + presenceChanges.push_back(presence); + } + + private: + DummyEventLoop* eventLoop; + boost::shared_ptr querier; + LinkLocalServiceBrowser* browser; + std::vector< boost::shared_ptr > rosterChanges; + std::vector< boost::shared_ptr > presenceChanges; }; CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalPresenceManagerTest); diff --git a/Slimber/UnitTest/MenuletControllerTest.cpp b/Slimber/UnitTest/MenuletControllerTest.cpp index c379b8b..e3b46ab 100644 --- a/Slimber/UnitTest/MenuletControllerTest.cpp +++ b/Slimber/UnitTest/MenuletControllerTest.cpp @@ -11,145 +11,145 @@ #include class MenuletControllerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(MenuletControllerTest); - CPPUNIT_TEST(testConstructor); - CPPUNIT_TEST(testUpdate); - CPPUNIT_TEST(testSetXMPPStatus_Online); - CPPUNIT_TEST(testSetXMPPStatus_Offline); - CPPUNIT_TEST(testSetUserNames); - CPPUNIT_TEST(testSetUserNames_NoUsers); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - menulet = new FakeMenulet(); - } - - void tearDown() { - delete menulet; - } - - void testConstructor() { - MenuletController testling(menulet); - - CPPUNIT_ASSERT_EQUAL(8, static_cast(menulet->items.size())); - size_t i = 0; - CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("[Offline] "), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]); - } - - void testUpdate() { - MenuletController testling(menulet); - - testling.setXMPPStatus("You are connected", MenuletController::Online); - - CPPUNIT_ASSERT_EQUAL(8, static_cast(menulet->items.size())); - size_t i = 0; - CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]); - } - - void testSetXMPPStatus_Online() { - MenuletController testling(menulet); - - testling.setXMPPStatus("You are connected", MenuletController::Online); - - size_t i = 0; - CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]); - } - - - void testSetXMPPStatus_Offline() { - MenuletController testling(menulet); - - testling.setXMPPStatus("You are not connected", MenuletController::Offline); - - size_t i = 0; - CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("[Offline] You are not connected"), menulet->items[i++]); - } - - void testSetUserNames() { - MenuletController testling(menulet); - - std::vector users; - users.push_back("Alice In Wonderland"); - users.push_back("The Mad Hatter"); - testling.setUserNames(users); - - size_t i = 0; - CPPUNIT_ASSERT_EQUAL(std::string("Online users:"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string(" Alice In Wonderland"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string(" The Mad Hatter"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - } - - void testSetUserNames_NoUsers() { - MenuletController testling(menulet); - - std::vector users; - testling.setUserNames(users); - - size_t i = 0; - CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); - } - - private: - struct FakeMenulet : public Menulet { - virtual void clear() { - items.clear(); - } - - virtual void addItem(const std::string& name, const std::string& icon = std::string()) { - std::string result; - if (!icon.empty()) { - result += "[" + icon + "] "; - } - result += name; - items.push_back(result); - } - - virtual void addAboutItem() { - items.push_back("*About*"); - } - - virtual void addRestartItem() { - items.push_back("*Restart*"); - } - - virtual void addExitItem() { - items.push_back("*Exit*"); - } - - virtual void addSeparator() { - items.push_back("-"); - } - - virtual void setIcon(const std::string& i) { - icon = i; - } - - std::vector items; - std::string icon; - }; - - FakeMenulet* menulet; + CPPUNIT_TEST_SUITE(MenuletControllerTest); + CPPUNIT_TEST(testConstructor); + CPPUNIT_TEST(testUpdate); + CPPUNIT_TEST(testSetXMPPStatus_Online); + CPPUNIT_TEST(testSetXMPPStatus_Offline); + CPPUNIT_TEST(testSetUserNames); + CPPUNIT_TEST(testSetUserNames_NoUsers); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + menulet = new FakeMenulet(); + } + + void tearDown() { + delete menulet; + } + + void testConstructor() { + MenuletController testling(menulet); + + CPPUNIT_ASSERT_EQUAL(8, static_cast(menulet->items.size())); + size_t i = 0; + CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("[Offline] "), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]); + } + + void testUpdate() { + MenuletController testling(menulet); + + testling.setXMPPStatus("You are connected", MenuletController::Online); + + CPPUNIT_ASSERT_EQUAL(8, static_cast(menulet->items.size())); + size_t i = 0; + CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("*About*"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("*Restart*"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("*Exit*"), menulet->items[i++]); + } + + void testSetXMPPStatus_Online() { + MenuletController testling(menulet); + + testling.setXMPPStatus("You are connected", MenuletController::Online); + + size_t i = 0; + CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("[Online] You are connected"), menulet->items[i++]); + } + + + void testSetXMPPStatus_Offline() { + MenuletController testling(menulet); + + testling.setXMPPStatus("You are not connected", MenuletController::Offline); + + size_t i = 0; + CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("[Offline] You are not connected"), menulet->items[i++]); + } + + void testSetUserNames() { + MenuletController testling(menulet); + + std::vector users; + users.push_back("Alice In Wonderland"); + users.push_back("The Mad Hatter"); + testling.setUserNames(users); + + size_t i = 0; + CPPUNIT_ASSERT_EQUAL(std::string("Online users:"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string(" Alice In Wonderland"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string(" The Mad Hatter"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + } + + void testSetUserNames_NoUsers() { + MenuletController testling(menulet); + + std::vector users; + testling.setUserNames(users); + + size_t i = 0; + CPPUNIT_ASSERT_EQUAL(std::string("No online users"), menulet->items[i++]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), menulet->items[i++]); + } + + private: + struct FakeMenulet : public Menulet { + virtual void clear() { + items.clear(); + } + + virtual void addItem(const std::string& name, const std::string& icon = std::string()) { + std::string result; + if (!icon.empty()) { + result += "[" + icon + "] "; + } + result += name; + items.push_back(result); + } + + virtual void addAboutItem() { + items.push_back("*About*"); + } + + virtual void addRestartItem() { + items.push_back("*Restart*"); + } + + virtual void addExitItem() { + items.push_back("*Exit*"); + } + + virtual void addSeparator() { + items.push_back("-"); + } + + virtual void setIcon(const std::string& i) { + icon = i; + } + + std::vector items; + std::string icon; + }; + + FakeMenulet* menulet; }; CPPUNIT_TEST_SUITE_REGISTRATION(MenuletControllerTest); diff --git a/Slimber/VCardCollection.h b/Slimber/VCardCollection.h index 0e7d27f..3295039 100644 --- a/Slimber/VCardCollection.h +++ b/Slimber/VCardCollection.h @@ -11,11 +11,11 @@ #include namespace Swift { - class VCardCollection { - public: - virtual ~VCardCollection(); + class VCardCollection { + public: + virtual ~VCardCollection(); - virtual boost::shared_ptr getOwnVCard() const = 0; - virtual void setOwnVCard(boost::shared_ptr vcard) = 0; - }; + virtual boost::shared_ptr getOwnVCard() const = 0; + virtual void setOwnVCard(boost::shared_ptr vcard) = 0; + }; } diff --git a/Sluift/Completer.h b/Sluift/Completer.h index 1e9defb..564c647 100644 --- a/Sluift/Completer.h +++ b/Sluift/Completer.h @@ -10,10 +10,10 @@ #include namespace Swift { - class Completer { - public: - virtual ~Completer(); + class Completer { + public: + virtual ~Completer(); - virtual std::vector getCompletions(const std::string& buffer, int start, int end) = 0; - }; + virtual std::vector getCompletions(const std::string& buffer, int start, int end) = 0; + }; } diff --git a/Sluift/Console.cpp b/Sluift/Console.cpp index 623a38f..ef0b1a4 100644 --- a/Sluift/Console.cpp +++ b/Sluift/Console.cpp @@ -28,256 +28,256 @@ using namespace Swift; * Adds the backtrace to the error message. */ static int traceback(lua_State* L) { - if (!lua_isstring(L, 1)) { - return 1; - } - lua_getglobal(L, "debug"); - if (!lua_istable(L, -1)) { - lua_pop(L, 1); - return 1; - } - lua_getfield(L, -1, "traceback"); - if (!lua_isfunction(L, -1)) { - lua_pop(L, 2); - return 1; - } - lua_pushvalue(L, 1); - lua_pushinteger(L, 2); - lua_call(L, 2, 1); - return 1; + if (!lua_isstring(L, 1)) { + return 1; + } + lua_getglobal(L, "debug"); + if (!lua_istable(L, -1)) { + lua_pop(L, 1); + return 1; + } + lua_getfield(L, -1, "traceback"); + if (!lua_isfunction(L, -1)) { + lua_pop(L, 2); + return 1; + } + lua_pushvalue(L, 1); + lua_pushinteger(L, 2); + lua_call(L, 2, 1); + return 1; } Console::Console(lua_State* L, Terminal* terminal) : L(L), terminal(terminal), previousNumberOfReturnArguments(0) { - terminal->setCompleter(this); + terminal->setCompleter(this); } Console::~Console() { } void Console::run() { - while (true) { - lua_settop(L, 0); - try { - if (!readCommand()) { - return; - } - int result = call(L, 0, true); - if (result != 0) { - throw std::runtime_error(getErrorMessage()); - } - - // Clear the previous results - for (int i = 0; i < previousNumberOfReturnArguments; ++i) { - lua_pushnil(L); - lua_setglobal(L, ("_" + boost::lexical_cast(i+1)).c_str()); - } - - // Store the results - for (int i = 0; i < lua_gettop(L); ++i) { - lua_pushvalue(L, i+1); - lua_setglobal(L, ("_" + boost::lexical_cast(i+1)).c_str()); - } - previousNumberOfReturnArguments = lua_gettop(L); - - // Print results - if (lua_gettop(L) > 0) { - lua_getglobal(L, "print"); - lua_insert(L, 1); - if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) { - throw std::runtime_error("Error calling 'print': " + getErrorMessage()); - } - } - } - catch (const std::exception& e) { - terminal->printError(e.what()); - } - } + while (true) { + lua_settop(L, 0); + try { + if (!readCommand()) { + return; + } + int result = call(L, 0, true); + if (result != 0) { + throw std::runtime_error(getErrorMessage()); + } + + // Clear the previous results + for (int i = 0; i < previousNumberOfReturnArguments; ++i) { + lua_pushnil(L); + lua_setglobal(L, ("_" + boost::lexical_cast(i+1)).c_str()); + } + + // Store the results + for (int i = 0; i < lua_gettop(L); ++i) { + lua_pushvalue(L, i+1); + lua_setglobal(L, ("_" + boost::lexical_cast(i+1)).c_str()); + } + previousNumberOfReturnArguments = lua_gettop(L); + + // Print results + if (lua_gettop(L) > 0) { + lua_getglobal(L, "print"); + lua_insert(L, 1); + if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) { + throw std::runtime_error("Error calling 'print': " + getErrorMessage()); + } + } + } + catch (const std::exception& e) { + terminal->printError(e.what()); + } + } } int Console::tryLoadCommand(const std::string& originalCommand) { - std::string command = originalCommand; + std::string command = originalCommand; - // Replace '=' by 'return' (for compatibility with Lua console) - if (boost::algorithm::starts_with(command, "=")) { - command = "return " + command.substr(1); - } + // Replace '=' by 'return' (for compatibility with Lua console) + if (boost::algorithm::starts_with(command, "=")) { + command = "return " + command.substr(1); + } - std::string commandAsExpression = "return " + command; + std::string commandAsExpression = "return " + command; - // Try to load the command as an expression - if (luaL_loadbuffer(L, commandAsExpression.c_str(), commandAsExpression.size(), "=stdin") == 0) { - return 0; - } - lua_pop(L, 1); + // Try to load the command as an expression + if (luaL_loadbuffer(L, commandAsExpression.c_str(), commandAsExpression.size(), "=stdin") == 0) { + return 0; + } + lua_pop(L, 1); - // Try to load the command as a regular command - return luaL_loadbuffer(L, command.c_str(), command.size(), "=stdin"); + // Try to load the command as a regular command + return luaL_loadbuffer(L, command.c_str(), command.size(), "=stdin"); } bool Console::readCommand() { - boost::optional line = terminal->readLine(getPrompt(true)); - if (!line) { - return false; - } - std::string command = *line; - while (true) { - int result = tryLoadCommand(command); - - // Check if we need to read more - if (result == LUA_ERRSYNTAX) { - std::string errorMessage(lua_tostring(L, -1)); - if (boost::algorithm::ends_with(errorMessage, "''")) { - lua_pop(L, 1); - - // Read another line - boost::optional line = terminal->readLine(getPrompt(false)); - if (!line) { - return false; - } - command = command + "\n" + *line; - continue; - } - } - if (!command.empty()) { - terminal->addToHistory(command); - } - if (result != 0) { - throw std::runtime_error(getErrorMessage()); - } - return true; - } + boost::optional line = terminal->readLine(getPrompt(true)); + if (!line) { + return false; + } + std::string command = *line; + while (true) { + int result = tryLoadCommand(command); + + // Check if we need to read more + if (result == LUA_ERRSYNTAX) { + std::string errorMessage(lua_tostring(L, -1)); + if (boost::algorithm::ends_with(errorMessage, "''")) { + lua_pop(L, 1); + + // Read another line + boost::optional line = terminal->readLine(getPrompt(false)); + if (!line) { + return false; + } + command = command + "\n" + *line; + continue; + } + } + if (!command.empty()) { + terminal->addToHistory(command); + } + if (result != 0) { + throw std::runtime_error(getErrorMessage()); + } + return true; + } } std::string Console::getErrorMessage() const { - if (lua_isnil(L, -1)) { - return ""; - } - const char* errorMessage = lua_tostring(L, -1); - return errorMessage ? errorMessage : ""; + if (lua_isnil(L, -1)) { + return ""; + } + const char* errorMessage = lua_tostring(L, -1); + return errorMessage ? errorMessage : ""; } int Console::call(lua_State* L, int numberOfArguments, bool keepResult) { - // Put traceback function on stack below call - int tracebackIndex = lua_gettop(L) - numberOfArguments; - lua_pushcfunction(L, traceback); - lua_insert(L, tracebackIndex); + // Put traceback function on stack below call + int tracebackIndex = lua_gettop(L) - numberOfArguments; + lua_pushcfunction(L, traceback); + lua_insert(L, tracebackIndex); - int result = lua_pcall(L, numberOfArguments, keepResult ? LUA_MULTRET : 0, tracebackIndex); + int result = lua_pcall(L, numberOfArguments, keepResult ? LUA_MULTRET : 0, tracebackIndex); - // Remove traceback - lua_remove(L, tracebackIndex); + // Remove traceback + lua_remove(L, tracebackIndex); - return result; + return result; } std::string Console::getPrompt(bool firstLine) const { - lua_getglobal(L,firstLine ? "_PROMPT" : "_PROMPT2"); - const char* rawPrompt = lua_tostring(L, -1); - std::string prompt; - if (rawPrompt) { - prompt = std::string(rawPrompt); - } - else { - prompt = firstLine ? "> " : ">> "; - } - lua_pop(L, 1); - return prompt; + lua_getglobal(L,firstLine ? "_PROMPT" : "_PROMPT2"); + const char* rawPrompt = lua_tostring(L, -1); + std::string prompt; + if (rawPrompt) { + prompt = std::string(rawPrompt); + } + else { + prompt = firstLine ? "> " : ">> "; + } + lua_pop(L, 1); + return prompt; } static void addMatchingTableKeys(lua_State* L, const std::string& match, std::vector& result) { - for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { - const char* rawKey = lua_tostring(L, -2); - if (rawKey) { - std::string key(rawKey); - if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) { - result.push_back(key); - } - } - } + for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { + const char* rawKey = lua_tostring(L, -2); + if (rawKey) { + std::string key(rawKey); + if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) { + result.push_back(key); + } + } + } } static void addMatchingTableValues(lua_State* L, const std::string& match, std::vector& result) { - for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { - const char* rawValue = lua_tostring(L, -1); - if (rawValue) { - std::string key(rawValue); - if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) { - result.push_back(key); - } - } - } + for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { + const char* rawValue = lua_tostring(L, -1); + if (rawValue) { + std::string key(rawValue); + if (boost::starts_with(key, match) && !(match == "" && boost::starts_with(key, "_"))) { + result.push_back(key); + } + } + } } std::vector Console::getCompletions(const std::string& input, int start, int end) { - std::string prefix = input.substr(boost::numeric_cast(start), boost::numeric_cast(end - start)); - - std::vector tokens; - if (end) { - tokens = Lua::tokenize(input.substr(0, boost::numeric_cast(end))); - } - - // Don't autocomplete strings - if (!tokens.empty() && ((*tokens.rbegin())[0] == '\'' || (*tokens.rbegin())[0] == '"')) { - return std::vector(); - } - - std::vector context; - for (std::vector::reverse_iterator i = tokens.rbegin(); i != tokens.rend(); ++i) { - if (std::isalpha((*i)[0]) || (*i)[0] == '_') { - if (i != tokens.rbegin()) { - context.push_back(*i); - } - } - else if (*i != "." && *i != ":") { - break; - } - } - - // Drill into context - int top = lua_gettop(L); - lua_pushglobaltable(L); - for (std::vector::reverse_iterator i = context.rbegin(); i != context.rend(); ++i) { - if (lua_istable(L, -1) || lua_isuserdata(L, -1)) { - lua_getfield(L, -1, i->c_str()); - if (!lua_isnil(L, 1)) { - continue; - } - } - lua_settop(L, top); - return std::vector(); - } - - // Collect all keys from the table - std::vector result; - if (lua_istable(L, -1)) { - addMatchingTableKeys(L, prefix, result); - } - - // Collect all keys from the metatable - if (lua_getmetatable(L, -1)) { - lua_getfield(L, -1, "__index"); - if (lua_istable(L, -1)) { - addMatchingTableKeys(L, prefix, result); - } - lua_pop(L, 1); - - lua_getfield(L, -1, "_completions"); - if (lua_isfunction(L, -1)) { - lua_pushvalue(L, -3); - if (lua_pcall(L, 1, 1, 0) != 0) { - throw std::runtime_error("Error calling '_completions': " + getErrorMessage()); - } - } - if (lua_istable(L, -1)) { - addMatchingTableValues(L, prefix, result); - } - lua_pop(L, 2); - } - - lua_settop(L, top); - - return result; + std::string prefix = input.substr(boost::numeric_cast(start), boost::numeric_cast(end - start)); + + std::vector tokens; + if (end) { + tokens = Lua::tokenize(input.substr(0, boost::numeric_cast(end))); + } + + // Don't autocomplete strings + if (!tokens.empty() && ((*tokens.rbegin())[0] == '\'' || (*tokens.rbegin())[0] == '"')) { + return std::vector(); + } + + std::vector context; + for (std::vector::reverse_iterator i = tokens.rbegin(); i != tokens.rend(); ++i) { + if (std::isalpha((*i)[0]) || (*i)[0] == '_') { + if (i != tokens.rbegin()) { + context.push_back(*i); + } + } + else if (*i != "." && *i != ":") { + break; + } + } + + // Drill into context + int top = lua_gettop(L); + lua_pushglobaltable(L); + for (std::vector::reverse_iterator i = context.rbegin(); i != context.rend(); ++i) { + if (lua_istable(L, -1) || lua_isuserdata(L, -1)) { + lua_getfield(L, -1, i->c_str()); + if (!lua_isnil(L, 1)) { + continue; + } + } + lua_settop(L, top); + return std::vector(); + } + + // Collect all keys from the table + std::vector result; + if (lua_istable(L, -1)) { + addMatchingTableKeys(L, prefix, result); + } + + // Collect all keys from the metatable + if (lua_getmetatable(L, -1)) { + lua_getfield(L, -1, "__index"); + if (lua_istable(L, -1)) { + addMatchingTableKeys(L, prefix, result); + } + lua_pop(L, 1); + + lua_getfield(L, -1, "_completions"); + if (lua_isfunction(L, -1)) { + lua_pushvalue(L, -3); + if (lua_pcall(L, 1, 1, 0) != 0) { + throw std::runtime_error("Error calling '_completions': " + getErrorMessage()); + } + } + if (lua_istable(L, -1)) { + addMatchingTableValues(L, prefix, result); + } + lua_pop(L, 2); + } + + lua_settop(L, top); + + return result; } diff --git a/Sluift/Console.h b/Sluift/Console.h index 4f444fe..d1687bf 100644 --- a/Sluift/Console.h +++ b/Sluift/Console.h @@ -17,28 +17,28 @@ struct lua_State; namespace Swift { - class Terminal; + class Terminal; - class Console : public Completer { - public: - Console(lua_State* L, Terminal* terminal); - virtual ~Console(); + class Console : public Completer { + public: + Console(lua_State* L, Terminal* terminal); + virtual ~Console(); - void run(); + void run(); - static int call(lua_State* L, int numberOfArguments, bool keepResult); + static int call(lua_State* L, int numberOfArguments, bool keepResult); - private: - std::string getPrompt(bool firstLine) const; - std::string getErrorMessage() const; - bool readCommand(); - int tryLoadCommand(const std::string& command); + private: + std::string getPrompt(bool firstLine) const; + std::string getErrorMessage() const; + bool readCommand(); + int tryLoadCommand(const std::string& command); - virtual std::vector getCompletions(const std::string&, int start, int end) SWIFTEN_OVERRIDE; + virtual std::vector getCompletions(const std::string&, int start, int end) SWIFTEN_OVERRIDE; - private: - lua_State* L; - Terminal* terminal; - int previousNumberOfReturnArguments; - }; + private: + lua_State* L; + Terminal* terminal; + int previousNumberOfReturnArguments; + }; } diff --git a/Sluift/EditlineTerminal.cpp b/Sluift/EditlineTerminal.cpp index 4d48bd7..fc62142 100644 --- a/Sluift/EditlineTerminal.cpp +++ b/Sluift/EditlineTerminal.cpp @@ -27,55 +27,55 @@ static EditlineTerminal* globalInstance = NULL; static int completionStart = -1; static int completionEnd = -1; -#if defined(SWIFTEN_PLATFORM_WINDOWS) +#if defined(SWIFTEN_PLATFORM_WINDOWS) static char* getEmptyCompletions(const char*, int) { #else static int getEmptyCompletions(const char*, int) { #endif - return 0; + return 0; } static char* getCompletions(const char*, int state) { - rl_completion_append_character = 0; + rl_completion_append_character = 0; #if RL_READLINE_VERSION >= 0x0600 - rl_completion_suppress_append = 1; + rl_completion_suppress_append = 1; #endif - static std::vector completions; - if (state == 0) { - assert(globalInstance); - completions.clear(); - if (globalInstance->getCompleter()) { - completions = globalInstance->getCompleter()->getCompletions(rl_line_buffer, completionStart, completionEnd); - } - } - if (boost::numeric_cast(state) >= completions.size()) { - return 0; - } - return strdup(completions[boost::numeric_cast(state)].c_str()); + static std::vector completions; + if (state == 0) { + assert(globalInstance); + completions.clear(); + if (globalInstance->getCompleter()) { + completions = globalInstance->getCompleter()->getCompletions(rl_line_buffer, completionStart, completionEnd); + } + } + if (boost::numeric_cast(state) >= completions.size()) { + return 0; + } + return strdup(completions[boost::numeric_cast(state)].c_str()); } static char** getAttemptedCompletions(const char* text, int start, int end) { - completionStart = start; - completionEnd = end; - return rl_completion_matches(text, getCompletions); + completionStart = start; + completionEnd = end; + return rl_completion_matches(text, getCompletions); } EditlineTerminal& EditlineTerminal::getInstance() { - static EditlineTerminal instance; - globalInstance = &instance; - return instance; + static EditlineTerminal instance; + globalInstance = &instance; + return instance; } EditlineTerminal::EditlineTerminal() { - rl_attempted_completion_function = getAttemptedCompletions; - rl_completion_entry_function = getEmptyCompletions; // Fallback. Do nothing. + rl_attempted_completion_function = getAttemptedCompletions; + rl_completion_entry_function = getEmptyCompletions; // Fallback. Do nothing. #if defined(SWIFTEN_PLATFORM_WINDOWS) - // rl_basic_word_break is a cons char[] in MinGWEditLine. - // This one seems to work, although it doesn't on OS X for some reason. - rl_completer_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}"); + // rl_basic_word_break is a cons char[] in MinGWEditLine. + // This one seems to work, although it doesn't on OS X for some reason. + rl_completer_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}"); #else - rl_basic_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}"); + rl_basic_word_break_characters = strdup(" \t\n.:+-*/><=;|&()[]{}"); #endif } @@ -83,19 +83,19 @@ EditlineTerminal::~EditlineTerminal() { } void EditlineTerminal::printError(const std::string& message) { - std::cout << message << std::endl; + std::cout << message << std::endl; } boost::optional EditlineTerminal::readLine(const std::string& prompt) { - const char* line = readline(prompt.c_str()); - return line ? std::string(line) : boost::optional(); + const char* line = readline(prompt.c_str()); + return line ? std::string(line) : boost::optional(); } void EditlineTerminal::addToHistory(const std::string& line) { #if defined(SWIFTEN_PLATFORM_WINDOWS) - // MinGWEditLine copies the string, so this is safe - add_history(const_cast(line.c_str())); + // MinGWEditLine copies the string, so this is safe + add_history(const_cast(line.c_str())); #else - add_history(line.c_str()); + add_history(line.c_str()); #endif } diff --git a/Sluift/EditlineTerminal.h b/Sluift/EditlineTerminal.h index 3919c46..ec4cf63 100644 --- a/Sluift/EditlineTerminal.h +++ b/Sluift/EditlineTerminal.h @@ -11,16 +11,16 @@ #include namespace Swift { - class EditlineTerminal : public Terminal { - public: - static EditlineTerminal& getInstance(); + class EditlineTerminal : public Terminal { + public: + static EditlineTerminal& getInstance(); - private: - EditlineTerminal(); - virtual ~EditlineTerminal(); + private: + EditlineTerminal(); + virtual ~EditlineTerminal(); - virtual boost::optional readLine(const std::string& prompt) SWIFTEN_OVERRIDE; - virtual void printError(const std::string& message) SWIFTEN_OVERRIDE; - virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE; - }; + virtual boost::optional readLine(const std::string& prompt) SWIFTEN_OVERRIDE; + virtual void printError(const std::string& message) SWIFTEN_OVERRIDE; + virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/BodyConvertor.cpp b/Sluift/ElementConvertors/BodyConvertor.cpp index 8c1a6cd..4593f01 100644 --- a/Sluift/ElementConvertors/BodyConvertor.cpp +++ b/Sluift/ElementConvertors/BodyConvertor.cpp @@ -21,17 +21,17 @@ BodyConvertor::~BodyConvertor() { } boost::shared_ptr BodyConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - if (boost::optional value = Lua::getStringField(L, -1, "text")) { - result->setText(*value); - } - return result; + boost::shared_ptr result = boost::make_shared(); + if (boost::optional value = Lua::getStringField(L, -1, "text")) { + result->setText(*value); + } + return result; } void BodyConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (!payload->getText().empty()) { - lua_pushstring(L, payload->getText().c_str()); - lua_setfield(L, -2, "text"); - } + lua_createtable(L, 0, 0); + if (!payload->getText().empty()) { + lua_pushstring(L, payload->getText().c_str()); + lua_setfield(L, -2, "text"); + } } diff --git a/Sluift/ElementConvertors/BodyConvertor.h b/Sluift/ElementConvertors/BodyConvertor.h index 6b7b3c7..75d23e7 100644 --- a/Sluift/ElementConvertors/BodyConvertor.h +++ b/Sluift/ElementConvertors/BodyConvertor.h @@ -12,14 +12,14 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class BodyConvertor : public GenericLuaElementConvertor { - public: - BodyConvertor(); - virtual ~BodyConvertor(); + class BodyConvertor : public GenericLuaElementConvertor { + public: + BodyConvertor(); + virtual ~BodyConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/CommandConvertor.cpp b/Sluift/ElementConvertors/CommandConvertor.cpp index d3a8739..272e5d1 100644 --- a/Sluift/ElementConvertors/CommandConvertor.cpp +++ b/Sluift/ElementConvertors/CommandConvertor.cpp @@ -20,179 +20,179 @@ using namespace Swift; static Command::Action convertActionFromString(const std::string& action) { - if (action == "cancel") { return Command::Cancel; } - else if (action == "execute") { return Command::Execute; } - else if (action == "complete") { return Command::Complete; } - else if (action == "prev") { return Command::Prev; } - else if (action == "next") { return Command::Next; } - return Command::NoAction; + if (action == "cancel") { return Command::Cancel; } + else if (action == "execute") { return Command::Execute; } + else if (action == "complete") { return Command::Complete; } + else if (action == "prev") { return Command::Prev; } + else if (action == "next") { return Command::Next; } + return Command::NoAction; } static std::string convertActionToString(Command::Action action) { - switch (action) { - case Command::Cancel: return "cancel"; - case Command::Execute: return "execute"; - case Command::Complete: return "complete"; - case Command::Prev: return "prev"; - case Command::Next: return "next"; - case Command::NoAction: assert(false); return ""; - } - assert(false); - return ""; + switch (action) { + case Command::Cancel: return "cancel"; + case Command::Execute: return "execute"; + case Command::Complete: return "complete"; + case Command::Prev: return "prev"; + case Command::Next: return "next"; + case Command::NoAction: assert(false); return ""; + } + assert(false); + return ""; } -CommandConvertor::CommandConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("command"), - convertors(convertors) { +CommandConvertor::CommandConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("command"), + convertors(convertors) { } CommandConvertor::~CommandConvertor() { } boost::shared_ptr CommandConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - - lua_getfield(L, -1, "node"); - if (!lua_isnil(L, -1)) { - result->setNode(std::string(Lua::checkString(L, -1))); - } - lua_pop(L, 1); - - lua_getfield(L, -1, "session_id"); - if (!lua_isnil(L, -1)) { - result->setSessionID(std::string(Lua::checkString(L, -1))); - } - lua_pop(L, 1); - - lua_getfield(L, -1, "status"); - if (!lua_isnil(L, -1)) { - std::string statusText = Lua::checkString(L, -1); - Command::Status status = Command::NoStatus; - if (statusText == "executing") { status = Command::Executing; } - else if (statusText == "completed") { status = Command::Completed; } - else if (statusText == "canceled") { status = Command::Canceled; } - result->setStatus(status); - } - lua_pop(L, 1); - - lua_getfield(L, -1, "action"); - if (!lua_isnil(L, -1)) { - result->setAction(convertActionFromString(Lua::checkString(L, -1))); - } - lua_pop(L, 1); - - lua_getfield(L, -1, "execute_action"); - if (!lua_isnil(L, -1)) { - result->setExecuteAction(convertActionFromString(Lua::checkString(L, -1))); - } - lua_pop(L, 1); - - lua_getfield(L, -1, "available_actions"); - if (!lua_isnil(L, -1)) { - Lua::checkType(L, -1, LUA_TTABLE); - lua_pushnil(L); - for (lua_pushnil(L); lua_next(L, -2) != 0; ) { - result->addAvailableAction(convertActionFromString(Lua::checkString(L, -1))); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - - lua_getfield(L, -1, "notes"); - if (!lua_isnil(L, -1)) { - Lua::checkType(L, -1, LUA_TTABLE); - lua_pushnil(L); - for (lua_pushnil(L); lua_next(L, -2) != 0; ) { - Lua::checkType(L, -1, LUA_TTABLE); - std::string note; - lua_getfield(L, -1, "note"); - if (!lua_isnil(L, -1)) { - note = Lua::checkString(L, -1); - } - lua_pop(L, 1); - - Command::Note::Type noteType = Command::Note::Info; - lua_getfield(L, -1, "type"); - if (!lua_isnil(L, -1)) { - std::string type = Lua::checkString(L, -1); - if (type == "info") { noteType = Command::Note::Info; } - else if (type == "warn") { noteType = Command::Note::Warn; } - else if (type == "error") { noteType = Command::Note::Error; } - } - lua_pop(L, 1); - - result->addNote(Command::Note(note, noteType)); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - - lua_getfield(L, -1, "form"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr
form = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { - result->setForm(form); - } - } - lua_pop(L, 1); - - return result; + boost::shared_ptr result = boost::make_shared(); + + lua_getfield(L, -1, "node"); + if (!lua_isnil(L, -1)) { + result->setNode(std::string(Lua::checkString(L, -1))); + } + lua_pop(L, 1); + + lua_getfield(L, -1, "session_id"); + if (!lua_isnil(L, -1)) { + result->setSessionID(std::string(Lua::checkString(L, -1))); + } + lua_pop(L, 1); + + lua_getfield(L, -1, "status"); + if (!lua_isnil(L, -1)) { + std::string statusText = Lua::checkString(L, -1); + Command::Status status = Command::NoStatus; + if (statusText == "executing") { status = Command::Executing; } + else if (statusText == "completed") { status = Command::Completed; } + else if (statusText == "canceled") { status = Command::Canceled; } + result->setStatus(status); + } + lua_pop(L, 1); + + lua_getfield(L, -1, "action"); + if (!lua_isnil(L, -1)) { + result->setAction(convertActionFromString(Lua::checkString(L, -1))); + } + lua_pop(L, 1); + + lua_getfield(L, -1, "execute_action"); + if (!lua_isnil(L, -1)) { + result->setExecuteAction(convertActionFromString(Lua::checkString(L, -1))); + } + lua_pop(L, 1); + + lua_getfield(L, -1, "available_actions"); + if (!lua_isnil(L, -1)) { + Lua::checkType(L, -1, LUA_TTABLE); + lua_pushnil(L); + for (lua_pushnil(L); lua_next(L, -2) != 0; ) { + result->addAvailableAction(convertActionFromString(Lua::checkString(L, -1))); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + + lua_getfield(L, -1, "notes"); + if (!lua_isnil(L, -1)) { + Lua::checkType(L, -1, LUA_TTABLE); + lua_pushnil(L); + for (lua_pushnil(L); lua_next(L, -2) != 0; ) { + Lua::checkType(L, -1, LUA_TTABLE); + std::string note; + lua_getfield(L, -1, "note"); + if (!lua_isnil(L, -1)) { + note = Lua::checkString(L, -1); + } + lua_pop(L, 1); + + Command::Note::Type noteType = Command::Note::Info; + lua_getfield(L, -1, "type"); + if (!lua_isnil(L, -1)) { + std::string type = Lua::checkString(L, -1); + if (type == "info") { noteType = Command::Note::Info; } + else if (type == "warn") { noteType = Command::Note::Warn; } + else if (type == "error") { noteType = Command::Note::Error; } + } + lua_pop(L, 1); + + result->addNote(Command::Note(note, noteType)); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + + lua_getfield(L, -1, "form"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr form = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { + result->setForm(form); + } + } + lua_pop(L, 1); + + return result; } void CommandConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - Lua::Table result; - if (!payload->getNode().empty()) { - result["node"] = Lua::valueRef(payload->getNode()); - } - if (!payload->getSessionID().empty()) { - result["session_id"] = Lua::valueRef(payload->getSessionID()); - } - switch (payload->getStatus()) { - case Command::Executing: result["status"] = Lua::valueRef("executing"); break; - case Command::Completed: result["status"] = Lua::valueRef("completed"); break; - case Command::Canceled: result["status"] = Lua::valueRef("canceled"); break; - case Command::NoStatus: break; - } - - if (!payload->getNotes().empty()) { - std::vector notes; - foreach (const Command::Note& note, payload->getNotes()) { - Lua::Table noteTable; - if (!note.note.empty()) { - noteTable["note"] = Lua::valueRef(note.note); - } - switch (note.type) { - case Command::Note::Info: noteTable["type"] = Lua::valueRef("info"); break; - case Command::Note::Warn: noteTable["type"] = Lua::valueRef("warn"); break; - case Command::Note::Error: noteTable["type"] = Lua::valueRef("error"); break; - } - notes.push_back(noteTable); - } - result["notes"] = Lua::valueRef(notes); - } - - if (payload->getAction() != Command::NoAction) { - result["action"] = Lua::valueRef(convertActionToString(payload->getAction())); - } - - if (payload->getExecuteAction() != Command::NoAction) { - result["execute_action"] = Lua::valueRef(convertActionToString(payload->getAction())); - } - - if (!payload->getAvailableActions().empty()) { - std::vector availableActions; - foreach (const Command::Action& action, payload->getAvailableActions()) { - if (action != Command::NoAction) { - availableActions.push_back(convertActionToString(action)); - } - } - result["available_actions"] = Lua::valueRef(availableActions); - } - - Lua::pushValue(L, result); - - if (payload->getForm()) { - bool result = convertors->convertToLuaUntyped(L, payload->getForm()); - assert(result); - lua_setfield(L, -2, "form"); - } + Lua::Table result; + if (!payload->getNode().empty()) { + result["node"] = Lua::valueRef(payload->getNode()); + } + if (!payload->getSessionID().empty()) { + result["session_id"] = Lua::valueRef(payload->getSessionID()); + } + switch (payload->getStatus()) { + case Command::Executing: result["status"] = Lua::valueRef("executing"); break; + case Command::Completed: result["status"] = Lua::valueRef("completed"); break; + case Command::Canceled: result["status"] = Lua::valueRef("canceled"); break; + case Command::NoStatus: break; + } + + if (!payload->getNotes().empty()) { + std::vector notes; + foreach (const Command::Note& note, payload->getNotes()) { + Lua::Table noteTable; + if (!note.note.empty()) { + noteTable["note"] = Lua::valueRef(note.note); + } + switch (note.type) { + case Command::Note::Info: noteTable["type"] = Lua::valueRef("info"); break; + case Command::Note::Warn: noteTable["type"] = Lua::valueRef("warn"); break; + case Command::Note::Error: noteTable["type"] = Lua::valueRef("error"); break; + } + notes.push_back(noteTable); + } + result["notes"] = Lua::valueRef(notes); + } + + if (payload->getAction() != Command::NoAction) { + result["action"] = Lua::valueRef(convertActionToString(payload->getAction())); + } + + if (payload->getExecuteAction() != Command::NoAction) { + result["execute_action"] = Lua::valueRef(convertActionToString(payload->getAction())); + } + + if (!payload->getAvailableActions().empty()) { + std::vector availableActions; + foreach (const Command::Action& action, payload->getAvailableActions()) { + if (action != Command::NoAction) { + availableActions.push_back(convertActionToString(action)); + } + } + result["available_actions"] = Lua::valueRef(availableActions); + } + + Lua::pushValue(L, result); + + if (payload->getForm()) { + bool result = convertors->convertToLuaUntyped(L, payload->getForm()); + assert(result); + lua_setfield(L, -2, "form"); + } } diff --git a/Sluift/ElementConvertors/CommandConvertor.h b/Sluift/ElementConvertors/CommandConvertor.h index e129fd9..97b3f2f 100644 --- a/Sluift/ElementConvertors/CommandConvertor.h +++ b/Sluift/ElementConvertors/CommandConvertor.h @@ -12,17 +12,17 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class CommandConvertor : public GenericLuaElementConvertor { - public: - CommandConvertor(LuaElementConvertors* convertors); - virtual ~CommandConvertor(); + class CommandConvertor : public GenericLuaElementConvertor { + public: + CommandConvertor(LuaElementConvertors* convertors); + virtual ~CommandConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/DOMElementConvertor.cpp b/Sluift/ElementConvertors/DOMElementConvertor.cpp index 347bbfd..85b505d 100644 --- a/Sluift/ElementConvertors/DOMElementConvertor.cpp +++ b/Sluift/ElementConvertors/DOMElementConvertor.cpp @@ -30,133 +30,133 @@ using namespace Swift; namespace { - class ParserClient : public XMLParserClient { - public: - ParserClient(lua_State* L) : L(L), currentIndex(1) { - } - - virtual void handleStartElement( - const std::string& element, const std::string& ns, - const AttributeMap& attributes) SWIFTEN_OVERRIDE { - lua_checkstack(L, 6); - lua_pushnumber(L, currentIndex); - lua_newtable(L); - lua_pushstring(L, element.c_str()); - lua_setfield(L, -2, "tag"); - if (!ns.empty()) { - lua_pushstring(L, ns.c_str()); - lua_setfield(L, -2, "ns"); - } - if (!attributes.getEntries().empty()) { - lua_newtable(L); - int i = 1; - foreach(const AttributeMap::Entry& entry, attributes.getEntries()) { - lua_pushnumber(L, i); - lua_newtable(L); - lua_pushstring(L, entry.getAttribute().getName().c_str()); - lua_setfield(L, -2, "name"); - if (!entry.getAttribute().getNamespace().empty()) { - lua_pushstring(L, entry.getAttribute().getNamespace().c_str()); - lua_setfield(L, -2, "ns"); - } - lua_pushstring(L, entry.getValue().c_str()); - lua_setfield(L, -2, "value"); - lua_settable(L, -3); - ++i; - } - lua_setfield(L, -2, "attributes"); - } - - indexStack.push_back(currentIndex); - currentIndex = 1; - lua_newtable(L); - } - - virtual void handleEndElement( - const std::string&, const std::string&) SWIFTEN_OVERRIDE { - lua_setfield(L, -2, "children"); - lua_settable(L, -3); - currentIndex = indexStack.back(); - indexStack.pop_back(); - currentIndex++; - } - - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE { - lua_checkstack(L, 2); - lua_pushnumber(L, currentIndex); - lua_pushstring(L, data.c_str()); - lua_settable(L, -3); - currentIndex++; - } - - private: - lua_State* L; - std::vector indexStack; - int currentIndex; - }; - - std::string serializeElement(lua_State* L) { - std::string tag; - lua_getfield(L, -1, "tag"); - if (lua_isstring(L, -1)) { - tag = lua_tostring(L, -1); - } - lua_pop(L, 1); - - std::string ns; - lua_getfield(L, -1, "ns"); - if (lua_isstring(L, -1)) { - ns = lua_tostring(L, -1); - } - lua_pop(L, 1); - - XMLElement element(tag, ns); - - lua_getfield(L, -1, "attributes"); - if (lua_istable(L, -1)) { - int index = Lua::absoluteOffset(L, -1); - for (lua_pushnil(L); lua_next(L, index) != 0; ) { - if (lua_istable(L, -1)) { - std::string attributeName; - lua_getfield(L, -1, "name"); - if (lua_isstring(L, -1)) { - attributeName = lua_tostring(L, -1); - } - lua_pop(L, 1); - - std::string attributeValue; - lua_getfield(L, -1, "value"); - if (lua_isstring(L, -1)) { - attributeValue = lua_tostring(L, -1); - } - lua_pop(L, 1); - - if (!attributeName.empty()) { - element.setAttribute(attributeName, attributeValue); - } - } - lua_pop(L, 1); // value - } - } - lua_pop(L, 1); // children - - lua_getfield(L, -1, "children"); - if (lua_istable(L, -1)) { - int index = Lua::absoluteOffset(L, -1); - for (lua_pushnil(L); lua_next(L, index) != 0; ) { - if (lua_isstring(L, -1)) { - element.addNode(boost::make_shared(lua_tostring(L, -1))); - } - else if (lua_istable(L, -1)) { - element.addNode(boost::make_shared(serializeElement(L))); - } - lua_pop(L, 1); // value - } - } - lua_pop(L, 1); // children - - return element.serialize(); - } + class ParserClient : public XMLParserClient { + public: + ParserClient(lua_State* L) : L(L), currentIndex(1) { + } + + virtual void handleStartElement( + const std::string& element, const std::string& ns, + const AttributeMap& attributes) SWIFTEN_OVERRIDE { + lua_checkstack(L, 6); + lua_pushnumber(L, currentIndex); + lua_newtable(L); + lua_pushstring(L, element.c_str()); + lua_setfield(L, -2, "tag"); + if (!ns.empty()) { + lua_pushstring(L, ns.c_str()); + lua_setfield(L, -2, "ns"); + } + if (!attributes.getEntries().empty()) { + lua_newtable(L); + int i = 1; + foreach(const AttributeMap::Entry& entry, attributes.getEntries()) { + lua_pushnumber(L, i); + lua_newtable(L); + lua_pushstring(L, entry.getAttribute().getName().c_str()); + lua_setfield(L, -2, "name"); + if (!entry.getAttribute().getNamespace().empty()) { + lua_pushstring(L, entry.getAttribute().getNamespace().c_str()); + lua_setfield(L, -2, "ns"); + } + lua_pushstring(L, entry.getValue().c_str()); + lua_setfield(L, -2, "value"); + lua_settable(L, -3); + ++i; + } + lua_setfield(L, -2, "attributes"); + } + + indexStack.push_back(currentIndex); + currentIndex = 1; + lua_newtable(L); + } + + virtual void handleEndElement( + const std::string&, const std::string&) SWIFTEN_OVERRIDE { + lua_setfield(L, -2, "children"); + lua_settable(L, -3); + currentIndex = indexStack.back(); + indexStack.pop_back(); + currentIndex++; + } + + virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE { + lua_checkstack(L, 2); + lua_pushnumber(L, currentIndex); + lua_pushstring(L, data.c_str()); + lua_settable(L, -3); + currentIndex++; + } + + private: + lua_State* L; + std::vector indexStack; + int currentIndex; + }; + + std::string serializeElement(lua_State* L) { + std::string tag; + lua_getfield(L, -1, "tag"); + if (lua_isstring(L, -1)) { + tag = lua_tostring(L, -1); + } + lua_pop(L, 1); + + std::string ns; + lua_getfield(L, -1, "ns"); + if (lua_isstring(L, -1)) { + ns = lua_tostring(L, -1); + } + lua_pop(L, 1); + + XMLElement element(tag, ns); + + lua_getfield(L, -1, "attributes"); + if (lua_istable(L, -1)) { + int index = Lua::absoluteOffset(L, -1); + for (lua_pushnil(L); lua_next(L, index) != 0; ) { + if (lua_istable(L, -1)) { + std::string attributeName; + lua_getfield(L, -1, "name"); + if (lua_isstring(L, -1)) { + attributeName = lua_tostring(L, -1); + } + lua_pop(L, 1); + + std::string attributeValue; + lua_getfield(L, -1, "value"); + if (lua_isstring(L, -1)) { + attributeValue = lua_tostring(L, -1); + } + lua_pop(L, 1); + + if (!attributeName.empty()) { + element.setAttribute(attributeName, attributeValue); + } + } + lua_pop(L, 1); // value + } + } + lua_pop(L, 1); // children + + lua_getfield(L, -1, "children"); + if (lua_istable(L, -1)) { + int index = Lua::absoluteOffset(L, -1); + for (lua_pushnil(L); lua_next(L, index) != 0; ) { + if (lua_isstring(L, -1)) { + element.addNode(boost::make_shared(lua_tostring(L, -1))); + } + else if (lua_istable(L, -1)) { + element.addNode(boost::make_shared(serializeElement(L))); + } + lua_pop(L, 1); // value + } + } + lua_pop(L, 1); // children + + return element.serialize(); + } } DOMElementConvertor::DOMElementConvertor() { @@ -166,39 +166,39 @@ DOMElementConvertor::~DOMElementConvertor() { } boost::shared_ptr DOMElementConvertor::convertFromLua(lua_State* L, int index, const std::string& type) { - if (!lua_istable(L, index) || type != "dom") { - return boost::shared_ptr(); - } - return boost::make_shared(serializeElement(L).c_str()); + if (!lua_istable(L, index) || type != "dom") { + return boost::shared_ptr(); + } + return boost::make_shared(serializeElement(L).c_str()); } boost::optional DOMElementConvertor::convertToLua( - lua_State* L, boost::shared_ptr element) { - // Serialize payload to XML - boost::shared_ptr payload = boost::dynamic_pointer_cast(element); - if (!payload) { - return boost::optional(); - } - - PayloadSerializer* serializer = serializers.getPayloadSerializer(payload); - assert(serializer); - std::string serializedPayload = serializer->serialize(payload); - - lua_newtable(L); - - // Parse the payload again - ParserClient parserClient(L); - boost::shared_ptr parser(parsers.createXMLParser(&parserClient)); - bool result = parser->parse(serializedPayload); - assert(result); - - // There can only be one element, so stripping the list - lua_pushnil(L); - lua_next(L, -2); - Lua::registerTableToString(L, -1); - - lua_replace(L, -3); - lua_settop(L, -2); - - return std::string("dom"); + lua_State* L, boost::shared_ptr element) { + // Serialize payload to XML + boost::shared_ptr payload = boost::dynamic_pointer_cast(element); + if (!payload) { + return boost::optional(); + } + + PayloadSerializer* serializer = serializers.getPayloadSerializer(payload); + assert(serializer); + std::string serializedPayload = serializer->serialize(payload); + + lua_newtable(L); + + // Parse the payload again + ParserClient parserClient(L); + boost::shared_ptr parser(parsers.createXMLParser(&parserClient)); + bool result = parser->parse(serializedPayload); + assert(result); + + // There can only be one element, so stripping the list + lua_pushnil(L); + lua_next(L, -2); + Lua::registerTableToString(L, -1); + + lua_replace(L, -3); + lua_settop(L, -2); + + return std::string("dom"); } diff --git a/Sluift/ElementConvertors/DOMElementConvertor.h b/Sluift/ElementConvertors/DOMElementConvertor.h index 550bc3b..0d20251 100644 --- a/Sluift/ElementConvertors/DOMElementConvertor.h +++ b/Sluift/ElementConvertors/DOMElementConvertor.h @@ -13,16 +13,16 @@ #include namespace Swift { - class DOMElementConvertor : public LuaElementConvertor { - public: - DOMElementConvertor(); - virtual ~DOMElementConvertor(); + class DOMElementConvertor : public LuaElementConvertor { + public: + DOMElementConvertor(); + virtual ~DOMElementConvertor(); - virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE; - virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE; + virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - private: - PlatformXMLParserFactory parsers; - FullPayloadSerializerCollection serializers; - }; + private: + PlatformXMLParserFactory parsers; + FullPayloadSerializerCollection serializers; + }; } diff --git a/Sluift/ElementConvertors/DefaultElementConvertor.cpp b/Sluift/ElementConvertors/DefaultElementConvertor.cpp index a1e27fa..8353207 100644 --- a/Sluift/ElementConvertors/DefaultElementConvertor.cpp +++ b/Sluift/ElementConvertors/DefaultElementConvertor.cpp @@ -19,12 +19,12 @@ DefaultElementConvertor::~DefaultElementConvertor() { } boost::shared_ptr DefaultElementConvertor::convertFromLua(lua_State*, int, const std::string& type) { - std::cerr << "Warning: Unable to convert type '" << type << "'" << std::endl; - return boost::shared_ptr(); + std::cerr << "Warning: Unable to convert type '" << type << "'" << std::endl; + return boost::shared_ptr(); } boost::optional DefaultElementConvertor::convertToLua(lua_State*, boost::shared_ptr) { - // Should have been handled by the raw XML convertor - assert(false); - return NO_RESULT; + // Should have been handled by the raw XML convertor + assert(false); + return NO_RESULT; } diff --git a/Sluift/ElementConvertors/DefaultElementConvertor.h b/Sluift/ElementConvertors/DefaultElementConvertor.h index e08bb98..8f57e4f 100644 --- a/Sluift/ElementConvertors/DefaultElementConvertor.h +++ b/Sluift/ElementConvertors/DefaultElementConvertor.h @@ -11,12 +11,12 @@ #include namespace Swift { - class DefaultElementConvertor : public LuaElementConvertor { - public: - DefaultElementConvertor(); - virtual ~DefaultElementConvertor(); + class DefaultElementConvertor : public LuaElementConvertor { + public: + DefaultElementConvertor(); + virtual ~DefaultElementConvertor(); - virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE; - virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE; + virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/DelayConvertor.cpp b/Sluift/ElementConvertors/DelayConvertor.cpp index a2ea132..b59744b 100644 --- a/Sluift/ElementConvertors/DelayConvertor.cpp +++ b/Sluift/ElementConvertors/DelayConvertor.cpp @@ -24,27 +24,27 @@ DelayConvertor::~DelayConvertor() { } boost::shared_ptr DelayConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "stamp"); - if (lua_isstring(L, -1)) { - result->setStamp(stringToDateTime(lua_tostring(L, -1))); - } - lua_pop(L, 1); - - lua_getfield(L, -1, "from"); - if (lua_isstring(L, -1)) { - result->setFrom(lua_tostring(L, -1)); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "stamp"); + if (lua_isstring(L, -1)) { + result->setStamp(stringToDateTime(lua_tostring(L, -1))); + } + lua_pop(L, 1); + + lua_getfield(L, -1, "from"); + if (lua_isstring(L, -1)) { + result->setFrom(lua_tostring(L, -1)); + } + lua_pop(L, 1); + return result; } void DelayConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getFrom()) { - lua_pushstring(L, (*payload->getFrom()).toString().c_str()); - lua_setfield(L, -2, "from"); - } - lua_pushstring(L, dateTimeToString(payload->getStamp()).c_str()); - lua_setfield(L, -2, "stamp"); + lua_createtable(L, 0, 0); + if (payload->getFrom()) { + lua_pushstring(L, (*payload->getFrom()).toString().c_str()); + lua_setfield(L, -2, "from"); + } + lua_pushstring(L, dateTimeToString(payload->getStamp()).c_str()); + lua_setfield(L, -2, "stamp"); } diff --git a/Sluift/ElementConvertors/DelayConvertor.h b/Sluift/ElementConvertors/DelayConvertor.h index fed032f..064406c 100644 --- a/Sluift/ElementConvertors/DelayConvertor.h +++ b/Sluift/ElementConvertors/DelayConvertor.h @@ -12,12 +12,12 @@ #include namespace Swift { - class DelayConvertor : public GenericLuaElementConvertor { - public: - DelayConvertor(); - virtual ~DelayConvertor(); + class DelayConvertor : public GenericLuaElementConvertor { + public: + DelayConvertor(); + virtual ~DelayConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/DiscoInfoConvertor.cpp b/Sluift/ElementConvertors/DiscoInfoConvertor.cpp index 4ebd6a3..fc48e6c 100644 --- a/Sluift/ElementConvertors/DiscoInfoConvertor.cpp +++ b/Sluift/ElementConvertors/DiscoInfoConvertor.cpp @@ -22,97 +22,97 @@ DiscoInfoConvertor::~DiscoInfoConvertor() { } boost::shared_ptr DiscoInfoConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - if (boost::optional value = Lua::getStringField(L, -1, "node")) { - result->setNode(*value); - } - - lua_getfield(L, -1, "identities"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - result->addIdentity(DiscoInfo::Identity( - Lua::getStringField(L, -1, "name").get_value_or(""), - Lua::getStringField(L, -1, "category").get_value_or("client"), - Lua::getStringField(L, -1, "type").get_value_or("pc"), - Lua::getStringField(L, -1, "language").get_value_or(""))); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - - lua_getfield(L, -1, "features"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - result->addFeature(lua_tostring(L, -1)); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - - // TODO: Extension - - return result; + boost::shared_ptr result = boost::make_shared(); + if (boost::optional value = Lua::getStringField(L, -1, "node")) { + result->setNode(*value); + } + + lua_getfield(L, -1, "identities"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + result->addIdentity(DiscoInfo::Identity( + Lua::getStringField(L, -1, "name").get_value_or(""), + Lua::getStringField(L, -1, "category").get_value_or("client"), + Lua::getStringField(L, -1, "type").get_value_or("pc"), + Lua::getStringField(L, -1, "language").get_value_or(""))); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + + lua_getfield(L, -1, "features"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + result->addFeature(lua_tostring(L, -1)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + + // TODO: Extension + + return result; } void DiscoInfoConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_newtable(L); - if (!payload->getNode().empty()) { - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - } - - const std::vector& identities = payload->getIdentities(); - if (!identities.empty()) { - lua_createtable(L, boost::numeric_cast(identities.size()), 0); - for (size_t i = 0; i < identities.size(); ++i) { - lua_createtable(L, 0, 0); - if (!identities[i].getName().empty()) { - lua_pushstring(L, identities[i].getName().c_str()); - lua_setfield(L, -2, "name"); - } - if (!identities[i].getCategory().empty()) { - lua_pushstring(L, identities[i].getCategory().c_str()); - lua_setfield(L, -2, "category"); - } - if (!identities[i].getType().empty()) { - lua_pushstring(L, identities[i].getType().c_str()); - lua_setfield(L, -2, "type"); - } - if (!identities[i].getLanguage().empty()) { - lua_pushstring(L, identities[i].getLanguage().c_str()); - lua_setfield(L, -2, "language"); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "identities"); - } - - const std::vector& features = payload->getFeatures(); - if (!features.empty()) { - lua_createtable(L, boost::numeric_cast(features.size()), 0); - for (size_t i = 0; i < features.size(); ++i) { - lua_pushstring(L, features[i].c_str()); - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "features"); - } - - // TODO: Extension + lua_newtable(L); + if (!payload->getNode().empty()) { + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + } + + const std::vector& identities = payload->getIdentities(); + if (!identities.empty()) { + lua_createtable(L, boost::numeric_cast(identities.size()), 0); + for (size_t i = 0; i < identities.size(); ++i) { + lua_createtable(L, 0, 0); + if (!identities[i].getName().empty()) { + lua_pushstring(L, identities[i].getName().c_str()); + lua_setfield(L, -2, "name"); + } + if (!identities[i].getCategory().empty()) { + lua_pushstring(L, identities[i].getCategory().c_str()); + lua_setfield(L, -2, "category"); + } + if (!identities[i].getType().empty()) { + lua_pushstring(L, identities[i].getType().c_str()); + lua_setfield(L, -2, "type"); + } + if (!identities[i].getLanguage().empty()) { + lua_pushstring(L, identities[i].getLanguage().c_str()); + lua_setfield(L, -2, "language"); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "identities"); + } + + const std::vector& features = payload->getFeatures(); + if (!features.empty()) { + lua_createtable(L, boost::numeric_cast(features.size()), 0); + for (size_t i = 0; i < features.size(); ++i) { + lua_pushstring(L, features[i].c_str()); + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "features"); + } + + // TODO: Extension } boost::optional DiscoInfoConvertor::getDocumentation() const { - return Documentation( - "DiscoInfo", - "Represents `disco#info` service discovery data.\n\n" - "This table has the following structure:\n\n" - "- `node`: string\n" - "- `identities`: array(table)\n" - " - `name`: string\n" - " - `category`: string\n" - " - `type`: string\n" - " - `language`: string\n" - "- `features`: array(string)\n" - ); + return Documentation( + "DiscoInfo", + "Represents `disco#info` service discovery data.\n\n" + "This table has the following structure:\n\n" + "- `node`: string\n" + "- `identities`: array(table)\n" + " - `name`: string\n" + " - `category`: string\n" + " - `type`: string\n" + " - `language`: string\n" + "- `features`: array(string)\n" + ); } diff --git a/Sluift/ElementConvertors/DiscoInfoConvertor.h b/Sluift/ElementConvertors/DiscoInfoConvertor.h index 4f397b0..9e8d36d 100644 --- a/Sluift/ElementConvertors/DiscoInfoConvertor.h +++ b/Sluift/ElementConvertors/DiscoInfoConvertor.h @@ -12,13 +12,13 @@ #include namespace Swift { - class DiscoInfoConvertor : public GenericLuaElementConvertor { - public: - DiscoInfoConvertor(); - virtual ~DiscoInfoConvertor(); + class DiscoInfoConvertor : public GenericLuaElementConvertor { + public: + DiscoInfoConvertor(); + virtual ~DiscoInfoConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/DiscoItemsConvertor.cpp b/Sluift/ElementConvertors/DiscoItemsConvertor.cpp index a01fa7e..32cbb6e 100644 --- a/Sluift/ElementConvertors/DiscoItemsConvertor.cpp +++ b/Sluift/ElementConvertors/DiscoItemsConvertor.cpp @@ -22,49 +22,49 @@ DiscoItemsConvertor::~DiscoItemsConvertor() { } boost::shared_ptr DiscoItemsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - if (boost::optional value = Lua::getStringField(L, -1, "node")) { - result->setNode(*value); - } - lua_getfield(L, -1, "items"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - result->addItem(DiscoItems::Item( - Lua::getStringField(L, -1, "name").get_value_or(""), - JID(Lua::getStringField(L, -1, "jid").get_value_or("")), - Lua::getStringField(L, -1, "node").get_value_or(""))); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + if (boost::optional value = Lua::getStringField(L, -1, "node")) { + result->setNode(*value); + } + lua_getfield(L, -1, "items"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + result->addItem(DiscoItems::Item( + Lua::getStringField(L, -1, "name").get_value_or(""), + JID(Lua::getStringField(L, -1, "jid").get_value_or("")), + Lua::getStringField(L, -1, "node").get_value_or(""))); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + return result; } void DiscoItemsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_newtable(L); - if (!payload->getNode().empty()) { - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - } - const std::vector& items = payload->getItems(); - if (!items.empty()) { - lua_createtable(L, boost::numeric_cast(items.size()), 0); - for (size_t i = 0; i < items.size(); ++i) { - lua_createtable(L, 0, 0); - if (!items[i].getName().empty()) { - lua_pushstring(L, items[i].getName().c_str()); - lua_setfield(L, -2, "name"); - } - if (!items[i].getNode().empty()) { - lua_pushstring(L, items[i].getNode().c_str()); - lua_setfield(L, -2, "node"); - } - if (items[i].getJID().isValid()) { - lua_pushstring(L, items[i].getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "items"); - } + lua_newtable(L); + if (!payload->getNode().empty()) { + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + } + const std::vector& items = payload->getItems(); + if (!items.empty()) { + lua_createtable(L, boost::numeric_cast(items.size()), 0); + for (size_t i = 0; i < items.size(); ++i) { + lua_createtable(L, 0, 0); + if (!items[i].getName().empty()) { + lua_pushstring(L, items[i].getName().c_str()); + lua_setfield(L, -2, "name"); + } + if (!items[i].getNode().empty()) { + lua_pushstring(L, items[i].getNode().c_str()); + lua_setfield(L, -2, "node"); + } + if (items[i].getJID().isValid()) { + lua_pushstring(L, items[i].getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "items"); + } } diff --git a/Sluift/ElementConvertors/DiscoItemsConvertor.h b/Sluift/ElementConvertors/DiscoItemsConvertor.h index a1261a4..aa1f1e5 100644 --- a/Sluift/ElementConvertors/DiscoItemsConvertor.h +++ b/Sluift/ElementConvertors/DiscoItemsConvertor.h @@ -12,12 +12,12 @@ #include namespace Swift { - class DiscoItemsConvertor : public GenericLuaElementConvertor { - public: - DiscoItemsConvertor(); - virtual ~DiscoItemsConvertor(); + class DiscoItemsConvertor : public GenericLuaElementConvertor { + public: + DiscoItemsConvertor(); + virtual ~DiscoItemsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/ElementConvertors.ipp b/Sluift/ElementConvertors/ElementConvertors.ipp index 57e24a4..64e7540 100644 --- a/Sluift/ElementConvertors/ElementConvertors.ipp +++ b/Sluift/ElementConvertors/ElementConvertors.ipp @@ -45,43 +45,43 @@ #include void LuaElementConvertors::registerConvertors() { - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); } diff --git a/Sluift/ElementConvertors/FormConvertor.cpp b/Sluift/ElementConvertors/FormConvertor.cpp index d1617b6..5b6f664 100644 --- a/Sluift/ElementConvertors/FormConvertor.cpp +++ b/Sluift/ElementConvertors/FormConvertor.cpp @@ -22,326 +22,326 @@ using namespace Swift; namespace { - int formIndex(lua_State* L) { - lua_getfield(L, 1, "fields"); - if (lua_type(L, -1) != LUA_TTABLE) { - return 0; - } - int index = Lua::absoluteOffset(L, -1); - lua_pushnil(L); - for (lua_pushnil(L); lua_next(L, index) != 0; ) { - lua_getfield(L, -1, "name"); - if (lua_equal(L, -1, 2)) { - lua_pop(L, 1); - return 1; - } - lua_pop(L, 2); - } - return 0; - } - - int formNewIndex(lua_State* L) { - lua_getfield(L, 1, "fields"); - bool foundField = false; - if (lua_type(L, -1) == LUA_TTABLE) { - for (lua_pushnil(L); lua_next(L, -2) != 0; ) { - lua_getfield(L, -1, "name"); - if (lua_equal(L, -1, 2)) { - lua_pushvalue(L, 3); - lua_setfield(L, -3, "value"); - foundField = true; - lua_pop(L, 3); - break; - } - lua_pop(L, 2); - } - } - lua_pop(L, 1); - - if (!foundField) { - lua_pushvalue(L, 2); - lua_pushvalue(L, 3); - lua_rawset(L, 1); - } - return 0; - } - - Lua::Table convertFieldToLua(boost::shared_ptr field) { - Lua::Table luaField = boost::assign::map_list_of("name", Lua::valueRef(field->getName())); - std::string type; - switch (field->getType()) { - case FormField::UnknownType: type = ""; break; - case FormField::BooleanType: type = "boolean"; break; - case FormField::FixedType: type = "fixed"; break; - case FormField::HiddenType: type = "hidden"; break; - case FormField::ListSingleType: type = "list-single"; break; - case FormField::TextMultiType: type = "text-multi"; break; - case FormField::TextPrivateType: type = "text-private"; break; - case FormField::TextSingleType: type = "text-single"; break; - case FormField::JIDSingleType: type = "jid-single"; break; - case FormField::JIDMultiType: type = "jid-multi"; break; - case FormField::ListMultiType: type = "list-multi"; break; - } - if (!type.empty()) { - luaField["type"] = Lua::valueRef(type); - } - if (!field->getLabel().empty()) { - luaField["label"] = Lua::valueRef(field->getLabel()); - } - if (field->getRequired()) { - luaField["required"] = Lua::boolRef(field->getRequired()); - } - if (!field->getDescription().empty()) { - luaField["description"] = Lua::valueRef(field->getDescription()); - } - if (field->getType() == FormField::BooleanType) { - luaField["value"] = Lua::boolRef(field->getBoolValue()); - } - else if (field->getValues().size() > 1) { - luaField["value"] = Lua::valueRef(Lua::Array(field->getValues().begin(), field->getValues().end())); - } - else if (field->getValues().size() == 1) { - luaField["value"] = Lua::valueRef(field->getValues()[0]); - } - if (!field->getOptions().empty()) { - Lua::Array options; - foreach(const FormField::Option& option, field->getOptions()) { - Lua::Table luaOption = boost::assign::map_list_of - ("label", Lua::valueRef(option.label)) - ("value", Lua::valueRef(option.value)); - options.push_back(luaOption); - } - luaField["options"] = valueRef(options); - } - return luaField; - } - - Lua::Array convertFieldListToLua(const std::vector< boost::shared_ptr >& fieldList) { - Lua::Array fields; - foreach(boost::shared_ptr field, fieldList) { - fields.push_back(convertFieldToLua(field)); - } - return fields; - } - - - boost::shared_ptr convertFieldFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - FormField::Type fieldType = FormField::UnknownType; - boost::optional type = Lua::getStringField(L, -1, "type"); - if (type) { - if (*type == "boolean") { - fieldType = FormField::BooleanType; - } - if (*type == "fixed") { - fieldType = FormField::FixedType; - } - if (*type == "hidden") { - fieldType = FormField::HiddenType; - } - if (*type == "list-single") { - fieldType = FormField::ListSingleType; - } - if (*type == "text-multi") { - fieldType = FormField::TextMultiType; - } - if (*type == "text-private") { - fieldType = FormField::TextPrivateType; - } - if (*type == "text-single") { - fieldType = FormField::TextSingleType; - } - if (*type == "jid-single") { - fieldType = FormField::JIDSingleType; - } - if (*type == "jid-multi") { - fieldType = FormField::JIDMultiType; - } - if (*type == "list-multi") { - fieldType = FormField::ListMultiType; - } - } - result->setType(fieldType); - if (boost::optional name = Lua::getStringField(L, -1, "name")) { - result->setName(*name); - } - if (boost::optional description = Lua::getStringField(L, -1, "description")) { - result->setDescription(*description); - } - if (boost::optional label = Lua::getStringField(L, -1, "label")) { - result->setLabel(*label); - } - if (boost::optional required = Lua::getBooleanField(L, -1, "required")) { - result->setRequired(*required); - } - if (boost::optional value = Lua::getStringField(L, -1, "value")) { - result->addValue(*value); - } - else if (boost::optional value = Lua::getBooleanField(L, -1, "value")) { - result->setBoolValue(*value); - } - else { - lua_getfield(L, -1, "value"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - result->addValue(lua_tostring(L, -1)); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - } - lua_getfield(L, -1, "options"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_istable(L, -1)) { - FormField::Option option("", ""); - if (boost::optional value = Lua::getStringField(L, -1, "value")) { - option.value = *value; - } - if (boost::optional label = Lua::getStringField(L, -1, "label")) { - option.label = *label; - } - result->addOption(option); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - return result; - } - - std::vector< boost::shared_ptr > convertFieldListFromLua(lua_State* L) { - std::vector< boost::shared_ptr > result; - for (lua_pushnil(L); lua_next(L, -2);) { - result.push_back(convertFieldFromLua(L)); - lua_pop(L, 1); - } - return result; - } - - boost::shared_ptr convertFormFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - if (boost::optional title = Lua::getStringField(L, -1, "title")) { - result->setTitle(*title); - } - if (boost::optional instructions = Lua::getStringField(L, -1, "instructions")) { - result->setInstructions(*instructions); - } - if (boost::optional type = Lua::getStringField(L, -1, "type")) { - Form::Type formType = Form::FormType; - if (*type == "submit") { - formType = Form::SubmitType; - } - else if (*type == "cancel") { - formType = Form::CancelType; - } - else if (*type == "result") { - formType = Form::ResultType; - } - result->setType(formType); - } - - lua_getfield(L, -1, "fields"); - if (lua_istable(L, -1)) { - foreach (boost::shared_ptr formField, convertFieldListFromLua(L)) { - result->addField(formField); - } - } - lua_pop(L, 1); - - lua_getfield(L, -1, "reported_fields"); - if (lua_istable(L, -1)) { - foreach (boost::shared_ptr formField, convertFieldListFromLua(L)) { - result->addReportedField(formField); - } - } - lua_pop(L, 1); - - lua_getfield(L, -1, "items"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2);) { - result->addItem(convertFieldListFromLua(L)); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - - return result; - } - - void convertFormToLua(lua_State* L, boost::shared_ptr payload) { - std::string type; - switch (payload->getType()) { - case Form::FormType: type = "form"; break; - case Form::SubmitType: type = "submit"; break; - case Form::CancelType: type = "cancel"; break; - case Form::ResultType: type = "result"; break; - } - - Lua::Table result = boost::assign::map_list_of("type", Lua::valueRef(type)); - if (!payload->getTitle().empty()) { - result["title"] = Lua::valueRef(payload->getTitle()); - } - if (!payload->getInstructions().empty()) { - result["instructions"] = Lua::valueRef(payload->getInstructions()); - } - if (!payload->getFields().empty()) { - result["fields"] = valueRef(convertFieldListToLua(payload->getFields())); - } - if (!payload->getReportedFields().empty()) { - result["reported_fields"] = valueRef(convertFieldListToLua(payload->getReportedFields())); - } - - if (!payload->getItems().empty()) { - Lua::Array luaItems; - foreach(const Form::FormItem& item, payload->getItems()) { - if (!item.empty()) { - luaItems.push_back(convertFieldListToLua(item)); - } - } - result["items"] = valueRef(luaItems); - } - - Lua::pushValue(L, result); - - lua_newtable(L); - lua_pushcfunction(L, formIndex); - lua_setfield(L, -2, "__index"); - lua_pushcfunction(L, formNewIndex); - lua_setfield(L, -2, "__newindex"); - lua_setmetatable(L, -2); - } - - int createSubmission(lua_State* L) { - boost::shared_ptr form = convertFormFromLua(L); - - // Remove all redundant elements - form->setInstructions(""); - form->setTitle(""); - form->clearItems(); - form->clearReportedFields(); - std::vector< boost::shared_ptr > fields(form->getFields()); - form->clearFields(); - foreach (boost::shared_ptr field, fields) { - if (field->getType() == FormField::FixedType) { - continue; - } - field->clearOptions(); - field->setLabel(""); - field->setType(FormField::UnknownType); - field->setDescription(""); - form->addField(field); - } - form->setType(Form::SubmitType); - - // Convert back - convertFormToLua(L, form); - Lua::registerTableToString(L, -1); - - return 1; - } + int formIndex(lua_State* L) { + lua_getfield(L, 1, "fields"); + if (lua_type(L, -1) != LUA_TTABLE) { + return 0; + } + int index = Lua::absoluteOffset(L, -1); + lua_pushnil(L); + for (lua_pushnil(L); lua_next(L, index) != 0; ) { + lua_getfield(L, -1, "name"); + if (lua_equal(L, -1, 2)) { + lua_pop(L, 1); + return 1; + } + lua_pop(L, 2); + } + return 0; + } + + int formNewIndex(lua_State* L) { + lua_getfield(L, 1, "fields"); + bool foundField = false; + if (lua_type(L, -1) == LUA_TTABLE) { + for (lua_pushnil(L); lua_next(L, -2) != 0; ) { + lua_getfield(L, -1, "name"); + if (lua_equal(L, -1, 2)) { + lua_pushvalue(L, 3); + lua_setfield(L, -3, "value"); + foundField = true; + lua_pop(L, 3); + break; + } + lua_pop(L, 2); + } + } + lua_pop(L, 1); + + if (!foundField) { + lua_pushvalue(L, 2); + lua_pushvalue(L, 3); + lua_rawset(L, 1); + } + return 0; + } + + Lua::Table convertFieldToLua(boost::shared_ptr field) { + Lua::Table luaField = boost::assign::map_list_of("name", Lua::valueRef(field->getName())); + std::string type; + switch (field->getType()) { + case FormField::UnknownType: type = ""; break; + case FormField::BooleanType: type = "boolean"; break; + case FormField::FixedType: type = "fixed"; break; + case FormField::HiddenType: type = "hidden"; break; + case FormField::ListSingleType: type = "list-single"; break; + case FormField::TextMultiType: type = "text-multi"; break; + case FormField::TextPrivateType: type = "text-private"; break; + case FormField::TextSingleType: type = "text-single"; break; + case FormField::JIDSingleType: type = "jid-single"; break; + case FormField::JIDMultiType: type = "jid-multi"; break; + case FormField::ListMultiType: type = "list-multi"; break; + } + if (!type.empty()) { + luaField["type"] = Lua::valueRef(type); + } + if (!field->getLabel().empty()) { + luaField["label"] = Lua::valueRef(field->getLabel()); + } + if (field->getRequired()) { + luaField["required"] = Lua::boolRef(field->getRequired()); + } + if (!field->getDescription().empty()) { + luaField["description"] = Lua::valueRef(field->getDescription()); + } + if (field->getType() == FormField::BooleanType) { + luaField["value"] = Lua::boolRef(field->getBoolValue()); + } + else if (field->getValues().size() > 1) { + luaField["value"] = Lua::valueRef(Lua::Array(field->getValues().begin(), field->getValues().end())); + } + else if (field->getValues().size() == 1) { + luaField["value"] = Lua::valueRef(field->getValues()[0]); + } + if (!field->getOptions().empty()) { + Lua::Array options; + foreach(const FormField::Option& option, field->getOptions()) { + Lua::Table luaOption = boost::assign::map_list_of + ("label", Lua::valueRef(option.label)) + ("value", Lua::valueRef(option.value)); + options.push_back(luaOption); + } + luaField["options"] = valueRef(options); + } + return luaField; + } + + Lua::Array convertFieldListToLua(const std::vector< boost::shared_ptr >& fieldList) { + Lua::Array fields; + foreach(boost::shared_ptr field, fieldList) { + fields.push_back(convertFieldToLua(field)); + } + return fields; + } + + + boost::shared_ptr convertFieldFromLua(lua_State* L) { + boost::shared_ptr result = boost::make_shared(); + FormField::Type fieldType = FormField::UnknownType; + boost::optional type = Lua::getStringField(L, -1, "type"); + if (type) { + if (*type == "boolean") { + fieldType = FormField::BooleanType; + } + if (*type == "fixed") { + fieldType = FormField::FixedType; + } + if (*type == "hidden") { + fieldType = FormField::HiddenType; + } + if (*type == "list-single") { + fieldType = FormField::ListSingleType; + } + if (*type == "text-multi") { + fieldType = FormField::TextMultiType; + } + if (*type == "text-private") { + fieldType = FormField::TextPrivateType; + } + if (*type == "text-single") { + fieldType = FormField::TextSingleType; + } + if (*type == "jid-single") { + fieldType = FormField::JIDSingleType; + } + if (*type == "jid-multi") { + fieldType = FormField::JIDMultiType; + } + if (*type == "list-multi") { + fieldType = FormField::ListMultiType; + } + } + result->setType(fieldType); + if (boost::optional name = Lua::getStringField(L, -1, "name")) { + result->setName(*name); + } + if (boost::optional description = Lua::getStringField(L, -1, "description")) { + result->setDescription(*description); + } + if (boost::optional label = Lua::getStringField(L, -1, "label")) { + result->setLabel(*label); + } + if (boost::optional required = Lua::getBooleanField(L, -1, "required")) { + result->setRequired(*required); + } + if (boost::optional value = Lua::getStringField(L, -1, "value")) { + result->addValue(*value); + } + else if (boost::optional value = Lua::getBooleanField(L, -1, "value")) { + result->setBoolValue(*value); + } + else { + lua_getfield(L, -1, "value"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + result->addValue(lua_tostring(L, -1)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + } + lua_getfield(L, -1, "options"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_istable(L, -1)) { + FormField::Option option("", ""); + if (boost::optional value = Lua::getStringField(L, -1, "value")) { + option.value = *value; + } + if (boost::optional label = Lua::getStringField(L, -1, "label")) { + option.label = *label; + } + result->addOption(option); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + return result; + } + + std::vector< boost::shared_ptr > convertFieldListFromLua(lua_State* L) { + std::vector< boost::shared_ptr > result; + for (lua_pushnil(L); lua_next(L, -2);) { + result.push_back(convertFieldFromLua(L)); + lua_pop(L, 1); + } + return result; + } + + boost::shared_ptr convertFormFromLua(lua_State* L) { + boost::shared_ptr result = boost::make_shared(); + if (boost::optional title = Lua::getStringField(L, -1, "title")) { + result->setTitle(*title); + } + if (boost::optional instructions = Lua::getStringField(L, -1, "instructions")) { + result->setInstructions(*instructions); + } + if (boost::optional type = Lua::getStringField(L, -1, "type")) { + Form::Type formType = Form::FormType; + if (*type == "submit") { + formType = Form::SubmitType; + } + else if (*type == "cancel") { + formType = Form::CancelType; + } + else if (*type == "result") { + formType = Form::ResultType; + } + result->setType(formType); + } + + lua_getfield(L, -1, "fields"); + if (lua_istable(L, -1)) { + foreach (boost::shared_ptr formField, convertFieldListFromLua(L)) { + result->addField(formField); + } + } + lua_pop(L, 1); + + lua_getfield(L, -1, "reported_fields"); + if (lua_istable(L, -1)) { + foreach (boost::shared_ptr formField, convertFieldListFromLua(L)) { + result->addReportedField(formField); + } + } + lua_pop(L, 1); + + lua_getfield(L, -1, "items"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2);) { + result->addItem(convertFieldListFromLua(L)); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + + return result; + } + + void convertFormToLua(lua_State* L, boost::shared_ptr payload) { + std::string type; + switch (payload->getType()) { + case Form::FormType: type = "form"; break; + case Form::SubmitType: type = "submit"; break; + case Form::CancelType: type = "cancel"; break; + case Form::ResultType: type = "result"; break; + } + + Lua::Table result = boost::assign::map_list_of("type", Lua::valueRef(type)); + if (!payload->getTitle().empty()) { + result["title"] = Lua::valueRef(payload->getTitle()); + } + if (!payload->getInstructions().empty()) { + result["instructions"] = Lua::valueRef(payload->getInstructions()); + } + if (!payload->getFields().empty()) { + result["fields"] = valueRef(convertFieldListToLua(payload->getFields())); + } + if (!payload->getReportedFields().empty()) { + result["reported_fields"] = valueRef(convertFieldListToLua(payload->getReportedFields())); + } + + if (!payload->getItems().empty()) { + Lua::Array luaItems; + foreach(const Form::FormItem& item, payload->getItems()) { + if (!item.empty()) { + luaItems.push_back(convertFieldListToLua(item)); + } + } + result["items"] = valueRef(luaItems); + } + + Lua::pushValue(L, result); + + lua_newtable(L); + lua_pushcfunction(L, formIndex); + lua_setfield(L, -2, "__index"); + lua_pushcfunction(L, formNewIndex); + lua_setfield(L, -2, "__newindex"); + lua_setmetatable(L, -2); + } + + int createSubmission(lua_State* L) { + boost::shared_ptr form = convertFormFromLua(L); + + // Remove all redundant elements + form->setInstructions(""); + form->setTitle(""); + form->clearItems(); + form->clearReportedFields(); + std::vector< boost::shared_ptr > fields(form->getFields()); + form->clearFields(); + foreach (boost::shared_ptr field, fields) { + if (field->getType() == FormField::FixedType) { + continue; + } + field->clearOptions(); + field->setLabel(""); + field->setType(FormField::UnknownType); + field->setDescription(""); + form->addField(field); + } + form->setType(Form::SubmitType); + + // Convert back + convertFormToLua(L, form); + Lua::registerTableToString(L, -1); + + return 1; + } } FormConvertor::FormConvertor() : GenericLuaElementConvertor("form") { @@ -351,13 +351,13 @@ FormConvertor::~FormConvertor() { } boost::shared_ptr FormConvertor::doConvertFromLua(lua_State* L) { - return convertFormFromLua(L); + return convertFormFromLua(L); } void FormConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - convertFormToLua(L, payload); + convertFormToLua(L, payload); - lua_pushstring(L, "create_submission"); - lua_pushcfunction(L, createSubmission); - lua_rawset(L, -3); + lua_pushstring(L, "create_submission"); + lua_pushcfunction(L, createSubmission); + lua_rawset(L, -3); } diff --git a/Sluift/ElementConvertors/FormConvertor.h b/Sluift/ElementConvertors/FormConvertor.h index af9020d..05ca57f 100644 --- a/Sluift/ElementConvertors/FormConvertor.h +++ b/Sluift/ElementConvertors/FormConvertor.h @@ -12,12 +12,12 @@ #include namespace Swift { - class FormConvertor : public GenericLuaElementConvertor { - public: - FormConvertor(); - virtual ~FormConvertor(); + class FormConvertor : public GenericLuaElementConvertor { + public: + FormConvertor(); + virtual ~FormConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/ForwardedConvertor.cpp b/Sluift/ElementConvertors/ForwardedConvertor.cpp index a1f53a3..82539bb 100644 --- a/Sluift/ElementConvertors/ForwardedConvertor.cpp +++ b/Sluift/ElementConvertors/ForwardedConvertor.cpp @@ -21,54 +21,54 @@ using namespace Swift; -ForwardedConvertor::ForwardedConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("forwarded"), - convertors(convertors) { +ForwardedConvertor::ForwardedConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("forwarded"), + convertors(convertors) { } ForwardedConvertor::~ForwardedConvertor() { } boost::shared_ptr ForwardedConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "delay"); - if (!lua_isnil(L, -1)) { - boost::shared_ptr delay = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "delay")); - if (!!delay) { - result->setDelay(delay); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "stanza"); - if (!lua_isnil(L, -1)) { - boost::shared_ptr stanza = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1)); - if (!!stanza) { - result->setStanza(stanza); - } - lua_pop(L, 1); - return result; - } - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "delay"); + if (!lua_isnil(L, -1)) { + boost::shared_ptr delay = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "delay")); + if (!!delay) { + result->setDelay(delay); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "stanza"); + if (!lua_isnil(L, -1)) { + boost::shared_ptr stanza = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1)); + if (!!stanza) { + result->setStanza(stanza); + } + lua_pop(L, 1); + return result; + } + return result; } void ForwardedConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (convertors->convertToLuaUntyped(L, payload->getDelay()) > 0) { - lua_setfield(L, -2, "delay"); - } - boost::shared_ptr stanza = payload->getStanza(); - if (!!stanza) { - if (convertors->convertToLua(L, stanza) > 0) { - lua_setfield(L, -2, "stanza"); - } - } + lua_createtable(L, 0, 0); + if (convertors->convertToLuaUntyped(L, payload->getDelay()) > 0) { + lua_setfield(L, -2, "delay"); + } + boost::shared_ptr stanza = payload->getStanza(); + if (!!stanza) { + if (convertors->convertToLua(L, stanza) > 0) { + lua_setfield(L, -2, "stanza"); + } + } } boost::optional ForwardedConvertor::getDocumentation() const { - return Documentation( - "Forwarded", - "This table has the following fields:\n\n" - "- `delay`: @{Delay} (Optional)\n" - "- `stanza`: @{Stanza} (Optional)\n" - ); + return Documentation( + "Forwarded", + "This table has the following fields:\n\n" + "- `delay`: @{Delay} (Optional)\n" + "- `stanza`: @{Stanza} (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/ForwardedConvertor.h b/Sluift/ElementConvertors/ForwardedConvertor.h index 6c4848a..ee022fa 100644 --- a/Sluift/ElementConvertors/ForwardedConvertor.h +++ b/Sluift/ElementConvertors/ForwardedConvertor.h @@ -12,20 +12,20 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class ForwardedConvertor : public GenericLuaElementConvertor { - public: - ForwardedConvertor(LuaElementConvertors* convertors); - virtual ~ForwardedConvertor(); + class ForwardedConvertor : public GenericLuaElementConvertor { + public: + ForwardedConvertor(LuaElementConvertors* convertors); + virtual ~ForwardedConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - private: - LuaElementConvertors* convertors; - }; + private: + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/IQConvertor.cpp b/Sluift/ElementConvertors/IQConvertor.cpp index 019ec57..7e2cb7e 100644 --- a/Sluift/ElementConvertors/IQConvertor.cpp +++ b/Sluift/ElementConvertors/IQConvertor.cpp @@ -14,62 +14,62 @@ using namespace Swift; -IQConvertor::IQConvertor(LuaElementConvertors* convertors) : - StanzaConvertor("iq"), - convertors(convertors) { +IQConvertor::IQConvertor(LuaElementConvertors* convertors) : + StanzaConvertor("iq"), + convertors(convertors) { } IQConvertor::~IQConvertor() { } boost::shared_ptr IQConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = getStanza(L, convertors); - lua_getfield(L, -1, "type"); - if (lua_isstring(L, -1)) { - result->setType(IQConvertor::convertIQTypeFromString(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = getStanza(L, convertors); + lua_getfield(L, -1, "type"); + if (lua_isstring(L, -1)) { + result->setType(IQConvertor::convertIQTypeFromString(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void IQConvertor::doConvertToLua(lua_State* L, boost::shared_ptr stanza) { - pushStanza(L, stanza, convertors); - const std::string type = IQConvertor::convertIQTypeToString(stanza->getType()); - lua_pushstring(L, type.c_str()); - lua_setfield(L, -2, "type"); + pushStanza(L, stanza, convertors); + const std::string type = IQConvertor::convertIQTypeToString(stanza->getType()); + lua_pushstring(L, type.c_str()); + lua_setfield(L, -2, "type"); } boost::optional IQConvertor::getDocumentation() const { - return Documentation( - "IQ", - "This table has the following fields:\n\n" - "- `type`: string\n" - "- `id`: string\n" - "- `from`: string\n" - "- `to`: string\n" - "- `payloads`: array<@{Payload}>\n" - ); + return Documentation( + "IQ", + "This table has the following fields:\n\n" + "- `type`: string\n" + "- `id`: string\n" + "- `from`: string\n" + "- `to`: string\n" + "- `payloads`: array<@{Payload}>\n" + ); } std::string IQConvertor::convertIQTypeToString(IQ::Type type) { - switch (type) { - case IQ::Get: return "get"; - case IQ::Set: return "set"; - case IQ::Result: return "result"; - case IQ::Error: return "error"; - } - assert(false); - return ""; + switch (type) { + case IQ::Get: return "get"; + case IQ::Set: return "set"; + case IQ::Result: return "result"; + case IQ::Error: return "error"; + } + assert(false); + return ""; } IQ::Type IQConvertor::convertIQTypeFromString(const std::string& type) { - if (type == "get") { - return IQ::Get; - } - else if (type == "set") { - return IQ::Set; - } - else { - throw Lua::Exception("Illegal query type: '" + type + "'"); - } + if (type == "get") { + return IQ::Get; + } + else if (type == "set") { + return IQ::Set; + } + else { + throw Lua::Exception("Illegal query type: '" + type + "'"); + } } diff --git a/Sluift/ElementConvertors/IQConvertor.h b/Sluift/ElementConvertors/IQConvertor.h index 68bda38..49896e7 100644 --- a/Sluift/ElementConvertors/IQConvertor.h +++ b/Sluift/ElementConvertors/IQConvertor.h @@ -12,23 +12,23 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class IQConvertor : public StanzaConvertor { - public: - IQConvertor(LuaElementConvertors* convertors); - virtual ~IQConvertor(); + class IQConvertor : public StanzaConvertor { + public: + IQConvertor(LuaElementConvertors* convertors); + virtual ~IQConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - static std::string convertIQTypeToString(IQ::Type type); - static IQ::Type convertIQTypeFromString(const std::string& type); + static std::string convertIQTypeToString(IQ::Type type); + static IQ::Type convertIQTypeFromString(const std::string& type); - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp index bb1de94..e256dc7 100644 --- a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp +++ b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.cpp @@ -14,37 +14,37 @@ using namespace Swift; -IsodeIQDelegationConvertor::IsodeIQDelegationConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("isode_iq_delegation"), - convertors(convertors) { +IsodeIQDelegationConvertor::IsodeIQDelegationConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("isode_iq_delegation"), + convertors(convertors) { } IsodeIQDelegationConvertor::~IsodeIQDelegationConvertor() { } boost::shared_ptr IsodeIQDelegationConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "forward"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "forwarded"))) { - result->setForward(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "forward"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "forwarded"))) { + result->setForward(payload); + } + } + lua_pop(L, 1); + return result; } void IsodeIQDelegationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (convertors->convertToLuaUntyped(L, payload->getForward()) > 0) { - lua_setfield(L, -2, "forward"); - } + lua_createtable(L, 0, 0); + if (convertors->convertToLuaUntyped(L, payload->getForward()) > 0) { + lua_setfield(L, -2, "forward"); + } } boost::optional IsodeIQDelegationConvertor::getDocumentation() const { - return Documentation( - "IsodeIQDelegation", - "This table has the following fields:\n\n" - "- `forward`: @{Forwarded}\n" - ); + return Documentation( + "IsodeIQDelegation", + "This table has the following fields:\n\n" + "- `forward`: @{Forwarded}\n" + ); } diff --git a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h index bcbeb40..9fa005b 100644 --- a/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h +++ b/Sluift/ElementConvertors/IsodeIQDelegationConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class IsodeIQDelegationConvertor : public GenericLuaElementConvertor { - public: - IsodeIQDelegationConvertor(LuaElementConvertors* convertors); - virtual ~IsodeIQDelegationConvertor(); + class IsodeIQDelegationConvertor : public GenericLuaElementConvertor { + public: + IsodeIQDelegationConvertor(LuaElementConvertors* convertors); + virtual ~IsodeIQDelegationConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/MAMFinConvertor.cpp b/Sluift/ElementConvertors/MAMFinConvertor.cpp index 977dbc9..1bb6c05 100644 --- a/Sluift/ElementConvertors/MAMFinConvertor.cpp +++ b/Sluift/ElementConvertors/MAMFinConvertor.cpp @@ -17,64 +17,64 @@ using namespace Swift; -MAMFinConvertor::MAMFinConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("mam_fin"), - convertors(convertors) { +MAMFinConvertor::MAMFinConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("mam_fin"), + convertors(convertors) { } MAMFinConvertor::~MAMFinConvertor() { } boost::shared_ptr MAMFinConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "query_id"); - if (lua_isstring(L, -1)) { - result->setQueryID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "complete"); - if (lua_isboolean(L, -1)) { - result->setComplete(lua_toboolean(L, -1) != 0); - } - lua_pop(L, 1); - lua_getfield(L, -1, "stable"); - if (!lua_isnil(L, -1)) { - result->setStable(lua_toboolean(L, -1) != 0); - } - lua_pop(L, 1); - lua_getfield(L, -1, "result_set"); - if (!lua_isnil(L, -1)) { - boost::shared_ptr resultSet = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "result_set")); - if (!!resultSet) { - result->setResultSet(resultSet); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "query_id"); + if (lua_isstring(L, -1)) { + result->setQueryID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "complete"); + if (lua_isboolean(L, -1)) { + result->setComplete(lua_toboolean(L, -1) != 0); + } + lua_pop(L, 1); + lua_getfield(L, -1, "stable"); + if (!lua_isnil(L, -1)) { + result->setStable(lua_toboolean(L, -1) != 0); + } + lua_pop(L, 1); + lua_getfield(L, -1, "result_set"); + if (!lua_isnil(L, -1)) { + boost::shared_ptr resultSet = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "result_set")); + if (!!resultSet) { + result->setResultSet(resultSet); + } + } + lua_pop(L, 1); + return result; } void MAMFinConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getQueryID()) { - lua_pushstring(L, (*payload->getQueryID()).c_str()); - lua_setfield(L, -2, "query_id"); - } - lua_pushboolean(L, payload->isComplete()); - lua_setfield(L, -2, "complete"); - lua_pushboolean(L, payload->isStable()); - lua_setfield(L, -2, "stable"); - if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) { - lua_setfield(L, -2, "result_set"); - } + lua_createtable(L, 0, 0); + if (payload->getQueryID()) { + lua_pushstring(L, (*payload->getQueryID()).c_str()); + lua_setfield(L, -2, "query_id"); + } + lua_pushboolean(L, payload->isComplete()); + lua_setfield(L, -2, "complete"); + lua_pushboolean(L, payload->isStable()); + lua_setfield(L, -2, "stable"); + if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) { + lua_setfield(L, -2, "result_set"); + } } boost::optional MAMFinConvertor::getDocumentation() const { - return Documentation( - "MAMFin", - "This table has the following fields:\n\n" - "- `query_id`: string (Optional)\n" - "- `complete`: boolean (Optional)\n" - "- `stable`: boolean (Optional)\n" - "- `result_set`: @{ResultSet} (Optional)\n" - ); + return Documentation( + "MAMFin", + "This table has the following fields:\n\n" + "- `query_id`: string (Optional)\n" + "- `complete`: boolean (Optional)\n" + "- `stable`: boolean (Optional)\n" + "- `result_set`: @{ResultSet} (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/MAMFinConvertor.h b/Sluift/ElementConvertors/MAMFinConvertor.h index 1727403..9345aeb 100644 --- a/Sluift/ElementConvertors/MAMFinConvertor.h +++ b/Sluift/ElementConvertors/MAMFinConvertor.h @@ -12,19 +12,19 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class MAMFinConvertor : public GenericLuaElementConvertor { - public: - MAMFinConvertor(LuaElementConvertors* convertors); - virtual ~MAMFinConvertor(); + class MAMFinConvertor : public GenericLuaElementConvertor { + public: + MAMFinConvertor(LuaElementConvertors* convertors); + virtual ~MAMFinConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/MAMQueryConvertor.cpp b/Sluift/ElementConvertors/MAMQueryConvertor.cpp index 89a8876..a52abd9 100644 --- a/Sluift/ElementConvertors/MAMQueryConvertor.cpp +++ b/Sluift/ElementConvertors/MAMQueryConvertor.cpp @@ -18,70 +18,70 @@ using namespace Swift; -MAMQueryConvertor::MAMQueryConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("mam"), - convertors(convertors) { +MAMQueryConvertor::MAMQueryConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("mam"), + convertors(convertors) { } MAMQueryConvertor::~MAMQueryConvertor() { } boost::shared_ptr MAMQueryConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "query_id"); - if (lua_isstring(L, -1)) { - result->setQueryID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "form"); - if (!lua_isnil(L, -1)) { - boost::shared_ptr form = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form")); - if (!!form) { - result->setForm(form); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "result_set"); - if (!lua_isnil(L, -1)) { - boost::shared_ptr resultSet = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "result_set")); - if (!!resultSet) { - result->setResultSet(resultSet); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "query_id"); + if (lua_isstring(L, -1)) { + result->setQueryID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "form"); + if (!lua_isnil(L, -1)) { + boost::shared_ptr form = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form")); + if (!!form) { + result->setForm(form); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "result_set"); + if (!lua_isnil(L, -1)) { + boost::shared_ptr resultSet = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "result_set")); + if (!!resultSet) { + result->setResultSet(resultSet); + } + } + lua_pop(L, 1); + return result; } void MAMQueryConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getQueryID()) { - lua_pushstring(L, (*payload->getQueryID()).c_str()); - lua_setfield(L, -2, "query_id"); - } - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - if (convertors->convertToLuaUntyped(L, payload->getForm()) > 0) { - lua_setfield(L, -2, "form"); - } - if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) { - lua_setfield(L, -2, "result_set"); - } + lua_createtable(L, 0, 0); + if (payload->getQueryID()) { + lua_pushstring(L, (*payload->getQueryID()).c_str()); + lua_setfield(L, -2, "query_id"); + } + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + if (convertors->convertToLuaUntyped(L, payload->getForm()) > 0) { + lua_setfield(L, -2, "form"); + } + if (convertors->convertToLuaUntyped(L, payload->getResultSet()) > 0) { + lua_setfield(L, -2, "result_set"); + } } boost::optional MAMQueryConvertor::getDocumentation() const { - return Documentation( - "MAMQuery", - "This table has the following fields:\n\n" - "- `query_id`: string (Optional)\n" - "- `node`: string (Optional)\n" - "- `form`: string @{Form} (Optional)\n" - "- `result_set`: @{ResultSet} (Optional)\n" - ); + return Documentation( + "MAMQuery", + "This table has the following fields:\n\n" + "- `query_id`: string (Optional)\n" + "- `node`: string (Optional)\n" + "- `form`: string @{Form} (Optional)\n" + "- `result_set`: @{ResultSet} (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/MAMQueryConvertor.h b/Sluift/ElementConvertors/MAMQueryConvertor.h index e839a24..54a99e0 100644 --- a/Sluift/ElementConvertors/MAMQueryConvertor.h +++ b/Sluift/ElementConvertors/MAMQueryConvertor.h @@ -12,19 +12,19 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class MAMQueryConvertor : public GenericLuaElementConvertor { - public: - MAMQueryConvertor(LuaElementConvertors* convertors); - virtual ~MAMQueryConvertor(); + class MAMQueryConvertor : public GenericLuaElementConvertor { + public: + MAMQueryConvertor(LuaElementConvertors* convertors); + virtual ~MAMQueryConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/MAMResultConvertor.cpp b/Sluift/ElementConvertors/MAMResultConvertor.cpp index 02c5976..2260eb1 100644 --- a/Sluift/ElementConvertors/MAMResultConvertor.cpp +++ b/Sluift/ElementConvertors/MAMResultConvertor.cpp @@ -17,56 +17,56 @@ using namespace Swift; -MAMResultConvertor::MAMResultConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("mam_result"), - convertors(convertors) { +MAMResultConvertor::MAMResultConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("mam_result"), + convertors(convertors) { } MAMResultConvertor::~MAMResultConvertor() { } boost::shared_ptr MAMResultConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "payload"); - if (!lua_isnil(L, -1)) { - boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "payload")); - if (!!payload) { - result->setPayload(payload); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "id"); - if (lua_isstring(L, -1)) { - result->setID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "query_id"); - if (lua_isstring(L, -1)) { - result->setQueryID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "payload"); + if (!lua_isnil(L, -1)) { + boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "payload")); + if (!!payload) { + result->setPayload(payload); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "id"); + if (lua_isstring(L, -1)) { + result->setID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "query_id"); + if (lua_isstring(L, -1)) { + result->setQueryID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void MAMResultConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (convertors->convertToLuaUntyped(L, payload->getPayload()) > 0) { - lua_setfield(L, -2, "payload"); - } - lua_pushstring(L, payload->getID().c_str()); - lua_setfield(L, -2, "id"); - if (payload->getQueryID()) { - lua_pushstring(L, (*payload->getQueryID()).c_str()); - lua_setfield(L, -2, "query_id"); - } + lua_createtable(L, 0, 0); + if (convertors->convertToLuaUntyped(L, payload->getPayload()) > 0) { + lua_setfield(L, -2, "payload"); + } + lua_pushstring(L, payload->getID().c_str()); + lua_setfield(L, -2, "id"); + if (payload->getQueryID()) { + lua_pushstring(L, (*payload->getQueryID()).c_str()); + lua_setfield(L, -2, "query_id"); + } } boost::optional MAMResultConvertor::getDocumentation() const { - return Documentation( - "MAMResult", - "This table has the following fields:\n\n" - "- `payload`: @{Forwarded}\n" - "- `id`: string\n" - "- `query_id`: string (Optional)\n" - ); + return Documentation( + "MAMResult", + "This table has the following fields:\n\n" + "- `payload`: @{Forwarded}\n" + "- `id`: string\n" + "- `query_id`: string (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/MAMResultConvertor.h b/Sluift/ElementConvertors/MAMResultConvertor.h index 49b14e2..c1ddf31 100644 --- a/Sluift/ElementConvertors/MAMResultConvertor.h +++ b/Sluift/ElementConvertors/MAMResultConvertor.h @@ -12,19 +12,19 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class MAMResultConvertor : public GenericLuaElementConvertor { - public: - MAMResultConvertor(LuaElementConvertors* convertors); - virtual ~MAMResultConvertor(); + class MAMResultConvertor : public GenericLuaElementConvertor { + public: + MAMResultConvertor(LuaElementConvertors* convertors); + virtual ~MAMResultConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/MessageConvertor.cpp b/Sluift/ElementConvertors/MessageConvertor.cpp index 52b3b90..c9285ef 100644 --- a/Sluift/ElementConvertors/MessageConvertor.cpp +++ b/Sluift/ElementConvertors/MessageConvertor.cpp @@ -14,72 +14,72 @@ using namespace Swift; -MessageConvertor::MessageConvertor(LuaElementConvertors* convertors) : - StanzaConvertor("message"), - convertors(convertors) { +MessageConvertor::MessageConvertor(LuaElementConvertors* convertors) : + StanzaConvertor("message"), + convertors(convertors) { } MessageConvertor::~MessageConvertor() { } boost::shared_ptr MessageConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = getStanza(L, convertors); - lua_getfield(L, -1, "type"); - if (lua_isstring(L, -1)) { - result->setType(convertMessageTypeFromString(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = getStanza(L, convertors); + lua_getfield(L, -1, "type"); + if (lua_isstring(L, -1)) { + result->setType(convertMessageTypeFromString(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void MessageConvertor::doConvertToLua(lua_State* L, boost::shared_ptr stanza) { - pushStanza(L, stanza, convertors); - const std::string type = convertMessageTypeToString(stanza->getType()); - lua_pushstring(L, type.c_str()); - lua_setfield(L, -2, "type"); + pushStanza(L, stanza, convertors); + const std::string type = convertMessageTypeToString(stanza->getType()); + lua_pushstring(L, type.c_str()); + lua_setfield(L, -2, "type"); } boost::optional MessageConvertor::getDocumentation() const { - return Documentation( - "Message", - "This table has the following fields:\n\n" - "- `type`: string\n" - "- `id`: string\n" - "- `from`: string\n" - "- `to`: string\n" - "- `payloads`: array<@{Payload}>\n" - ); + return Documentation( + "Message", + "This table has the following fields:\n\n" + "- `type`: string\n" + "- `id`: string\n" + "- `from`: string\n" + "- `to`: string\n" + "- `payloads`: array<@{Payload}>\n" + ); } std::string MessageConvertor::convertMessageTypeToString(Message::Type type) { - switch (type) { - case Message::Normal: return "normal"; - case Message::Chat: return "chat"; - case Message::Error: return "error"; - case Message::Groupchat: return "groupchat"; - case Message::Headline: return "headline"; - } - assert(false); - return ""; + switch (type) { + case Message::Normal: return "normal"; + case Message::Chat: return "chat"; + case Message::Error: return "error"; + case Message::Groupchat: return "groupchat"; + case Message::Headline: return "headline"; + } + assert(false); + return ""; } Message::Type MessageConvertor::convertMessageTypeFromString(const std::string& type) { - if (type == "normal") { - return Message::Normal; - } - else if (type == "chat") { - return Message::Chat; - } - else if (type == "error") { - return Message::Error; - } - else if (type == "groupchat") { - return Message::Groupchat; - } - else if (type == "headline") { - return Message::Headline; - } - else { - throw Lua::Exception("Illegal message type: '" + type + "'"); - } + if (type == "normal") { + return Message::Normal; + } + else if (type == "chat") { + return Message::Chat; + } + else if (type == "error") { + return Message::Error; + } + else if (type == "groupchat") { + return Message::Groupchat; + } + else if (type == "headline") { + return Message::Headline; + } + else { + throw Lua::Exception("Illegal message type: '" + type + "'"); + } } diff --git a/Sluift/ElementConvertors/MessageConvertor.h b/Sluift/ElementConvertors/MessageConvertor.h index 92efea3..e05e00e 100644 --- a/Sluift/ElementConvertors/MessageConvertor.h +++ b/Sluift/ElementConvertors/MessageConvertor.h @@ -12,23 +12,23 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class MessageConvertor : public StanzaConvertor { - public: - MessageConvertor(LuaElementConvertors* convertors); - virtual ~MessageConvertor(); + class MessageConvertor : public StanzaConvertor { + public: + MessageConvertor(LuaElementConvertors* convertors); + virtual ~MessageConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - static std::string convertMessageTypeToString(Message::Type type); - static Message::Type convertMessageTypeFromString(const std::string& type); + static std::string convertMessageTypeToString(Message::Type type); + static Message::Type convertMessageTypeFromString(const std::string& type); - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PresenceConvertor.cpp b/Sluift/ElementConvertors/PresenceConvertor.cpp index edf3941..1b423cc 100644 --- a/Sluift/ElementConvertors/PresenceConvertor.cpp +++ b/Sluift/ElementConvertors/PresenceConvertor.cpp @@ -14,84 +14,84 @@ using namespace Swift; -PresenceConvertor::PresenceConvertor(LuaElementConvertors* convertors) : - StanzaConvertor("presence"), - convertors(convertors) { +PresenceConvertor::PresenceConvertor(LuaElementConvertors* convertors) : + StanzaConvertor("presence"), + convertors(convertors) { } PresenceConvertor::~PresenceConvertor() { } boost::shared_ptr PresenceConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = getStanza(L, convertors); - lua_getfield(L, -1, "type"); - if (lua_isstring(L, -1)) { - result->setType(convertPresenceTypeFromString(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = getStanza(L, convertors); + lua_getfield(L, -1, "type"); + if (lua_isstring(L, -1)) { + result->setType(convertPresenceTypeFromString(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PresenceConvertor::doConvertToLua(lua_State* L, boost::shared_ptr stanza) { - pushStanza(L, stanza, convertors); - const std::string type = convertPresenceTypeToString(stanza->getType()); - lua_pushstring(L, type.c_str()); - lua_setfield(L, -2, "type"); + pushStanza(L, stanza, convertors); + const std::string type = convertPresenceTypeToString(stanza->getType()); + lua_pushstring(L, type.c_str()); + lua_setfield(L, -2, "type"); } boost::optional PresenceConvertor::getDocumentation() const { - return Documentation( - "Presence", - "This table has the following fields:\n\n" - "- `type`: string\n" - "- `id`: string\n" - "- `from`: string\n" - "- `to`: string\n" - "- `payloads`: array<@{Payload}>\n" - ); + return Documentation( + "Presence", + "This table has the following fields:\n\n" + "- `type`: string\n" + "- `id`: string\n" + "- `from`: string\n" + "- `to`: string\n" + "- `payloads`: array<@{Payload}>\n" + ); } std::string PresenceConvertor::convertPresenceTypeToString(Presence::Type type) { - switch (type) { - case Presence::Available: return "available"; - case Presence::Error: return "error"; - case Presence::Probe: return "probe"; - case Presence::Subscribe: return "subscribe"; - case Presence::Subscribed: return "subscribed"; - case Presence::Unavailable: return "unavailable"; - case Presence::Unsubscribe: return "unsubscribe"; - case Presence::Unsubscribed: return "unsubscribed"; - } - assert(false); - return ""; + switch (type) { + case Presence::Available: return "available"; + case Presence::Error: return "error"; + case Presence::Probe: return "probe"; + case Presence::Subscribe: return "subscribe"; + case Presence::Subscribed: return "subscribed"; + case Presence::Unavailable: return "unavailable"; + case Presence::Unsubscribe: return "unsubscribe"; + case Presence::Unsubscribed: return "unsubscribed"; + } + assert(false); + return ""; } Presence::Type PresenceConvertor::convertPresenceTypeFromString(const std::string& type) { - if (type == "available") { - return Presence::Available; - } - else if (type == "error") { - return Presence::Error; - } - else if (type == "probe") { - return Presence::Probe; - } - else if (type == "subscribe") { - return Presence::Subscribe; - } - else if (type == "subscribed") { - return Presence::Subscribed; - } - else if (type == "unavailable") { - return Presence::Unavailable; - } - else if (type == "unsubscribe") { - return Presence::Unsubscribe; - } - else if (type == "unsubscribed") { - return Presence::Unsubscribed; - } - else { - throw Lua::Exception("Illegal presence type: '" + type + "'"); - } + if (type == "available") { + return Presence::Available; + } + else if (type == "error") { + return Presence::Error; + } + else if (type == "probe") { + return Presence::Probe; + } + else if (type == "subscribe") { + return Presence::Subscribe; + } + else if (type == "subscribed") { + return Presence::Subscribed; + } + else if (type == "unavailable") { + return Presence::Unavailable; + } + else if (type == "unsubscribe") { + return Presence::Unsubscribe; + } + else if (type == "unsubscribed") { + return Presence::Unsubscribed; + } + else { + throw Lua::Exception("Illegal presence type: '" + type + "'"); + } } diff --git a/Sluift/ElementConvertors/PresenceConvertor.h b/Sluift/ElementConvertors/PresenceConvertor.h index c919f3a..ae2e78a 100644 --- a/Sluift/ElementConvertors/PresenceConvertor.h +++ b/Sluift/ElementConvertors/PresenceConvertor.h @@ -12,23 +12,23 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PresenceConvertor : public StanzaConvertor { - public: - PresenceConvertor(LuaElementConvertors* convertors); - virtual ~PresenceConvertor(); + class PresenceConvertor : public StanzaConvertor { + public: + PresenceConvertor(LuaElementConvertors* convertors); + virtual ~PresenceConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - static std::string convertPresenceTypeToString(Presence::Type type); - static Presence::Type convertPresenceTypeFromString(const std::string& type); + static std::string convertPresenceTypeToString(Presence::Type type); + static Presence::Type convertPresenceTypeFromString(const std::string& type); - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp b/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp index 717d01c..84d8f55 100644 --- a/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubAffiliationConvertor.cpp @@ -13,76 +13,76 @@ using namespace Swift; PubSubAffiliationConvertor::PubSubAffiliationConvertor() : - GenericLuaElementConvertor("pubsub_affiliation") { + GenericLuaElementConvertor("pubsub_affiliation") { } PubSubAffiliationConvertor::~PubSubAffiliationConvertor() { } boost::shared_ptr PubSubAffiliationConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "type"); - if (lua_isstring(L, -1)) { - if (std::string(lua_tostring(L, -1)) == "none") { - result->setType(PubSubAffiliation::None); - } - if (std::string(lua_tostring(L, -1)) == "member") { - result->setType(PubSubAffiliation::Member); - } - if (std::string(lua_tostring(L, -1)) == "outcast") { - result->setType(PubSubAffiliation::Outcast); - } - if (std::string(lua_tostring(L, -1)) == "owner") { - result->setType(PubSubAffiliation::Owner); - } - if (std::string(lua_tostring(L, -1)) == "publisher") { - result->setType(PubSubAffiliation::Publisher); - } - if (std::string(lua_tostring(L, -1)) == "publish_only") { - result->setType(PubSubAffiliation::PublishOnly); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "type"); + if (lua_isstring(L, -1)) { + if (std::string(lua_tostring(L, -1)) == "none") { + result->setType(PubSubAffiliation::None); + } + if (std::string(lua_tostring(L, -1)) == "member") { + result->setType(PubSubAffiliation::Member); + } + if (std::string(lua_tostring(L, -1)) == "outcast") { + result->setType(PubSubAffiliation::Outcast); + } + if (std::string(lua_tostring(L, -1)) == "owner") { + result->setType(PubSubAffiliation::Owner); + } + if (std::string(lua_tostring(L, -1)) == "publisher") { + result->setType(PubSubAffiliation::Publisher); + } + if (std::string(lua_tostring(L, -1)) == "publish_only") { + result->setType(PubSubAffiliation::PublishOnly); + } + } + lua_pop(L, 1); + return result; } void PubSubAffiliationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - switch (payload->getType()) { - case PubSubAffiliation::None: - lua_pushstring(L, "none"); - break; - case PubSubAffiliation::Member: - lua_pushstring(L, "member"); - break; - case PubSubAffiliation::Outcast: - lua_pushstring(L, "outcast"); - break; - case PubSubAffiliation::Owner: - lua_pushstring(L, "owner"); - break; - case PubSubAffiliation::Publisher: - lua_pushstring(L, "publisher"); - break; - case PubSubAffiliation::PublishOnly: - lua_pushstring(L, "publish_only"); - break; - } - lua_setfield(L, -2, "type"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + switch (payload->getType()) { + case PubSubAffiliation::None: + lua_pushstring(L, "none"); + break; + case PubSubAffiliation::Member: + lua_pushstring(L, "member"); + break; + case PubSubAffiliation::Outcast: + lua_pushstring(L, "outcast"); + break; + case PubSubAffiliation::Owner: + lua_pushstring(L, "owner"); + break; + case PubSubAffiliation::Publisher: + lua_pushstring(L, "publisher"); + break; + case PubSubAffiliation::PublishOnly: + lua_pushstring(L, "publish_only"); + break; + } + lua_setfield(L, -2, "type"); } boost::optional PubSubAffiliationConvertor::getDocumentation() const { - return Documentation( - "PubSubAffiliation", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n" - ); + return Documentation( + "PubSubAffiliation", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubAffiliationConvertor.h b/Sluift/ElementConvertors/PubSubAffiliationConvertor.h index 7faf9e5..e91342c 100644 --- a/Sluift/ElementConvertors/PubSubAffiliationConvertor.h +++ b/Sluift/ElementConvertors/PubSubAffiliationConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubAffiliationConvertor : public GenericLuaElementConvertor { - public: - PubSubAffiliationConvertor(); - virtual ~PubSubAffiliationConvertor(); + class PubSubAffiliationConvertor : public GenericLuaElementConvertor { + public: + PubSubAffiliationConvertor(); + virtual ~PubSubAffiliationConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp index e0d003c..f5eab7a 100644 --- a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.cpp @@ -17,63 +17,63 @@ using namespace Swift; -PubSubAffiliationsConvertor::PubSubAffiliationsConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_affiliations"), - convertors(convertors) { +PubSubAffiliationsConvertor::PubSubAffiliationsConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_affiliations"), + convertors(convertors) { } PubSubAffiliationsConvertor::~PubSubAffiliationsConvertor() { } boost::shared_ptr PubSubAffiliationsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_affiliation"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_affiliation"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setAffiliations(items); - } - return result; + result->setAffiliations(items); + } + return result; } void PubSubAffiliationsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - if (!payload->getAffiliations().empty()) { - { - int i = 0; - foreach(boost::shared_ptr item, payload->getAffiliations()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - } + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + if (!payload->getAffiliations().empty()) { + { + int i = 0; + foreach(boost::shared_ptr item, payload->getAffiliations()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + } } boost::optional PubSubAffiliationsConvertor::getDocumentation() const { - return Documentation( - "PubSubAffiliations", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `affiliations`: array<@{PubSubAffiliation}>\n" - ); + return Documentation( + "PubSubAffiliations", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `affiliations`: array<@{PubSubAffiliation}>\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h index b98ff4c..965fb2a 100644 --- a/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h +++ b/Sluift/ElementConvertors/PubSubAffiliationsConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubAffiliationsConvertor : public GenericLuaElementConvertor { - public: - PubSubAffiliationsConvertor(LuaElementConvertors* convertors); - virtual ~PubSubAffiliationsConvertor(); + class PubSubAffiliationsConvertor : public GenericLuaElementConvertor { + public: + PubSubAffiliationsConvertor(LuaElementConvertors* convertors); + virtual ~PubSubAffiliationsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp b/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp index 9153d9e..13ffb7b 100644 --- a/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubConfigureConvertor.cpp @@ -14,37 +14,37 @@ using namespace Swift; -PubSubConfigureConvertor::PubSubConfigureConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_configure"), - convertors(convertors) { +PubSubConfigureConvertor::PubSubConfigureConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_configure"), + convertors(convertors) { } PubSubConfigureConvertor::~PubSubConfigureConvertor() { } boost::shared_ptr PubSubConfigureConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "data"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { - result->setData(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "data"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { + result->setData(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubConfigureConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { - lua_setfield(L, -2, "data"); - } + lua_createtable(L, 0, 0); + if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { + lua_setfield(L, -2, "data"); + } } boost::optional PubSubConfigureConvertor::getDocumentation() const { - return Documentation( - "PubSubConfigure", - "This table has the following fields:\n\n" - "- `data`: @{Form}\n" - ); + return Documentation( + "PubSubConfigure", + "This table has the following fields:\n\n" + "- `data`: @{Form}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubConfigureConvertor.h b/Sluift/ElementConvertors/PubSubConfigureConvertor.h index 27aa906..865d30a 100644 --- a/Sluift/ElementConvertors/PubSubConfigureConvertor.h +++ b/Sluift/ElementConvertors/PubSubConfigureConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubConfigureConvertor : public GenericLuaElementConvertor { - public: - PubSubConfigureConvertor(LuaElementConvertors* convertors); - virtual ~PubSubConfigureConvertor(); + class PubSubConfigureConvertor : public GenericLuaElementConvertor { + public: + PubSubConfigureConvertor(LuaElementConvertors* convertors); + virtual ~PubSubConfigureConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubCreateConvertor.cpp b/Sluift/ElementConvertors/PubSubCreateConvertor.cpp index af5056f..8a4086b 100644 --- a/Sluift/ElementConvertors/PubSubCreateConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubCreateConvertor.cpp @@ -14,45 +14,45 @@ using namespace Swift; -PubSubCreateConvertor::PubSubCreateConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_create"), - convertors(convertors) { +PubSubCreateConvertor::PubSubCreateConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_create"), + convertors(convertors) { } PubSubCreateConvertor::~PubSubCreateConvertor() { } boost::shared_ptr PubSubCreateConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "configure"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_configure"))) { - result->setConfigure(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "configure"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_configure"))) { + result->setConfigure(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubCreateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (convertors->convertToLuaUntyped(L, payload->getConfigure()) > 0) { - lua_setfield(L, -2, "configure"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (convertors->convertToLuaUntyped(L, payload->getConfigure()) > 0) { + lua_setfield(L, -2, "configure"); + } } boost::optional PubSubCreateConvertor::getDocumentation() const { - return Documentation( - "PubSubCreate", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `configure`: @{PubSubConfigure}\n" - ); + return Documentation( + "PubSubCreate", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `configure`: @{PubSubConfigure}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubCreateConvertor.h b/Sluift/ElementConvertors/PubSubCreateConvertor.h index bcf06af..189da27 100644 --- a/Sluift/ElementConvertors/PubSubCreateConvertor.h +++ b/Sluift/ElementConvertors/PubSubCreateConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubCreateConvertor : public GenericLuaElementConvertor { - public: - PubSubCreateConvertor(LuaElementConvertors* convertors); - virtual ~PubSubCreateConvertor(); + class PubSubCreateConvertor : public GenericLuaElementConvertor { + public: + PubSubCreateConvertor(LuaElementConvertors* convertors); + virtual ~PubSubCreateConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp b/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp index 43dcbe4..5f8fe24 100644 --- a/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubDefaultConvertor.cpp @@ -13,60 +13,60 @@ using namespace Swift; PubSubDefaultConvertor::PubSubDefaultConvertor() : - GenericLuaElementConvertor("pubsub_default") { + GenericLuaElementConvertor("pubsub_default") { } PubSubDefaultConvertor::~PubSubDefaultConvertor() { } boost::shared_ptr PubSubDefaultConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "type"); - if (lua_isstring(L, -1)) { - if (std::string(lua_tostring(L, -1)) == "none") { - result->setType(PubSubDefault::None); - } - if (std::string(lua_tostring(L, -1)) == "collection") { - result->setType(PubSubDefault::Collection); - } - if (std::string(lua_tostring(L, -1)) == "leaf") { - result->setType(PubSubDefault::Leaf); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "type"); + if (lua_isstring(L, -1)) { + if (std::string(lua_tostring(L, -1)) == "none") { + result->setType(PubSubDefault::None); + } + if (std::string(lua_tostring(L, -1)) == "collection") { + result->setType(PubSubDefault::Collection); + } + if (std::string(lua_tostring(L, -1)) == "leaf") { + result->setType(PubSubDefault::Leaf); + } + } + lua_pop(L, 1); + return result; } void PubSubDefaultConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - switch (payload->getType()) { - case PubSubDefault::None: - lua_pushstring(L, "none"); - break; - case PubSubDefault::Collection: - lua_pushstring(L, "collection"); - break; - case PubSubDefault::Leaf: - lua_pushstring(L, "leaf"); - break; - } - lua_setfield(L, -2, "type"); + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + switch (payload->getType()) { + case PubSubDefault::None: + lua_pushstring(L, "none"); + break; + case PubSubDefault::Collection: + lua_pushstring(L, "collection"); + break; + case PubSubDefault::Leaf: + lua_pushstring(L, "leaf"); + break; + } + lua_setfield(L, -2, "type"); } boost::optional PubSubDefaultConvertor::getDocumentation() const { - return Documentation( - "PubSubDefault", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `type`: `\"none\"`, `\"collection\"`, or `\"leaf\"`\n" - ); + return Documentation( + "PubSubDefault", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `type`: `\"none\"`, `\"collection\"`, or `\"leaf\"`\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubDefaultConvertor.h b/Sluift/ElementConvertors/PubSubDefaultConvertor.h index 2eeeaa1..968e03e 100644 --- a/Sluift/ElementConvertors/PubSubDefaultConvertor.h +++ b/Sluift/ElementConvertors/PubSubDefaultConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubDefaultConvertor : public GenericLuaElementConvertor { - public: - PubSubDefaultConvertor(); - virtual ~PubSubDefaultConvertor(); + class PubSubDefaultConvertor : public GenericLuaElementConvertor { + public: + PubSubDefaultConvertor(); + virtual ~PubSubDefaultConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp index fdfec29..bc43b93 100644 --- a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubEventAssociateConvertor::PubSubEventAssociateConvertor() : - GenericLuaElementConvertor("pubsub_event_associate") { + GenericLuaElementConvertor("pubsub_event_associate") { } PubSubEventAssociateConvertor::~PubSubEventAssociateConvertor() { } boost::shared_ptr PubSubEventAssociateConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubEventAssociateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); } boost::optional PubSubEventAssociateConvertor::getDocumentation() const { - return Documentation( - "PubSubEventAssociate", - "This table has the following fields:\n\n" - "- `node`: string\n" - ); + return Documentation( + "PubSubEventAssociate", + "This table has the following fields:\n\n" + "- `node`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h index 116947d..2ba3b40 100644 --- a/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventAssociateConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventAssociateConvertor : public GenericLuaElementConvertor { - public: - PubSubEventAssociateConvertor(); - virtual ~PubSubEventAssociateConvertor(); + class PubSubEventAssociateConvertor : public GenericLuaElementConvertor { + public: + PubSubEventAssociateConvertor(); + virtual ~PubSubEventAssociateConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp index 35eeda4..88c7419 100644 --- a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.cpp @@ -14,58 +14,58 @@ using namespace Swift; -PubSubEventCollectionConvertor::PubSubEventCollectionConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_event_collection"), - convertors(convertors) { +PubSubEventCollectionConvertor::PubSubEventCollectionConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_event_collection"), + convertors(convertors) { } PubSubEventCollectionConvertor::~PubSubEventCollectionConvertor() { } boost::shared_ptr PubSubEventCollectionConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "disassociate"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_disassociate"))) { - result->setDisassociate(payload); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "associate"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_associate"))) { - result->setAssociate(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "disassociate"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_disassociate"))) { + result->setDisassociate(payload); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "associate"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_associate"))) { + result->setAssociate(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubEventCollectionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - if (convertors->convertToLuaUntyped(L, payload->getDisassociate()) > 0) { - lua_setfield(L, -2, "disassociate"); - } - if (convertors->convertToLuaUntyped(L, payload->getAssociate()) > 0) { - lua_setfield(L, -2, "associate"); - } + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + if (convertors->convertToLuaUntyped(L, payload->getDisassociate()) > 0) { + lua_setfield(L, -2, "disassociate"); + } + if (convertors->convertToLuaUntyped(L, payload->getAssociate()) > 0) { + lua_setfield(L, -2, "associate"); + } } boost::optional PubSubEventCollectionConvertor::getDocumentation() const { - return Documentation( - "PubSubEventCollection", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `disassociate`: @{PubSubEventDisassociate}\n" - "- `associate`: @{PubSubEventAssociate}\n" - ); + return Documentation( + "PubSubEventCollection", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `disassociate`: @{PubSubEventDisassociate}\n" + "- `associate`: @{PubSubEventAssociate}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h index 38ffd64..7c11178 100644 --- a/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventCollectionConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventCollectionConvertor : public GenericLuaElementConvertor { - public: - PubSubEventCollectionConvertor(LuaElementConvertors* convertors); - virtual ~PubSubEventCollectionConvertor(); + class PubSubEventCollectionConvertor : public GenericLuaElementConvertor { + public: + PubSubEventCollectionConvertor(LuaElementConvertors* convertors); + virtual ~PubSubEventCollectionConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp index 72c15ae..2c149fa 100644 --- a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.cpp @@ -14,45 +14,45 @@ using namespace Swift; -PubSubEventConfigurationConvertor::PubSubEventConfigurationConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_event_configuration"), - convertors(convertors) { +PubSubEventConfigurationConvertor::PubSubEventConfigurationConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_event_configuration"), + convertors(convertors) { } PubSubEventConfigurationConvertor::~PubSubEventConfigurationConvertor() { } boost::shared_ptr PubSubEventConfigurationConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "data"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { - result->setData(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "data"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { + result->setData(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubEventConfigurationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { - lua_setfield(L, -2, "data"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { + lua_setfield(L, -2, "data"); + } } boost::optional PubSubEventConfigurationConvertor::getDocumentation() const { - return Documentation( - "PubSubEventConfiguration", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `data`: @{Form}\n" - ); + return Documentation( + "PubSubEventConfiguration", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `data`: @{Form}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h index 7e8ea02..e8a17e7 100644 --- a/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventConfigurationConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventConfigurationConvertor : public GenericLuaElementConvertor { - public: - PubSubEventConfigurationConvertor(LuaElementConvertors* convertors); - virtual ~PubSubEventConfigurationConvertor(); + class PubSubEventConfigurationConvertor : public GenericLuaElementConvertor { + public: + PubSubEventConfigurationConvertor(LuaElementConvertors* convertors); + virtual ~PubSubEventConfigurationConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventConvertor.cpp b/Sluift/ElementConvertors/PubSubEventConvertor.cpp index fa64e7f..2330bcc 100644 --- a/Sluift/ElementConvertors/PubSubEventConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventConvertor.cpp @@ -14,22 +14,22 @@ using namespace Swift; -PubSubEventConvertor::PubSubEventConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_event"), - convertors(convertors) { +PubSubEventConvertor::PubSubEventConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_event"), + convertors(convertors) { } PubSubEventConvertor::~PubSubEventConvertor() { } boost::shared_ptr PubSubEventConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1))) { - result->setPayload(payload); - } - return result; + boost::shared_ptr result = boost::make_shared(); + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1))) { + result->setPayload(payload); + } + return result; } void PubSubEventConvertor::doConvertToLua(lua_State* L, boost::shared_ptr event) { - convertors->convertToLua(L, event->getPayload()); + convertors->convertToLua(L, event->getPayload()); } diff --git a/Sluift/ElementConvertors/PubSubEventConvertor.h b/Sluift/ElementConvertors/PubSubEventConvertor.h index ab19c8f..2797b88 100644 --- a/Sluift/ElementConvertors/PubSubEventConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventConvertor.h @@ -12,17 +12,17 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventConvertor : public GenericLuaElementConvertor { - public: - PubSubEventConvertor(LuaElementConvertors* convertors); - virtual ~PubSubEventConvertor(); + class PubSubEventConvertor : public GenericLuaElementConvertor { + public: + PubSubEventConvertor(LuaElementConvertors* convertors); + virtual ~PubSubEventConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp index d44d1a6..aa77319 100644 --- a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.cpp @@ -14,45 +14,45 @@ using namespace Swift; -PubSubEventDeleteConvertor::PubSubEventDeleteConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_event_delete"), - convertors(convertors) { +PubSubEventDeleteConvertor::PubSubEventDeleteConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_event_delete"), + convertors(convertors) { } PubSubEventDeleteConvertor::~PubSubEventDeleteConvertor() { } boost::shared_ptr PubSubEventDeleteConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "redirects"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_redirect"))) { - result->setRedirects(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "redirects"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_redirect"))) { + result->setRedirects(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubEventDeleteConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (convertors->convertToLuaUntyped(L, payload->getRedirects()) > 0) { - lua_setfield(L, -2, "redirects"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (convertors->convertToLuaUntyped(L, payload->getRedirects()) > 0) { + lua_setfield(L, -2, "redirects"); + } } boost::optional PubSubEventDeleteConvertor::getDocumentation() const { - return Documentation( - "PubSubEventDelete", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `redirects`: @{PubSubEventRedirect}\n" - ); + return Documentation( + "PubSubEventDelete", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `redirects`: @{PubSubEventRedirect}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h index c8ff8cd..b53c3d7 100644 --- a/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventDeleteConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventDeleteConvertor : public GenericLuaElementConvertor { - public: - PubSubEventDeleteConvertor(LuaElementConvertors* convertors); - virtual ~PubSubEventDeleteConvertor(); + class PubSubEventDeleteConvertor : public GenericLuaElementConvertor { + public: + PubSubEventDeleteConvertor(LuaElementConvertors* convertors); + virtual ~PubSubEventDeleteConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp index 4811cc2..1d417ac 100644 --- a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubEventDisassociateConvertor::PubSubEventDisassociateConvertor() : - GenericLuaElementConvertor("pubsub_event_disassociate") { + GenericLuaElementConvertor("pubsub_event_disassociate") { } PubSubEventDisassociateConvertor::~PubSubEventDisassociateConvertor() { } boost::shared_ptr PubSubEventDisassociateConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubEventDisassociateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); } boost::optional PubSubEventDisassociateConvertor::getDocumentation() const { - return Documentation( - "PubSubEventDisassociate", - "This table has the following fields:\n\n" - "- `node`: string\n" - ); + return Documentation( + "PubSubEventDisassociate", + "This table has the following fields:\n\n" + "- `node`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h index 69f2d11..9a34ac3 100644 --- a/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventDisassociateConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventDisassociateConvertor : public GenericLuaElementConvertor { - public: - PubSubEventDisassociateConvertor(); - virtual ~PubSubEventDisassociateConvertor(); + class PubSubEventDisassociateConvertor : public GenericLuaElementConvertor { + public: + PubSubEventDisassociateConvertor(); + virtual ~PubSubEventDisassociateConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp b/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp index 7e6131a..c8373f5 100644 --- a/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventItemConvertor.cpp @@ -17,87 +17,87 @@ using namespace Swift; -PubSubEventItemConvertor::PubSubEventItemConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_event_item"), - convertors(convertors) { +PubSubEventItemConvertor::PubSubEventItemConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_event_item"), + convertors(convertors) { } PubSubEventItemConvertor::~PubSubEventItemConvertor() { } boost::shared_ptr PubSubEventItemConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "publisher"); - if (lua_isstring(L, -1)) { - result->setPublisher(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "data"); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "publisher"); + if (lua_isstring(L, -1)) { + result->setPublisher(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "data"); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setData(items); - } - lua_pop(L, 1); - lua_getfield(L, -1, "id"); - if (lua_isstring(L, -1)) { - result->setID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + result->setData(items); + } + lua_pop(L, 1); + lua_getfield(L, -1, "id"); + if (lua_isstring(L, -1)) { + result->setID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubEventItemConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - if (payload->getPublisher()) { - lua_pushstring(L, (*payload->getPublisher()).c_str()); - lua_setfield(L, -2, "publisher"); - } - if (!payload->getData().empty()) { - lua_createtable(L, boost::numeric_cast(payload->getData().size()), 0); - { - int i = 0; - foreach(boost::shared_ptr item, payload->getData()) { - if (convertors->convertToLua(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - lua_setfield(L, -2, "data"); - } - if (payload->getID()) { - lua_pushstring(L, (*payload->getID()).c_str()); - lua_setfield(L, -2, "id"); - } + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + if (payload->getPublisher()) { + lua_pushstring(L, (*payload->getPublisher()).c_str()); + lua_setfield(L, -2, "publisher"); + } + if (!payload->getData().empty()) { + lua_createtable(L, boost::numeric_cast(payload->getData().size()), 0); + { + int i = 0; + foreach(boost::shared_ptr item, payload->getData()) { + if (convertors->convertToLua(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + lua_setfield(L, -2, "data"); + } + if (payload->getID()) { + lua_pushstring(L, (*payload->getID()).c_str()); + lua_setfield(L, -2, "id"); + } } boost::optional PubSubEventItemConvertor::getDocumentation() const { - return Documentation( - "PubSubEventItem", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `publisher`: string (Optional)\n" - "- `data`: array\n" - "- `id`: string (Optional)\n" - ); + return Documentation( + "PubSubEventItem", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `publisher`: string (Optional)\n" + "- `data`: array\n" + "- `id`: string (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventItemConvertor.h b/Sluift/ElementConvertors/PubSubEventItemConvertor.h index 7dfeef6..1f67b9f 100644 --- a/Sluift/ElementConvertors/PubSubEventItemConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventItemConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventItemConvertor : public GenericLuaElementConvertor { - public: - PubSubEventItemConvertor(LuaElementConvertors* convertors); - virtual ~PubSubEventItemConvertor(); + class PubSubEventItemConvertor : public GenericLuaElementConvertor { + public: + PubSubEventItemConvertor(LuaElementConvertors* convertors); + virtual ~PubSubEventItemConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp b/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp index 66400e9..0c2035f 100644 --- a/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventItemsConvertor.cpp @@ -17,96 +17,96 @@ using namespace Swift; -PubSubEventItemsConvertor::PubSubEventItemsConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_event_items"), - convertors(convertors) { +PubSubEventItemsConvertor::PubSubEventItemsConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_event_items"), + convertors(convertors) { } PubSubEventItemsConvertor::~PubSubEventItemsConvertor() { } boost::shared_ptr PubSubEventItemsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "items"); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_item"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "items"); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_item"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setItems(items); - } - lua_pop(L, 1); - lua_getfield(L, -1, "retracts"); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_retract"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + result->setItems(items); + } + lua_pop(L, 1); + lua_getfield(L, -1, "retracts"); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_event_retract"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setRetracts(items); - } - lua_pop(L, 1); - return result; + result->setRetracts(items); + } + lua_pop(L, 1); + return result; } void PubSubEventItemsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (!payload->getItems().empty()) { - lua_createtable(L, boost::numeric_cast(payload->getItems().size()), 0); - { - int i = 0; - foreach(boost::shared_ptr item, payload->getItems()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - lua_setfield(L, -2, "items"); - } - if (!payload->getRetracts().empty()) { - lua_createtable(L, boost::numeric_cast(payload->getRetracts().size()), 0); - { - int i = 0; - foreach(boost::shared_ptr item, payload->getRetracts()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - lua_setfield(L, -2, "retracts"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (!payload->getItems().empty()) { + lua_createtable(L, boost::numeric_cast(payload->getItems().size()), 0); + { + int i = 0; + foreach(boost::shared_ptr item, payload->getItems()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + lua_setfield(L, -2, "items"); + } + if (!payload->getRetracts().empty()) { + lua_createtable(L, boost::numeric_cast(payload->getRetracts().size()), 0); + { + int i = 0; + foreach(boost::shared_ptr item, payload->getRetracts()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + lua_setfield(L, -2, "retracts"); + } } boost::optional PubSubEventItemsConvertor::getDocumentation() const { - return Documentation( - "PubSubEventItems", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `items`: array<@{PubSubEventItem}>\n" - "- `retracts`: array<@{PubSubEventRetract}>\n" - ); + return Documentation( + "PubSubEventItems", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `items`: array<@{PubSubEventItem}>\n" + "- `retracts`: array<@{PubSubEventRetract}>\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventItemsConvertor.h b/Sluift/ElementConvertors/PubSubEventItemsConvertor.h index 347200e..b644e7a 100644 --- a/Sluift/ElementConvertors/PubSubEventItemsConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventItemsConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventItemsConvertor : public GenericLuaElementConvertor { - public: - PubSubEventItemsConvertor(LuaElementConvertors* convertors); - virtual ~PubSubEventItemsConvertor(); + class PubSubEventItemsConvertor : public GenericLuaElementConvertor { + public: + PubSubEventItemsConvertor(LuaElementConvertors* convertors); + virtual ~PubSubEventItemsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp index bd036c1..3b67704 100644 --- a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubEventPurgeConvertor::PubSubEventPurgeConvertor() : - GenericLuaElementConvertor("pubsub_event_purge") { + GenericLuaElementConvertor("pubsub_event_purge") { } PubSubEventPurgeConvertor::~PubSubEventPurgeConvertor() { } boost::shared_ptr PubSubEventPurgeConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubEventPurgeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); } boost::optional PubSubEventPurgeConvertor::getDocumentation() const { - return Documentation( - "PubSubEventPurge", - "This table has the following fields:\n\n" - "- `node`: string\n" - ); + return Documentation( + "PubSubEventPurge", + "This table has the following fields:\n\n" + "- `node`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h index 88af6f4..b149426 100644 --- a/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventPurgeConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventPurgeConvertor : public GenericLuaElementConvertor { - public: - PubSubEventPurgeConvertor(); - virtual ~PubSubEventPurgeConvertor(); + class PubSubEventPurgeConvertor : public GenericLuaElementConvertor { + public: + PubSubEventPurgeConvertor(); + virtual ~PubSubEventPurgeConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp index 81584e3..ac40d31 100644 --- a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubEventRedirectConvertor::PubSubEventRedirectConvertor() : - GenericLuaElementConvertor("pubsub_event_redirect") { + GenericLuaElementConvertor("pubsub_event_redirect") { } PubSubEventRedirectConvertor::~PubSubEventRedirectConvertor() { } boost::shared_ptr PubSubEventRedirectConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "uri"); - if (lua_isstring(L, -1)) { - result->setURI(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "uri"); + if (lua_isstring(L, -1)) { + result->setURI(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubEventRedirectConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getURI().c_str()); - lua_setfield(L, -2, "uri"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getURI().c_str()); + lua_setfield(L, -2, "uri"); } boost::optional PubSubEventRedirectConvertor::getDocumentation() const { - return Documentation( - "PubSubEventRedirect", - "This table has the following fields:\n\n" - "- `uri`: string\n" - ); + return Documentation( + "PubSubEventRedirect", + "This table has the following fields:\n\n" + "- `uri`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h index d5724ae..bdf7951 100644 --- a/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventRedirectConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventRedirectConvertor : public GenericLuaElementConvertor { - public: - PubSubEventRedirectConvertor(); - virtual ~PubSubEventRedirectConvertor(); + class PubSubEventRedirectConvertor : public GenericLuaElementConvertor { + public: + PubSubEventRedirectConvertor(); + virtual ~PubSubEventRedirectConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp b/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp index f851306..15eec91 100644 --- a/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventRetractConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubEventRetractConvertor::PubSubEventRetractConvertor() : - GenericLuaElementConvertor("pubsub_event_retract") { + GenericLuaElementConvertor("pubsub_event_retract") { } PubSubEventRetractConvertor::~PubSubEventRetractConvertor() { } boost::shared_ptr PubSubEventRetractConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "id"); - if (lua_isstring(L, -1)) { - result->setID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "id"); + if (lua_isstring(L, -1)) { + result->setID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubEventRetractConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getID().c_str()); - lua_setfield(L, -2, "id"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getID().c_str()); + lua_setfield(L, -2, "id"); } boost::optional PubSubEventRetractConvertor::getDocumentation() const { - return Documentation( - "PubSubEventRetract", - "This table has the following fields:\n\n" - "- `id`: string\n" - ); + return Documentation( + "PubSubEventRetract", + "This table has the following fields:\n\n" + "- `id`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventRetractConvertor.h b/Sluift/ElementConvertors/PubSubEventRetractConvertor.h index 72ca0a3..38208b0 100644 --- a/Sluift/ElementConvertors/PubSubEventRetractConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventRetractConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventRetractConvertor : public GenericLuaElementConvertor { - public: - PubSubEventRetractConvertor(); - virtual ~PubSubEventRetractConvertor(); + class PubSubEventRetractConvertor : public GenericLuaElementConvertor { + public: + PubSubEventRetractConvertor(); + virtual ~PubSubEventRetractConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp index d83f6be..57be1c4 100644 --- a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.cpp @@ -15,90 +15,90 @@ using namespace Swift; PubSubEventSubscriptionConvertor::PubSubEventSubscriptionConvertor() : - GenericLuaElementConvertor("pubsub_event_subscription") { + GenericLuaElementConvertor("pubsub_event_subscription") { } PubSubEventSubscriptionConvertor::~PubSubEventSubscriptionConvertor() { } boost::shared_ptr PubSubEventSubscriptionConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "jid"); - if (lua_isstring(L, -1)) { - result->setJID(JID(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription"); - if (lua_isstring(L, -1)) { - if (std::string(lua_tostring(L, -1)) == "none") { - result->setSubscription(PubSubEventSubscription::None); - } - if (std::string(lua_tostring(L, -1)) == "pending") { - result->setSubscription(PubSubEventSubscription::Pending); - } - if (std::string(lua_tostring(L, -1)) == "subscribed") { - result->setSubscription(PubSubEventSubscription::Subscribed); - } - if (std::string(lua_tostring(L, -1)) == "unconfigured") { - result->setSubscription(PubSubEventSubscription::Unconfigured); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription_id"); - if (lua_isstring(L, -1)) { - result->setSubscriptionID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "expiry"); - if (lua_isstring(L, -1)) { - result->setExpiry(stringToDateTime(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "jid"); + if (lua_isstring(L, -1)) { + result->setJID(JID(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription"); + if (lua_isstring(L, -1)) { + if (std::string(lua_tostring(L, -1)) == "none") { + result->setSubscription(PubSubEventSubscription::None); + } + if (std::string(lua_tostring(L, -1)) == "pending") { + result->setSubscription(PubSubEventSubscription::Pending); + } + if (std::string(lua_tostring(L, -1)) == "subscribed") { + result->setSubscription(PubSubEventSubscription::Subscribed); + } + if (std::string(lua_tostring(L, -1)) == "unconfigured") { + result->setSubscription(PubSubEventSubscription::Unconfigured); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription_id"); + if (lua_isstring(L, -1)) { + result->setSubscriptionID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "expiry"); + if (lua_isstring(L, -1)) { + result->setExpiry(stringToDateTime(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + return result; } void PubSubEventSubscriptionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - lua_pushstring(L, payload->getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - switch (payload->getSubscription()) { - case PubSubEventSubscription::None: - lua_pushstring(L, "none"); - break; - case PubSubEventSubscription::Pending: - lua_pushstring(L, "pending"); - break; - case PubSubEventSubscription::Subscribed: - lua_pushstring(L, "subscribed"); - break; - case PubSubEventSubscription::Unconfigured: - lua_pushstring(L, "unconfigured"); - break; - } - lua_setfield(L, -2, "subscription"); - if (payload->getSubscriptionID()) { - lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); - lua_setfield(L, -2, "subscription_id"); - } - lua_pushstring(L, dateTimeToString(payload->getExpiry()).c_str()); - lua_setfield(L, -2, "expiry"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + lua_pushstring(L, payload->getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + switch (payload->getSubscription()) { + case PubSubEventSubscription::None: + lua_pushstring(L, "none"); + break; + case PubSubEventSubscription::Pending: + lua_pushstring(L, "pending"); + break; + case PubSubEventSubscription::Subscribed: + lua_pushstring(L, "subscribed"); + break; + case PubSubEventSubscription::Unconfigured: + lua_pushstring(L, "unconfigured"); + break; + } + lua_setfield(L, -2, "subscription"); + if (payload->getSubscriptionID()) { + lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); + lua_setfield(L, -2, "subscription_id"); + } + lua_pushstring(L, dateTimeToString(payload->getExpiry()).c_str()); + lua_setfield(L, -2, "expiry"); } boost::optional PubSubEventSubscriptionConvertor::getDocumentation() const { - return Documentation( - "PubSubEventSubscription", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `jid`: jid (string)\n" - "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n" - "- `subscription_id`: string (Optional)\n" - "- `expiry`: datetime (string)\n" - ); + return Documentation( + "PubSubEventSubscription", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `jid`: jid (string)\n" + "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n" + "- `subscription_id`: string (Optional)\n" + "- `expiry`: datetime (string)\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h index 837a03b..8ee9da5 100644 --- a/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h +++ b/Sluift/ElementConvertors/PubSubEventSubscriptionConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubEventSubscriptionConvertor : public GenericLuaElementConvertor { - public: - PubSubEventSubscriptionConvertor(); - virtual ~PubSubEventSubscriptionConvertor(); + class PubSubEventSubscriptionConvertor : public GenericLuaElementConvertor { + public: + PubSubEventSubscriptionConvertor(); + virtual ~PubSubEventSubscriptionConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubItemConvertor.cpp b/Sluift/ElementConvertors/PubSubItemConvertor.cpp index 60f7946..b88f989 100644 --- a/Sluift/ElementConvertors/PubSubItemConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubItemConvertor.cpp @@ -17,65 +17,65 @@ using namespace Swift; -PubSubItemConvertor::PubSubItemConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_item"), - convertors(convertors) { +PubSubItemConvertor::PubSubItemConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_item"), + convertors(convertors) { } PubSubItemConvertor::~PubSubItemConvertor() { } boost::shared_ptr PubSubItemConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "data"); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "data"); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setData(items); - } - lua_pop(L, 1); - lua_getfield(L, -1, "id"); - if (lua_isstring(L, -1)) { - result->setID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + result->setData(items); + } + lua_pop(L, 1); + lua_getfield(L, -1, "id"); + if (lua_isstring(L, -1)) { + result->setID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubItemConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (!payload->getData().empty()) { - lua_createtable(L, boost::numeric_cast(payload->getData().size()), 0); - { - int i = 0; - foreach(boost::shared_ptr item, payload->getData()) { - if (convertors->convertToLua(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - lua_setfield(L, -2, "data"); - } - lua_pushstring(L, payload->getID().c_str()); - lua_setfield(L, -2, "id"); + lua_createtable(L, 0, 0); + if (!payload->getData().empty()) { + lua_createtable(L, boost::numeric_cast(payload->getData().size()), 0); + { + int i = 0; + foreach(boost::shared_ptr item, payload->getData()) { + if (convertors->convertToLua(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + lua_setfield(L, -2, "data"); + } + lua_pushstring(L, payload->getID().c_str()); + lua_setfield(L, -2, "id"); } boost::optional PubSubItemConvertor::getDocumentation() const { - return Documentation( - "PubSubItem", - "This table has the following fields:\n\n" - "- `data`: array\n" - "- `id`: string\n" - ); + return Documentation( + "PubSubItem", + "This table has the following fields:\n\n" + "- `data`: array\n" + "- `id`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubItemConvertor.h b/Sluift/ElementConvertors/PubSubItemConvertor.h index 7f4adbf..1bc2467 100644 --- a/Sluift/ElementConvertors/PubSubItemConvertor.h +++ b/Sluift/ElementConvertors/PubSubItemConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubItemConvertor : public GenericLuaElementConvertor { - public: - PubSubItemConvertor(LuaElementConvertors* convertors); - virtual ~PubSubItemConvertor(); + class PubSubItemConvertor : public GenericLuaElementConvertor { + public: + PubSubItemConvertor(LuaElementConvertors* convertors); + virtual ~PubSubItemConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubItemsConvertor.cpp b/Sluift/ElementConvertors/PubSubItemsConvertor.cpp index 9b99c86..571bc46 100644 --- a/Sluift/ElementConvertors/PubSubItemsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubItemsConvertor.cpp @@ -17,81 +17,81 @@ using namespace Swift; -PubSubItemsConvertor::PubSubItemsConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_items"), - convertors(convertors) { +PubSubItemsConvertor::PubSubItemsConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_items"), + convertors(convertors) { } PubSubItemsConvertor::~PubSubItemsConvertor() { } boost::shared_ptr PubSubItemsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setItems(items); - } - lua_getfield(L, -1, "maximum_items"); - if (lua_isnumber(L, -1)) { - result->setMaximumItems(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription_id"); - if (lua_isstring(L, -1)) { - result->setSubscriptionID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + result->setItems(items); + } + lua_getfield(L, -1, "maximum_items"); + if (lua_isnumber(L, -1)) { + result->setMaximumItems(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription_id"); + if (lua_isstring(L, -1)) { + result->setSubscriptionID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubItemsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (!payload->getItems().empty()) { - { - int i = 0; - foreach(boost::shared_ptr item, payload->getItems()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - } - if (payload->getMaximumItems()) { - lua_pushnumber(L, (*payload->getMaximumItems())); - lua_setfield(L, -2, "maximum_items"); - } - if (payload->getSubscriptionID()) { - lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); - lua_setfield(L, -2, "subscription_id"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (!payload->getItems().empty()) { + { + int i = 0; + foreach(boost::shared_ptr item, payload->getItems()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + } + if (payload->getMaximumItems()) { + lua_pushnumber(L, (*payload->getMaximumItems())); + lua_setfield(L, -2, "maximum_items"); + } + if (payload->getSubscriptionID()) { + lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); + lua_setfield(L, -2, "subscription_id"); + } } boost::optional PubSubItemsConvertor::getDocumentation() const { - return Documentation( - "PubSubItems", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `items`: array<@{PubSubItem}>\n" - "- `maximum_items`: number (Optional)\n" - "- `subscription_id`: string (Optional)\n" - ); + return Documentation( + "PubSubItems", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `items`: array<@{PubSubItem}>\n" + "- `maximum_items`: number (Optional)\n" + "- `subscription_id`: string (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubItemsConvertor.h b/Sluift/ElementConvertors/PubSubItemsConvertor.h index 04943ac..e40d545 100644 --- a/Sluift/ElementConvertors/PubSubItemsConvertor.h +++ b/Sluift/ElementConvertors/PubSubItemsConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubItemsConvertor : public GenericLuaElementConvertor { - public: - PubSubItemsConvertor(LuaElementConvertors* convertors); - virtual ~PubSubItemsConvertor(); + class PubSubItemsConvertor : public GenericLuaElementConvertor { + public: + PubSubItemsConvertor(LuaElementConvertors* convertors); + virtual ~PubSubItemsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp index 2beaee9..52976ea 100644 --- a/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOptionsConvertor.cpp @@ -14,63 +14,63 @@ using namespace Swift; -PubSubOptionsConvertor::PubSubOptionsConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_options"), - convertors(convertors) { +PubSubOptionsConvertor::PubSubOptionsConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_options"), + convertors(convertors) { } PubSubOptionsConvertor::~PubSubOptionsConvertor() { } boost::shared_ptr PubSubOptionsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "jid"); - if (lua_isstring(L, -1)) { - result->setJID(JID(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "data"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { - result->setData(payload); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription_id"); - if (lua_isstring(L, -1)) { - result->setSubscriptionID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "jid"); + if (lua_isstring(L, -1)) { + result->setJID(JID(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "data"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { + result->setData(payload); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription_id"); + if (lua_isstring(L, -1)) { + result->setSubscriptionID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubOptionsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - lua_pushstring(L, payload->getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { - lua_setfield(L, -2, "data"); - } - if (payload->getSubscriptionID()) { - lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); - lua_setfield(L, -2, "subscription_id"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + lua_pushstring(L, payload->getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { + lua_setfield(L, -2, "data"); + } + if (payload->getSubscriptionID()) { + lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); + lua_setfield(L, -2, "subscription_id"); + } } boost::optional PubSubOptionsConvertor::getDocumentation() const { - return Documentation( - "PubSubOptions", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `jid`: jid (string)\n" - "- `data`: @{Form}\n" - "- `subscription_id`: string (Optional)\n" - ); + return Documentation( + "PubSubOptions", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `jid`: jid (string)\n" + "- `data`: @{Form}\n" + "- `subscription_id`: string (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOptionsConvertor.h b/Sluift/ElementConvertors/PubSubOptionsConvertor.h index a0ec68e..88fafd3 100644 --- a/Sluift/ElementConvertors/PubSubOptionsConvertor.h +++ b/Sluift/ElementConvertors/PubSubOptionsConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOptionsConvertor : public GenericLuaElementConvertor { - public: - PubSubOptionsConvertor(LuaElementConvertors* convertors); - virtual ~PubSubOptionsConvertor(); + class PubSubOptionsConvertor : public GenericLuaElementConvertor { + public: + PubSubOptionsConvertor(LuaElementConvertors* convertors); + virtual ~PubSubOptionsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp index 7e1ec9a..da835af 100644 --- a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.cpp @@ -13,76 +13,76 @@ using namespace Swift; PubSubOwnerAffiliationConvertor::PubSubOwnerAffiliationConvertor() : - GenericLuaElementConvertor("pubsub_owner_affiliation") { + GenericLuaElementConvertor("pubsub_owner_affiliation") { } PubSubOwnerAffiliationConvertor::~PubSubOwnerAffiliationConvertor() { } boost::shared_ptr PubSubOwnerAffiliationConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "jid"); - if (lua_isstring(L, -1)) { - result->setJID(JID(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "type"); - if (lua_isstring(L, -1)) { - if (std::string(lua_tostring(L, -1)) == "none") { - result->setType(PubSubOwnerAffiliation::None); - } - if (std::string(lua_tostring(L, -1)) == "member") { - result->setType(PubSubOwnerAffiliation::Member); - } - if (std::string(lua_tostring(L, -1)) == "outcast") { - result->setType(PubSubOwnerAffiliation::Outcast); - } - if (std::string(lua_tostring(L, -1)) == "owner") { - result->setType(PubSubOwnerAffiliation::Owner); - } - if (std::string(lua_tostring(L, -1)) == "publisher") { - result->setType(PubSubOwnerAffiliation::Publisher); - } - if (std::string(lua_tostring(L, -1)) == "publish_only") { - result->setType(PubSubOwnerAffiliation::PublishOnly); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "jid"); + if (lua_isstring(L, -1)) { + result->setJID(JID(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "type"); + if (lua_isstring(L, -1)) { + if (std::string(lua_tostring(L, -1)) == "none") { + result->setType(PubSubOwnerAffiliation::None); + } + if (std::string(lua_tostring(L, -1)) == "member") { + result->setType(PubSubOwnerAffiliation::Member); + } + if (std::string(lua_tostring(L, -1)) == "outcast") { + result->setType(PubSubOwnerAffiliation::Outcast); + } + if (std::string(lua_tostring(L, -1)) == "owner") { + result->setType(PubSubOwnerAffiliation::Owner); + } + if (std::string(lua_tostring(L, -1)) == "publisher") { + result->setType(PubSubOwnerAffiliation::Publisher); + } + if (std::string(lua_tostring(L, -1)) == "publish_only") { + result->setType(PubSubOwnerAffiliation::PublishOnly); + } + } + lua_pop(L, 1); + return result; } void PubSubOwnerAffiliationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - switch (payload->getType()) { - case PubSubOwnerAffiliation::None: - lua_pushstring(L, "none"); - break; - case PubSubOwnerAffiliation::Member: - lua_pushstring(L, "member"); - break; - case PubSubOwnerAffiliation::Outcast: - lua_pushstring(L, "outcast"); - break; - case PubSubOwnerAffiliation::Owner: - lua_pushstring(L, "owner"); - break; - case PubSubOwnerAffiliation::Publisher: - lua_pushstring(L, "publisher"); - break; - case PubSubOwnerAffiliation::PublishOnly: - lua_pushstring(L, "publish_only"); - break; - } - lua_setfield(L, -2, "type"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + switch (payload->getType()) { + case PubSubOwnerAffiliation::None: + lua_pushstring(L, "none"); + break; + case PubSubOwnerAffiliation::Member: + lua_pushstring(L, "member"); + break; + case PubSubOwnerAffiliation::Outcast: + lua_pushstring(L, "outcast"); + break; + case PubSubOwnerAffiliation::Owner: + lua_pushstring(L, "owner"); + break; + case PubSubOwnerAffiliation::Publisher: + lua_pushstring(L, "publisher"); + break; + case PubSubOwnerAffiliation::PublishOnly: + lua_pushstring(L, "publish_only"); + break; + } + lua_setfield(L, -2, "type"); } boost::optional PubSubOwnerAffiliationConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerAffiliation", - "This table has the following fields:\n\n" - "- `jid`: jid (string)\n" - "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n" - ); + return Documentation( + "PubSubOwnerAffiliation", + "This table has the following fields:\n\n" + "- `jid`: jid (string)\n" + "- `type`: `\"none\"`, `\"member\"`, `\"outcast\"`, `\"owner\"`, `\"publisher\"`, or `\"publish_only\"`\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h index 6876882..965e708 100644 --- a/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerAffiliationConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerAffiliationConvertor(); - virtual ~PubSubOwnerAffiliationConvertor(); + class PubSubOwnerAffiliationConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerAffiliationConvertor(); + virtual ~PubSubOwnerAffiliationConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp index 4827914..01a4503 100644 --- a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.cpp @@ -17,61 +17,61 @@ using namespace Swift; -PubSubOwnerAffiliationsConvertor::PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_owner_affiliations"), - convertors(convertors) { +PubSubOwnerAffiliationsConvertor::PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_owner_affiliations"), + convertors(convertors) { } PubSubOwnerAffiliationsConvertor::~PubSubOwnerAffiliationsConvertor() { } boost::shared_ptr PubSubOwnerAffiliationsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_affiliation"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_affiliation"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setAffiliations(items); - } - return result; + result->setAffiliations(items); + } + return result; } void PubSubOwnerAffiliationsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (!payload->getAffiliations().empty()) { - { - int i = 0; - foreach(boost::shared_ptr item, payload->getAffiliations()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (!payload->getAffiliations().empty()) { + { + int i = 0; + foreach(boost::shared_ptr item, payload->getAffiliations()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + } } boost::optional PubSubOwnerAffiliationsConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerAffiliations", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `affiliations`: array<@{PubSubOwnerAffiliation}>\n" - ); + return Documentation( + "PubSubOwnerAffiliations", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `affiliations`: array<@{PubSubOwnerAffiliation}>\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h index f64426a..3644cd8 100644 --- a/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerAffiliationsConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerAffiliationsConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors); - virtual ~PubSubOwnerAffiliationsConvertor(); + class PubSubOwnerAffiliationsConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerAffiliationsConvertor(LuaElementConvertors* convertors); + virtual ~PubSubOwnerAffiliationsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp index 2620649..0d0d49a 100644 --- a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.cpp @@ -14,47 +14,47 @@ using namespace Swift; -PubSubOwnerConfigureConvertor::PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_owner_configure"), - convertors(convertors) { +PubSubOwnerConfigureConvertor::PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_owner_configure"), + convertors(convertors) { } PubSubOwnerConfigureConvertor::~PubSubOwnerConfigureConvertor() { } boost::shared_ptr PubSubOwnerConfigureConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "data"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { - result->setData(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "data"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { + result->setData(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubOwnerConfigureConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { - lua_setfield(L, -2, "data"); - } + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { + lua_setfield(L, -2, "data"); + } } boost::optional PubSubOwnerConfigureConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerConfigure", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `data`: @{Form}\n" - ); + return Documentation( + "PubSubOwnerConfigure", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `data`: @{Form}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h index 7555922..d2fb229 100644 --- a/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerConfigureConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerConfigureConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors); - virtual ~PubSubOwnerConfigureConvertor(); + class PubSubOwnerConfigureConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerConfigureConvertor(LuaElementConvertors* convertors); + virtual ~PubSubOwnerConfigureConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp index e493601..9147900 100644 --- a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.cpp @@ -14,37 +14,37 @@ using namespace Swift; -PubSubOwnerDefaultConvertor::PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_owner_default"), - convertors(convertors) { +PubSubOwnerDefaultConvertor::PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_owner_default"), + convertors(convertors) { } PubSubOwnerDefaultConvertor::~PubSubOwnerDefaultConvertor() { } boost::shared_ptr PubSubOwnerDefaultConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "data"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { - result->setData(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "data"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "form"))) { + result->setData(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubOwnerDefaultConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { - lua_setfield(L, -2, "data"); - } + lua_createtable(L, 0, 0); + if (convertors->convertToLuaUntyped(L, payload->getData()) > 0) { + lua_setfield(L, -2, "data"); + } } boost::optional PubSubOwnerDefaultConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerDefault", - "This table has the following fields:\n\n" - "- `data`: @{Form}\n" - ); + return Documentation( + "PubSubOwnerDefault", + "This table has the following fields:\n\n" + "- `data`: @{Form}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h index d51223a..274cb12 100644 --- a/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerDefaultConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerDefaultConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors); - virtual ~PubSubOwnerDefaultConvertor(); + class PubSubOwnerDefaultConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerDefaultConvertor(LuaElementConvertors* convertors); + virtual ~PubSubOwnerDefaultConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp index 2c818f1..63579b6 100644 --- a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.cpp @@ -14,45 +14,45 @@ using namespace Swift; -PubSubOwnerDeleteConvertor::PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_owner_delete"), - convertors(convertors) { +PubSubOwnerDeleteConvertor::PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_owner_delete"), + convertors(convertors) { } PubSubOwnerDeleteConvertor::~PubSubOwnerDeleteConvertor() { } boost::shared_ptr PubSubOwnerDeleteConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "redirect"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_redirect"))) { - result->setRedirect(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "redirect"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_redirect"))) { + result->setRedirect(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubOwnerDeleteConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (convertors->convertToLuaUntyped(L, payload->getRedirect()) > 0) { - lua_setfield(L, -2, "redirect"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (convertors->convertToLuaUntyped(L, payload->getRedirect()) > 0) { + lua_setfield(L, -2, "redirect"); + } } boost::optional PubSubOwnerDeleteConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerDelete", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `redirect`: @{PubSubOwnerRedirect}\n" - ); + return Documentation( + "PubSubOwnerDelete", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `redirect`: @{PubSubOwnerRedirect}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h index 4673b92..548fb79 100644 --- a/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerDeleteConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerDeleteConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors); - virtual ~PubSubOwnerDeleteConvertor(); + class PubSubOwnerDeleteConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerDeleteConvertor(LuaElementConvertors* convertors); + virtual ~PubSubOwnerDeleteConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp index cf56f6b..f7d5c50 100644 --- a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubOwnerPurgeConvertor::PubSubOwnerPurgeConvertor() : - GenericLuaElementConvertor("pubsub_owner_purge") { + GenericLuaElementConvertor("pubsub_owner_purge") { } PubSubOwnerPurgeConvertor::~PubSubOwnerPurgeConvertor() { } boost::shared_ptr PubSubOwnerPurgeConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubOwnerPurgeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); } boost::optional PubSubOwnerPurgeConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerPurge", - "This table has the following fields:\n\n" - "- `node`: string\n" - ); + return Documentation( + "PubSubOwnerPurge", + "This table has the following fields:\n\n" + "- `node`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h index 2ef7bd5..fc627c6 100644 --- a/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerPurgeConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerPurgeConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerPurgeConvertor(); - virtual ~PubSubOwnerPurgeConvertor(); + class PubSubOwnerPurgeConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerPurgeConvertor(); + virtual ~PubSubOwnerPurgeConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp index a98a213..86c26ac 100644 --- a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubOwnerRedirectConvertor::PubSubOwnerRedirectConvertor() : - GenericLuaElementConvertor("pubsub_owner_redirect") { + GenericLuaElementConvertor("pubsub_owner_redirect") { } PubSubOwnerRedirectConvertor::~PubSubOwnerRedirectConvertor() { } boost::shared_ptr PubSubOwnerRedirectConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "uri"); - if (lua_isstring(L, -1)) { - result->setURI(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "uri"); + if (lua_isstring(L, -1)) { + result->setURI(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubOwnerRedirectConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getURI().c_str()); - lua_setfield(L, -2, "uri"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getURI().c_str()); + lua_setfield(L, -2, "uri"); } boost::optional PubSubOwnerRedirectConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerRedirect", - "This table has the following fields:\n\n" - "- `uri`: string\n" - ); + return Documentation( + "PubSubOwnerRedirect", + "This table has the following fields:\n\n" + "- `uri`: string\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h index 8a61ef2..528e9e5 100644 --- a/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerRedirectConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerRedirectConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerRedirectConvertor(); - virtual ~PubSubOwnerRedirectConvertor(); + class PubSubOwnerRedirectConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerRedirectConvertor(); + virtual ~PubSubOwnerRedirectConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp index 57d4f3d..2e5aff3 100644 --- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.cpp @@ -13,64 +13,64 @@ using namespace Swift; PubSubOwnerSubscriptionConvertor::PubSubOwnerSubscriptionConvertor() : - GenericLuaElementConvertor("pubsub_owner_subscription") { + GenericLuaElementConvertor("pubsub_owner_subscription") { } PubSubOwnerSubscriptionConvertor::~PubSubOwnerSubscriptionConvertor() { } boost::shared_ptr PubSubOwnerSubscriptionConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "jid"); - if (lua_isstring(L, -1)) { - result->setJID(JID(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription"); - if (lua_isstring(L, -1)) { - if (std::string(lua_tostring(L, -1)) == "none") { - result->setSubscription(PubSubOwnerSubscription::None); - } - if (std::string(lua_tostring(L, -1)) == "pending") { - result->setSubscription(PubSubOwnerSubscription::Pending); - } - if (std::string(lua_tostring(L, -1)) == "subscribed") { - result->setSubscription(PubSubOwnerSubscription::Subscribed); - } - if (std::string(lua_tostring(L, -1)) == "unconfigured") { - result->setSubscription(PubSubOwnerSubscription::Unconfigured); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "jid"); + if (lua_isstring(L, -1)) { + result->setJID(JID(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription"); + if (lua_isstring(L, -1)) { + if (std::string(lua_tostring(L, -1)) == "none") { + result->setSubscription(PubSubOwnerSubscription::None); + } + if (std::string(lua_tostring(L, -1)) == "pending") { + result->setSubscription(PubSubOwnerSubscription::Pending); + } + if (std::string(lua_tostring(L, -1)) == "subscribed") { + result->setSubscription(PubSubOwnerSubscription::Subscribed); + } + if (std::string(lua_tostring(L, -1)) == "unconfigured") { + result->setSubscription(PubSubOwnerSubscription::Unconfigured); + } + } + lua_pop(L, 1); + return result; } void PubSubOwnerSubscriptionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - switch (payload->getSubscription()) { - case PubSubOwnerSubscription::None: - lua_pushstring(L, "none"); - break; - case PubSubOwnerSubscription::Pending: - lua_pushstring(L, "pending"); - break; - case PubSubOwnerSubscription::Subscribed: - lua_pushstring(L, "subscribed"); - break; - case PubSubOwnerSubscription::Unconfigured: - lua_pushstring(L, "unconfigured"); - break; - } - lua_setfield(L, -2, "subscription"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + switch (payload->getSubscription()) { + case PubSubOwnerSubscription::None: + lua_pushstring(L, "none"); + break; + case PubSubOwnerSubscription::Pending: + lua_pushstring(L, "pending"); + break; + case PubSubOwnerSubscription::Subscribed: + lua_pushstring(L, "subscribed"); + break; + case PubSubOwnerSubscription::Unconfigured: + lua_pushstring(L, "unconfigured"); + break; + } + lua_setfield(L, -2, "subscription"); } boost::optional PubSubOwnerSubscriptionConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerSubscription", - "This table has the following fields:\n\n" - "- `jid`: jid (string)\n" - "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n" - ); + return Documentation( + "PubSubOwnerSubscription", + "This table has the following fields:\n\n" + "- `jid`: jid (string)\n" + "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h index 61c1a5e..0924c35 100644 --- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerSubscriptionConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerSubscriptionConvertor(); - virtual ~PubSubOwnerSubscriptionConvertor(); + class PubSubOwnerSubscriptionConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerSubscriptionConvertor(); + virtual ~PubSubOwnerSubscriptionConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp index 3298096..b6f49ad 100644 --- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.cpp @@ -17,61 +17,61 @@ using namespace Swift; -PubSubOwnerSubscriptionsConvertor::PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_owner_subscriptions"), - convertors(convertors) { +PubSubOwnerSubscriptionsConvertor::PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_owner_subscriptions"), + convertors(convertors) { } PubSubOwnerSubscriptionsConvertor::~PubSubOwnerSubscriptionsConvertor() { } boost::shared_ptr PubSubOwnerSubscriptionsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_subscription"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_owner_subscription"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setSubscriptions(items); - } - return result; + result->setSubscriptions(items); + } + return result; } void PubSubOwnerSubscriptionsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (!payload->getSubscriptions().empty()) { - { - int i = 0; - foreach(boost::shared_ptr item, payload->getSubscriptions()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (!payload->getSubscriptions().empty()) { + { + int i = 0; + foreach(boost::shared_ptr item, payload->getSubscriptions()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + } } boost::optional PubSubOwnerSubscriptionsConvertor::getDocumentation() const { - return Documentation( - "PubSubOwnerSubscriptions", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `subscriptions`: array<@{PubSubOwnerSubscription}>\n" - ); + return Documentation( + "PubSubOwnerSubscriptions", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `subscriptions`: array<@{PubSubOwnerSubscription}>\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h index b1793e3..1511d20 100644 --- a/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h +++ b/Sluift/ElementConvertors/PubSubOwnerSubscriptionsConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubOwnerSubscriptionsConvertor : public GenericLuaElementConvertor { - public: - PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors); - virtual ~PubSubOwnerSubscriptionsConvertor(); + class PubSubOwnerSubscriptionsConvertor : public GenericLuaElementConvertor { + public: + PubSubOwnerSubscriptionsConvertor(LuaElementConvertors* convertors); + virtual ~PubSubOwnerSubscriptionsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubPublishConvertor.cpp b/Sluift/ElementConvertors/PubSubPublishConvertor.cpp index 89a7d8d..68045fb 100644 --- a/Sluift/ElementConvertors/PubSubPublishConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubPublishConvertor.cpp @@ -17,65 +17,65 @@ using namespace Swift; -PubSubPublishConvertor::PubSubPublishConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_publish"), - convertors(convertors) { +PubSubPublishConvertor::PubSubPublishConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_publish"), + convertors(convertors) { } PubSubPublishConvertor::~PubSubPublishConvertor() { } boost::shared_ptr PubSubPublishConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "items"); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "items"); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setItems(items); - } - lua_pop(L, 1); - return result; + result->setItems(items); + } + lua_pop(L, 1); + return result; } void PubSubPublishConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (!payload->getItems().empty()) { - lua_createtable(L, boost::numeric_cast(payload->getItems().size()), 0); - { - int i = 0; - foreach(boost::shared_ptr item, payload->getItems()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - lua_setfield(L, -2, "items"); - } + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (!payload->getItems().empty()) { + lua_createtable(L, boost::numeric_cast(payload->getItems().size()), 0); + { + int i = 0; + foreach(boost::shared_ptr item, payload->getItems()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + lua_setfield(L, -2, "items"); + } } boost::optional PubSubPublishConvertor::getDocumentation() const { - return Documentation( - "PubSubPublish", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `items`: array<@{PubSubItem}>\n" - ); + return Documentation( + "PubSubPublish", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `items`: array<@{PubSubItem}>\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubPublishConvertor.h b/Sluift/ElementConvertors/PubSubPublishConvertor.h index d886368..1372c55 100644 --- a/Sluift/ElementConvertors/PubSubPublishConvertor.h +++ b/Sluift/ElementConvertors/PubSubPublishConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubPublishConvertor : public GenericLuaElementConvertor { - public: - PubSubPublishConvertor(LuaElementConvertors* convertors); - virtual ~PubSubPublishConvertor(); + class PubSubPublishConvertor : public GenericLuaElementConvertor { + public: + PubSubPublishConvertor(LuaElementConvertors* convertors); + virtual ~PubSubPublishConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubRetractConvertor.cpp b/Sluift/ElementConvertors/PubSubRetractConvertor.cpp index f6d186e..bc0e3d0 100644 --- a/Sluift/ElementConvertors/PubSubRetractConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubRetractConvertor.cpp @@ -17,73 +17,73 @@ using namespace Swift; -PubSubRetractConvertor::PubSubRetractConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_retract"), - convertors(convertors) { +PubSubRetractConvertor::PubSubRetractConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_retract"), + convertors(convertors) { } PubSubRetractConvertor::~PubSubRetractConvertor() { } boost::shared_ptr PubSubRetractConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "items"); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "items"); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_item"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setItems(items); - } - lua_pop(L, 1); - lua_getfield(L, -1, "notify"); - if (lua_isboolean(L, -1)) { - result->setNotify(lua_toboolean(L, -1)); - } - lua_pop(L, 1); - return result; + result->setItems(items); + } + lua_pop(L, 1); + lua_getfield(L, -1, "notify"); + if (lua_isboolean(L, -1)) { + result->setNotify(lua_toboolean(L, -1)); + } + lua_pop(L, 1); + return result; } void PubSubRetractConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getNode().c_str()); - lua_setfield(L, -2, "node"); - if (!payload->getItems().empty()) { - lua_createtable(L, boost::numeric_cast(payload->getItems().size()), 0); - { - int i = 0; - foreach(boost::shared_ptr item, payload->getItems()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - lua_setfield(L, -2, "items"); - } - lua_pushboolean(L, payload->isNotify()); - lua_setfield(L, -2, "notify"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getNode().c_str()); + lua_setfield(L, -2, "node"); + if (!payload->getItems().empty()) { + lua_createtable(L, boost::numeric_cast(payload->getItems().size()), 0); + { + int i = 0; + foreach(boost::shared_ptr item, payload->getItems()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + lua_setfield(L, -2, "items"); + } + lua_pushboolean(L, payload->isNotify()); + lua_setfield(L, -2, "notify"); } boost::optional PubSubRetractConvertor::getDocumentation() const { - return Documentation( - "PubSubRetract", - "This table has the following fields:\n\n" - "- `node`: string\n" - "- `items`: array<@{PubSubItem}>\n" - "- `notify`: boolean\n" - ); + return Documentation( + "PubSubRetract", + "This table has the following fields:\n\n" + "- `node`: string\n" + "- `items`: array<@{PubSubItem}>\n" + "- `notify`: boolean\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubRetractConvertor.h b/Sluift/ElementConvertors/PubSubRetractConvertor.h index 6b27ac7..c1f8bd6 100644 --- a/Sluift/ElementConvertors/PubSubRetractConvertor.h +++ b/Sluift/ElementConvertors/PubSubRetractConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubRetractConvertor : public GenericLuaElementConvertor { - public: - PubSubRetractConvertor(LuaElementConvertors* convertors); - virtual ~PubSubRetractConvertor(); + class PubSubRetractConvertor : public GenericLuaElementConvertor { + public: + PubSubRetractConvertor(LuaElementConvertors* convertors); + virtual ~PubSubRetractConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp index 436b660..bb3dcb4 100644 --- a/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubSubscribeConvertor.cpp @@ -14,55 +14,55 @@ using namespace Swift; -PubSubSubscribeConvertor::PubSubSubscribeConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_subscribe"), - convertors(convertors) { +PubSubSubscribeConvertor::PubSubSubscribeConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_subscribe"), + convertors(convertors) { } PubSubSubscribeConvertor::~PubSubSubscribeConvertor() { } boost::shared_ptr PubSubSubscribeConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "jid"); - if (lua_isstring(L, -1)) { - result->setJID(JID(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "options"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_options"))) { - result->setOptions(payload); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "jid"); + if (lua_isstring(L, -1)) { + result->setJID(JID(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "options"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_options"))) { + result->setOptions(payload); + } + } + lua_pop(L, 1); + return result; } void PubSubSubscribeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - lua_pushstring(L, payload->getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) { - lua_setfield(L, -2, "options"); - } + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + lua_pushstring(L, payload->getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) { + lua_setfield(L, -2, "options"); + } } boost::optional PubSubSubscribeConvertor::getDocumentation() const { - return Documentation( - "PubSubSubscribe", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `jid`: jid (string)\n" - "- `options`: @{PubSubOptions}\n" - ); + return Documentation( + "PubSubSubscribe", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `jid`: jid (string)\n" + "- `options`: @{PubSubOptions}\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubSubscribeConvertor.h b/Sluift/ElementConvertors/PubSubSubscribeConvertor.h index a7eac09..592b5aa 100644 --- a/Sluift/ElementConvertors/PubSubSubscribeConvertor.h +++ b/Sluift/ElementConvertors/PubSubSubscribeConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubSubscribeConvertor : public GenericLuaElementConvertor { - public: - PubSubSubscribeConvertor(LuaElementConvertors* convertors); - virtual ~PubSubSubscribeConvertor(); + class PubSubSubscribeConvertor : public GenericLuaElementConvertor { + public: + PubSubSubscribeConvertor(LuaElementConvertors* convertors); + virtual ~PubSubSubscribeConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp index 3640084..70c5b4f 100644 --- a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.cpp @@ -13,32 +13,32 @@ using namespace Swift; PubSubSubscribeOptionsConvertor::PubSubSubscribeOptionsConvertor() : - GenericLuaElementConvertor("pubsub_subscribe_options") { + GenericLuaElementConvertor("pubsub_subscribe_options") { } PubSubSubscribeOptionsConvertor::~PubSubSubscribeOptionsConvertor() { } boost::shared_ptr PubSubSubscribeOptionsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "required"); - if (lua_isboolean(L, -1)) { - result->setRequired(lua_toboolean(L, -1)); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "required"); + if (lua_isboolean(L, -1)) { + result->setRequired(lua_toboolean(L, -1)); + } + lua_pop(L, 1); + return result; } void PubSubSubscribeOptionsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushboolean(L, payload->isRequired()); - lua_setfield(L, -2, "required"); + lua_createtable(L, 0, 0); + lua_pushboolean(L, payload->isRequired()); + lua_setfield(L, -2, "required"); } boost::optional PubSubSubscribeOptionsConvertor::getDocumentation() const { - return Documentation( - "PubSubSubscribeOptions", - "This table has the following fields:\n\n" - "- `required`: boolean\n" - ); + return Documentation( + "PubSubSubscribeOptions", + "This table has the following fields:\n\n" + "- `required`: boolean\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h index 1135300..3214dcf 100644 --- a/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h +++ b/Sluift/ElementConvertors/PubSubSubscribeOptionsConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubSubscribeOptionsConvertor : public GenericLuaElementConvertor { - public: - PubSubSubscribeOptionsConvertor(); - virtual ~PubSubSubscribeOptionsConvertor(); + class PubSubSubscribeOptionsConvertor : public GenericLuaElementConvertor { + public: + PubSubSubscribeOptionsConvertor(); + virtual ~PubSubSubscribeOptionsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp index 21a7fc8..79c188c 100644 --- a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.cpp @@ -14,97 +14,97 @@ using namespace Swift; -PubSubSubscriptionConvertor::PubSubSubscriptionConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_subscription"), - convertors(convertors) { +PubSubSubscriptionConvertor::PubSubSubscriptionConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_subscription"), + convertors(convertors) { } PubSubSubscriptionConvertor::~PubSubSubscriptionConvertor() { } boost::shared_ptr PubSubSubscriptionConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription_id"); - if (lua_isstring(L, -1)) { - result->setSubscriptionID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "jid"); - if (lua_isstring(L, -1)) { - result->setJID(JID(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "options"); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscribe_options"))) { - result->setOptions(payload); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription"); - if (lua_isstring(L, -1)) { - if (std::string(lua_tostring(L, -1)) == "none") { - result->setSubscription(PubSubSubscription::None); - } - if (std::string(lua_tostring(L, -1)) == "pending") { - result->setSubscription(PubSubSubscription::Pending); - } - if (std::string(lua_tostring(L, -1)) == "subscribed") { - result->setSubscription(PubSubSubscription::Subscribed); - } - if (std::string(lua_tostring(L, -1)) == "unconfigured") { - result->setSubscription(PubSubSubscription::Unconfigured); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription_id"); + if (lua_isstring(L, -1)) { + result->setSubscriptionID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "jid"); + if (lua_isstring(L, -1)) { + result->setJID(JID(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "options"); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscribe_options"))) { + result->setOptions(payload); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription"); + if (lua_isstring(L, -1)) { + if (std::string(lua_tostring(L, -1)) == "none") { + result->setSubscription(PubSubSubscription::None); + } + if (std::string(lua_tostring(L, -1)) == "pending") { + result->setSubscription(PubSubSubscription::Pending); + } + if (std::string(lua_tostring(L, -1)) == "subscribed") { + result->setSubscription(PubSubSubscription::Subscribed); + } + if (std::string(lua_tostring(L, -1)) == "unconfigured") { + result->setSubscription(PubSubSubscription::Unconfigured); + } + } + lua_pop(L, 1); + return result; } void PubSubSubscriptionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - if (payload->getSubscriptionID()) { - lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); - lua_setfield(L, -2, "subscription_id"); - } - lua_pushstring(L, payload->getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) { - lua_setfield(L, -2, "options"); - } - switch (payload->getSubscription()) { - case PubSubSubscription::None: - lua_pushstring(L, "none"); - break; - case PubSubSubscription::Pending: - lua_pushstring(L, "pending"); - break; - case PubSubSubscription::Subscribed: - lua_pushstring(L, "subscribed"); - break; - case PubSubSubscription::Unconfigured: - lua_pushstring(L, "unconfigured"); - break; - } - lua_setfield(L, -2, "subscription"); + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + if (payload->getSubscriptionID()) { + lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); + lua_setfield(L, -2, "subscription_id"); + } + lua_pushstring(L, payload->getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + if (convertors->convertToLuaUntyped(L, payload->getOptions()) > 0) { + lua_setfield(L, -2, "options"); + } + switch (payload->getSubscription()) { + case PubSubSubscription::None: + lua_pushstring(L, "none"); + break; + case PubSubSubscription::Pending: + lua_pushstring(L, "pending"); + break; + case PubSubSubscription::Subscribed: + lua_pushstring(L, "subscribed"); + break; + case PubSubSubscription::Unconfigured: + lua_pushstring(L, "unconfigured"); + break; + } + lua_setfield(L, -2, "subscription"); } boost::optional PubSubSubscriptionConvertor::getDocumentation() const { - return Documentation( - "PubSubSubscription", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `subscription_id`: string (Optional)\n" - "- `jid`: jid (string)\n" - "- `options`: @{PubSubSubscribeOptions}\n" - "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n" - ); + return Documentation( + "PubSubSubscription", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `subscription_id`: string (Optional)\n" + "- `jid`: jid (string)\n" + "- `options`: @{PubSubSubscribeOptions}\n" + "- `subscription`: `\"none\"`, `\"pending\"`, `\"subscribed\"`, or `\"unconfigured\"`\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h index 7c1b213..84aa275 100644 --- a/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h +++ b/Sluift/ElementConvertors/PubSubSubscriptionConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubSubscriptionConvertor : public GenericLuaElementConvertor { - public: - PubSubSubscriptionConvertor(LuaElementConvertors* convertors); - virtual ~PubSubSubscriptionConvertor(); + class PubSubSubscriptionConvertor : public GenericLuaElementConvertor { + public: + PubSubSubscriptionConvertor(LuaElementConvertors* convertors); + virtual ~PubSubSubscriptionConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp index cdaf5c7..a81817e 100644 --- a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.cpp @@ -17,63 +17,63 @@ using namespace Swift; -PubSubSubscriptionsConvertor::PubSubSubscriptionsConvertor(LuaElementConvertors* convertors) : - GenericLuaElementConvertor("pubsub_subscriptions"), - convertors(convertors) { +PubSubSubscriptionsConvertor::PubSubSubscriptionsConvertor(LuaElementConvertors* convertors) : + GenericLuaElementConvertor("pubsub_subscriptions"), + convertors(convertors) { } PubSubSubscriptionsConvertor::~PubSubSubscriptionsConvertor() { } boost::shared_ptr PubSubSubscriptionsConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< boost::shared_ptr > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscription"))) { - items.push_back(payload); - } - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< boost::shared_ptr > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + if (boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLuaUntyped(L, -1, "pubsub_subscription"))) { + items.push_back(payload); + } + } + lua_pop(L, 1); + } - result->setSubscriptions(items); - } - return result; + result->setSubscriptions(items); + } + return result; } void PubSubSubscriptionsConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - if (!payload->getSubscriptions().empty()) { - { - int i = 0; - foreach(boost::shared_ptr item, payload->getSubscriptions()) { - if (convertors->convertToLuaUntyped(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - } + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + if (!payload->getSubscriptions().empty()) { + { + int i = 0; + foreach(boost::shared_ptr item, payload->getSubscriptions()) { + if (convertors->convertToLuaUntyped(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + } } boost::optional PubSubSubscriptionsConvertor::getDocumentation() const { - return Documentation( - "PubSubSubscriptions", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `subscriptions`: array<@{PubSubSubscription}>\n" - ); + return Documentation( + "PubSubSubscriptions", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `subscriptions`: array<@{PubSubSubscription}>\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h index de5e9f4..82fa1f7 100644 --- a/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h +++ b/Sluift/ElementConvertors/PubSubSubscriptionsConvertor.h @@ -12,18 +12,18 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubSubscriptionsConvertor : public GenericLuaElementConvertor { - public: - PubSubSubscriptionsConvertor(LuaElementConvertors* convertors); - virtual ~PubSubSubscriptionsConvertor(); + class PubSubSubscriptionsConvertor : public GenericLuaElementConvertor { + public: + PubSubSubscriptionsConvertor(LuaElementConvertors* convertors); + virtual ~PubSubSubscriptionsConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - private: - LuaElementConvertors* convertors; - }; + private: + LuaElementConvertors* convertors; + }; } diff --git a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp index f25e9cf..3e83a97 100644 --- a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp +++ b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.cpp @@ -13,52 +13,52 @@ using namespace Swift; PubSubUnsubscribeConvertor::PubSubUnsubscribeConvertor() : - GenericLuaElementConvertor("pubsub_unsubscribe") { + GenericLuaElementConvertor("pubsub_unsubscribe") { } PubSubUnsubscribeConvertor::~PubSubUnsubscribeConvertor() { } boost::shared_ptr PubSubUnsubscribeConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "node"); - if (lua_isstring(L, -1)) { - result->setNode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "jid"); - if (lua_isstring(L, -1)) { - result->setJID(JID(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "subscription_id"); - if (lua_isstring(L, -1)) { - result->setSubscriptionID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "node"); + if (lua_isstring(L, -1)) { + result->setNode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "jid"); + if (lua_isstring(L, -1)) { + result->setJID(JID(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "subscription_id"); + if (lua_isstring(L, -1)) { + result->setSubscriptionID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void PubSubUnsubscribeConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getNode()) { - lua_pushstring(L, (*payload->getNode()).c_str()); - lua_setfield(L, -2, "node"); - } - lua_pushstring(L, payload->getJID().toString().c_str()); - lua_setfield(L, -2, "jid"); - if (payload->getSubscriptionID()) { - lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); - lua_setfield(L, -2, "subscription_id"); - } + lua_createtable(L, 0, 0); + if (payload->getNode()) { + lua_pushstring(L, (*payload->getNode()).c_str()); + lua_setfield(L, -2, "node"); + } + lua_pushstring(L, payload->getJID().toString().c_str()); + lua_setfield(L, -2, "jid"); + if (payload->getSubscriptionID()) { + lua_pushstring(L, (*payload->getSubscriptionID()).c_str()); + lua_setfield(L, -2, "subscription_id"); + } } boost::optional PubSubUnsubscribeConvertor::getDocumentation() const { - return Documentation( - "PubSubUnsubscribe", - "This table has the following fields:\n\n" - "- `node`: string (Optional)\n" - "- `jid`: jid (string)\n" - "- `subscription_id`: string (Optional)\n" - ); + return Documentation( + "PubSubUnsubscribe", + "This table has the following fields:\n\n" + "- `node`: string (Optional)\n" + "- `jid`: jid (string)\n" + "- `subscription_id`: string (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h index 91c856a..c6c3d06 100644 --- a/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h +++ b/Sluift/ElementConvertors/PubSubUnsubscribeConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class PubSubUnsubscribeConvertor : public GenericLuaElementConvertor { - public: - PubSubUnsubscribeConvertor(); - virtual ~PubSubUnsubscribeConvertor(); + class PubSubUnsubscribeConvertor : public GenericLuaElementConvertor { + public: + PubSubUnsubscribeConvertor(); + virtual ~PubSubUnsubscribeConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/RawXMLElementConvertor.cpp b/Sluift/ElementConvertors/RawXMLElementConvertor.cpp index 1b26e74..07ca021 100644 --- a/Sluift/ElementConvertors/RawXMLElementConvertor.cpp +++ b/Sluift/ElementConvertors/RawXMLElementConvertor.cpp @@ -26,19 +26,19 @@ RawXMLElementConvertor::~RawXMLElementConvertor() { } boost::shared_ptr RawXMLElementConvertor::convertFromLua(lua_State* L, int index, const std::string& type) { - if (type == "xml") { - return boost::make_shared(std::string(Lua::checkString(L, index))); - } - return boost::shared_ptr(); + if (type == "xml") { + return boost::make_shared(std::string(Lua::checkString(L, index))); + } + return boost::shared_ptr(); } boost::optional RawXMLElementConvertor::convertToLua(lua_State* L, boost::shared_ptr element) { - boost::shared_ptr payload = boost::dynamic_pointer_cast(element); - if (!payload) { - return boost::optional(); - } - PayloadSerializer* serializer = serializers.getPayloadSerializer(payload); - assert(serializer); - lua_pushstring(L, serializer->serialize(payload).c_str()); - return std::string("xml"); + boost::shared_ptr payload = boost::dynamic_pointer_cast(element); + if (!payload) { + return boost::optional(); + } + PayloadSerializer* serializer = serializers.getPayloadSerializer(payload); + assert(serializer); + lua_pushstring(L, serializer->serialize(payload).c_str()); + return std::string("xml"); } diff --git a/Sluift/ElementConvertors/RawXMLElementConvertor.h b/Sluift/ElementConvertors/RawXMLElementConvertor.h index 0a3b463..22323ec 100644 --- a/Sluift/ElementConvertors/RawXMLElementConvertor.h +++ b/Sluift/ElementConvertors/RawXMLElementConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class RawXMLElementConvertor : public LuaElementConvertor { - public: - RawXMLElementConvertor(); - virtual ~RawXMLElementConvertor(); + class RawXMLElementConvertor : public LuaElementConvertor { + public: + RawXMLElementConvertor(); + virtual ~RawXMLElementConvertor(); - virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE; - virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) SWIFTEN_OVERRIDE; + virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - private: - FullPayloadSerializerCollection serializers; - }; + private: + FullPayloadSerializerCollection serializers; + }; } diff --git a/Sluift/ElementConvertors/ResultSetConvertor.cpp b/Sluift/ElementConvertors/ResultSetConvertor.cpp index 166ddd4..aa84aac 100644 --- a/Sluift/ElementConvertors/ResultSetConvertor.cpp +++ b/Sluift/ElementConvertors/ResultSetConvertor.cpp @@ -14,102 +14,102 @@ using namespace Swift; ResultSetConvertor::ResultSetConvertor() : - GenericLuaElementConvertor("result_set") { + GenericLuaElementConvertor("result_set") { } ResultSetConvertor::~ResultSetConvertor() { } boost::shared_ptr ResultSetConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "max_items"); - if (lua_isstring(L, -1)) { - result->setMaxItems(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "count"); - if (lua_isnumber(L, -1)) { - result->setCount(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "index"); - if (lua_isnumber(L, -1)) { - result->setIndex(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "first_id_index"); - if (lua_isstring(L, -1)) { - result->setFirstIDIndex(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "first_id"); - if (lua_isstring(L, -1)) { - result->setFirstID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "last_id"); - if (lua_isstring(L, -1)) { - result->setLastID(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "after"); - if (lua_isstring(L, -1)) { - result->setAfter(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "before"); - if (lua_isstring(L, -1)) { - result->setBefore(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "max_items"); + if (lua_isstring(L, -1)) { + result->setMaxItems(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "count"); + if (lua_isnumber(L, -1)) { + result->setCount(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "index"); + if (lua_isnumber(L, -1)) { + result->setIndex(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "first_id_index"); + if (lua_isstring(L, -1)) { + result->setFirstIDIndex(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "first_id"); + if (lua_isstring(L, -1)) { + result->setFirstID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "last_id"); + if (lua_isstring(L, -1)) { + result->setLastID(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "after"); + if (lua_isstring(L, -1)) { + result->setAfter(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "before"); + if (lua_isstring(L, -1)) { + result->setBefore(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void ResultSetConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getMaxItems()) { - lua_pushnumber(L, *payload->getMaxItems()); - lua_setfield(L, -2, "max_items"); - } - if (payload->getCount()) { - lua_pushnumber(L, *payload->getCount()); - lua_setfield(L, -2, "count"); - } - if (payload->getIndex()) { - lua_pushnumber(L, *payload->getIndex()); - lua_setfield(L, -2, "index"); - } - if (payload->getFirstIDIndex()) { - lua_pushnumber(L, *payload->getFirstIDIndex()); - lua_setfield(L, -2, "first_id_index"); - } - if (payload->getFirstID()) { - lua_pushstring(L, (*payload->getFirstID()).c_str()); - lua_setfield(L, -2, "first_id"); - } - if (payload->getLastID()) { - lua_pushstring(L, (*payload->getLastID()).c_str()); - lua_setfield(L, -2, "last_id"); - } - if (payload->getAfter()) { - lua_pushstring(L, (*payload->getAfter()).c_str()); - lua_setfield(L, -2, "after"); - } - if (payload->getBefore()) { - lua_pushstring(L, (*payload->getBefore()).c_str()); - lua_setfield(L, -2, "before"); - } + lua_createtable(L, 0, 0); + if (payload->getMaxItems()) { + lua_pushnumber(L, *payload->getMaxItems()); + lua_setfield(L, -2, "max_items"); + } + if (payload->getCount()) { + lua_pushnumber(L, *payload->getCount()); + lua_setfield(L, -2, "count"); + } + if (payload->getIndex()) { + lua_pushnumber(L, *payload->getIndex()); + lua_setfield(L, -2, "index"); + } + if (payload->getFirstIDIndex()) { + lua_pushnumber(L, *payload->getFirstIDIndex()); + lua_setfield(L, -2, "first_id_index"); + } + if (payload->getFirstID()) { + lua_pushstring(L, (*payload->getFirstID()).c_str()); + lua_setfield(L, -2, "first_id"); + } + if (payload->getLastID()) { + lua_pushstring(L, (*payload->getLastID()).c_str()); + lua_setfield(L, -2, "last_id"); + } + if (payload->getAfter()) { + lua_pushstring(L, (*payload->getAfter()).c_str()); + lua_setfield(L, -2, "after"); + } + if (payload->getBefore()) { + lua_pushstring(L, (*payload->getBefore()).c_str()); + lua_setfield(L, -2, "before"); + } } boost::optional ResultSetConvertor::getDocumentation() const { - return Documentation( - "ResultSet", - "This table has the following fields:\n\n" - "- `max_items`: number (Optional)\n" - "- `count`: number (Optional)\n" - "- `first_id_index`: number (Optional)\n" - "- `first_id`: string (Optional)\n" - "- `last_id`: string (Optional)\n" - "- `after`: string (Optional)\n" - ); + return Documentation( + "ResultSet", + "This table has the following fields:\n\n" + "- `max_items`: number (Optional)\n" + "- `count`: number (Optional)\n" + "- `first_id_index`: number (Optional)\n" + "- `first_id`: string (Optional)\n" + "- `last_id`: string (Optional)\n" + "- `after`: string (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/ResultSetConvertor.h b/Sluift/ElementConvertors/ResultSetConvertor.h index 46353f2..5df9c3e 100644 --- a/Sluift/ElementConvertors/ResultSetConvertor.h +++ b/Sluift/ElementConvertors/ResultSetConvertor.h @@ -12,16 +12,16 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class ResultSetConvertor : public GenericLuaElementConvertor { - public: - ResultSetConvertor(); - virtual ~ResultSetConvertor(); + class ResultSetConvertor : public GenericLuaElementConvertor { + public: + ResultSetConvertor(); + virtual ~ResultSetConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp index 011cfda..a5cae40 100644 --- a/Sluift/ElementConvertors/SecurityLabelConvertor.cpp +++ b/Sluift/ElementConvertors/SecurityLabelConvertor.cpp @@ -16,84 +16,84 @@ using namespace Swift; SecurityLabelConvertor::SecurityLabelConvertor() : - GenericLuaElementConvertor("security_label") { + GenericLuaElementConvertor("security_label") { } SecurityLabelConvertor::~SecurityLabelConvertor() { } boost::shared_ptr SecurityLabelConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "equivalent_labels"); - if (lua_type(L, -1) == LUA_TTABLE) { - std::vector< std::string > items; - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (lua_isstring(L, -1)) { - items.push_back(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - } + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "equivalent_labels"); + if (lua_type(L, -1) == LUA_TTABLE) { + std::vector< std::string > items; + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (lua_isstring(L, -1)) { + items.push_back(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + } - result->setEquivalentLabels(items); - } - lua_pop(L, 1); - lua_getfield(L, -1, "foreground_color"); - if (lua_isstring(L, -1)) { - result->setForegroundColor(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "display_marking"); - if (lua_isstring(L, -1)) { - result->setDisplayMarking(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "background_color"); - if (lua_isstring(L, -1)) { - result->setBackgroundColor(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "label"); - if (lua_isstring(L, -1)) { - result->setLabel(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + result->setEquivalentLabels(items); + } + lua_pop(L, 1); + lua_getfield(L, -1, "foreground_color"); + if (lua_isstring(L, -1)) { + result->setForegroundColor(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "display_marking"); + if (lua_isstring(L, -1)) { + result->setDisplayMarking(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "background_color"); + if (lua_isstring(L, -1)) { + result->setBackgroundColor(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "label"); + if (lua_isstring(L, -1)) { + result->setLabel(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void SecurityLabelConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (!payload->getEquivalentLabels().empty()) { - lua_createtable(L, boost::numeric_cast(payload->getEquivalentLabels().size()), 0); - { - int i = 0; - foreach(const std::string& item, payload->getEquivalentLabels()) { - lua_pushstring(L, item.c_str()); - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - lua_setfield(L, -2, "equivalent_labels"); - } - lua_pushstring(L, payload->getForegroundColor().c_str()); - lua_setfield(L, -2, "foreground_color"); - lua_pushstring(L, payload->getDisplayMarking().c_str()); - lua_setfield(L, -2, "display_marking"); - lua_pushstring(L, payload->getBackgroundColor().c_str()); - lua_setfield(L, -2, "background_color"); - lua_pushstring(L, payload->getLabel().c_str()); - lua_setfield(L, -2, "label"); + lua_createtable(L, 0, 0); + if (!payload->getEquivalentLabels().empty()) { + lua_createtable(L, boost::numeric_cast(payload->getEquivalentLabels().size()), 0); + { + int i = 0; + foreach(const std::string& item, payload->getEquivalentLabels()) { + lua_pushstring(L, item.c_str()); + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + lua_setfield(L, -2, "equivalent_labels"); + } + lua_pushstring(L, payload->getForegroundColor().c_str()); + lua_setfield(L, -2, "foreground_color"); + lua_pushstring(L, payload->getDisplayMarking().c_str()); + lua_setfield(L, -2, "display_marking"); + lua_pushstring(L, payload->getBackgroundColor().c_str()); + lua_setfield(L, -2, "background_color"); + lua_pushstring(L, payload->getLabel().c_str()); + lua_setfield(L, -2, "label"); } boost::optional SecurityLabelConvertor::getDocumentation() const { - return Documentation( - "SecurityLabel", - "This table has the following fields:\n\n" - "- `equivalent_labels`: array\n" - "- `foreground_color`: string\n" - "- `display_marking`: string\n" - "- `background_color`: string\n" - "- `label`: string\n" - ); + return Documentation( + "SecurityLabel", + "This table has the following fields:\n\n" + "- `equivalent_labels`: array\n" + "- `foreground_color`: string\n" + "- `display_marking`: string\n" + "- `background_color`: string\n" + "- `label`: string\n" + ); } diff --git a/Sluift/ElementConvertors/SecurityLabelConvertor.h b/Sluift/ElementConvertors/SecurityLabelConvertor.h index 001123d..eff455c 100644 --- a/Sluift/ElementConvertors/SecurityLabelConvertor.h +++ b/Sluift/ElementConvertors/SecurityLabelConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class SecurityLabelConvertor : public GenericLuaElementConvertor { - public: - SecurityLabelConvertor(); - virtual ~SecurityLabelConvertor(); + class SecurityLabelConvertor : public GenericLuaElementConvertor { + public: + SecurityLabelConvertor(); + virtual ~SecurityLabelConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp b/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp index 9ac1679..4f372c2 100644 --- a/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp +++ b/Sluift/ElementConvertors/SoftwareVersionConvertor.cpp @@ -22,31 +22,31 @@ SoftwareVersionConvertor::~SoftwareVersionConvertor() { } boost::shared_ptr SoftwareVersionConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "name"); - if (!lua_isnil(L, -1)) { - result->setName(std::string(Lua::checkString(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "version"); - if (!lua_isnil(L, -1)) { - result->setVersion(std::string(Lua::checkString(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "os"); - if (!lua_isnil(L, -1)) { - result->setOS(std::string(Lua::checkString(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "name"); + if (!lua_isnil(L, -1)) { + result->setName(std::string(Lua::checkString(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "version"); + if (!lua_isnil(L, -1)) { + result->setVersion(std::string(Lua::checkString(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "os"); + if (!lua_isnil(L, -1)) { + result->setOS(std::string(Lua::checkString(L, -1))); + } + lua_pop(L, 1); + return result; } void SoftwareVersionConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getName().c_str()); - lua_setfield(L, -2, "name"); - lua_pushstring(L, payload->getVersion().c_str()); - lua_setfield(L, -2, "version"); - lua_pushstring(L, payload->getOS().c_str()); - lua_setfield(L, -2, "os"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getName().c_str()); + lua_setfield(L, -2, "name"); + lua_pushstring(L, payload->getVersion().c_str()); + lua_setfield(L, -2, "version"); + lua_pushstring(L, payload->getOS().c_str()); + lua_setfield(L, -2, "os"); } diff --git a/Sluift/ElementConvertors/SoftwareVersionConvertor.h b/Sluift/ElementConvertors/SoftwareVersionConvertor.h index 77b2ad6..4df23c0 100644 --- a/Sluift/ElementConvertors/SoftwareVersionConvertor.h +++ b/Sluift/ElementConvertors/SoftwareVersionConvertor.h @@ -12,12 +12,12 @@ #include namespace Swift { - class SoftwareVersionConvertor : public GenericLuaElementConvertor { - public: - SoftwareVersionConvertor(); - virtual ~SoftwareVersionConvertor(); + class SoftwareVersionConvertor : public GenericLuaElementConvertor { + public: + SoftwareVersionConvertor(); + virtual ~SoftwareVersionConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/StanzaConvertor.h b/Sluift/ElementConvertors/StanzaConvertor.h index 420232a..309121e 100644 --- a/Sluift/ElementConvertors/StanzaConvertor.h +++ b/Sluift/ElementConvertors/StanzaConvertor.h @@ -19,71 +19,71 @@ #include namespace Swift { - template class StanzaConvertor : public GenericLuaElementConvertor { - public: - StanzaConvertor(const std::string& tag) - : GenericLuaElementConvertor(tag) { - } + template class StanzaConvertor : public GenericLuaElementConvertor { + public: + StanzaConvertor(const std::string& tag) + : GenericLuaElementConvertor(tag) { + } - virtual ~StanzaConvertor() { - } + virtual ~StanzaConvertor() { + } - boost::shared_ptr getStanza(lua_State* L, LuaElementConvertors* convertors) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "id"); - if (lua_isstring(L, -1)) { - result->setID(lua_tostring(L, -1)); - } - lua_pop(L, 1); - lua_getfield(L, -1, "from"); - if (lua_isstring(L, -1)) { - result->setFrom(lua_tostring(L, -1)); - } - lua_pop(L, 1); - lua_getfield(L, -1, "to"); - if (lua_isstring(L, -1)) { - result->setTo(lua_tostring(L, -1)); - } - lua_pop(L, 1); - lua_getfield(L, -1, "payloads"); - if (lua_type(L, -1) == LUA_TTABLE) { - for(size_t i = 0; i < lua_objlen(L, -1); ++i) { - lua_pushnumber(L, i + 1); - lua_gettable(L, -2); - if (!lua_isnil(L, -1)) { - boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1)); - if (!!payload) { - result->addPayload(payload); - } - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - return result; - } + boost::shared_ptr getStanza(lua_State* L, LuaElementConvertors* convertors) { + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "id"); + if (lua_isstring(L, -1)) { + result->setID(lua_tostring(L, -1)); + } + lua_pop(L, 1); + lua_getfield(L, -1, "from"); + if (lua_isstring(L, -1)) { + result->setFrom(lua_tostring(L, -1)); + } + lua_pop(L, 1); + lua_getfield(L, -1, "to"); + if (lua_isstring(L, -1)) { + result->setTo(lua_tostring(L, -1)); + } + lua_pop(L, 1); + lua_getfield(L, -1, "payloads"); + if (lua_type(L, -1) == LUA_TTABLE) { + for(size_t i = 0; i < lua_objlen(L, -1); ++i) { + lua_pushnumber(L, i + 1); + lua_gettable(L, -2); + if (!lua_isnil(L, -1)) { + boost::shared_ptr payload = boost::dynamic_pointer_cast(convertors->convertFromLua(L, -1)); + if (!!payload) { + result->addPayload(payload); + } + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + return result; + } - void pushStanza(lua_State* L, const boost::shared_ptr stanza, LuaElementConvertors* convertors) { - lua_createtable(L, 0, 0); - lua_pushstring(L, stanza->getID().c_str()); - lua_setfield(L, -2, "id"); - lua_pushstring(L, stanza->getFrom().toString().c_str()); - lua_setfield(L, -2, "from"); - lua_pushstring(L, stanza->getTo().toString().c_str()); - lua_setfield(L, -2, "to"); - if (!stanza->getPayloads().empty()) { - lua_createtable(L, boost::numeric_cast(stanza->getPayloads().size()), 0); - { - int i = 0; - foreach(const boost::shared_ptr &item, stanza->getPayloads()) { - if (convertors->convertToLua(L, item) > 0) { - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - ++i; - } - } - } - lua_setfield(L, -2, "payloads"); - } - } - }; + void pushStanza(lua_State* L, const boost::shared_ptr stanza, LuaElementConvertors* convertors) { + lua_createtable(L, 0, 0); + lua_pushstring(L, stanza->getID().c_str()); + lua_setfield(L, -2, "id"); + lua_pushstring(L, stanza->getFrom().toString().c_str()); + lua_setfield(L, -2, "from"); + lua_pushstring(L, stanza->getTo().toString().c_str()); + lua_setfield(L, -2, "to"); + if (!stanza->getPayloads().empty()) { + lua_createtable(L, boost::numeric_cast(stanza->getPayloads().size()), 0); + { + int i = 0; + foreach(const boost::shared_ptr &item, stanza->getPayloads()) { + if (convertors->convertToLua(L, item) > 0) { + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + ++i; + } + } + } + lua_setfield(L, -2, "payloads"); + } + } + }; } diff --git a/Sluift/ElementConvertors/StatusConvertor.cpp b/Sluift/ElementConvertors/StatusConvertor.cpp index 575a4ea..241a2cc 100644 --- a/Sluift/ElementConvertors/StatusConvertor.cpp +++ b/Sluift/ElementConvertors/StatusConvertor.cpp @@ -22,17 +22,17 @@ StatusConvertor::~StatusConvertor() { } boost::shared_ptr StatusConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "text"); - if (lua_isstring(L, -1)) { - result->setText(lua_tostring(L, -1)); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "text"); + if (lua_isstring(L, -1)) { + result->setText(lua_tostring(L, -1)); + } + lua_pop(L, 1); + return result; } void StatusConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - lua_pushstring(L, payload->getText().c_str()); - lua_setfield(L, -2, "text"); + lua_createtable(L, 0, 0); + lua_pushstring(L, payload->getText().c_str()); + lua_setfield(L, -2, "text"); } diff --git a/Sluift/ElementConvertors/StatusConvertor.h b/Sluift/ElementConvertors/StatusConvertor.h index 33fe861..739d319 100644 --- a/Sluift/ElementConvertors/StatusConvertor.h +++ b/Sluift/ElementConvertors/StatusConvertor.h @@ -12,12 +12,12 @@ #include namespace Swift { - class StatusConvertor : public GenericLuaElementConvertor { - public: - StatusConvertor(); - virtual ~StatusConvertor(); + class StatusConvertor : public GenericLuaElementConvertor { + public: + StatusConvertor(); + virtual ~StatusConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/StatusShowConvertor.cpp b/Sluift/ElementConvertors/StatusShowConvertor.cpp index faae289..d1c1e85 100644 --- a/Sluift/ElementConvertors/StatusShowConvertor.cpp +++ b/Sluift/ElementConvertors/StatusShowConvertor.cpp @@ -23,54 +23,54 @@ StatusShowConvertor::~StatusShowConvertor() { } boost::shared_ptr StatusShowConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "type"); - if (lua_isstring(L, -1)) { - result->setType(convertStatusShowTypeFromString(lua_tostring(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "type"); + if (lua_isstring(L, -1)) { + result->setType(convertStatusShowTypeFromString(lua_tostring(L, -1))); + } + lua_pop(L, 1); + return result; } void StatusShowConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - const std::string show = convertStatusShowTypeToString(payload->getType()); - if (!show.empty()) { - lua_pushstring(L, show.c_str()); - lua_setfield(L, -2, "type"); - } + lua_createtable(L, 0, 0); + const std::string show = convertStatusShowTypeToString(payload->getType()); + if (!show.empty()) { + lua_pushstring(L, show.c_str()); + lua_setfield(L, -2, "type"); + } } std::string StatusShowConvertor::convertStatusShowTypeToString(const StatusShow::Type &show) { - switch (show) { - case StatusShow::Online: return "online"; - case StatusShow::FFC: return "ffc"; - case StatusShow::Away: return "away"; - case StatusShow::XA: return "xa"; - case StatusShow::DND: return "dnd"; - case StatusShow::None: return ""; - } - assert(false); - return ""; + switch (show) { + case StatusShow::Online: return "online"; + case StatusShow::FFC: return "ffc"; + case StatusShow::Away: return "away"; + case StatusShow::XA: return "xa"; + case StatusShow::DND: return "dnd"; + case StatusShow::None: return ""; + } + assert(false); + return ""; } StatusShow::Type StatusShowConvertor::convertStatusShowTypeFromString(const std::string& show) { - if (show == "online") { - return StatusShow::Online; - } - else if (show == "ffc") { - return StatusShow::FFC; - } - else if (show == "away") { - return StatusShow::Away; - } - else if (show == "xa") { - return StatusShow::XA; - } - else if (show == "dnd") { - return StatusShow::DND; - } - else { - throw Lua::Exception("Illegal status show: '" + show + "'"); - } + if (show == "online") { + return StatusShow::Online; + } + else if (show == "ffc") { + return StatusShow::FFC; + } + else if (show == "away") { + return StatusShow::Away; + } + else if (show == "xa") { + return StatusShow::XA; + } + else if (show == "dnd") { + return StatusShow::DND; + } + else { + throw Lua::Exception("Illegal status show: '" + show + "'"); + } } diff --git a/Sluift/ElementConvertors/StatusShowConvertor.h b/Sluift/ElementConvertors/StatusShowConvertor.h index d71493d..1eef447 100644 --- a/Sluift/ElementConvertors/StatusShowConvertor.h +++ b/Sluift/ElementConvertors/StatusShowConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class StatusShowConvertor : public GenericLuaElementConvertor { - public: - StatusShowConvertor(); - virtual ~StatusShowConvertor(); + class StatusShowConvertor : public GenericLuaElementConvertor { + public: + StatusShowConvertor(); + virtual ~StatusShowConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - static std::string convertStatusShowTypeToString(const StatusShow::Type &show); - static StatusShow::Type convertStatusShowTypeFromString(const std::string& show); - }; + static std::string convertStatusShowTypeToString(const StatusShow::Type &show); + static StatusShow::Type convertStatusShowTypeFromString(const std::string& show); + }; } diff --git a/Sluift/ElementConvertors/SubjectConvertor.cpp b/Sluift/ElementConvertors/SubjectConvertor.cpp index 8f15515..ac40744 100644 --- a/Sluift/ElementConvertors/SubjectConvertor.cpp +++ b/Sluift/ElementConvertors/SubjectConvertor.cpp @@ -21,17 +21,17 @@ SubjectConvertor::~SubjectConvertor() { } boost::shared_ptr SubjectConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - if (boost::optional value = Lua::getStringField(L, -1, "text")) { - result->setText(*value); - } - return result; + boost::shared_ptr result = boost::make_shared(); + if (boost::optional value = Lua::getStringField(L, -1, "text")) { + result->setText(*value); + } + return result; } void SubjectConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (!payload->getText().empty()) { - lua_pushstring(L, payload->getText().c_str()); - lua_setfield(L, -2, "text"); - } + lua_createtable(L, 0, 0); + if (!payload->getText().empty()) { + lua_pushstring(L, payload->getText().c_str()); + lua_setfield(L, -2, "text"); + } } diff --git a/Sluift/ElementConvertors/SubjectConvertor.h b/Sluift/ElementConvertors/SubjectConvertor.h index 5969293..604ad9c 100644 --- a/Sluift/ElementConvertors/SubjectConvertor.h +++ b/Sluift/ElementConvertors/SubjectConvertor.h @@ -12,14 +12,14 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class SubjectConvertor : public GenericLuaElementConvertor { - public: - SubjectConvertor(); - virtual ~SubjectConvertor(); + class SubjectConvertor : public GenericLuaElementConvertor { + public: + SubjectConvertor(); + virtual ~SubjectConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/UserLocationConvertor.cpp b/Sluift/ElementConvertors/UserLocationConvertor.cpp index 67c4ec0..d59382b 100644 --- a/Sluift/ElementConvertors/UserLocationConvertor.cpp +++ b/Sluift/ElementConvertors/UserLocationConvertor.cpp @@ -16,244 +16,244 @@ using namespace Swift; UserLocationConvertor::UserLocationConvertor() : - GenericLuaElementConvertor("user_location") { + GenericLuaElementConvertor("user_location") { } UserLocationConvertor::~UserLocationConvertor() { } boost::shared_ptr UserLocationConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "area"); - if (lua_isstring(L, -1)) { - result->setArea(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "altitude"); - if (lua_isnumber(L, -1)) { - result->setAltitude(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "locality"); - if (lua_isstring(L, -1)) { - result->setLocality(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "latitude"); - if (lua_isnumber(L, -1)) { - result->setLatitude(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "accuracy"); - if (lua_isnumber(L, -1)) { - result->setAccuracy(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "description"); - if (lua_isstring(L, -1)) { - result->setDescription(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "country_code"); - if (lua_isstring(L, -1)) { - result->setCountryCode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "timestamp"); - if (lua_isstring(L, -1)) { - result->setTimestamp(stringToDateTime(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "floor"); - if (lua_isstring(L, -1)) { - result->setFloor(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "building"); - if (lua_isstring(L, -1)) { - result->setBuilding(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "room"); - if (lua_isstring(L, -1)) { - result->setRoom(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "country"); - if (lua_isstring(L, -1)) { - result->setCountry(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "region"); - if (lua_isstring(L, -1)) { - result->setRegion(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "uri"); - if (lua_isstring(L, -1)) { - result->setURI(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "longitude"); - if (lua_isnumber(L, -1)) { - result->setLongitude(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "error"); - if (lua_isnumber(L, -1)) { - result->setError(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "postal_code"); - if (lua_isstring(L, -1)) { - result->setPostalCode(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "bearing"); - if (lua_isnumber(L, -1)) { - result->setBearing(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "text"); - if (lua_isstring(L, -1)) { - result->setText(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "datum"); - if (lua_isstring(L, -1)) { - result->setDatum(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "street"); - if (lua_isstring(L, -1)) { - result->setStreet(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "speed"); - if (lua_isnumber(L, -1)) { - result->setSpeed(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "area"); + if (lua_isstring(L, -1)) { + result->setArea(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "altitude"); + if (lua_isnumber(L, -1)) { + result->setAltitude(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "locality"); + if (lua_isstring(L, -1)) { + result->setLocality(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "latitude"); + if (lua_isnumber(L, -1)) { + result->setLatitude(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "accuracy"); + if (lua_isnumber(L, -1)) { + result->setAccuracy(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "description"); + if (lua_isstring(L, -1)) { + result->setDescription(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "country_code"); + if (lua_isstring(L, -1)) { + result->setCountryCode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "timestamp"); + if (lua_isstring(L, -1)) { + result->setTimestamp(stringToDateTime(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "floor"); + if (lua_isstring(L, -1)) { + result->setFloor(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "building"); + if (lua_isstring(L, -1)) { + result->setBuilding(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "room"); + if (lua_isstring(L, -1)) { + result->setRoom(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "country"); + if (lua_isstring(L, -1)) { + result->setCountry(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "region"); + if (lua_isstring(L, -1)) { + result->setRegion(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "uri"); + if (lua_isstring(L, -1)) { + result->setURI(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "longitude"); + if (lua_isnumber(L, -1)) { + result->setLongitude(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "error"); + if (lua_isnumber(L, -1)) { + result->setError(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "postal_code"); + if (lua_isstring(L, -1)) { + result->setPostalCode(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "bearing"); + if (lua_isnumber(L, -1)) { + result->setBearing(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "text"); + if (lua_isstring(L, -1)) { + result->setText(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "datum"); + if (lua_isstring(L, -1)) { + result->setDatum(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "street"); + if (lua_isstring(L, -1)) { + result->setStreet(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "speed"); + if (lua_isnumber(L, -1)) { + result->setSpeed(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + return result; } void UserLocationConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getArea()) { - lua_pushstring(L, (*payload->getArea()).c_str()); - lua_setfield(L, -2, "area"); - } - if (payload->getAltitude()) { - lua_pushnumber(L, (*payload->getAltitude())); - lua_setfield(L, -2, "altitude"); - } - if (payload->getLocality()) { - lua_pushstring(L, (*payload->getLocality()).c_str()); - lua_setfield(L, -2, "locality"); - } - if (payload->getLatitude()) { - lua_pushnumber(L, (*payload->getLatitude())); - lua_setfield(L, -2, "latitude"); - } - if (payload->getAccuracy()) { - lua_pushnumber(L, (*payload->getAccuracy())); - lua_setfield(L, -2, "accuracy"); - } - if (payload->getDescription()) { - lua_pushstring(L, (*payload->getDescription()).c_str()); - lua_setfield(L, -2, "description"); - } - if (payload->getCountryCode()) { - lua_pushstring(L, (*payload->getCountryCode()).c_str()); - lua_setfield(L, -2, "country_code"); - } - if (payload->getTimestamp()) { - lua_pushstring(L, dateTimeToString((*payload->getTimestamp())).c_str()); - lua_setfield(L, -2, "timestamp"); - } - if (payload->getFloor()) { - lua_pushstring(L, (*payload->getFloor()).c_str()); - lua_setfield(L, -2, "floor"); - } - if (payload->getBuilding()) { - lua_pushstring(L, (*payload->getBuilding()).c_str()); - lua_setfield(L, -2, "building"); - } - if (payload->getRoom()) { - lua_pushstring(L, (*payload->getRoom()).c_str()); - lua_setfield(L, -2, "room"); - } - if (payload->getCountry()) { - lua_pushstring(L, (*payload->getCountry()).c_str()); - lua_setfield(L, -2, "country"); - } - if (payload->getRegion()) { - lua_pushstring(L, (*payload->getRegion()).c_str()); - lua_setfield(L, -2, "region"); - } - if (payload->getURI()) { - lua_pushstring(L, (*payload->getURI()).c_str()); - lua_setfield(L, -2, "uri"); - } - if (payload->getLongitude()) { - lua_pushnumber(L, (*payload->getLongitude())); - lua_setfield(L, -2, "longitude"); - } - if (payload->getError()) { - lua_pushnumber(L, (*payload->getError())); - lua_setfield(L, -2, "error"); - } - if (payload->getPostalCode()) { - lua_pushstring(L, (*payload->getPostalCode()).c_str()); - lua_setfield(L, -2, "postal_code"); - } - if (payload->getBearing()) { - lua_pushnumber(L, (*payload->getBearing())); - lua_setfield(L, -2, "bearing"); - } - if (payload->getText()) { - lua_pushstring(L, (*payload->getText()).c_str()); - lua_setfield(L, -2, "text"); - } - if (payload->getDatum()) { - lua_pushstring(L, (*payload->getDatum()).c_str()); - lua_setfield(L, -2, "datum"); - } - if (payload->getStreet()) { - lua_pushstring(L, (*payload->getStreet()).c_str()); - lua_setfield(L, -2, "street"); - } - if (payload->getSpeed()) { - lua_pushnumber(L, (*payload->getSpeed())); - lua_setfield(L, -2, "speed"); - } + lua_createtable(L, 0, 0); + if (payload->getArea()) { + lua_pushstring(L, (*payload->getArea()).c_str()); + lua_setfield(L, -2, "area"); + } + if (payload->getAltitude()) { + lua_pushnumber(L, (*payload->getAltitude())); + lua_setfield(L, -2, "altitude"); + } + if (payload->getLocality()) { + lua_pushstring(L, (*payload->getLocality()).c_str()); + lua_setfield(L, -2, "locality"); + } + if (payload->getLatitude()) { + lua_pushnumber(L, (*payload->getLatitude())); + lua_setfield(L, -2, "latitude"); + } + if (payload->getAccuracy()) { + lua_pushnumber(L, (*payload->getAccuracy())); + lua_setfield(L, -2, "accuracy"); + } + if (payload->getDescription()) { + lua_pushstring(L, (*payload->getDescription()).c_str()); + lua_setfield(L, -2, "description"); + } + if (payload->getCountryCode()) { + lua_pushstring(L, (*payload->getCountryCode()).c_str()); + lua_setfield(L, -2, "country_code"); + } + if (payload->getTimestamp()) { + lua_pushstring(L, dateTimeToString((*payload->getTimestamp())).c_str()); + lua_setfield(L, -2, "timestamp"); + } + if (payload->getFloor()) { + lua_pushstring(L, (*payload->getFloor()).c_str()); + lua_setfield(L, -2, "floor"); + } + if (payload->getBuilding()) { + lua_pushstring(L, (*payload->getBuilding()).c_str()); + lua_setfield(L, -2, "building"); + } + if (payload->getRoom()) { + lua_pushstring(L, (*payload->getRoom()).c_str()); + lua_setfield(L, -2, "room"); + } + if (payload->getCountry()) { + lua_pushstring(L, (*payload->getCountry()).c_str()); + lua_setfield(L, -2, "country"); + } + if (payload->getRegion()) { + lua_pushstring(L, (*payload->getRegion()).c_str()); + lua_setfield(L, -2, "region"); + } + if (payload->getURI()) { + lua_pushstring(L, (*payload->getURI()).c_str()); + lua_setfield(L, -2, "uri"); + } + if (payload->getLongitude()) { + lua_pushnumber(L, (*payload->getLongitude())); + lua_setfield(L, -2, "longitude"); + } + if (payload->getError()) { + lua_pushnumber(L, (*payload->getError())); + lua_setfield(L, -2, "error"); + } + if (payload->getPostalCode()) { + lua_pushstring(L, (*payload->getPostalCode()).c_str()); + lua_setfield(L, -2, "postal_code"); + } + if (payload->getBearing()) { + lua_pushnumber(L, (*payload->getBearing())); + lua_setfield(L, -2, "bearing"); + } + if (payload->getText()) { + lua_pushstring(L, (*payload->getText()).c_str()); + lua_setfield(L, -2, "text"); + } + if (payload->getDatum()) { + lua_pushstring(L, (*payload->getDatum()).c_str()); + lua_setfield(L, -2, "datum"); + } + if (payload->getStreet()) { + lua_pushstring(L, (*payload->getStreet()).c_str()); + lua_setfield(L, -2, "street"); + } + if (payload->getSpeed()) { + lua_pushnumber(L, (*payload->getSpeed())); + lua_setfield(L, -2, "speed"); + } } boost::optional UserLocationConvertor::getDocumentation() const { - return Documentation( - "UserLocation", - "This table has the following fields:\n\n" - "- `area`: string (Optional)\n" - "- `altitude`: @{float} (Optional)\n" - "- `locality`: string (Optional)\n" - "- `latitude`: @{float} (Optional)\n" - "- `accuracy`: @{float} (Optional)\n" - "- `description`: string (Optional)\n" - "- `country_code`: string (Optional)\n" - "- `timestamp`: datetime (string) (Optional)\n" - "- `floor`: string (Optional)\n" - "- `building`: string (Optional)\n" - "- `room`: string (Optional)\n" - "- `country`: string (Optional)\n" - "- `region`: string (Optional)\n" - "- `uri`: string (Optional)\n" - "- `longitude`: @{float} (Optional)\n" - "- `error`: @{float} (Optional)\n" - "- `postal_code`: string (Optional)\n" - "- `bearing`: @{float} (Optional)\n" - "- `text`: string (Optional)\n" - "- `datum`: string (Optional)\n" - "- `street`: string (Optional)\n" - "- `speed`: @{float} (Optional)\n" - ); + return Documentation( + "UserLocation", + "This table has the following fields:\n\n" + "- `area`: string (Optional)\n" + "- `altitude`: @{float} (Optional)\n" + "- `locality`: string (Optional)\n" + "- `latitude`: @{float} (Optional)\n" + "- `accuracy`: @{float} (Optional)\n" + "- `description`: string (Optional)\n" + "- `country_code`: string (Optional)\n" + "- `timestamp`: datetime (string) (Optional)\n" + "- `floor`: string (Optional)\n" + "- `building`: string (Optional)\n" + "- `room`: string (Optional)\n" + "- `country`: string (Optional)\n" + "- `region`: string (Optional)\n" + "- `uri`: string (Optional)\n" + "- `longitude`: @{float} (Optional)\n" + "- `error`: @{float} (Optional)\n" + "- `postal_code`: string (Optional)\n" + "- `bearing`: @{float} (Optional)\n" + "- `text`: string (Optional)\n" + "- `datum`: string (Optional)\n" + "- `street`: string (Optional)\n" + "- `speed`: @{float} (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/UserLocationConvertor.h b/Sluift/ElementConvertors/UserLocationConvertor.h index 74c0856..d8f7e55 100644 --- a/Sluift/ElementConvertors/UserLocationConvertor.h +++ b/Sluift/ElementConvertors/UserLocationConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class UserLocationConvertor : public GenericLuaElementConvertor { - public: - UserLocationConvertor(); - virtual ~UserLocationConvertor(); + class UserLocationConvertor : public GenericLuaElementConvertor { + public: + UserLocationConvertor(); + virtual ~UserLocationConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/UserTuneConvertor.cpp b/Sluift/ElementConvertors/UserTuneConvertor.cpp index d721a34..09bf9bf 100644 --- a/Sluift/ElementConvertors/UserTuneConvertor.cpp +++ b/Sluift/ElementConvertors/UserTuneConvertor.cpp @@ -14,94 +14,94 @@ using namespace Swift; UserTuneConvertor::UserTuneConvertor() : - GenericLuaElementConvertor("user_tune") { + GenericLuaElementConvertor("user_tune") { } UserTuneConvertor::~UserTuneConvertor() { } boost::shared_ptr UserTuneConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "rating"); - if (lua_isnumber(L, -1)) { - result->setRating(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "title"); - if (lua_isstring(L, -1)) { - result->setTitle(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "track"); - if (lua_isstring(L, -1)) { - result->setTrack(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "artist"); - if (lua_isstring(L, -1)) { - result->setArtist(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "uri"); - if (lua_isstring(L, -1)) { - result->setURI(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "source"); - if (lua_isstring(L, -1)) { - result->setSource(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "length"); - if (lua_isnumber(L, -1)) { - result->setLength(boost::numeric_cast(lua_tonumber(L, -1))); - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "rating"); + if (lua_isnumber(L, -1)) { + result->setRating(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "title"); + if (lua_isstring(L, -1)) { + result->setTitle(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "track"); + if (lua_isstring(L, -1)) { + result->setTrack(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "artist"); + if (lua_isstring(L, -1)) { + result->setArtist(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "uri"); + if (lua_isstring(L, -1)) { + result->setURI(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "source"); + if (lua_isstring(L, -1)) { + result->setSource(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "length"); + if (lua_isnumber(L, -1)) { + result->setLength(boost::numeric_cast(lua_tonumber(L, -1))); + } + lua_pop(L, 1); + return result; } void UserTuneConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_createtable(L, 0, 0); - if (payload->getRating()) { - lua_pushnumber(L, (*payload->getRating())); - lua_setfield(L, -2, "rating"); - } - if (payload->getTitle()) { - lua_pushstring(L, (*payload->getTitle()).c_str()); - lua_setfield(L, -2, "title"); - } - if (payload->getTrack()) { - lua_pushstring(L, (*payload->getTrack()).c_str()); - lua_setfield(L, -2, "track"); - } - if (payload->getArtist()) { - lua_pushstring(L, (*payload->getArtist()).c_str()); - lua_setfield(L, -2, "artist"); - } - if (payload->getURI()) { - lua_pushstring(L, (*payload->getURI()).c_str()); - lua_setfield(L, -2, "uri"); - } - if (payload->getSource()) { - lua_pushstring(L, (*payload->getSource()).c_str()); - lua_setfield(L, -2, "source"); - } - if (payload->getLength()) { - lua_pushnumber(L, (*payload->getLength())); - lua_setfield(L, -2, "length"); - } + lua_createtable(L, 0, 0); + if (payload->getRating()) { + lua_pushnumber(L, (*payload->getRating())); + lua_setfield(L, -2, "rating"); + } + if (payload->getTitle()) { + lua_pushstring(L, (*payload->getTitle()).c_str()); + lua_setfield(L, -2, "title"); + } + if (payload->getTrack()) { + lua_pushstring(L, (*payload->getTrack()).c_str()); + lua_setfield(L, -2, "track"); + } + if (payload->getArtist()) { + lua_pushstring(L, (*payload->getArtist()).c_str()); + lua_setfield(L, -2, "artist"); + } + if (payload->getURI()) { + lua_pushstring(L, (*payload->getURI()).c_str()); + lua_setfield(L, -2, "uri"); + } + if (payload->getSource()) { + lua_pushstring(L, (*payload->getSource()).c_str()); + lua_setfield(L, -2, "source"); + } + if (payload->getLength()) { + lua_pushnumber(L, (*payload->getLength())); + lua_setfield(L, -2, "length"); + } } boost::optional UserTuneConvertor::getDocumentation() const { - return Documentation( - "UserTune", - "This table has the following fields:\n\n" - "- `rating`: number (Optional)\n" - "- `title`: string (Optional)\n" - "- `track`: string (Optional)\n" - "- `artist`: string (Optional)\n" - "- `uri`: string (Optional)\n" - "- `source`: string (Optional)\n" - "- `length`: number (Optional)\n" - ); + return Documentation( + "UserTune", + "This table has the following fields:\n\n" + "- `rating`: number (Optional)\n" + "- `title`: string (Optional)\n" + "- `track`: string (Optional)\n" + "- `artist`: string (Optional)\n" + "- `uri`: string (Optional)\n" + "- `source`: string (Optional)\n" + "- `length`: number (Optional)\n" + ); } diff --git a/Sluift/ElementConvertors/UserTuneConvertor.h b/Sluift/ElementConvertors/UserTuneConvertor.h index 282b9fc..9fb03ed 100644 --- a/Sluift/ElementConvertors/UserTuneConvertor.h +++ b/Sluift/ElementConvertors/UserTuneConvertor.h @@ -12,15 +12,15 @@ #include namespace Swift { - class LuaElementConvertors; + class LuaElementConvertors; - class UserTuneConvertor : public GenericLuaElementConvertor { - public: - UserTuneConvertor(); - virtual ~UserTuneConvertor(); + class UserTuneConvertor : public GenericLuaElementConvertor { + public: + UserTuneConvertor(); + virtual ~UserTuneConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual boost::optional getDocumentation() const SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/VCardConvertor.cpp b/Sluift/ElementConvertors/VCardConvertor.cpp index f704083..108d233 100644 --- a/Sluift/ElementConvertors/VCardConvertor.cpp +++ b/Sluift/ElementConvertors/VCardConvertor.cpp @@ -25,608 +25,608 @@ VCardConvertor::~VCardConvertor() { } boost::shared_ptr VCardConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - lua_getfield(L, -1, "fullname"); - if (lua_isstring(L, -1)) { - result->setFullName(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "familyname"); - if (lua_isstring(L, -1)) { - result->setFamilyName(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "givenname"); - if (lua_isstring(L, -1)) { - result->setGivenName(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "middlename"); - if (lua_isstring(L, -1)) { - result->setMiddleName(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "prefix"); - if (lua_isstring(L, -1)) { - result->setPrefix(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "suffix"); - if (lua_isstring(L, -1)) { - result->setSuffix(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "nick"); - if (lua_isstring(L, -1)) { - result->setNickname(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "description"); - if (lua_isstring(L, -1)) { - result->setDescription(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "photo"); - if (lua_isstring(L, -1)) { - size_t len; - const char* data = lua_tolstring(L, -1, &len); - result->setPhoto(createByteArray(data, len)); - } - lua_pop(L, 1); - lua_getfield(L, -1, "phototype"); - if (lua_isstring(L, -1)) { - result->setPhotoType(std::string(lua_tostring(L, -1))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "birthday"); - if (lua_isstring(L, -1)) { - result->setBirthday(stringToDateTime(std::string(lua_tostring(L, -1)))); - } - lua_pop(L, 1); - lua_getfield(L, -1, "email"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - VCard::EMailAddress emailAddress; - emailAddress.address = Lua::getStringField(L, -1, "address").get_value_or(""); - if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { - emailAddress.isHome = *home; - } - if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { - emailAddress.isWork = *work; - } - if (boost::optional internet = Lua::getBooleanField(L, -1, "internet")) { - emailAddress.isInternet = *internet; - } - if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { - emailAddress.isPreferred = *preferred; - } - if (boost::optional x400 = Lua::getBooleanField(L, -1, "x400")) { - emailAddress.isX400 = *x400; - } - result->addEMailAddress(emailAddress); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "telephone"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - VCard::Telephone telephone; - telephone.number = Lua::getStringField(L, -1, "number").get_value_or(""); - if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { - telephone.isHome = *home; - } - if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { - telephone.isWork = *work; - } - if (boost::optional voice = Lua::getBooleanField(L, -1, "voice")) { - telephone.isVoice = *voice; - } - if (boost::optional fax = Lua::getBooleanField(L, -1, "fax")) { - telephone.isFax = *fax; - } - if (boost::optional pager = Lua::getBooleanField(L, -1, "pager")) { - telephone.isPager = *pager; - } - if (boost::optional msg = Lua::getBooleanField(L, -1, "msg")) { - telephone.isMSG = *msg; - } - if (boost::optional cell = Lua::getBooleanField(L, -1, "cell")) { - telephone.isCell = *cell; - } - if (boost::optional video = Lua::getBooleanField(L, -1, "video")) { - telephone.isVideo = *video; - } - if (boost::optional bbs = Lua::getBooleanField(L, -1, "bbs")) { - telephone.isBBS = *bbs; - } - if (boost::optional modem = Lua::getBooleanField(L, -1, "modem")) { - telephone.isModem = *modem; - } - if (boost::optional isdn = Lua::getBooleanField(L, -1, "isdn")) { - telephone.isISDN = *isdn; - } - if (boost::optional pcs = Lua::getBooleanField(L, -1, "pcs")) { - telephone.isPCS = *pcs; - } - if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { - telephone.isPreferred = *preferred; - } - result->addTelephone(telephone); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "address"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - VCard::Address address; - address.poBox = Lua::getStringField(L, -1, "pobox").get_value_or(""); - address.addressExtension = Lua::getStringField(L, -1, "extension").get_value_or(""); - address.street = Lua::getStringField(L, -1, "street").get_value_or(""); - address.locality = Lua::getStringField(L, -1, "locality").get_value_or(""); - address.region = Lua::getStringField(L, -1, "region").get_value_or(""); - address.postalCode = Lua::getStringField(L, -1, "postalcode").get_value_or(""); - address.country = Lua::getStringField(L, -1, "country").get_value_or(""); - if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { - address.isHome = *home; - } - if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { - address.isWork = *work; - } - if (boost::optional postal = Lua::getBooleanField(L, -1, "postal")) { - address.isPostal = *postal; - } - if (boost::optional parcel = Lua::getBooleanField(L, -1, "parcel")) { - address.isParcel = *parcel; - } - if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { - address.isPreferred = *preferred; - } - if (boost::optional domestic = Lua::getBooleanField(L, -1, "domestic")) { - if (*domestic) { - address.deliveryType = VCard::DomesticDelivery; - } - } - if (boost::optional international = Lua::getBooleanField(L, -1, "international")) { - if (*international) { - address.deliveryType = VCard::InternationalDelivery; - } - } - result->addAddress(address); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "addresslabel"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - VCard::AddressLabel addresslabel; - lua_getfield(L, -1, "lines"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - addresslabel.lines.push_back(lua_tostring(L, -1)); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { - addresslabel.isHome = *home; - } - if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { - addresslabel.isWork = *work; - } - if (boost::optional postal = Lua::getBooleanField(L, -1, "postal")) { - addresslabel.isPostal = *postal; - } - if (boost::optional parcel = Lua::getBooleanField(L, -1, "parcel")) { - addresslabel.isParcel = *parcel; - } - if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { - addresslabel.isPreferred = *preferred; - } - if (boost::optional domestic = Lua::getBooleanField(L, -1, "domestic")) { - if (*domestic) { - addresslabel.deliveryType = VCard::DomesticDelivery; - } - } - if (boost::optional international = Lua::getBooleanField(L, -1, "international")) { - if (*international) { - addresslabel.deliveryType = VCard::InternationalDelivery; - } - } - result->addAddressLabel(addresslabel); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "organization"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - VCard::Organization organization; - organization.name = Lua::getStringField(L, -1, "name").get_value_or(""); - lua_getfield(L, -1, "units"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - organization.units.push_back(lua_tostring(L, -1)); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - result->addOrganization(organization); - lua_pop(L, 1); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "jid"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - result->addJID(lua_tostring(L, -1)); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "title"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - result->addTitle(lua_tostring(L, -1)); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - lua_getfield(L, -1, "role"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - result->addRole(lua_tostring(L, -1)); - } - lua_pop(L, 1); } - } - lua_pop(L, 1); - lua_getfield(L, -1, "url"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); ) { - if (lua_isstring(L, -1)) { - result->addURL(lua_tostring(L, -1)); - } - lua_pop(L, 1); - } - } - lua_pop(L, 1); - return result; + boost::shared_ptr result = boost::make_shared(); + lua_getfield(L, -1, "fullname"); + if (lua_isstring(L, -1)) { + result->setFullName(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "familyname"); + if (lua_isstring(L, -1)) { + result->setFamilyName(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "givenname"); + if (lua_isstring(L, -1)) { + result->setGivenName(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "middlename"); + if (lua_isstring(L, -1)) { + result->setMiddleName(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "prefix"); + if (lua_isstring(L, -1)) { + result->setPrefix(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "suffix"); + if (lua_isstring(L, -1)) { + result->setSuffix(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "nick"); + if (lua_isstring(L, -1)) { + result->setNickname(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "description"); + if (lua_isstring(L, -1)) { + result->setDescription(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "photo"); + if (lua_isstring(L, -1)) { + size_t len; + const char* data = lua_tolstring(L, -1, &len); + result->setPhoto(createByteArray(data, len)); + } + lua_pop(L, 1); + lua_getfield(L, -1, "phototype"); + if (lua_isstring(L, -1)) { + result->setPhotoType(std::string(lua_tostring(L, -1))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "birthday"); + if (lua_isstring(L, -1)) { + result->setBirthday(stringToDateTime(std::string(lua_tostring(L, -1)))); + } + lua_pop(L, 1); + lua_getfield(L, -1, "email"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + VCard::EMailAddress emailAddress; + emailAddress.address = Lua::getStringField(L, -1, "address").get_value_or(""); + if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { + emailAddress.isHome = *home; + } + if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { + emailAddress.isWork = *work; + } + if (boost::optional internet = Lua::getBooleanField(L, -1, "internet")) { + emailAddress.isInternet = *internet; + } + if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { + emailAddress.isPreferred = *preferred; + } + if (boost::optional x400 = Lua::getBooleanField(L, -1, "x400")) { + emailAddress.isX400 = *x400; + } + result->addEMailAddress(emailAddress); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "telephone"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + VCard::Telephone telephone; + telephone.number = Lua::getStringField(L, -1, "number").get_value_or(""); + if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { + telephone.isHome = *home; + } + if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { + telephone.isWork = *work; + } + if (boost::optional voice = Lua::getBooleanField(L, -1, "voice")) { + telephone.isVoice = *voice; + } + if (boost::optional fax = Lua::getBooleanField(L, -1, "fax")) { + telephone.isFax = *fax; + } + if (boost::optional pager = Lua::getBooleanField(L, -1, "pager")) { + telephone.isPager = *pager; + } + if (boost::optional msg = Lua::getBooleanField(L, -1, "msg")) { + telephone.isMSG = *msg; + } + if (boost::optional cell = Lua::getBooleanField(L, -1, "cell")) { + telephone.isCell = *cell; + } + if (boost::optional video = Lua::getBooleanField(L, -1, "video")) { + telephone.isVideo = *video; + } + if (boost::optional bbs = Lua::getBooleanField(L, -1, "bbs")) { + telephone.isBBS = *bbs; + } + if (boost::optional modem = Lua::getBooleanField(L, -1, "modem")) { + telephone.isModem = *modem; + } + if (boost::optional isdn = Lua::getBooleanField(L, -1, "isdn")) { + telephone.isISDN = *isdn; + } + if (boost::optional pcs = Lua::getBooleanField(L, -1, "pcs")) { + telephone.isPCS = *pcs; + } + if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { + telephone.isPreferred = *preferred; + } + result->addTelephone(telephone); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "address"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + VCard::Address address; + address.poBox = Lua::getStringField(L, -1, "pobox").get_value_or(""); + address.addressExtension = Lua::getStringField(L, -1, "extension").get_value_or(""); + address.street = Lua::getStringField(L, -1, "street").get_value_or(""); + address.locality = Lua::getStringField(L, -1, "locality").get_value_or(""); + address.region = Lua::getStringField(L, -1, "region").get_value_or(""); + address.postalCode = Lua::getStringField(L, -1, "postalcode").get_value_or(""); + address.country = Lua::getStringField(L, -1, "country").get_value_or(""); + if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { + address.isHome = *home; + } + if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { + address.isWork = *work; + } + if (boost::optional postal = Lua::getBooleanField(L, -1, "postal")) { + address.isPostal = *postal; + } + if (boost::optional parcel = Lua::getBooleanField(L, -1, "parcel")) { + address.isParcel = *parcel; + } + if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { + address.isPreferred = *preferred; + } + if (boost::optional domestic = Lua::getBooleanField(L, -1, "domestic")) { + if (*domestic) { + address.deliveryType = VCard::DomesticDelivery; + } + } + if (boost::optional international = Lua::getBooleanField(L, -1, "international")) { + if (*international) { + address.deliveryType = VCard::InternationalDelivery; + } + } + result->addAddress(address); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "addresslabel"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + VCard::AddressLabel addresslabel; + lua_getfield(L, -1, "lines"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + addresslabel.lines.push_back(lua_tostring(L, -1)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + if (boost::optional home = Lua::getBooleanField(L, -1, "home")) { + addresslabel.isHome = *home; + } + if (boost::optional work = Lua::getBooleanField(L, -1, "work")) { + addresslabel.isWork = *work; + } + if (boost::optional postal = Lua::getBooleanField(L, -1, "postal")) { + addresslabel.isPostal = *postal; + } + if (boost::optional parcel = Lua::getBooleanField(L, -1, "parcel")) { + addresslabel.isParcel = *parcel; + } + if (boost::optional preferred = Lua::getBooleanField(L, -1, "preferred")) { + addresslabel.isPreferred = *preferred; + } + if (boost::optional domestic = Lua::getBooleanField(L, -1, "domestic")) { + if (*domestic) { + addresslabel.deliveryType = VCard::DomesticDelivery; + } + } + if (boost::optional international = Lua::getBooleanField(L, -1, "international")) { + if (*international) { + addresslabel.deliveryType = VCard::InternationalDelivery; + } + } + result->addAddressLabel(addresslabel); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "organization"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + VCard::Organization organization; + organization.name = Lua::getStringField(L, -1, "name").get_value_or(""); + lua_getfield(L, -1, "units"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + organization.units.push_back(lua_tostring(L, -1)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + result->addOrganization(organization); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "jid"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + result->addJID(lua_tostring(L, -1)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "title"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + result->addTitle(lua_tostring(L, -1)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + lua_getfield(L, -1, "role"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + result->addRole(lua_tostring(L, -1)); + } + lua_pop(L, 1); } + } + lua_pop(L, 1); + lua_getfield(L, -1, "url"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); ) { + if (lua_isstring(L, -1)) { + result->addURL(lua_tostring(L, -1)); + } + lua_pop(L, 1); + } + } + lua_pop(L, 1); + return result; } void VCardConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_newtable(L); - if (!payload->getFullName().empty()) { - lua_pushstring(L, payload->getFullName().c_str()); - lua_setfield(L, -2, "fullname"); - } - if (!payload->getFamilyName().empty()) { - lua_pushstring(L, payload->getFamilyName().c_str()); - lua_setfield(L, -2, "familyname"); - } - if (!payload->getGivenName().empty()) { - lua_pushstring(L, payload->getGivenName().c_str()); - lua_setfield(L, -2, "givenname"); - } - if (!payload->getMiddleName().empty()) { - lua_pushstring(L, payload->getMiddleName().c_str()); - lua_setfield(L, -2, "middlename"); - } - if (!payload->getPrefix().empty()) { - lua_pushstring(L, payload->getPrefix().c_str()); - lua_setfield(L, -2, "prefix"); - } - if (!payload->getSuffix().empty()) { - lua_pushstring(L, payload->getSuffix().c_str()); - lua_setfield(L, -2, "suffix"); - } - if (!payload->getNickname().empty()) { - lua_pushstring(L, payload->getNickname().c_str()); - lua_setfield(L, -2, "nick"); - } - if (!payload->getDescription().empty()) { - lua_pushstring(L, payload->getDescription().c_str()); - lua_setfield(L, -2, "description"); - } - if (!payload->getPhoto().empty()) { - lua_pushlstring(L, reinterpret_cast(vecptr(payload->getPhoto())), payload->getPhoto().size()); - lua_setfield(L, -2, "photo"); - } - if (!payload->getPhotoType().empty()) { - lua_pushstring(L, payload->getPhotoType().c_str()); - lua_setfield(L, -2, "phototype"); - } - if (!payload->getBirthday().is_not_a_date_time()) { - lua_pushstring(L, dateTimeToString(payload->getBirthday()).c_str()); - lua_setfield(L, -2, "birthday"); - } - const std::vector& emails = payload->getEMailAddresses(); - if (!emails.empty()) { - lua_createtable(L, boost::numeric_cast(emails.size()), 0); - for (size_t i = 0; i < emails.size(); ++i) { - lua_createtable(L, 0, 0); - if (!emails[i].address.empty()) { - lua_pushstring(L, emails[i].address.c_str()); - lua_setfield(L, -2, "address"); - } - if (emails[i].isHome) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "home"); - } - if (emails[i].isWork) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "work"); - } - if (emails[i].isInternet) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "internet"); - } - if (emails[i].isPreferred) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "preferred"); - } - if (emails[i].isX400) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "x400"); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "email"); - } - const std::vector& telephones = payload->getTelephones(); - if (!telephones.empty()) { - lua_createtable(L, boost::numeric_cast(telephones.size()), 0); - for (size_t i = 0; i < telephones.size(); ++i) { - lua_createtable(L, 0, 0); - if (!telephones[i].number.empty()) { - lua_pushstring(L, telephones[i].number.c_str()); - lua_setfield(L, -2, "number"); - } - if (telephones[i].isHome) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "home"); - } - if (telephones[i].isWork) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "work"); - } - if (telephones[i].isVoice) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "voice"); - } - if (telephones[i].isFax) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "fax"); - } - if (telephones[i].isPager) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "pager"); - } - if (telephones[i].isMSG) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "msg"); - } - if (telephones[i].isCell) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "cell"); - } - if (telephones[i].isVideo) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "video"); - } - if (telephones[i].isBBS) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "bbs"); - } - if (telephones[i].isModem) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "modem"); - } - if (telephones[i].isISDN) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "isdn"); - } - if (telephones[i].isPCS) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "pcs"); - } - if (telephones[i].isPreferred) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "preferred"); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "telephone"); - } - const std::vector& addresses = payload->getAddresses(); - if (!addresses.empty()) { - lua_createtable(L, boost::numeric_cast(addresses.size()), 0); - for (size_t i = 0; i < addresses.size(); ++i) { - lua_createtable(L, 0, 0); - if (!addresses[i].poBox.empty()) { - lua_pushstring(L, addresses[i].poBox.c_str()); - lua_setfield(L, -2, "pobox"); - } - if (!addresses[i].addressExtension.empty()) { - lua_pushstring(L, addresses[i].addressExtension.c_str()); - lua_setfield(L, -2, "extension"); - } - if (!addresses[i].street.empty()) { - lua_pushstring(L, addresses[i].street.c_str()); - lua_setfield(L, -2, "street"); - } - if (!addresses[i].locality.empty()) { - lua_pushstring(L, addresses[i].locality.c_str()); - lua_setfield(L, -2, "locality"); - } - if (!addresses[i].region.empty()) { - lua_pushstring(L, addresses[i].region.c_str()); - lua_setfield(L, -2, "region"); - } - if (!addresses[i].postalCode.empty()) { - lua_pushstring(L, addresses[i].postalCode.c_str()); - lua_setfield(L, -2, "postalcode"); - } - if (!addresses[i].country.empty()) { - lua_pushstring(L, addresses[i].country.c_str()); - lua_setfield(L, -2, "country"); - } - if (addresses[i].isHome) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "home"); - } - if (addresses[i].isWork) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "work"); - } - if (addresses[i].isPostal) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "postal"); - } - if (addresses[i].isParcel) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "parcel"); - } - if (addresses[i].isPreferred) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "preferred"); - } - if (addresses[i].deliveryType == VCard::DomesticDelivery) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "domestic"); - } - if (addresses[i].deliveryType == VCard::InternationalDelivery) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "international"); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "address"); - } - const std::vector& addresslabels = payload->getAddressLabels(); - if (!addresslabels.empty()) { - lua_createtable(L, boost::numeric_cast(addresslabels.size()), 0); - for (size_t i = 0; i < addresslabels.size(); ++i) { - lua_createtable(L, 0, 0); - const std::vector& lines = addresslabels[i].lines; - if (!lines.empty()) { - lua_createtable(L, boost::numeric_cast(addresslabels[i].lines.size()), 0); - for (size_t j = 0; j < lines.size(); ++j) { - if (!lines[j].empty()) { - lua_pushstring(L, lines[j].c_str()); - } - lua_rawseti(L, -2, boost::numeric_cast(j+1)); - } - lua_setfield(L, -2, "lines"); - } - if (addresslabels[i].isHome) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "home"); - } - if (addresslabels[i].isWork) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "work"); - } - if (addresslabels[i].isPostal) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "postal"); - } - if (addresslabels[i].isParcel) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "parcel"); - } - if (addresslabels[i].isPreferred) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "preferred"); - } - if (addresslabels[i].deliveryType == VCard::DomesticDelivery) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "domestic"); - } - if (addresslabels[i].deliveryType == VCard::InternationalDelivery) { - lua_pushboolean(L, true); - lua_setfield(L, -2, "international"); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "addresslabel"); - } - const std::vector& organizations = payload->getOrganizations(); - if (!organizations.empty()) { - lua_createtable(L, boost::numeric_cast(organizations.size()), 0); - for (size_t i = 0; i < organizations.size(); ++i) { - lua_createtable(L, 0, 0); - if (!organizations[i].name.empty()) { - lua_pushstring(L, organizations[i].name.c_str()); - lua_setfield(L, -2, "name"); - } - const std::vector& units = organizations[i].units; - if (!units.empty()) { - lua_createtable(L, boost::numeric_cast(organizations[i].units.size()), 0); - for (size_t j = 0; j < units.size(); ++j) { - if (!units[j].empty()) { - lua_pushstring(L, units[j].c_str()); - } - lua_rawseti(L, -2, boost::numeric_cast(j+1)); - } - lua_setfield(L, -2, "units"); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "organization"); - } - const std::vector& jids = payload->getJIDs(); - if (!jids.empty()) { - lua_createtable(L, boost::numeric_cast(jids.size()), 0); - for (size_t i = 0; i < jids.size(); ++i) { - if (!jids[i].toString().empty()) { - lua_pushstring(L, jids[i].toString().c_str()); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "jid"); - } - const std::vector& titles = payload->getTitles(); - if (!titles.empty()) { - lua_createtable(L, boost::numeric_cast(titles.size()), 0); - for (size_t i = 0; i < titles.size(); ++i) { - if (!titles[i].empty()) { - lua_pushstring(L, titles[i].c_str()); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "title"); - } - const std::vector& roles = payload->getRoles(); - if (!roles.empty()) { - lua_createtable(L, boost::numeric_cast(roles.size()), 0); - for (size_t i = 0; i < roles.size(); ++i) { - if (!roles[i].empty()) { - lua_pushstring(L, roles[i].c_str()); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "role"); - } - const std::vector& urls = payload->getURLs(); - if (!urls.empty()) { - lua_createtable(L, boost::numeric_cast(urls.size()), 0); - for (size_t i = 0; i < urls.size(); ++i) { - if (!urls[i].empty()) { - lua_pushstring(L, urls[i].c_str()); - } - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setfield(L, -2, "url"); - } + lua_newtable(L); + if (!payload->getFullName().empty()) { + lua_pushstring(L, payload->getFullName().c_str()); + lua_setfield(L, -2, "fullname"); + } + if (!payload->getFamilyName().empty()) { + lua_pushstring(L, payload->getFamilyName().c_str()); + lua_setfield(L, -2, "familyname"); + } + if (!payload->getGivenName().empty()) { + lua_pushstring(L, payload->getGivenName().c_str()); + lua_setfield(L, -2, "givenname"); + } + if (!payload->getMiddleName().empty()) { + lua_pushstring(L, payload->getMiddleName().c_str()); + lua_setfield(L, -2, "middlename"); + } + if (!payload->getPrefix().empty()) { + lua_pushstring(L, payload->getPrefix().c_str()); + lua_setfield(L, -2, "prefix"); + } + if (!payload->getSuffix().empty()) { + lua_pushstring(L, payload->getSuffix().c_str()); + lua_setfield(L, -2, "suffix"); + } + if (!payload->getNickname().empty()) { + lua_pushstring(L, payload->getNickname().c_str()); + lua_setfield(L, -2, "nick"); + } + if (!payload->getDescription().empty()) { + lua_pushstring(L, payload->getDescription().c_str()); + lua_setfield(L, -2, "description"); + } + if (!payload->getPhoto().empty()) { + lua_pushlstring(L, reinterpret_cast(vecptr(payload->getPhoto())), payload->getPhoto().size()); + lua_setfield(L, -2, "photo"); + } + if (!payload->getPhotoType().empty()) { + lua_pushstring(L, payload->getPhotoType().c_str()); + lua_setfield(L, -2, "phototype"); + } + if (!payload->getBirthday().is_not_a_date_time()) { + lua_pushstring(L, dateTimeToString(payload->getBirthday()).c_str()); + lua_setfield(L, -2, "birthday"); + } + const std::vector& emails = payload->getEMailAddresses(); + if (!emails.empty()) { + lua_createtable(L, boost::numeric_cast(emails.size()), 0); + for (size_t i = 0; i < emails.size(); ++i) { + lua_createtable(L, 0, 0); + if (!emails[i].address.empty()) { + lua_pushstring(L, emails[i].address.c_str()); + lua_setfield(L, -2, "address"); + } + if (emails[i].isHome) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "home"); + } + if (emails[i].isWork) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "work"); + } + if (emails[i].isInternet) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "internet"); + } + if (emails[i].isPreferred) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "preferred"); + } + if (emails[i].isX400) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "x400"); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "email"); + } + const std::vector& telephones = payload->getTelephones(); + if (!telephones.empty()) { + lua_createtable(L, boost::numeric_cast(telephones.size()), 0); + for (size_t i = 0; i < telephones.size(); ++i) { + lua_createtable(L, 0, 0); + if (!telephones[i].number.empty()) { + lua_pushstring(L, telephones[i].number.c_str()); + lua_setfield(L, -2, "number"); + } + if (telephones[i].isHome) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "home"); + } + if (telephones[i].isWork) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "work"); + } + if (telephones[i].isVoice) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "voice"); + } + if (telephones[i].isFax) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "fax"); + } + if (telephones[i].isPager) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "pager"); + } + if (telephones[i].isMSG) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "msg"); + } + if (telephones[i].isCell) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "cell"); + } + if (telephones[i].isVideo) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "video"); + } + if (telephones[i].isBBS) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "bbs"); + } + if (telephones[i].isModem) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "modem"); + } + if (telephones[i].isISDN) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "isdn"); + } + if (telephones[i].isPCS) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "pcs"); + } + if (telephones[i].isPreferred) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "preferred"); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "telephone"); + } + const std::vector& addresses = payload->getAddresses(); + if (!addresses.empty()) { + lua_createtable(L, boost::numeric_cast(addresses.size()), 0); + for (size_t i = 0; i < addresses.size(); ++i) { + lua_createtable(L, 0, 0); + if (!addresses[i].poBox.empty()) { + lua_pushstring(L, addresses[i].poBox.c_str()); + lua_setfield(L, -2, "pobox"); + } + if (!addresses[i].addressExtension.empty()) { + lua_pushstring(L, addresses[i].addressExtension.c_str()); + lua_setfield(L, -2, "extension"); + } + if (!addresses[i].street.empty()) { + lua_pushstring(L, addresses[i].street.c_str()); + lua_setfield(L, -2, "street"); + } + if (!addresses[i].locality.empty()) { + lua_pushstring(L, addresses[i].locality.c_str()); + lua_setfield(L, -2, "locality"); + } + if (!addresses[i].region.empty()) { + lua_pushstring(L, addresses[i].region.c_str()); + lua_setfield(L, -2, "region"); + } + if (!addresses[i].postalCode.empty()) { + lua_pushstring(L, addresses[i].postalCode.c_str()); + lua_setfield(L, -2, "postalcode"); + } + if (!addresses[i].country.empty()) { + lua_pushstring(L, addresses[i].country.c_str()); + lua_setfield(L, -2, "country"); + } + if (addresses[i].isHome) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "home"); + } + if (addresses[i].isWork) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "work"); + } + if (addresses[i].isPostal) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "postal"); + } + if (addresses[i].isParcel) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "parcel"); + } + if (addresses[i].isPreferred) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "preferred"); + } + if (addresses[i].deliveryType == VCard::DomesticDelivery) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "domestic"); + } + if (addresses[i].deliveryType == VCard::InternationalDelivery) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "international"); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "address"); + } + const std::vector& addresslabels = payload->getAddressLabels(); + if (!addresslabels.empty()) { + lua_createtable(L, boost::numeric_cast(addresslabels.size()), 0); + for (size_t i = 0; i < addresslabels.size(); ++i) { + lua_createtable(L, 0, 0); + const std::vector& lines = addresslabels[i].lines; + if (!lines.empty()) { + lua_createtable(L, boost::numeric_cast(addresslabels[i].lines.size()), 0); + for (size_t j = 0; j < lines.size(); ++j) { + if (!lines[j].empty()) { + lua_pushstring(L, lines[j].c_str()); + } + lua_rawseti(L, -2, boost::numeric_cast(j+1)); + } + lua_setfield(L, -2, "lines"); + } + if (addresslabels[i].isHome) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "home"); + } + if (addresslabels[i].isWork) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "work"); + } + if (addresslabels[i].isPostal) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "postal"); + } + if (addresslabels[i].isParcel) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "parcel"); + } + if (addresslabels[i].isPreferred) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "preferred"); + } + if (addresslabels[i].deliveryType == VCard::DomesticDelivery) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "domestic"); + } + if (addresslabels[i].deliveryType == VCard::InternationalDelivery) { + lua_pushboolean(L, true); + lua_setfield(L, -2, "international"); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "addresslabel"); + } + const std::vector& organizations = payload->getOrganizations(); + if (!organizations.empty()) { + lua_createtable(L, boost::numeric_cast(organizations.size()), 0); + for (size_t i = 0; i < organizations.size(); ++i) { + lua_createtable(L, 0, 0); + if (!organizations[i].name.empty()) { + lua_pushstring(L, organizations[i].name.c_str()); + lua_setfield(L, -2, "name"); + } + const std::vector& units = organizations[i].units; + if (!units.empty()) { + lua_createtable(L, boost::numeric_cast(organizations[i].units.size()), 0); + for (size_t j = 0; j < units.size(); ++j) { + if (!units[j].empty()) { + lua_pushstring(L, units[j].c_str()); + } + lua_rawseti(L, -2, boost::numeric_cast(j+1)); + } + lua_setfield(L, -2, "units"); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "organization"); + } + const std::vector& jids = payload->getJIDs(); + if (!jids.empty()) { + lua_createtable(L, boost::numeric_cast(jids.size()), 0); + for (size_t i = 0; i < jids.size(); ++i) { + if (!jids[i].toString().empty()) { + lua_pushstring(L, jids[i].toString().c_str()); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "jid"); + } + const std::vector& titles = payload->getTitles(); + if (!titles.empty()) { + lua_createtable(L, boost::numeric_cast(titles.size()), 0); + for (size_t i = 0; i < titles.size(); ++i) { + if (!titles[i].empty()) { + lua_pushstring(L, titles[i].c_str()); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "title"); + } + const std::vector& roles = payload->getRoles(); + if (!roles.empty()) { + lua_createtable(L, boost::numeric_cast(roles.size()), 0); + for (size_t i = 0; i < roles.size(); ++i) { + if (!roles[i].empty()) { + lua_pushstring(L, roles[i].c_str()); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "role"); + } + const std::vector& urls = payload->getURLs(); + if (!urls.empty()) { + lua_createtable(L, boost::numeric_cast(urls.size()), 0); + for (size_t i = 0; i < urls.size(); ++i) { + if (!urls[i].empty()) { + lua_pushstring(L, urls[i].c_str()); + } + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setfield(L, -2, "url"); + } } diff --git a/Sluift/ElementConvertors/VCardConvertor.h b/Sluift/ElementConvertors/VCardConvertor.h index 39e9dda..95da590 100644 --- a/Sluift/ElementConvertors/VCardConvertor.h +++ b/Sluift/ElementConvertors/VCardConvertor.h @@ -12,12 +12,12 @@ #include namespace Swift { - class VCardConvertor : public GenericLuaElementConvertor { - public: - VCardConvertor(); - virtual ~VCardConvertor(); + class VCardConvertor : public GenericLuaElementConvertor { + public: + VCardConvertor(); + virtual ~VCardConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/ElementConvertors/VCardUpdateConvertor.cpp b/Sluift/ElementConvertors/VCardUpdateConvertor.cpp index b13443d..f3da05a 100644 --- a/Sluift/ElementConvertors/VCardUpdateConvertor.cpp +++ b/Sluift/ElementConvertors/VCardUpdateConvertor.cpp @@ -22,17 +22,17 @@ VCardUpdateConvertor::~VCardUpdateConvertor() { } boost::shared_ptr VCardUpdateConvertor::doConvertFromLua(lua_State* L) { - boost::shared_ptr result = boost::make_shared(); - if (boost::optional value = Lua::getStringField(L, -1, "photo_hash")) { - result->setPhotoHash(*value); - } - return result; + boost::shared_ptr result = boost::make_shared(); + if (boost::optional value = Lua::getStringField(L, -1, "photo_hash")) { + result->setPhotoHash(*value); + } + return result; } void VCardUpdateConvertor::doConvertToLua(lua_State* L, boost::shared_ptr payload) { - lua_newtable(L); - if (!payload->getPhotoHash().empty()) { - lua_pushstring(L, payload->getPhotoHash().c_str()); - lua_setfield(L, -2, "photo_hash"); - } + lua_newtable(L); + if (!payload->getPhotoHash().empty()) { + lua_pushstring(L, payload->getPhotoHash().c_str()); + lua_setfield(L, -2, "photo_hash"); + } } diff --git a/Sluift/ElementConvertors/VCardUpdateConvertor.h b/Sluift/ElementConvertors/VCardUpdateConvertor.h index 48c1be8..b4a3882 100644 --- a/Sluift/ElementConvertors/VCardUpdateConvertor.h +++ b/Sluift/ElementConvertors/VCardUpdateConvertor.h @@ -12,12 +12,12 @@ #include namespace Swift { - class VCardUpdateConvertor : public GenericLuaElementConvertor { - public: - VCardUpdateConvertor(); - virtual ~VCardUpdateConvertor(); + class VCardUpdateConvertor : public GenericLuaElementConvertor { + public: + VCardUpdateConvertor(); + virtual ~VCardUpdateConvertor(); - virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; - }; + virtual boost::shared_ptr doConvertFromLua(lua_State*) SWIFTEN_OVERRIDE; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/GenericLuaElementConvertor.h b/Sluift/GenericLuaElementConvertor.h index 8574f14..dd11c2b 100644 --- a/Sluift/GenericLuaElementConvertor.h +++ b/Sluift/GenericLuaElementConvertor.h @@ -17,40 +17,40 @@ #include namespace Swift { - template - class GenericLuaElementConvertor : public LuaElementConvertor { - public: - GenericLuaElementConvertor(const std::string& type) : type(type) { - } - - virtual ~GenericLuaElementConvertor() {} - - virtual boost::shared_ptr convertFromLua(lua_State* L, int index, const std::string& payloadType) SWIFTEN_OVERRIDE { - if (payloadType == type) { - Lua::checkType(L, index, LUA_TTABLE); - lua_pushvalue(L, index); - boost::shared_ptr result = doConvertFromLua(L); - lua_pop(L, 1); - return result; - } - return boost::shared_ptr(); - } - - virtual boost::optional convertToLua( - lua_State* L, boost::shared_ptr payload) SWIFTEN_OVERRIDE { - if (boost::shared_ptr actualPayload = boost::dynamic_pointer_cast(payload)) { - doConvertToLua(L, actualPayload); - assert(lua_type(L, -1) == LUA_TTABLE); - return type; - } - return NO_RESULT; - } - - protected: - virtual boost::shared_ptr doConvertFromLua(lua_State*) = 0; - virtual void doConvertToLua(lua_State*, boost::shared_ptr) = 0; - - private: - std::string type; - }; + template + class GenericLuaElementConvertor : public LuaElementConvertor { + public: + GenericLuaElementConvertor(const std::string& type) : type(type) { + } + + virtual ~GenericLuaElementConvertor() {} + + virtual boost::shared_ptr convertFromLua(lua_State* L, int index, const std::string& payloadType) SWIFTEN_OVERRIDE { + if (payloadType == type) { + Lua::checkType(L, index, LUA_TTABLE); + lua_pushvalue(L, index); + boost::shared_ptr result = doConvertFromLua(L); + lua_pop(L, 1); + return result; + } + return boost::shared_ptr(); + } + + virtual boost::optional convertToLua( + lua_State* L, boost::shared_ptr payload) SWIFTEN_OVERRIDE { + if (boost::shared_ptr actualPayload = boost::dynamic_pointer_cast(payload)) { + doConvertToLua(L, actualPayload); + assert(lua_type(L, -1) == LUA_TTABLE); + return type; + } + return NO_RESULT; + } + + protected: + virtual boost::shared_ptr doConvertFromLua(lua_State*) = 0; + virtual void doConvertToLua(lua_State*, boost::shared_ptr) = 0; + + private: + std::string type; + }; } diff --git a/Sluift/Helpers.cpp b/Sluift/Helpers.cpp index 12d2f8f..97d14ad 100644 --- a/Sluift/Helpers.cpp +++ b/Sluift/Helpers.cpp @@ -12,54 +12,54 @@ using namespace Swift; std::string Swift::getErrorString(const ClientError& error) { - std::string reason = "Disconnected: "; - switch(error.getType()) { - case ClientError::UnknownError: reason += "Unknown Error"; break; - case ClientError::ConnectionError: reason += "Error connecting to server"; break; - case ClientError::ConnectionReadError: reason += "Error while receiving server data"; break; - case ClientError::ConnectionWriteError: reason += "Error while sending data to the server"; break; - case ClientError::XMLError: reason += "Error parsing server data"; break; - case ClientError::AuthenticationFailedError: reason += "Login/password invalid"; break; - case ClientError::UnexpectedElementError: reason += "Unexpected response"; break; - case ClientError::DomainNameResolveError: reason += "Unable to find server"; break; - case ClientError::CompressionFailedError: reason += "Error while compressing stream"; break; - case ClientError::ServerVerificationFailedError: reason += "Server verification failed"; break; - case ClientError::NoSupportedAuthMechanismsError: reason += "Authentication mechanisms not supported"; break; - case ClientError::ResourceBindError: reason += "Error binding resource"; break; - case ClientError::RevokedError: reason += "Certificate got revoked"; break; - case ClientError::RevocationCheckFailedError: reason += "Failed to do revokation check"; break; - case ClientError::SessionStartError: reason += "Error starting session"; break; - case ClientError::StreamError: reason += "Stream error"; break; - case ClientError::TLSError: reason += "Encryption error"; break; - case ClientError::ClientCertificateLoadError: reason += "Error loading certificate (Invalid file or password?)"; break; - case ClientError::ClientCertificateError: reason += "Certificate not authorized"; break; - case ClientError::UnknownCertificateError: reason += "Unknown certificate"; break; - case ClientError::CertificateCardRemoved: reason += "Certificate card removed"; break; - case ClientError::CertificateExpiredError: reason += "Certificate has expired"; break; - case ClientError::CertificateNotYetValidError: reason += "Certificate is not yet valid"; break; - case ClientError::CertificateSelfSignedError: reason += "Certificate is self-signed"; break; - case ClientError::CertificateRejectedError: reason += "Certificate has been rejected"; break; - case ClientError::CertificateUntrustedError: reason += "Certificate is not trusted"; break; - case ClientError::InvalidCertificatePurposeError: reason += "Certificate cannot be used for encrypting your connection"; break; - case ClientError::CertificatePathLengthExceededError: reason += "Certificate path length constraint exceeded"; break; - case ClientError::InvalidCertificateSignatureError: reason += "Invalid certificate signature"; break; - case ClientError::InvalidCAError: reason += "Invalid Certificate Authority"; break; - case ClientError::InvalidServerIdentityError: reason += "Certificate does not match the host identity"; break; - } - return reason; + std::string reason = "Disconnected: "; + switch(error.getType()) { + case ClientError::UnknownError: reason += "Unknown Error"; break; + case ClientError::ConnectionError: reason += "Error connecting to server"; break; + case ClientError::ConnectionReadError: reason += "Error while receiving server data"; break; + case ClientError::ConnectionWriteError: reason += "Error while sending data to the server"; break; + case ClientError::XMLError: reason += "Error parsing server data"; break; + case ClientError::AuthenticationFailedError: reason += "Login/password invalid"; break; + case ClientError::UnexpectedElementError: reason += "Unexpected response"; break; + case ClientError::DomainNameResolveError: reason += "Unable to find server"; break; + case ClientError::CompressionFailedError: reason += "Error while compressing stream"; break; + case ClientError::ServerVerificationFailedError: reason += "Server verification failed"; break; + case ClientError::NoSupportedAuthMechanismsError: reason += "Authentication mechanisms not supported"; break; + case ClientError::ResourceBindError: reason += "Error binding resource"; break; + case ClientError::RevokedError: reason += "Certificate got revoked"; break; + case ClientError::RevocationCheckFailedError: reason += "Failed to do revokation check"; break; + case ClientError::SessionStartError: reason += "Error starting session"; break; + case ClientError::StreamError: reason += "Stream error"; break; + case ClientError::TLSError: reason += "Encryption error"; break; + case ClientError::ClientCertificateLoadError: reason += "Error loading certificate (Invalid file or password?)"; break; + case ClientError::ClientCertificateError: reason += "Certificate not authorized"; break; + case ClientError::UnknownCertificateError: reason += "Unknown certificate"; break; + case ClientError::CertificateCardRemoved: reason += "Certificate card removed"; break; + case ClientError::CertificateExpiredError: reason += "Certificate has expired"; break; + case ClientError::CertificateNotYetValidError: reason += "Certificate is not yet valid"; break; + case ClientError::CertificateSelfSignedError: reason += "Certificate is self-signed"; break; + case ClientError::CertificateRejectedError: reason += "Certificate has been rejected"; break; + case ClientError::CertificateUntrustedError: reason += "Certificate is not trusted"; break; + case ClientError::InvalidCertificatePurposeError: reason += "Certificate cannot be used for encrypting your connection"; break; + case ClientError::CertificatePathLengthExceededError: reason += "Certificate path length constraint exceeded"; break; + case ClientError::InvalidCertificateSignatureError: reason += "Invalid certificate signature"; break; + case ClientError::InvalidCAError: reason += "Invalid Certificate Authority"; break; + case ClientError::InvalidServerIdentityError: reason += "Certificate does not match the host identity"; break; + } + return reason; } std::string Swift::getErrorString(const ComponentError& error) { - std::string reason = "Disconnected: "; - switch(error.getType()) { - case ComponentError::UnknownError: reason += "Unknown Error"; break; - case ComponentError::ConnectionError: reason += "Error connecting to server"; break; - case ComponentError::ConnectionReadError: reason += "Error while receiving server data"; break; - case ComponentError::ConnectionWriteError: reason += "Error while sending data to the server"; break; - case ComponentError::XMLError: reason += "Error parsing server data"; break; - case ComponentError::AuthenticationFailedError: reason += "Login/password invalid"; break; - case ComponentError::UnexpectedElementError: reason += "Unexpected response"; break; - } - return reason; + std::string reason = "Disconnected: "; + switch(error.getType()) { + case ComponentError::UnknownError: reason += "Unknown Error"; break; + case ComponentError::ConnectionError: reason += "Error connecting to server"; break; + case ComponentError::ConnectionReadError: reason += "Error while receiving server data"; break; + case ComponentError::ConnectionWriteError: reason += "Error while sending data to the server"; break; + case ComponentError::XMLError: reason += "Error parsing server data"; break; + case ComponentError::AuthenticationFailedError: reason += "Login/password invalid"; break; + case ComponentError::UnexpectedElementError: reason += "Unexpected response"; break; + } + return reason; } diff --git a/Sluift/Helpers.h b/Sluift/Helpers.h index ebf50f1..6af3906 100644 --- a/Sluift/Helpers.h +++ b/Sluift/Helpers.h @@ -12,9 +12,9 @@ #include namespace Swift { - class ClientError; - class ComponentError; + class ClientError; + class ComponentError; - std::string getErrorString(const ClientError& error); - std::string getErrorString(const ComponentError& error); + std::string getErrorString(const ClientError& error); + std::string getErrorString(const ComponentError& error); } diff --git a/Sluift/ITunesInterface.h b/Sluift/ITunesInterface.h index 8862966..075ab35 100644 --- a/Sluift/ITunesInterface.h +++ b/Sluift/ITunesInterface.h @@ -12,27 +12,27 @@ #include namespace Swift { - class SWIFTEN_API ITunesInterface { - public: - struct Track { - std::string name; - std::string artist; - std::string album; - long trackNumber; - double duration; - long rating; - }; - - ITunesInterface(); - virtual ~ITunesInterface(); - - boost::optional getCurrentTrack() const; - - private: - bool haveApplication() const; - - private: - struct Private; - boost::shared_ptr p; - }; + class SWIFTEN_API ITunesInterface { + public: + struct Track { + std::string name; + std::string artist; + std::string album; + long trackNumber; + double duration; + long rating; + }; + + ITunesInterface(); + virtual ~ITunesInterface(); + + boost::optional getCurrentTrack() const; + + private: + bool haveApplication() const; + + private: + struct Private; + boost::shared_ptr p; + }; } diff --git a/Sluift/ITunesInterface.mm b/Sluift/ITunesInterface.mm index a11be20..a5ada5b 100644 --- a/Sluift/ITunesInterface.mm +++ b/Sluift/ITunesInterface.mm @@ -19,10 +19,10 @@ using namespace Swift; struct ITunesInterface::Private { - Private() : iTunes(nil) { - } + Private() : iTunes(nil) { + } - iTunesApplication* iTunes; + iTunesApplication* iTunes; }; ITunesInterface::ITunesInterface() : p(boost::make_shared()) { @@ -32,27 +32,27 @@ ITunesInterface::~ITunesInterface() { } boost::optional ITunesInterface::getCurrentTrack() const { - if (!haveApplication()) { - return boost::optional(); - } - iTunesTrack* currentTrack = p->iTunes.currentTrack; - if (!currentTrack) { - return boost::optional(); - } - ITunesInterface::Track result; - result.name = ns2StdString(currentTrack.name); - result.artist = ns2StdString(currentTrack.artist); - result.album = ns2StdString(currentTrack.album); - result.trackNumber = currentTrack.trackNumber; - result.duration = currentTrack.duration; - result.rating = currentTrack.rating; - return result; + if (!haveApplication()) { + return boost::optional(); + } + iTunesTrack* currentTrack = p->iTunes.currentTrack; + if (!currentTrack) { + return boost::optional(); + } + ITunesInterface::Track result; + result.name = ns2StdString(currentTrack.name); + result.artist = ns2StdString(currentTrack.artist); + result.album = ns2StdString(currentTrack.album); + result.trackNumber = currentTrack.trackNumber; + result.duration = currentTrack.duration; + result.rating = currentTrack.rating; + return result; } bool ITunesInterface::haveApplication() const { - if (!p->iTunes) { - p->iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"]; - } - return p->iTunes != nil && [p->iTunes isRunning]; + if (!p->iTunes) { + p->iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"]; + } + return p->iTunes != nil && [p->iTunes isRunning]; } diff --git a/Sluift/Lua/Check.cpp b/Sluift/Lua/Check.cpp index 4eebf4f..74c44be 100644 --- a/Sluift/Lua/Check.cpp +++ b/Sluift/Lua/Check.cpp @@ -21,49 +21,49 @@ using namespace Swift; static std::string getArgTypeError(lua_State* L, int arg, int tag) { - std::ostringstream s; - s << "Arg " << arg << ": expected " << lua_typename(L, tag) << ", got " << luaL_typename(L, arg); - return s.str(); + std::ostringstream s; + s << "Arg " << arg << ": expected " << lua_typename(L, tag) << ", got " << luaL_typename(L, arg); + return s.str(); } void Lua::checkType(lua_State* L, int arg, int type) { - if (lua_type(L, arg) != type) { - throw Lua::Exception(getArgTypeError(L, arg, type)); - } + if (lua_type(L, arg) != type) { + throw Lua::Exception(getArgTypeError(L, arg, type)); + } } int Lua::checkIntNumber(lua_State* L, int arg) { - if (!lua_isnumber(L, arg)) { - throw Lua::Exception(getArgTypeError(L, arg, LUA_TNUMBER)); - } - return boost::numeric_cast(lua_tonumber(L, arg)); + if (!lua_isnumber(L, arg)) { + throw Lua::Exception(getArgTypeError(L, arg, LUA_TNUMBER)); + } + return boost::numeric_cast(lua_tonumber(L, arg)); } std::string Lua::checkString(lua_State* L, int arg) { - const char *s = lua_tolstring(L, arg, NULL); - if (!s) { - throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING)); - } - return std::string(s); + const char *s = lua_tolstring(L, arg, NULL); + if (!s) { + throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING)); + } + return std::string(s); } ByteArray Lua::checkByteArray(lua_State* L, int arg) { - size_t len; - const char *s = lua_tolstring(L, arg, &len); - if (!s) { - throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING)); - } - return createByteArray(s, len); + size_t len; + const char *s = lua_tolstring(L, arg, &len); + if (!s) { + throw Lua::Exception(getArgTypeError(L, arg, LUA_TSTRING)); + } + return createByteArray(s, len); } void* Lua::checkUserDataRaw(lua_State* L, int arg) { - void* userData = lua_touserdata(L, arg); - if (!userData) { - throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA)); - } - if (!lua_getmetatable(L, arg)) { - throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA)); - } - lua_pop(L, 1); - return userData; + void* userData = lua_touserdata(L, arg); + if (!userData) { + throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA)); + } + if (!lua_getmetatable(L, arg)) { + throw Lua::Exception(getArgTypeError(L, arg, LUA_TUSERDATA)); + } + lua_pop(L, 1); + return userData; } diff --git a/Sluift/Lua/Check.h b/Sluift/Lua/Check.h index 4449cd5..61658a6 100644 --- a/Sluift/Lua/Check.h +++ b/Sluift/Lua/Check.h @@ -13,17 +13,17 @@ struct lua_State; namespace Swift { - namespace Lua { - void checkType(lua_State* L, int arg, int type); - int checkIntNumber(lua_State* L, int arg); - std::string checkString(lua_State* L, int arg); - ByteArray checkByteArray(lua_State* L, int arg); + namespace Lua { + void checkType(lua_State* L, int arg, int type); + int checkIntNumber(lua_State* L, int arg); + std::string checkString(lua_State* L, int arg); + ByteArray checkByteArray(lua_State* L, int arg); - void* checkUserDataRaw(lua_State* L, int arg); + void* checkUserDataRaw(lua_State* L, int arg); - template - T** checkUserData(lua_State* L, int arg) { - return reinterpret_cast(checkUserDataRaw(L, arg)); - } - } + template + T** checkUserData(lua_State* L, int arg) { + return reinterpret_cast(checkUserDataRaw(L, arg)); + } + } } diff --git a/Sluift/Lua/Debug.h b/Sluift/Lua/Debug.h index 32addd6..5f141e1 100644 --- a/Sluift/Lua/Debug.h +++ b/Sluift/Lua/Debug.h @@ -11,19 +11,19 @@ #include namespace Swift { - namespace Lua { - inline void dumpStack(lua_State *L) { - for (int i = 1; i <= lua_gettop(L); i++) { - int type = lua_type(L, i); - std::cout << i << ": [" << lua_typename(L, type) << "] "; - switch (type) { - case LUA_TSTRING: std::cout << lua_tostring(L, i); break; - case LUA_TNUMBER: std::cout << lua_tonumber(L, i); break; - case LUA_TBOOLEAN: std::cout << lua_toboolean(L, i); break; - default: break; - } - std::cout << std::endl; - } - } - } + namespace Lua { + inline void dumpStack(lua_State *L) { + for (int i = 1; i <= lua_gettop(L); i++) { + int type = lua_type(L, i); + std::cout << i << ": [" << lua_typename(L, type) << "] "; + switch (type) { + case LUA_TSTRING: std::cout << lua_tostring(L, i); break; + case LUA_TNUMBER: std::cout << lua_tonumber(L, i); break; + case LUA_TBOOLEAN: std::cout << lua_toboolean(L, i); break; + default: break; + } + std::cout << std::endl; + } + } + } } diff --git a/Sluift/Lua/Exception.h b/Sluift/Lua/Exception.h index 0d327e0..a8ecc5f 100644 --- a/Sluift/Lua/Exception.h +++ b/Sluift/Lua/Exception.h @@ -11,13 +11,13 @@ #include namespace Swift { - namespace Lua { - class Exception : public std::runtime_error { - public: - Exception(const std::string& what); - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Exception) - virtual ~Exception() SWIFTEN_NOEXCEPT; - }; - } + namespace Lua { + class Exception : public std::runtime_error { + public: + Exception(const std::string& what); + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Exception) + virtual ~Exception() SWIFTEN_NOEXCEPT; + }; + } } diff --git a/Sluift/Lua/FunctionRegistration.cpp b/Sluift/Lua/FunctionRegistration.cpp index 871ed1b..5a6d43e 100644 --- a/Sluift/Lua/FunctionRegistration.cpp +++ b/Sluift/Lua/FunctionRegistration.cpp @@ -9,7 +9,7 @@ using namespace Swift::Lua; FunctionRegistration::FunctionRegistration(const std::string& name, lua_CFunction function, const std::string& type, const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions) { - FunctionRegistry::getInstance().addFunction(name, function, type, helpDescription, helpParameters, helpOptions); + FunctionRegistry::getInstance().addFunction(name, function, type, helpDescription, helpParameters, helpOptions); } FunctionRegistration::~FunctionRegistration() { diff --git a/Sluift/Lua/FunctionRegistration.h b/Sluift/Lua/FunctionRegistration.h index 3f0afbb..8e1410d 100644 --- a/Sluift/Lua/FunctionRegistration.h +++ b/Sluift/Lua/FunctionRegistration.h @@ -16,31 +16,31 @@ #include namespace Swift { - namespace Lua { - class FunctionRegistration { - public: - FunctionRegistration( - const std::string& name, lua_CFunction function, const std::string& type, - const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions); - ~FunctionRegistration(); - }; - } + namespace Lua { + class FunctionRegistration { + public: + FunctionRegistration( + const std::string& name, lua_CFunction function, const std::string& type, + const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions); + ~FunctionRegistration(); + }; + } } #define SLUIFT_LUA_FUNCTION_WITH_HELP(TYPE, NAME, HELP_DESCRIPTION, HELP_PARAMETERS, HELP_OPTIONS) \ - static int TYPE##_##NAME(lua_State* L); \ - static int TYPE##_##NAME##_wrapper(lua_State* L); \ - static ::Swift::Lua::FunctionRegistration TYPE##_##NAME##_registration( #NAME , TYPE##_##NAME##_wrapper, #TYPE, HELP_DESCRIPTION, HELP_PARAMETERS, HELP_OPTIONS); \ - static int TYPE##_##NAME##_wrapper(lua_State* L) { \ - try { \ - return TYPE ## _ ## NAME (L); \ - } \ - catch (const std::exception& e) { \ - return luaL_error(L, e.what()); \ - } \ - } \ - static int TYPE ## _ ## NAME (lua_State* L) + static int TYPE##_##NAME(lua_State* L); \ + static int TYPE##_##NAME##_wrapper(lua_State* L); \ + static ::Swift::Lua::FunctionRegistration TYPE##_##NAME##_registration( #NAME , TYPE##_##NAME##_wrapper, #TYPE, HELP_DESCRIPTION, HELP_PARAMETERS, HELP_OPTIONS); \ + static int TYPE##_##NAME##_wrapper(lua_State* L) { \ + try { \ + return TYPE ## _ ## NAME (L); \ + } \ + catch (const std::exception& e) { \ + return luaL_error(L, e.what()); \ + } \ + } \ + static int TYPE ## _ ## NAME (lua_State* L) #define SLUIFT_LUA_FUNCTION(TYPE, NAME) \ - SLUIFT_LUA_FUNCTION_WITH_HELP(TYPE, NAME, "", "", "") + SLUIFT_LUA_FUNCTION_WITH_HELP(TYPE, NAME, "", "", "") diff --git a/Sluift/Lua/FunctionRegistry.cpp b/Sluift/Lua/FunctionRegistry.cpp index e1fac09..ebbd087 100644 --- a/Sluift/Lua/FunctionRegistry.cpp +++ b/Sluift/Lua/FunctionRegistry.cpp @@ -21,39 +21,39 @@ FunctionRegistry::~FunctionRegistry() { } FunctionRegistry& FunctionRegistry::getInstance() { - static FunctionRegistry instance; - return instance; + static FunctionRegistry instance; + return instance; } void FunctionRegistry::addFunction( - const std::string& name, lua_CFunction function, const std::string& type, - const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions) { - Registration registration; - registration.name = name; - registration.function = function; - registration.type = type; - registration.helpDescription = helpDescription; - registration.helpParameters = helpParameters; - registration.helpOptions = helpOptions; - registrations.push_back(registration); + const std::string& name, lua_CFunction function, const std::string& type, + const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions) { + Registration registration; + registration.name = name; + registration.function = function; + registration.type = type; + registration.helpDescription = helpDescription; + registration.helpParameters = helpParameters; + registration.helpOptions = helpOptions; + registrations.push_back(registration); } void FunctionRegistry::createFunctionTable(lua_State* L, const std::string& type) { - lua_newtable(L); - addFunctionsToTable(L, type); + lua_newtable(L); + addFunctionsToTable(L, type); } void FunctionRegistry::addFunctionsToTable(lua_State* L, const std::string& type) { - foreach(const Registration& registration, registrations) { - if (registration.type == type) { - lua_pushcclosure(L, registration.function, 0); - if (!registration.helpDescription.empty()) { - Lua::registerHelp(L, -1, registration.helpDescription, registration.helpParameters, registration.helpOptions); - } - else { - Lua::registerExtraHelp(L, -1, registration.type + "." + registration.name); - } - lua_setfield(L, -2, registration.name.c_str()); - } - } + foreach(const Registration& registration, registrations) { + if (registration.type == type) { + lua_pushcclosure(L, registration.function, 0); + if (!registration.helpDescription.empty()) { + Lua::registerHelp(L, -1, registration.helpDescription, registration.helpParameters, registration.helpOptions); + } + else { + Lua::registerExtraHelp(L, -1, registration.type + "." + registration.name); + } + lua_setfield(L, -2, registration.name.c_str()); + } + } } diff --git a/Sluift/Lua/FunctionRegistry.h b/Sluift/Lua/FunctionRegistry.h index b6260e0..acab3aa 100644 --- a/Sluift/Lua/FunctionRegistry.h +++ b/Sluift/Lua/FunctionRegistry.h @@ -14,36 +14,36 @@ #include namespace Swift { - namespace Lua { - class FunctionRegistry { - public: - ~FunctionRegistry(); - static FunctionRegistry& getInstance(); - - void addFunction(const std::string& name, lua_CFunction function, const std::string& type, - const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions); - - void createFunctionTable(lua_State* L, const std::string& type); - - /** - * Adds the functions to the table on the top of the stack. - */ - void addFunctionsToTable(lua_State* L, const std::string& type); - - private: - FunctionRegistry(); - - - private: - struct Registration { - std::string name; - lua_CFunction function; - std::string type; - std::string helpDescription; - std::string helpParameters; - std::string helpOptions; - }; - std::vector registrations; - }; - } + namespace Lua { + class FunctionRegistry { + public: + ~FunctionRegistry(); + static FunctionRegistry& getInstance(); + + void addFunction(const std::string& name, lua_CFunction function, const std::string& type, + const std::string& helpDescription, const std::string& helpParameters, const std::string& helpOptions); + + void createFunctionTable(lua_State* L, const std::string& type); + + /** + * Adds the functions to the table on the top of the stack. + */ + void addFunctionsToTable(lua_State* L, const std::string& type); + + private: + FunctionRegistry(); + + + private: + struct Registration { + std::string name; + lua_CFunction function; + std::string type; + std::string helpDescription; + std::string helpParameters; + std::string helpOptions; + }; + std::vector registrations; + }; + } } diff --git a/Sluift/Lua/LuaUtils.cpp b/Sluift/Lua/LuaUtils.cpp index df1afce..1088624 100644 --- a/Sluift/Lua/LuaUtils.cpp +++ b/Sluift/Lua/LuaUtils.cpp @@ -24,178 +24,178 @@ using namespace Swift::Lua; static const std::string INDENT = " "; void Swift::Lua::registerTableToString(lua_State* L, int index) { - index = Lua::absoluteOffset(L, index); - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "register_table_tostring"); - lua_pushvalue(L, index); - if (lua_pcall(L, 1, 0, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - lua_pop(L, 1); + index = Lua::absoluteOffset(L, index); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "register_table_tostring"); + lua_pushvalue(L, index); + if (lua_pcall(L, 1, 0, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + lua_pop(L, 1); } void Swift::Lua::registerTableEquals(lua_State* L, int index) { - index = Lua::absoluteOffset(L, index); - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "register_table_equals"); - lua_pushvalue(L, index); - if (lua_pcall(L, 1, 0, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - lua_pop(L, 1); + index = Lua::absoluteOffset(L, index); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "register_table_equals"); + lua_pushvalue(L, index); + if (lua_pcall(L, 1, 0, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + lua_pop(L, 1); } void Swift::Lua::registerGetByTypeIndex(lua_State* L, int index) { - index = Lua::absoluteOffset(L, index); - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "register_get_by_type_index"); - lua_pushvalue(L, index); - if (lua_pcall(L, 1, 0, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - lua_pop(L, 1); + index = Lua::absoluteOffset(L, index); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "register_get_by_type_index"); + lua_pushvalue(L, index); + if (lua_pcall(L, 1, 0, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + lua_pop(L, 1); } boost::optional Swift::Lua::getStringField(lua_State* L, int index, const std::string& field) { - lua_getfield(L, index, field.c_str()); - // Seems to generate warnings with some versions of CLang that i can't turn off. - // Leaving the more elegant code here, hoping we can re-enable it later (newer boost? c++11?). - // The same applies to the other get*Field functions. - //BOOST_SCOPE_EXIT(&L) { lua_pop(L,1); } BOOST_SCOPE_EXIT_END - //return lua_isstring(L, -1) ? std::string(lua_tostring(L, -1)) : boost::optional(); - - boost::optional result; - if (lua_isstring(L, -1)) { - result = std::string(lua_tostring(L, -1)); - } - lua_pop(L, 1); - return result; + lua_getfield(L, index, field.c_str()); + // Seems to generate warnings with some versions of CLang that i can't turn off. + // Leaving the more elegant code here, hoping we can re-enable it later (newer boost? c++11?). + // The same applies to the other get*Field functions. + //BOOST_SCOPE_EXIT(&L) { lua_pop(L,1); } BOOST_SCOPE_EXIT_END + //return lua_isstring(L, -1) ? std::string(lua_tostring(L, -1)) : boost::optional(); + + boost::optional result; + if (lua_isstring(L, -1)) { + result = std::string(lua_tostring(L, -1)); + } + lua_pop(L, 1); + return result; } boost::optional Swift::Lua::getBooleanField(lua_State* L, int index, const std::string& field) { - lua_getfield(L, index, field.c_str()); - boost::optional result; - if (lua_isboolean(L, -1)) { - result = lua_toboolean(L, -1); - } - lua_pop(L, 1); - return result; + lua_getfield(L, index, field.c_str()); + boost::optional result; + if (lua_isboolean(L, -1)) { + result = lua_toboolean(L, -1); + } + lua_pop(L, 1); + return result; } boost::optional Swift::Lua::getIntField(lua_State* L, int index, const std::string& field) { - lua_getfield(L, index, field.c_str()); - boost::optional result; - if (lua_isnumber(L, -1)) { - result = boost::numeric_cast(lua_tonumber(L, -1)); - } - lua_pop(L, 1); - return result; + lua_getfield(L, index, field.c_str()); + boost::optional result; + if (lua_isnumber(L, -1)) { + result = boost::numeric_cast(lua_tonumber(L, -1)); + } + lua_pop(L, 1); + return result; } void Swift::Lua::registerHelp(lua_State* L, int index, const std::string& description, const std::string& parameters, const std::string& options) { - index = Lua::absoluteOffset(L, index); - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "register_help"); - lua_pushvalue(L, index); - - lua_newtable(L); - lua_pushstring(L, description.c_str()); - lua_rawseti(L, -2, 1); - - if (!parameters.empty()) { - std::istringstream s(parameters); - lua_newtable(L); - int i = 1; - for (std::string line; std::getline(s, line); ) { - std::string trimmedLine = boost::trim_copy(line); - if (trimmedLine.empty()) { - continue; - } - size_t splitIndex = trimmedLine.find_first_of(" \t"); - std::string key; - std::string value; - if (splitIndex == std::string::npos) { - key = trimmedLine; - } - else { - key = trimmedLine.substr(0, splitIndex); - value = boost::trim_copy(trimmedLine.substr(splitIndex+1)); - } - lua_createtable(L, 2, 0); - lua_pushstring(L, key.c_str()); - lua_rawseti(L, -2, 1); - lua_pushstring(L, value.c_str()); - lua_rawseti(L, -2, 2); - - lua_rawseti(L, -2, i++); - } - lua_setfield(L, -2, "parameters"); - } - if (!options.empty()) { - std::istringstream s(options); - lua_newtable(L); - for (std::string line; std::getline(s, line); ) { - std::string trimmedLine = boost::trim_copy(line); - if (trimmedLine.empty()) { - continue; - } - size_t splitIndex = trimmedLine.find_first_of(" \t"); - std::string key; - std::string value; - if (splitIndex == std::string::npos) { - key = trimmedLine; - } - else { - key = trimmedLine.substr(0, splitIndex); - value = boost::trim_copy(trimmedLine.substr(splitIndex+1)); - } - lua_pushstring(L, value.c_str()); - lua_setfield(L, -2, key.c_str()); - } - lua_setfield(L, -2, "options"); - } - - if (lua_pcall(L, 2, 0, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - lua_pop(L, 1); + index = Lua::absoluteOffset(L, index); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "register_help"); + lua_pushvalue(L, index); + + lua_newtable(L); + lua_pushstring(L, description.c_str()); + lua_rawseti(L, -2, 1); + + if (!parameters.empty()) { + std::istringstream s(parameters); + lua_newtable(L); + int i = 1; + for (std::string line; std::getline(s, line); ) { + std::string trimmedLine = boost::trim_copy(line); + if (trimmedLine.empty()) { + continue; + } + size_t splitIndex = trimmedLine.find_first_of(" \t"); + std::string key; + std::string value; + if (splitIndex == std::string::npos) { + key = trimmedLine; + } + else { + key = trimmedLine.substr(0, splitIndex); + value = boost::trim_copy(trimmedLine.substr(splitIndex+1)); + } + lua_createtable(L, 2, 0); + lua_pushstring(L, key.c_str()); + lua_rawseti(L, -2, 1); + lua_pushstring(L, value.c_str()); + lua_rawseti(L, -2, 2); + + lua_rawseti(L, -2, i++); + } + lua_setfield(L, -2, "parameters"); + } + if (!options.empty()) { + std::istringstream s(options); + lua_newtable(L); + for (std::string line; std::getline(s, line); ) { + std::string trimmedLine = boost::trim_copy(line); + if (trimmedLine.empty()) { + continue; + } + size_t splitIndex = trimmedLine.find_first_of(" \t"); + std::string key; + std::string value; + if (splitIndex == std::string::npos) { + key = trimmedLine; + } + else { + key = trimmedLine.substr(0, splitIndex); + value = boost::trim_copy(trimmedLine.substr(splitIndex+1)); + } + lua_pushstring(L, value.c_str()); + lua_setfield(L, -2, key.c_str()); + } + lua_setfield(L, -2, "options"); + } + + if (lua_pcall(L, 2, 0, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + lua_pop(L, 1); } void Swift::Lua::registerClassHelp(lua_State* L, const std::string& name, const std::string& description) { - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "register_class_help"); - lua_pushstring(L, name.c_str()); - - lua_newtable(L); - lua_pushstring(L, description.c_str()); - lua_rawseti(L, -2, 1); - - if (lua_pcall(L, 2, 0, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - lua_pop(L, 1); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "register_class_help"); + lua_pushstring(L, name.c_str()); + + lua_newtable(L); + lua_pushstring(L, description.c_str()); + lua_rawseti(L, -2, 1); + + if (lua_pcall(L, 2, 0, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + lua_pop(L, 1); } void Swift::Lua::registerExtraHelp(lua_State* L, int index, const std::string& name) { - index = Lua::absoluteOffset(L, index); - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "extra_help"); - lua_getfield(L, -1, name.c_str()); - if (!lua_isnil(L, -1)) { - lua_getfield(L, -3, "register_help"); - lua_pushvalue(L, index); - lua_pushvalue(L, -3); - if (lua_pcall(L, 2, 0, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - } - lua_pop(L, 3); + index = Lua::absoluteOffset(L, index); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "extra_help"); + lua_getfield(L, -1, name.c_str()); + if (!lua_isnil(L, -1)) { + lua_getfield(L, -3, "register_help"); + lua_pushvalue(L, index); + lua_pushvalue(L, -3); + if (lua_pcall(L, 2, 0, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + } + lua_pop(L, 3); } void Swift::Lua::pushStringArray(lua_State* L, const std::vector& strings) { - lua_createtable(L, boost::numeric_cast(strings.size()), 0); - for (size_t i = 0; i < strings.size(); ++i) { - lua_pushstring(L, strings[i].c_str()); - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } + lua_createtable(L, boost::numeric_cast(strings.size()), 0); + for (size_t i = 0; i < strings.size(); ++i) { + lua_pushstring(L, strings[i].c_str()); + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } } diff --git a/Sluift/Lua/LuaUtils.h b/Sluift/Lua/LuaUtils.h index 19b6691..b87eb38 100644 --- a/Sluift/Lua/LuaUtils.h +++ b/Sluift/Lua/LuaUtils.h @@ -16,28 +16,28 @@ #endif namespace Swift { - namespace Lua { - /** - * Can be used as __tostring metamethod on a table. - */ - int convertTableToString(lua_State* L); - - void registerTableToString(lua_State* L, int index); - void registerTableEquals(lua_State* L, int index); - void registerGetByTypeIndex(lua_State* L, int index); - void registerHelp(lua_State* L, int index, - const std::string& description, const std::string& parameters, const std::string& options); - void registerClassHelp(lua_State* L, const std::string& name, const std::string& description); - void registerExtraHelp(lua_State* L, int index, const std::string& name); - - inline int absoluteOffset(lua_State* L, int index) { - return index > 0 ? index : lua_gettop(L) + index + 1; - } - - boost::optional getStringField(lua_State* L, int index, const std::string&); - boost::optional getBooleanField(lua_State* L, int index, const std::string&); - boost::optional getIntField(lua_State* L, int index, const std::string&); - - void pushStringArray(lua_State* L, const std::vector& strings); - } + namespace Lua { + /** + * Can be used as __tostring metamethod on a table. + */ + int convertTableToString(lua_State* L); + + void registerTableToString(lua_State* L, int index); + void registerTableEquals(lua_State* L, int index); + void registerGetByTypeIndex(lua_State* L, int index); + void registerHelp(lua_State* L, int index, + const std::string& description, const std::string& parameters, const std::string& options); + void registerClassHelp(lua_State* L, const std::string& name, const std::string& description); + void registerExtraHelp(lua_State* L, int index, const std::string& name); + + inline int absoluteOffset(lua_State* L, int index) { + return index > 0 ? index : lua_gettop(L) + index + 1; + } + + boost::optional getStringField(lua_State* L, int index, const std::string&); + boost::optional getBooleanField(lua_State* L, int index, const std::string&); + boost::optional getIntField(lua_State* L, int index, const std::string&); + + void pushStringArray(lua_State* L, const std::vector& strings); + } } diff --git a/Sluift/Lua/Value.cpp b/Sluift/Lua/Value.cpp index b5c459a..dd61d59 100644 --- a/Sluift/Lua/Value.cpp +++ b/Sluift/Lua/Value.cpp @@ -10,7 +10,7 @@ #include extern "C" { - #include + #include } #include @@ -19,50 +19,50 @@ using namespace Swift; using namespace Swift::Lua; namespace { - struct PushVisitor : public boost::static_visitor<> { - PushVisitor(lua_State* state) : state(state) { - } - - void operator()(const Nil&) const { - lua_pushnil(state); - } - - void operator()(const bool& b) const { - lua_pushboolean(state, b); - } - - void operator()(const int& i) const { - lua_pushnumber(state, i); - } - - void operator()(const std::string& s) const { - lua_pushstring(state, s.c_str()); - } - - void operator()(const std::vector& values) const { - lua_createtable(state, boost::numeric_cast(values.size()), 0); - for(size_t i = 0; i < values.size(); ++i) { - boost::apply_visitor(PushVisitor(state), values[i]); - lua_rawseti(state, -2, boost::numeric_cast(i + 1)); - } - } - - void operator()(const std::map >& table) const { - lua_createtable(state, 0, boost::numeric_cast(table.size())); - for(std::map >::const_iterator i = table.begin(); i != table.end(); ++i) { - boost::apply_visitor(PushVisitor(state), *i->second); - lua_setfield(state, -2, i->first.c_str()); - } - } - - lua_State* state; - }; + struct PushVisitor : public boost::static_visitor<> { + PushVisitor(lua_State* state) : state(state) { + } + + void operator()(const Nil&) const { + lua_pushnil(state); + } + + void operator()(const bool& b) const { + lua_pushboolean(state, b); + } + + void operator()(const int& i) const { + lua_pushnumber(state, i); + } + + void operator()(const std::string& s) const { + lua_pushstring(state, s.c_str()); + } + + void operator()(const std::vector& values) const { + lua_createtable(state, boost::numeric_cast(values.size()), 0); + for(size_t i = 0; i < values.size(); ++i) { + boost::apply_visitor(PushVisitor(state), values[i]); + lua_rawseti(state, -2, boost::numeric_cast(i + 1)); + } + } + + void operator()(const std::map >& table) const { + lua_createtable(state, 0, boost::numeric_cast(table.size())); + for(std::map >::const_iterator i = table.begin(); i != table.end(); ++i) { + boost::apply_visitor(PushVisitor(state), *i->second); + lua_setfield(state, -2, i->first.c_str()); + } + } + + lua_State* state; + }; } namespace Swift { namespace Lua { void pushValue(lua_State* state, const Value& value) { - boost::apply_visitor(PushVisitor(state), value); + boost::apply_visitor(PushVisitor(state), value); } }} diff --git a/Sluift/Lua/Value.h b/Sluift/Lua/Value.h index 537d764..f525fb8 100644 --- a/Sluift/Lua/Value.h +++ b/Sluift/Lua/Value.h @@ -17,45 +17,45 @@ struct lua_State; namespace Swift { - namespace Lua { - struct Nil {}; - - typedef boost::make_recursive_variant< - Nil, - bool, - int, - std::string, - std::vector< boost::recursive_variant_ >, - std::map > - >::type Value; - - typedef std::map > Table; - typedef std::vector Array; - - inline boost::shared_ptr nilRef() { - return boost::make_shared(Nil()); - } - - inline boost::shared_ptr valueRef(const std::string& value) { - return boost::make_shared(value); - } - - inline boost::shared_ptr intRef(int value) { - return boost::make_shared(value); - } - - inline boost::shared_ptr boolRef(bool value) { - return boost::make_shared(value); - } - - inline boost::shared_ptr valueRef(const Table& table) { - return boost::make_shared(table); - } - - inline boost::shared_ptr valueRef(const Array& array) { - return boost::make_shared(array); - } - - void pushValue(lua_State* state, const Value& value); - } + namespace Lua { + struct Nil {}; + + typedef boost::make_recursive_variant< + Nil, + bool, + int, + std::string, + std::vector< boost::recursive_variant_ >, + std::map > + >::type Value; + + typedef std::map > Table; + typedef std::vector Array; + + inline boost::shared_ptr nilRef() { + return boost::make_shared(Nil()); + } + + inline boost::shared_ptr valueRef(const std::string& value) { + return boost::make_shared(value); + } + + inline boost::shared_ptr intRef(int value) { + return boost::make_shared(value); + } + + inline boost::shared_ptr boolRef(bool value) { + return boost::make_shared(value); + } + + inline boost::shared_ptr valueRef(const Table& table) { + return boost::make_shared(table); + } + + inline boost::shared_ptr valueRef(const Array& array) { + return boost::make_shared(array); + } + + void pushValue(lua_State* state, const Value& value); + } } diff --git a/Sluift/LuaElementConvertor.h b/Sluift/LuaElementConvertor.h index 9587628..6c237fd 100644 --- a/Sluift/LuaElementConvertor.h +++ b/Sluift/LuaElementConvertor.h @@ -16,26 +16,26 @@ struct lua_State; namespace Swift { - class Element; + class Element; - class LuaElementConvertor { - public: - static boost::optional NO_RESULT; + class LuaElementConvertor { + public: + static boost::optional NO_RESULT; - struct Documentation { - Documentation(const std::string& className, const std::string& description) : - className(className), description(description) {} - std::string className; - std::string description; - }; + struct Documentation { + Documentation(const std::string& className, const std::string& description) : + className(className), description(description) {} + std::string className; + std::string description; + }; - virtual ~LuaElementConvertor(); + virtual ~LuaElementConvertor(); - virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) = 0; - virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) = 0; + virtual boost::shared_ptr convertFromLua(lua_State*, int index, const std::string& type) = 0; + virtual boost::optional convertToLua(lua_State*, boost::shared_ptr) = 0; - virtual boost::optional getDocumentation() const { - return boost::optional(); - } - }; + virtual boost::optional getDocumentation() const { + return boost::optional(); + } + }; } diff --git a/Sluift/LuaElementConvertors.cpp b/Sluift/LuaElementConvertors.cpp index 963a618..67c0545 100644 --- a/Sluift/LuaElementConvertors.cpp +++ b/Sluift/LuaElementConvertors.cpp @@ -41,31 +41,31 @@ using namespace Swift; LuaElementConvertors::LuaElementConvertors() { - registerConvertors(); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared(this)); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); - convertors.push_back(boost::make_shared()); + registerConvertors(); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared(this)); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); + convertors.push_back(boost::make_shared()); } LuaElementConvertors::~LuaElementConvertors() { @@ -74,64 +74,64 @@ LuaElementConvertors::~LuaElementConvertors() { #include boost::shared_ptr LuaElementConvertors::convertFromLua(lua_State* L, int index) { - if (lua_isstring(L, index)) { - return convertFromLuaUntyped(L, index, "xml"); - } - else if (lua_istable(L, index)) { - lua_getfield(L, index, "_type"); - if (lua_isstring(L, -1)) { - std::string type = lua_tostring(L, -1); - lua_pop(L, 1); - return convertFromLuaUntyped(L, index, type); - } - lua_pop(L, 1); - } - throw Lua::Exception("Unable to determine type"); + if (lua_isstring(L, index)) { + return convertFromLuaUntyped(L, index, "xml"); + } + else if (lua_istable(L, index)) { + lua_getfield(L, index, "_type"); + if (lua_isstring(L, -1)) { + std::string type = lua_tostring(L, -1); + lua_pop(L, 1); + return convertFromLuaUntyped(L, index, type); + } + lua_pop(L, 1); + } + throw Lua::Exception("Unable to determine type"); } boost::shared_ptr LuaElementConvertors::convertFromLuaUntyped(lua_State* L, int index, const std::string& type) { - index = Lua::absoluteOffset(L, index); - foreach (boost::shared_ptr convertor, convertors) { - if (boost::shared_ptr result = convertor->convertFromLua(L, index, type)) { - return result; - } - } - return boost::shared_ptr(); + index = Lua::absoluteOffset(L, index); + foreach (boost::shared_ptr convertor, convertors) { + if (boost::shared_ptr result = convertor->convertFromLua(L, index, type)) { + return result; + } + } + return boost::shared_ptr(); } int LuaElementConvertors::convertToLua(lua_State* L, boost::shared_ptr payload) { - if (boost::optional type = doConvertToLuaUntyped(L, payload)) { - if (lua_istable(L, -1)) { - lua_pushstring(L, type->c_str()); - lua_setfield(L, -2, "_type"); - Lua::registerTableToString(L, -1); - } - else { - assert(*type == "xml"); - } - return 1; - } - return 0; + if (boost::optional type = doConvertToLuaUntyped(L, payload)) { + if (lua_istable(L, -1)) { + lua_pushstring(L, type->c_str()); + lua_setfield(L, -2, "_type"); + Lua::registerTableToString(L, -1); + } + else { + assert(*type == "xml"); + } + return 1; + } + return 0; } int LuaElementConvertors::convertToLuaUntyped(lua_State* L, boost::shared_ptr payload) { - if (doConvertToLuaUntyped(L, payload)) { - return 1; - } - return 0; + if (doConvertToLuaUntyped(L, payload)) { + return 1; + } + return 0; } boost::optional LuaElementConvertors::doConvertToLuaUntyped( - lua_State* L, boost::shared_ptr payload) { - if (!payload) { - return LuaElementConvertor::NO_RESULT; - } - foreach (boost::shared_ptr convertor, convertors) { - if (boost::optional type = convertor->convertToLua(L, payload)) { - return *type; - } - } - return LuaElementConvertor::NO_RESULT; + lua_State* L, boost::shared_ptr payload) { + if (!payload) { + return LuaElementConvertor::NO_RESULT; + } + foreach (boost::shared_ptr convertor, convertors) { + if (boost::optional type = convertor->convertToLua(L, payload)) { + return *type; + } + } + return LuaElementConvertor::NO_RESULT; } diff --git a/Sluift/LuaElementConvertors.h b/Sluift/LuaElementConvertors.h index 1e9dc97..6b3d343 100644 --- a/Sluift/LuaElementConvertors.h +++ b/Sluift/LuaElementConvertors.h @@ -16,37 +16,37 @@ struct lua_State; namespace Swift { - class LuaElementConvertor; - class Element; - - class LuaElementConvertors { - public: - LuaElementConvertors(); - virtual ~LuaElementConvertors(); - - boost::shared_ptr convertFromLua(lua_State*, int index); - int convertToLua(lua_State*, boost::shared_ptr); - - /** - * Adds a toplevel type+data table with the given type. - */ - boost::shared_ptr convertFromLuaUntyped(lua_State*, int index, const std::string& type); - - /** - * Strips the toplevel type+data table, and only return the - * data. - */ - int convertToLuaUntyped(lua_State*, boost::shared_ptr); - - const std::vector< boost::shared_ptr >& getConvertors() const { - return convertors; - } - - private: - boost::optional doConvertToLuaUntyped(lua_State*, boost::shared_ptr); - void registerConvertors(); - - private: - std::vector< boost::shared_ptr > convertors; - }; + class LuaElementConvertor; + class Element; + + class LuaElementConvertors { + public: + LuaElementConvertors(); + virtual ~LuaElementConvertors(); + + boost::shared_ptr convertFromLua(lua_State*, int index); + int convertToLua(lua_State*, boost::shared_ptr); + + /** + * Adds a toplevel type+data table with the given type. + */ + boost::shared_ptr convertFromLuaUntyped(lua_State*, int index, const std::string& type); + + /** + * Strips the toplevel type+data table, and only return the + * data. + */ + int convertToLuaUntyped(lua_State*, boost::shared_ptr); + + const std::vector< boost::shared_ptr >& getConvertors() const { + return convertors; + } + + private: + boost::optional doConvertToLuaUntyped(lua_State*, boost::shared_ptr); + void registerConvertors(); + + private: + std::vector< boost::shared_ptr > convertors; + }; } diff --git a/Sluift/Response.cpp b/Sluift/Response.cpp index ff643f2..97a44d0 100644 --- a/Sluift/Response.cpp +++ b/Sluift/Response.cpp @@ -17,65 +17,65 @@ using namespace Swift; using namespace Swift::Sluift; static std::string getErrorString(boost::shared_ptr error) { - // Copied from ChatControllerBase. - // TODO: Share this code; - std::string defaultMessage = "Error sending message"; - if (!error->getText().empty()) { - return error->getText(); - } - else { - switch (error->getCondition()) { - case ErrorPayload::BadRequest: return "Bad request"; - case ErrorPayload::Conflict: return "Conflict"; - case ErrorPayload::FeatureNotImplemented: return "This feature is not implemented"; - case ErrorPayload::Forbidden: return "Forbidden"; - case ErrorPayload::Gone: return "Recipient can no longer be contacted"; - case ErrorPayload::InternalServerError: return "Internal server error"; - case ErrorPayload::ItemNotFound: return "Item not found"; - case ErrorPayload::JIDMalformed: return "JID Malformed"; - case ErrorPayload::NotAcceptable: return "Message was rejected"; - case ErrorPayload::NotAllowed: return "Not allowed"; - case ErrorPayload::NotAuthorized: return "Not authorized"; - case ErrorPayload::PaymentRequired: return "Payment is required"; - case ErrorPayload::RecipientUnavailable: return "Recipient is unavailable"; - case ErrorPayload::Redirect: return "Redirect"; - case ErrorPayload::RegistrationRequired: return "Registration required"; - case ErrorPayload::RemoteServerNotFound: return "Recipient's server not found"; - case ErrorPayload::RemoteServerTimeout: return "Remote server timeout"; - case ErrorPayload::ResourceConstraint: return "The server is low on resources"; - case ErrorPayload::ServiceUnavailable: return "The service is unavailable"; - case ErrorPayload::SubscriptionRequired: return "A subscription is required"; - case ErrorPayload::UndefinedCondition: return "Undefined condition"; - case ErrorPayload::UnexpectedRequest: return "Unexpected request"; - } - } - assert(false); - return defaultMessage; + // Copied from ChatControllerBase. + // TODO: Share this code; + std::string defaultMessage = "Error sending message"; + if (!error->getText().empty()) { + return error->getText(); + } + else { + switch (error->getCondition()) { + case ErrorPayload::BadRequest: return "Bad request"; + case ErrorPayload::Conflict: return "Conflict"; + case ErrorPayload::FeatureNotImplemented: return "This feature is not implemented"; + case ErrorPayload::Forbidden: return "Forbidden"; + case ErrorPayload::Gone: return "Recipient can no longer be contacted"; + case ErrorPayload::InternalServerError: return "Internal server error"; + case ErrorPayload::ItemNotFound: return "Item not found"; + case ErrorPayload::JIDMalformed: return "JID Malformed"; + case ErrorPayload::NotAcceptable: return "Message was rejected"; + case ErrorPayload::NotAllowed: return "Not allowed"; + case ErrorPayload::NotAuthorized: return "Not authorized"; + case ErrorPayload::PaymentRequired: return "Payment is required"; + case ErrorPayload::RecipientUnavailable: return "Recipient is unavailable"; + case ErrorPayload::Redirect: return "Redirect"; + case ErrorPayload::RegistrationRequired: return "Registration required"; + case ErrorPayload::RemoteServerNotFound: return "Recipient's server not found"; + case ErrorPayload::RemoteServerTimeout: return "Remote server timeout"; + case ErrorPayload::ResourceConstraint: return "The server is low on resources"; + case ErrorPayload::ServiceUnavailable: return "The service is unavailable"; + case ErrorPayload::SubscriptionRequired: return "A subscription is required"; + case ErrorPayload::UndefinedCondition: return "Undefined condition"; + case ErrorPayload::UnexpectedRequest: return "Unexpected request"; + } + } + assert(false); + return defaultMessage; } Response::~Response() { } int Response::convertToLuaResult(lua_State* L) { - if (error) { - lua_pushnil(L); - lua_pushstring(L, getErrorString(error).c_str()); - bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, error); - assert(converted); - Lua::registerTableToString(L, -1); - return 3; - } - else { - if (result) { - bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, result); - assert(converted); - Lua::registerTableToString(L, -1); - } - else { - lua_pushboolean(L, 1); - } - return 1; - } + if (error) { + lua_pushnil(L); + lua_pushstring(L, getErrorString(error).c_str()); + bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, error); + assert(converted); + Lua::registerTableToString(L, -1); + return 3; + } + else { + if (result) { + bool converted = Sluift::globals.elementConvertor.convertToLuaUntyped(L, result); + assert(converted); + Lua::registerTableToString(L, -1); + } + else { + lua_pushboolean(L, 1); + } + return 1; + } } diff --git a/Sluift/Response.h b/Sluift/Response.h index 9830dcc..c0bd28a 100644 --- a/Sluift/Response.h +++ b/Sluift/Response.h @@ -13,24 +13,24 @@ struct lua_State; namespace Swift { - namespace Sluift { - struct Response { - Response(boost::shared_ptr result, boost::shared_ptr error) : result(result), error(error) {} - SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Response) - ~Response(); - - static Response withResult(boost::shared_ptr response) { - return Response(response, boost::shared_ptr()); - } - - static Response withError(boost::shared_ptr error) { - return Response(boost::shared_ptr(), error); - } - - int convertToLuaResult(lua_State* L); - - boost::shared_ptr result; - boost::shared_ptr error; - }; - } + namespace Sluift { + struct Response { + Response(boost::shared_ptr result, boost::shared_ptr error) : result(result), error(error) {} + SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(Response) + ~Response(); + + static Response withResult(boost::shared_ptr response) { + return Response(response, boost::shared_ptr()); + } + + static Response withError(boost::shared_ptr error) { + return Response(boost::shared_ptr(), error); + } + + int convertToLuaResult(lua_State* L); + + boost::shared_ptr result; + boost::shared_ptr error; + }; + } } diff --git a/Sluift/SluiftClient.cpp b/Sluift/SluiftClient.cpp index 1de317c..fea3291 100644 --- a/Sluift/SluiftClient.cpp +++ b/Sluift/SluiftClient.cpp @@ -23,168 +23,168 @@ using namespace Swift; SluiftClient::SluiftClient( - const JID& jid, - const std::string& password, - NetworkFactories* networkFactories, - SimpleEventLoop* eventLoop) : - networkFactories(networkFactories), - eventLoop(eventLoop), - tracer(NULL) { - client = new Client(jid, password, networkFactories); - client->setAlwaysTrustCertificates(); - client->onDisconnected.connect(boost::bind(&SluiftClient::handleDisconnected, this, _1)); - client->onMessageReceived.connect(boost::bind(&SluiftClient::handleIncomingMessage, this, _1)); - client->onPresenceReceived.connect(boost::bind(&SluiftClient::handleIncomingPresence, this, _1)); - client->getPubSubManager()->onEvent.connect(boost::bind(&SluiftClient::handleIncomingPubSubEvent, this, _1, _2)); - client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SluiftClient::handleInitialRosterPopulated, this)); + const JID& jid, + const std::string& password, + NetworkFactories* networkFactories, + SimpleEventLoop* eventLoop) : + networkFactories(networkFactories), + eventLoop(eventLoop), + tracer(NULL) { + client = new Client(jid, password, networkFactories); + client->setAlwaysTrustCertificates(); + client->onDisconnected.connect(boost::bind(&SluiftClient::handleDisconnected, this, _1)); + client->onMessageReceived.connect(boost::bind(&SluiftClient::handleIncomingMessage, this, _1)); + client->onPresenceReceived.connect(boost::bind(&SluiftClient::handleIncomingPresence, this, _1)); + client->getPubSubManager()->onEvent.connect(boost::bind(&SluiftClient::handleIncomingPubSubEvent, this, _1, _2)); + client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SluiftClient::handleInitialRosterPopulated, this)); } SluiftClient::~SluiftClient() { - delete tracer; - delete client; + delete tracer; + delete client; } void SluiftClient::connect() { - rosterReceived = false; - disconnectedError = boost::optional(); - client->connect(options); + rosterReceived = false; + disconnectedError = boost::optional(); + client->connect(options); } void SluiftClient::connect(const std::string& host, int port) { - rosterReceived = false; - options.manualHostname = host; - options.manualPort = port; - disconnectedError = boost::optional(); - client->connect(options); + rosterReceived = false; + options.manualHostname = host; + options.manualPort = port; + disconnectedError = boost::optional(); + client->connect(options); } void SluiftClient::setTraceEnabled(bool b) { - if (b && !tracer) { - tracer = new ClientXMLTracer(client, options.boshURL.isEmpty()? false: true); - } - else if (!b && tracer) { - delete tracer; - tracer = NULL; - } + if (b && !tracer) { + tracer = new ClientXMLTracer(client, options.boshURL.isEmpty()? false: true); + } + else if (!b && tracer) { + delete tracer; + tracer = NULL; + } } void SluiftClient::waitConnected(int timeout) { - Watchdog watchdog(timeout, networkFactories->getTimerFactory()); - while (!watchdog.getTimedOut() && client->isActive() && !client->isAvailable()) { - eventLoop->runUntilEvents(); - } - if (watchdog.getTimedOut()) { - client->disconnect(); - throw Lua::Exception("Timeout while connecting"); - } - if (disconnectedError) { - throw Lua::Exception(getErrorString(*disconnectedError)); - } + Watchdog watchdog(timeout, networkFactories->getTimerFactory()); + while (!watchdog.getTimedOut() && client->isActive() && !client->isAvailable()) { + eventLoop->runUntilEvents(); + } + if (watchdog.getTimedOut()) { + client->disconnect(); + throw Lua::Exception("Timeout while connecting"); + } + if (disconnectedError) { + throw Lua::Exception(getErrorString(*disconnectedError)); + } } bool SluiftClient::isConnected() const { - return client->isAvailable(); + return client->isAvailable(); } void SluiftClient::disconnect() { - client->disconnect(); - while (client->isActive()) { - eventLoop->runUntilEvents(); - } + client->disconnect(); + while (client->isActive()) { + eventLoop->runUntilEvents(); + } } void SluiftClient::setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os) { - client->setSoftwareVersion(name, version, os); + client->setSoftwareVersion(name, version, os); } boost::optional SluiftClient::getNextEvent( - int timeout, boost::function condition) { - Watchdog watchdog(timeout, networkFactories->getTimerFactory()); - size_t currentIndex = 0; - while (true) { - // Look for pending events in the queue - while (currentIndex < pendingEvents.size()) { - Event event = pendingEvents[currentIndex]; - if (!condition || condition(event)) { - pendingEvents.erase( - pendingEvents.begin() - + boost::numeric_cast(currentIndex)); - return event; - } - ++currentIndex; - } - - // Wait for new events - while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && client->isActive()) { - eventLoop->runUntilEvents(); - } - - // Finish if we're disconnected or timed out - if (watchdog.getTimedOut() || !client->isActive()) { - return boost::optional(); - } - } + int timeout, boost::function condition) { + Watchdog watchdog(timeout, networkFactories->getTimerFactory()); + size_t currentIndex = 0; + while (true) { + // Look for pending events in the queue + while (currentIndex < pendingEvents.size()) { + Event event = pendingEvents[currentIndex]; + if (!condition || condition(event)) { + pendingEvents.erase( + pendingEvents.begin() + + boost::numeric_cast(currentIndex)); + return event; + } + ++currentIndex; + } + + // Wait for new events + while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && client->isActive()) { + eventLoop->runUntilEvents(); + } + + // Finish if we're disconnected or timed out + if (watchdog.getTimedOut() || !client->isActive()) { + return boost::optional(); + } + } } std::vector SluiftClient::getRoster(int timeout) { - Watchdog watchdog(timeout, networkFactories->getTimerFactory()); - if (!rosterReceived) { - // If we haven't requested it yet, request it for the first time - client->requestRoster(); + Watchdog watchdog(timeout, networkFactories->getTimerFactory()); + if (!rosterReceived) { + // If we haven't requested it yet, request it for the first time + client->requestRoster(); - // Wait for new events - while (!watchdog.getTimedOut() && !rosterReceived) { - eventLoop->runUntilEvents(); - } + // Wait for new events + while (!watchdog.getTimedOut() && !rosterReceived) { + eventLoop->runUntilEvents(); + } - // Throw an error if we're timed out - if (watchdog.getTimedOut()) { - throw Lua::Exception("Timeout while requesting roster"); - } - } - return client->getRoster()->getItems(); + // Throw an error if we're timed out + if (watchdog.getTimedOut()) { + throw Lua::Exception("Timeout while requesting roster"); + } + } + return client->getRoster()->getItems(); } void SluiftClient::handleIncomingMessage(boost::shared_ptr stanza) { - if (stanza->getPayload()) { - // Already handled by pubsub manager - return; - } - pendingEvents.push_back(Event(stanza)); + if (stanza->getPayload()) { + // Already handled by pubsub manager + return; + } + pendingEvents.push_back(Event(stanza)); } void SluiftClient::handleIncomingPresence(boost::shared_ptr stanza) { - pendingEvents.push_back(Event(stanza)); + pendingEvents.push_back(Event(stanza)); } void SluiftClient::handleIncomingPubSubEvent(const JID& from, boost::shared_ptr event) { - pendingEvents.push_back(Event(from, event)); + pendingEvents.push_back(Event(from, event)); } void SluiftClient::handleInitialRosterPopulated() { - rosterReceived = true; + rosterReceived = true; } void SluiftClient::handleRequestResponse(boost::shared_ptr response, boost::shared_ptr error) { - requestResponse = response; - requestError = error; - requestResponseReceived = true; + requestResponse = response; + requestError = error; + requestResponseReceived = true; } void SluiftClient::handleDisconnected(const boost::optional& error) { - disconnectedError = error; + disconnectedError = error; } Sluift::Response SluiftClient::doSendRequest(boost::shared_ptr request, int timeout) { - requestResponse.reset(); - requestError.reset(); - requestResponseReceived = false; - request->send(); - - Watchdog watchdog(timeout, networkFactories->getTimerFactory()); - while (!watchdog.getTimedOut() && !requestResponseReceived) { - eventLoop->runUntilEvents(); - } - return Sluift::Response(requestResponse, watchdog.getTimedOut() ? - boost::make_shared(ErrorPayload::RemoteServerTimeout) : requestError); + requestResponse.reset(); + requestError.reset(); + requestResponseReceived = false; + request->send(); + + Watchdog watchdog(timeout, networkFactories->getTimerFactory()); + while (!watchdog.getTimedOut() && !requestResponseReceived) { + eventLoop->runUntilEvents(); + } + return Sluift::Response(requestResponse, watchdog.getTimedOut() ? + boost::make_shared(ErrorPayload::RemoteServerTimeout) : requestError); } diff --git a/Sluift/SluiftClient.h b/Sluift/SluiftClient.h index 07073ce..d7c3b32 100644 --- a/Sluift/SluiftClient.h +++ b/Sluift/SluiftClient.h @@ -28,106 +28,106 @@ #include namespace Swift { - struct SluiftGlobals; - class ClientXMLTracer; - class Client; - class Stanza; - class Payload; - class ErrorPayload; - class JID; - - class SluiftClient { - public: - struct Event { - enum Type { - MessageType, - PresenceType, - PubSubEventType - }; - - Event(boost::shared_ptr stanza) : type(MessageType), stanza(stanza) {} - Event(boost::shared_ptr stanza) : type(PresenceType), stanza(stanza) {} - Event(const JID& from, boost::shared_ptr payload) : type(PubSubEventType), from(from), pubsubEvent(payload) {} - - Type type; - - // Message & Presence - boost::shared_ptr stanza; - - // PubSubEvent - JID from; - boost::shared_ptr pubsubEvent; - }; - - SluiftClient( - const JID& jid, - const std::string& password, - NetworkFactories* networkFactories, - SimpleEventLoop* eventLoop); - ~SluiftClient(); - - Client* getClient() { - return client; - } - - ClientOptions& getOptions() { - return options; - } - - void connect(); - void connect(const std::string& host, int port); - void waitConnected(int timeout); - bool isConnected() const; - void setTraceEnabled(bool b); - - template - Sluift::Response sendPubSubRequest( - IQ::Type type, const JID& jid, boost::shared_ptr payload, int timeout) { - return sendRequest(client->getPubSubManager()->createRequest( - type, jid, payload), timeout); - } - - template - Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) { - boost::signals::scoped_connection c = request->onResponse.connect( - boost::bind(&SluiftClient::handleRequestResponse, this, _1, _2)); - return doSendRequest(request, timeout); - } - - template - Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) { - boost::signals::scoped_connection c = request->onResponse.connect( - boost::bind(&SluiftClient::handleRequestResponse, this, boost::shared_ptr(), _1)); - return doSendRequest(request, timeout); - } - - void disconnect(); - void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os); - boost::optional getNextEvent(int timeout, - boost::function condition = 0); - std::vector getRoster(int timeout); - - private: - Sluift::Response doSendRequest(boost::shared_ptr request, int timeout); - - void handleIncomingMessage(boost::shared_ptr stanza); - void handleIncomingPresence(boost::shared_ptr stanza); - void handleIncomingPubSubEvent(const JID& from, boost::shared_ptr event); - void handleInitialRosterPopulated(); - void handleRequestResponse(boost::shared_ptr response, boost::shared_ptr error); - void handleDisconnected(const boost::optional& error); - - private: - NetworkFactories* networkFactories; - SimpleEventLoop* eventLoop; - Client* client; - ClientOptions options; - ClientXMLTracer* tracer; - bool rosterReceived; - std::deque pendingEvents; - boost::optional disconnectedError; - bool requestResponseReceived; - boost::shared_ptr requestResponse; - boost::shared_ptr requestError; - }; + struct SluiftGlobals; + class ClientXMLTracer; + class Client; + class Stanza; + class Payload; + class ErrorPayload; + class JID; + + class SluiftClient { + public: + struct Event { + enum Type { + MessageType, + PresenceType, + PubSubEventType + }; + + Event(boost::shared_ptr stanza) : type(MessageType), stanza(stanza) {} + Event(boost::shared_ptr stanza) : type(PresenceType), stanza(stanza) {} + Event(const JID& from, boost::shared_ptr payload) : type(PubSubEventType), from(from), pubsubEvent(payload) {} + + Type type; + + // Message & Presence + boost::shared_ptr stanza; + + // PubSubEvent + JID from; + boost::shared_ptr pubsubEvent; + }; + + SluiftClient( + const JID& jid, + const std::string& password, + NetworkFactories* networkFactories, + SimpleEventLoop* eventLoop); + ~SluiftClient(); + + Client* getClient() { + return client; + } + + ClientOptions& getOptions() { + return options; + } + + void connect(); + void connect(const std::string& host, int port); + void waitConnected(int timeout); + bool isConnected() const; + void setTraceEnabled(bool b); + + template + Sluift::Response sendPubSubRequest( + IQ::Type type, const JID& jid, boost::shared_ptr payload, int timeout) { + return sendRequest(client->getPubSubManager()->createRequest( + type, jid, payload), timeout); + } + + template + Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) { + boost::signals::scoped_connection c = request->onResponse.connect( + boost::bind(&SluiftClient::handleRequestResponse, this, _1, _2)); + return doSendRequest(request, timeout); + } + + template + Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) { + boost::signals::scoped_connection c = request->onResponse.connect( + boost::bind(&SluiftClient::handleRequestResponse, this, boost::shared_ptr(), _1)); + return doSendRequest(request, timeout); + } + + void disconnect(); + void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os); + boost::optional getNextEvent(int timeout, + boost::function condition = 0); + std::vector getRoster(int timeout); + + private: + Sluift::Response doSendRequest(boost::shared_ptr request, int timeout); + + void handleIncomingMessage(boost::shared_ptr stanza); + void handleIncomingPresence(boost::shared_ptr stanza); + void handleIncomingPubSubEvent(const JID& from, boost::shared_ptr event); + void handleInitialRosterPopulated(); + void handleRequestResponse(boost::shared_ptr response, boost::shared_ptr error); + void handleDisconnected(const boost::optional& error); + + private: + NetworkFactories* networkFactories; + SimpleEventLoop* eventLoop; + Client* client; + ClientOptions options; + ClientXMLTracer* tracer; + bool rosterReceived; + std::deque pendingEvents; + boost::optional disconnectedError; + bool requestResponseReceived; + boost::shared_ptr requestResponse; + boost::shared_ptr requestError; + }; } diff --git a/Sluift/SluiftComponent.cpp b/Sluift/SluiftComponent.cpp index 9d0a92e..c0dcd3c 100644 --- a/Sluift/SluiftComponent.cpp +++ b/Sluift/SluiftComponent.cpp @@ -22,125 +22,125 @@ using namespace Swift; SluiftComponent::SluiftComponent( - const JID& jid, - const std::string& password, - NetworkFactories* networkFactories, - SimpleEventLoop* eventLoop): - networkFactories(networkFactories), - eventLoop(eventLoop), - tracer(NULL) { - component = new Component(jid, password, networkFactories); - component->onError.connect(boost::bind(&SluiftComponent::handleError, this, _1)); - component->onMessageReceived.connect(boost::bind(&SluiftComponent::handleIncomingMessage, this, _1)); - component->onPresenceReceived.connect(boost::bind(&SluiftComponent::handleIncomingPresence, this, _1)); + const JID& jid, + const std::string& password, + NetworkFactories* networkFactories, + SimpleEventLoop* eventLoop): + networkFactories(networkFactories), + eventLoop(eventLoop), + tracer(NULL) { + component = new Component(jid, password, networkFactories); + component->onError.connect(boost::bind(&SluiftComponent::handleError, this, _1)); + component->onMessageReceived.connect(boost::bind(&SluiftComponent::handleIncomingMessage, this, _1)); + component->onPresenceReceived.connect(boost::bind(&SluiftComponent::handleIncomingPresence, this, _1)); } SluiftComponent::~SluiftComponent() { - delete tracer; - delete component; + delete tracer; + delete component; } void SluiftComponent::connect(const std::string& host, int port) { - disconnectedError = boost::optional(); - component->connect(host, port); + disconnectedError = boost::optional(); + component->connect(host, port); } void SluiftComponent::setTraceEnabled(bool b) { - if (b && !tracer) { - tracer = new ComponentXMLTracer(component); - } - else if (!b && tracer) { - delete tracer; - tracer = NULL; - } + if (b && !tracer) { + tracer = new ComponentXMLTracer(component); + } + else if (!b && tracer) { + delete tracer; + tracer = NULL; + } } void SluiftComponent::waitConnected(int timeout) { - Watchdog watchdog(timeout, networkFactories->getTimerFactory()); - while (!watchdog.getTimedOut() && !disconnectedError && !component->isAvailable()) { - eventLoop->runUntilEvents(); - } - if (watchdog.getTimedOut()) { - component->disconnect(); - throw Lua::Exception("Timeout while connecting"); - } - if (disconnectedError) { - throw Lua::Exception(getErrorString(*disconnectedError)); - } + Watchdog watchdog(timeout, networkFactories->getTimerFactory()); + while (!watchdog.getTimedOut() && !disconnectedError && !component->isAvailable()) { + eventLoop->runUntilEvents(); + } + if (watchdog.getTimedOut()) { + component->disconnect(); + throw Lua::Exception("Timeout while connecting"); + } + if (disconnectedError) { + throw Lua::Exception(getErrorString(*disconnectedError)); + } } bool SluiftComponent::isConnected() const { - return component->isAvailable(); + return component->isAvailable(); } void SluiftComponent::disconnect() { - component->disconnect(); - while (component->isAvailable()) { - eventLoop->runUntilEvents(); - } + component->disconnect(); + while (component->isAvailable()) { + eventLoop->runUntilEvents(); + } } void SluiftComponent::setSoftwareVersion(const std::string& name, const std::string& version, const std::string& /* os */) { - component->setSoftwareVersion(name, version); + component->setSoftwareVersion(name, version); } boost::optional SluiftComponent::getNextEvent( - int timeout, boost::function condition) { - Watchdog watchdog(timeout, networkFactories->getTimerFactory()); - size_t currentIndex = 0; - while (true) { - // Look for pending events in the queue - while (currentIndex < pendingEvents.size()) { - Event event = pendingEvents[currentIndex]; - if (!condition || condition(event)) { - pendingEvents.erase( - pendingEvents.begin() - + boost::numeric_cast(currentIndex)); - return event; - } - ++currentIndex; - } - - // Wait for new events - while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && component->isAvailable()) { - eventLoop->runUntilEvents(); - } - - // Finish if we're disconnected or timed out - if (watchdog.getTimedOut() || !component->isAvailable()) { - return boost::optional(); - } - } + int timeout, boost::function condition) { + Watchdog watchdog(timeout, networkFactories->getTimerFactory()); + size_t currentIndex = 0; + while (true) { + // Look for pending events in the queue + while (currentIndex < pendingEvents.size()) { + Event event = pendingEvents[currentIndex]; + if (!condition || condition(event)) { + pendingEvents.erase( + pendingEvents.begin() + + boost::numeric_cast(currentIndex)); + return event; + } + ++currentIndex; + } + + // Wait for new events + while (!watchdog.getTimedOut() && currentIndex >= pendingEvents.size() && component->isAvailable()) { + eventLoop->runUntilEvents(); + } + + // Finish if we're disconnected or timed out + if (watchdog.getTimedOut() || !component->isAvailable()) { + return boost::optional(); + } + } } void SluiftComponent::handleIncomingMessage(boost::shared_ptr stanza) { - pendingEvents.push_back(Event(stanza)); + pendingEvents.push_back(Event(stanza)); } void SluiftComponent::handleIncomingPresence(boost::shared_ptr stanza) { - pendingEvents.push_back(Event(stanza)); + pendingEvents.push_back(Event(stanza)); } void SluiftComponent::handleRequestResponse(boost::shared_ptr response, boost::shared_ptr error) { - requestResponse = response; - requestError = error; - requestResponseReceived = true; + requestResponse = response; + requestError = error; + requestResponseReceived = true; } void SluiftComponent::handleError(const boost::optional& error) { - disconnectedError = error; + disconnectedError = error; } Sluift::Response SluiftComponent::doSendRequest(boost::shared_ptr request, int timeout) { - requestResponse.reset(); - requestError.reset(); - requestResponseReceived = false; - request->send(); - - Watchdog watchdog(timeout, networkFactories->getTimerFactory()); - while (!watchdog.getTimedOut() && !requestResponseReceived) { - eventLoop->runUntilEvents(); - } - return Sluift::Response(requestResponse, watchdog.getTimedOut() ? - boost::make_shared(ErrorPayload::RemoteServerTimeout) : requestError); + requestResponse.reset(); + requestError.reset(); + requestResponseReceived = false; + request->send(); + + Watchdog watchdog(timeout, networkFactories->getTimerFactory()); + while (!watchdog.getTimedOut() && !requestResponseReceived) { + eventLoop->runUntilEvents(); + } + return Sluift::Response(requestResponse, watchdog.getTimedOut() ? + boost::make_shared(ErrorPayload::RemoteServerTimeout) : requestError); } diff --git a/Sluift/SluiftComponent.h b/Sluift/SluiftComponent.h index 7a8254c..fd1b97a 100644 --- a/Sluift/SluiftComponent.h +++ b/Sluift/SluiftComponent.h @@ -27,83 +27,83 @@ #include namespace Swift { - struct SluiftGlobals; - class ComponentXMLTracer; - class Component; - class Stanza; - class Payload; - class ErrorPayload; - class JID; - - class SluiftComponent { - public: - struct Event { - enum Type { - MessageType, - PresenceType - }; - - Event(boost::shared_ptr stanza) : type(MessageType), stanza(stanza) {} - Event(boost::shared_ptr stanza) : type(PresenceType), stanza(stanza) {} - - Type type; - - // Message & Presence - boost::shared_ptr stanza; - }; - - SluiftComponent( - const JID& jid, - const std::string& password, - NetworkFactories* networkFactories, - SimpleEventLoop* eventLoop); - ~SluiftComponent(); - - Component* getComponent() { - return component; - } - - void connect(const std::string& host, int port); - void waitConnected(int timeout); - bool isConnected() const; - void setTraceEnabled(bool b); - - template - Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) { - boost::signals::scoped_connection c = request->onResponse.connect( - boost::bind(&SluiftComponent::handleRequestResponse, this, _1, _2)); - return doSendRequest(request, timeout); - } - - template - Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) { - boost::signals::scoped_connection c = request->onResponse.connect( - boost::bind(&SluiftComponent::handleRequestResponse, this, boost::shared_ptr(), _1)); - return doSendRequest(request, timeout); - } - - void disconnect(); - void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os); - boost::optional getNextEvent(int timeout, - boost::function condition = 0); - - private: - Sluift::Response doSendRequest(boost::shared_ptr request, int timeout); - - void handleIncomingMessage(boost::shared_ptr stanza); - void handleIncomingPresence(boost::shared_ptr stanza); - void handleRequestResponse(boost::shared_ptr response, boost::shared_ptr error); - void handleError(const boost::optional& error); - - private: - NetworkFactories* networkFactories; - SimpleEventLoop* eventLoop; - Component* component; - ComponentXMLTracer* tracer; - std::deque pendingEvents; - boost::optional disconnectedError; - bool requestResponseReceived; - boost::shared_ptr requestResponse; - boost::shared_ptr requestError; - }; + struct SluiftGlobals; + class ComponentXMLTracer; + class Component; + class Stanza; + class Payload; + class ErrorPayload; + class JID; + + class SluiftComponent { + public: + struct Event { + enum Type { + MessageType, + PresenceType + }; + + Event(boost::shared_ptr stanza) : type(MessageType), stanza(stanza) {} + Event(boost::shared_ptr stanza) : type(PresenceType), stanza(stanza) {} + + Type type; + + // Message & Presence + boost::shared_ptr stanza; + }; + + SluiftComponent( + const JID& jid, + const std::string& password, + NetworkFactories* networkFactories, + SimpleEventLoop* eventLoop); + ~SluiftComponent(); + + Component* getComponent() { + return component; + } + + void connect(const std::string& host, int port); + void waitConnected(int timeout); + bool isConnected() const; + void setTraceEnabled(bool b); + + template + Sluift::Response sendRequest(REQUEST_TYPE request, int timeout) { + boost::signals::scoped_connection c = request->onResponse.connect( + boost::bind(&SluiftComponent::handleRequestResponse, this, _1, _2)); + return doSendRequest(request, timeout); + } + + template + Sluift::Response sendVoidRequest(REQUEST_TYPE request, int timeout) { + boost::signals::scoped_connection c = request->onResponse.connect( + boost::bind(&SluiftComponent::handleRequestResponse, this, boost::shared_ptr(), _1)); + return doSendRequest(request, timeout); + } + + void disconnect(); + void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os); + boost::optional getNextEvent(int timeout, + boost::function condition = 0); + + private: + Sluift::Response doSendRequest(boost::shared_ptr request, int timeout); + + void handleIncomingMessage(boost::shared_ptr stanza); + void handleIncomingPresence(boost::shared_ptr stanza); + void handleRequestResponse(boost::shared_ptr response, boost::shared_ptr error); + void handleError(const boost::optional& error); + + private: + NetworkFactories* networkFactories; + SimpleEventLoop* eventLoop; + Component* component; + ComponentXMLTracer* tracer; + std::deque pendingEvents; + boost::optional disconnectedError; + bool requestResponseReceived; + boost::shared_ptr requestResponse; + boost::shared_ptr requestError; + }; } diff --git a/Sluift/SluiftGlobals.h b/Sluift/SluiftGlobals.h index a9c5799..14ed6f3 100644 --- a/Sluift/SluiftGlobals.h +++ b/Sluift/SluiftGlobals.h @@ -16,22 +16,22 @@ #include namespace Swift { - struct SluiftGlobals { - SluiftGlobals() : - networkFactories(&eventLoop), - coreLibIndex(-1), - moduleLibIndex(-1), - interruptRequested(0) {} + struct SluiftGlobals { + SluiftGlobals() : + networkFactories(&eventLoop), + coreLibIndex(-1), + moduleLibIndex(-1), + interruptRequested(0) {} - LuaElementConvertors elementConvertor; - SimpleEventLoop eventLoop; - BoostNetworkFactories networkFactories; - PlatformTLSFactories tlsFactories; - int coreLibIndex; - int moduleLibIndex; - sig_atomic_t interruptRequested; + LuaElementConvertors elementConvertor; + SimpleEventLoop eventLoop; + BoostNetworkFactories networkFactories; + PlatformTLSFactories tlsFactories; + int coreLibIndex; + int moduleLibIndex; + sig_atomic_t interruptRequested; #ifdef HAVE_ITUNES - ITunesInterface iTunes; + ITunesInterface iTunes; #endif - }; + }; } diff --git a/Sluift/StandardTerminal.cpp b/Sluift/StandardTerminal.cpp index 8dad2b0..1378346 100644 --- a/Sluift/StandardTerminal.cpp +++ b/Sluift/StandardTerminal.cpp @@ -20,19 +20,19 @@ StandardTerminal::~StandardTerminal() { } void StandardTerminal::printError(const std::string& message) { - std::cout << message << std::endl; + std::cout << message << std::endl; } boost::optional StandardTerminal::readLine(const std::string& prompt) { - std::cout << prompt << std::flush; - std::string input; - if (!std::getline(std::cin, input)) { - if (std::cin.eof()) { - return boost::optional(); - } - throw std::runtime_error("Input error"); - } - return input; + std::cout << prompt << std::flush; + std::string input; + if (!std::getline(std::cin, input)) { + if (std::cin.eof()) { + return boost::optional(); + } + throw std::runtime_error("Input error"); + } + return input; } void StandardTerminal::addToHistory(const std::string&) { diff --git a/Sluift/StandardTerminal.h b/Sluift/StandardTerminal.h index ca71672..2109878 100644 --- a/Sluift/StandardTerminal.h +++ b/Sluift/StandardTerminal.h @@ -11,13 +11,13 @@ #include namespace Swift { - class StandardTerminal : public Terminal { - public: - StandardTerminal(); - virtual ~StandardTerminal(); + class StandardTerminal : public Terminal { + public: + StandardTerminal(); + virtual ~StandardTerminal(); - virtual boost::optional readLine(const std::string& prompt) SWIFTEN_OVERRIDE; - virtual void printError(const std::string& message) SWIFTEN_OVERRIDE; - virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE; - }; + virtual boost::optional readLine(const std::string& prompt) SWIFTEN_OVERRIDE; + virtual void printError(const std::string& message) SWIFTEN_OVERRIDE; + virtual void addToHistory(const std::string& command) SWIFTEN_OVERRIDE; + }; } diff --git a/Sluift/Terminal.h b/Sluift/Terminal.h index 72ca3d8..9d44095 100644 --- a/Sluift/Terminal.h +++ b/Sluift/Terminal.h @@ -11,26 +11,26 @@ #include namespace Swift { - class Completer; + class Completer; - class Terminal { - public: - Terminal(); - virtual ~Terminal(); + class Terminal { + public: + Terminal(); + virtual ~Terminal(); - Completer* getCompleter() const { - return completer; - } + Completer* getCompleter() const { + return completer; + } - void setCompleter(Completer* completer) { - this->completer = completer; - } + void setCompleter(Completer* completer) { + this->completer = completer; + } - virtual boost::optional readLine(const std::string& prompt) = 0; - virtual void addToHistory(const std::string& command) = 0; - virtual void printError(const std::string& message) = 0; + virtual boost::optional readLine(const std::string& prompt) = 0; + virtual void addToHistory(const std::string& command) = 0; + virtual void printError(const std::string& message) = 0; - private: - Completer* completer; - }; + private: + Completer* completer; + }; } diff --git a/Sluift/UnitTest/TokenizeTest.cpp b/Sluift/UnitTest/TokenizeTest.cpp index fb7dbbd..cd617b5 100644 --- a/Sluift/UnitTest/TokenizeTest.cpp +++ b/Sluift/UnitTest/TokenizeTest.cpp @@ -12,52 +12,52 @@ using namespace Swift; class TokenizeTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(TokenizeTest); - CPPUNIT_TEST(testTokenize); - CPPUNIT_TEST(testTokenize); - CPPUNIT_TEST(testTokenize_String); - CPPUNIT_TEST(testTokenize_IncompleteString); - CPPUNIT_TEST(testTokenize_Identifier); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(TokenizeTest); + CPPUNIT_TEST(testTokenize); + CPPUNIT_TEST(testTokenize); + CPPUNIT_TEST(testTokenize_String); + CPPUNIT_TEST(testTokenize_IncompleteString); + CPPUNIT_TEST(testTokenize_Identifier); + CPPUNIT_TEST_SUITE_END(); - public: - void testTokenize() { - std::vector tokens = Lua::tokenize("foo.bar + 1.23 - bam"); + public: + void testTokenize() { + std::vector tokens = Lua::tokenize("foo.bar + 1.23 - bam"); - CPPUNIT_ASSERT_EQUAL(7, static_cast(tokens.size())); - CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]); - CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]); - CPPUNIT_ASSERT_EQUAL(std::string("bar"), tokens[2]); - CPPUNIT_ASSERT_EQUAL(std::string("+"), tokens[3]); - CPPUNIT_ASSERT_EQUAL(std::string("1.23"), tokens[4]); - CPPUNIT_ASSERT_EQUAL(std::string("-"), tokens[5]); - CPPUNIT_ASSERT_EQUAL(std::string("bam"), tokens[6]); - } + CPPUNIT_ASSERT_EQUAL(7, static_cast(tokens.size())); + CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]); + CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), tokens[2]); + CPPUNIT_ASSERT_EQUAL(std::string("+"), tokens[3]); + CPPUNIT_ASSERT_EQUAL(std::string("1.23"), tokens[4]); + CPPUNIT_ASSERT_EQUAL(std::string("-"), tokens[5]); + CPPUNIT_ASSERT_EQUAL(std::string("bam"), tokens[6]); + } - void testTokenize_String() { - std::vector tokens = Lua::tokenize(" foo .. \"1234\\\"bla blo\""); + void testTokenize_String() { + std::vector tokens = Lua::tokenize(" foo .. \"1234\\\"bla blo\""); - CPPUNIT_ASSERT_EQUAL(3, static_cast(tokens.size())); - CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]); - CPPUNIT_ASSERT_EQUAL(std::string(".."), tokens[1]); - CPPUNIT_ASSERT_EQUAL(std::string("\"1234\\\"bla blo\""), tokens[2]); - } + CPPUNIT_ASSERT_EQUAL(3, static_cast(tokens.size())); + CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]); + CPPUNIT_ASSERT_EQUAL(std::string(".."), tokens[1]); + CPPUNIT_ASSERT_EQUAL(std::string("\"1234\\\"bla blo\""), tokens[2]); + } - void testTokenize_IncompleteString() { - std::vector tokens = Lua::tokenize("\"1234"); + void testTokenize_IncompleteString() { + std::vector tokens = Lua::tokenize("\"1234"); - CPPUNIT_ASSERT_EQUAL(1, static_cast(tokens.size())); - CPPUNIT_ASSERT_EQUAL(std::string("\"1234"), tokens[0]); - } + CPPUNIT_ASSERT_EQUAL(1, static_cast(tokens.size())); + CPPUNIT_ASSERT_EQUAL(std::string("\"1234"), tokens[0]); + } - void testTokenize_Identifier() { - std::vector tokens = Lua::tokenize("foo.bar_baz"); + void testTokenize_Identifier() { + std::vector tokens = Lua::tokenize("foo.bar_baz"); - CPPUNIT_ASSERT_EQUAL(3, static_cast(tokens.size())); - CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]); - CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]); - CPPUNIT_ASSERT_EQUAL(std::string("bar_baz"), tokens[2]); - } + CPPUNIT_ASSERT_EQUAL(3, static_cast(tokens.size())); + CPPUNIT_ASSERT_EQUAL(std::string("foo"), tokens[0]); + CPPUNIT_ASSERT_EQUAL(std::string("."), tokens[1]); + CPPUNIT_ASSERT_EQUAL(std::string("bar_baz"), tokens[2]); + } }; diff --git a/Sluift/Watchdog.cpp b/Sluift/Watchdog.cpp index 6494850..a99d63a 100644 --- a/Sluift/Watchdog.cpp +++ b/Sluift/Watchdog.cpp @@ -13,38 +13,38 @@ static const int INTERVAL_MS = 500; using namespace Swift; -Watchdog::Watchdog(int timeout, TimerFactory* timerFactory) : - remainingTime(timeout), - timerFactory(timerFactory), - timedOut(false) { - Sluift::globals.interruptRequested = 0; - - int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS; - - timer = timerFactory->createTimer(nextTimeout); - timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this)); - remainingTime -= nextTimeout; - timer->start(); +Watchdog::Watchdog(int timeout, TimerFactory* timerFactory) : + remainingTime(timeout), + timerFactory(timerFactory), + timedOut(false) { + Sluift::globals.interruptRequested = 0; + + int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS; + + timer = timerFactory->createTimer(nextTimeout); + timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this)); + remainingTime -= nextTimeout; + timer->start(); } Watchdog::~Watchdog() { - if (timer) { - timer->stop(); - } + if (timer) { + timer->stop(); + } } void Watchdog::handleTimerTick() { - if (Sluift::globals.interruptRequested || remainingTime == 0) { - timedOut = true; - } - else { - int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS; - if (nextTimeout != INTERVAL_MS) { - timer->onTick.disconnect(boost::bind(&Watchdog::handleTimerTick, this)); - timer = timerFactory->createTimer(nextTimeout); - timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this)); - } - remainingTime -= nextTimeout; - timer->start(); - } + if (Sluift::globals.interruptRequested || remainingTime == 0) { + timedOut = true; + } + else { + int nextTimeout = remainingTime >= 0 ? std::min(remainingTime, INTERVAL_MS) : INTERVAL_MS; + if (nextTimeout != INTERVAL_MS) { + timer->onTick.disconnect(boost::bind(&Watchdog::handleTimerTick, this)); + timer = timerFactory->createTimer(nextTimeout); + timer->onTick.connect(boost::bind(&Watchdog::handleTimerTick, this)); + } + remainingTime -= nextTimeout; + timer->start(); + } } diff --git a/Sluift/Watchdog.h b/Sluift/Watchdog.h index 8f73128..271c610 100644 --- a/Sluift/Watchdog.h +++ b/Sluift/Watchdog.h @@ -11,22 +11,22 @@ #include namespace Swift { - class Watchdog { - public: - Watchdog(int timeout, TimerFactory* timerFactory); - ~Watchdog(); + class Watchdog { + public: + Watchdog(int timeout, TimerFactory* timerFactory); + ~Watchdog(); - bool getTimedOut() const { - return timedOut; - } + bool getTimedOut() const { + return timedOut; + } - private: - void handleTimerTick(); + private: + void handleTimerTick(); - private: - Timer::ref timer; - int remainingTime; - TimerFactory* timerFactory; - bool timedOut; - }; + private: + Timer::ref timer; + int remainingTime; + TimerFactory* timerFactory; + bool timedOut; + }; } diff --git a/Sluift/client.cpp b/Sluift/client.cpp index 3a8b137..3f7861c 100644 --- a/Sluift/client.cpp +++ b/Sluift/client.cpp @@ -49,731 +49,731 @@ using namespace Swift; namespace lambda = boost::lambda; static inline SluiftClient* getClient(lua_State* L) { - return *Lua::checkUserData(L, 1); + return *Lua::checkUserData(L, 1); } static inline int getGlobalTimeout(lua_State* L) { - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex); - lua_getfield(L, -1, "timeout"); - int result = boost::numeric_cast(lua_tointeger(L, -1)); - lua_pop(L, 2); - return result; + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex); + lua_getfield(L, -1, "timeout"); + int result = boost::numeric_cast(lua_tointeger(L, -1)); + lua_pop(L, 2); + return result; } static void addPayloadsToTable(lua_State* L, const std::vector >& payloads) { - if (!payloads.empty()) { - lua_createtable(L, boost::numeric_cast(payloads.size()), 0); - for (size_t i = 0; i < payloads.size(); ++i) { - Sluift::globals.elementConvertor.convertToLua(L, payloads[i]); - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - Lua::registerGetByTypeIndex(L, -1); - lua_setfield(L, -2, "payloads"); - } + if (!payloads.empty()) { + lua_createtable(L, boost::numeric_cast(payloads.size()), 0); + for (size_t i = 0; i < payloads.size(); ++i) { + Sluift::globals.elementConvertor.convertToLua(L, payloads[i]); + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + Lua::registerGetByTypeIndex(L, -1); + lua_setfield(L, -2, "payloads"); + } } static boost::shared_ptr getPayload(lua_State* L, int index) { - if (lua_type(L, index) == LUA_TTABLE) { - return boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLua(L, index)); - } - else if (lua_type(L, index) == LUA_TSTRING) { - return boost::make_shared(Lua::checkString(L, index)); - } - else { - return boost::shared_ptr(); - } + if (lua_type(L, index) == LUA_TTABLE) { + return boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLua(L, index)); + } + else if (lua_type(L, index) == LUA_TSTRING) { + return boost::make_shared(Lua::checkString(L, index)); + } + else { + return boost::shared_ptr(); + } } static std::vector< boost::shared_ptr > getPayloadsFromTable(lua_State* L, int index) { - index = Lua::absoluteOffset(L, index); - std::vector< boost::shared_ptr > result; - lua_getfield(L, index, "payloads"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { - boost::shared_ptr payload = getPayload(L, -1); - if (payload) { - result.push_back(payload); - } - } - } - lua_pop(L, 1); - return result; + index = Lua::absoluteOffset(L, index); + std::vector< boost::shared_ptr > result; + lua_getfield(L, index, "payloads"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { + boost::shared_ptr payload = getPayload(L, -1); + if (payload) { + result.push_back(payload); + } + } + } + lua_pop(L, 1); + return result; } SLUIFT_LUA_FUNCTION(Client, async_connect) { - SluiftClient* client = getClient(L); - - std::string host = client->getOptions().manualHostname; - int port = client->getOptions().manualPort; - if (lua_istable(L, 2)) { - if (boost::optional hostString = Lua::getStringField(L, 2, "host")) { - host = *hostString; - } - if (boost::optional portInt = Lua::getIntField(L, 2, "port")) { - port = *portInt; - } - } - client->connect(host, port); - return 0; + SluiftClient* client = getClient(L); + + std::string host = client->getOptions().manualHostname; + int port = client->getOptions().manualPort; + if (lua_istable(L, 2)) { + if (boost::optional hostString = Lua::getStringField(L, 2, "host")) { + host = *hostString; + } + if (boost::optional portInt = Lua::getIntField(L, 2, "port")) { + port = *portInt; + } + } + client->connect(host, port); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, set_trace_enabled, - "Enable/disable tracing of the data sent/received.\n\n.", - "self\n" - "enable a boolean specifying whether to enable/disable tracing", - "" + Client, set_trace_enabled, + "Enable/disable tracing of the data sent/received.\n\n.", + "self\n" + "enable a boolean specifying whether to enable/disable tracing", + "" ) { - getClient(L)->setTraceEnabled(lua_toboolean(L, 1)); - return 0; + getClient(L)->setTraceEnabled(lua_toboolean(L, 1)); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, wait_connected, - "Block until the client is connected.\n\nThis is useful after an `async_connect`.", - "self", - "" + Client, wait_connected, + "Block until the client is connected.\n\nThis is useful after an `async_connect`.", + "self", + "" ) { - getClient(L)->waitConnected(getGlobalTimeout(L)); - return 0; + getClient(L)->waitConnected(getGlobalTimeout(L)); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, is_connected, - "Checks whether this client is still connected.\n\nReturns a boolean.", - "self\n", - "" + Client, is_connected, + "Checks whether this client is still connected.\n\nReturns a boolean.", + "self\n", + "" ) { - lua_pushboolean(L, getClient(L)->isConnected()); - return 1; + lua_pushboolean(L, getClient(L)->isConnected()); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, disconnect, - "Disconnect from the server", - "self\n", - "" + Client, disconnect, + "Disconnect from the server", + "self\n", + "" ) { - Sluift::globals.eventLoop.runOnce(); - getClient(L)->disconnect(); - return 0; + Sluift::globals.eventLoop.runOnce(); + getClient(L)->disconnect(); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, set_version, + Client, set_version, - "Sets the published version of this client.", + "Sets the published version of this client.", - "self", + "self", - "name the name of the client software\n" - "version the version identifier of this client\n" - "os the OS this client is running on\n" + "name the name of the client software\n" + "version the version identifier of this client\n" + "os the OS this client is running on\n" ) { - Sluift::globals.eventLoop.runOnce(); - SluiftClient* client = getClient(L); - if (boost::shared_ptr version = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) { - client->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS()); - } - return 0; + Sluift::globals.eventLoop.runOnce(); + SluiftClient* client = getClient(L); + if (boost::shared_ptr version = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) { + client->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS()); + } + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, get_contacts, - "Returns a table of all the contacts in the contact list.", - "self\n", - "" + Client, get_contacts, + "Returns a table of all the contacts in the contact list.", + "self\n", + "" ) { - Sluift::globals.eventLoop.runOnce(); - - SluiftClient* client = getClient(L); - Lua::Table contactsTable; - foreach(const XMPPRosterItem& item, client->getRoster(getGlobalTimeout(L))) { - std::string subscription; - switch(item.getSubscription()) { - case RosterItemPayload::None: subscription = "none"; break; - case RosterItemPayload::To: subscription = "to"; break; - case RosterItemPayload::From: subscription = "from"; break; - case RosterItemPayload::Both: subscription = "both"; break; - case RosterItemPayload::Remove: subscription = "remove"; break; - } - Lua::Table itemTable = boost::assign::map_list_of - ("jid", boost::make_shared(item.getJID().toString())) - ("name", boost::make_shared(item.getName())) - ("subscription", boost::make_shared(subscription)) - ("groups", boost::make_shared(std::vector(item.getGroups().begin(), item.getGroups().end()))); - contactsTable[item.getJID().toString()] = boost::make_shared(itemTable); - } - pushValue(L, contactsTable); - Lua::registerTableToString(L, -1); - return 1; + Sluift::globals.eventLoop.runOnce(); + + SluiftClient* client = getClient(L); + Lua::Table contactsTable; + foreach(const XMPPRosterItem& item, client->getRoster(getGlobalTimeout(L))) { + std::string subscription; + switch(item.getSubscription()) { + case RosterItemPayload::None: subscription = "none"; break; + case RosterItemPayload::To: subscription = "to"; break; + case RosterItemPayload::From: subscription = "from"; break; + case RosterItemPayload::Both: subscription = "both"; break; + case RosterItemPayload::Remove: subscription = "remove"; break; + } + Lua::Table itemTable = boost::assign::map_list_of + ("jid", boost::make_shared(item.getJID().toString())) + ("name", boost::make_shared(item.getName())) + ("subscription", boost::make_shared(subscription)) + ("groups", boost::make_shared(std::vector(item.getGroups().begin(), item.getGroups().end()))); + contactsTable[item.getJID().toString()] = boost::make_shared(itemTable); + } + pushValue(L, contactsTable); + Lua::registerTableToString(L, -1); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, send_message, - "Send a message.", - "self\n" - "to the JID to send the message to\n" - "body the body of the message. Can alternatively be specified using the `body` option\n", - - "to the JID to send the message to\n" - "body the body of the message\n" - "subject the subject of the MUC room to set\n" - "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n" - "payloads payloads to add to the message\n" + Client, send_message, + "Send a message.", + "self\n" + "to the JID to send the message to\n" + "body the body of the message. Can alternatively be specified using the `body` option\n", + + "to the JID to send the message to\n" + "body the body of the message\n" + "subject the subject of the MUC room to set\n" + "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n" + "payloads payloads to add to the message\n" ) { - Sluift::globals.eventLoop.runOnce(); - JID to; - boost::optional body; - boost::optional subject; - std::vector > payloads; - int index = 2; - Message::Type type = Message::Chat; - if (lua_isstring(L, index)) { - to = std::string(lua_tostring(L, index)); - ++index; - if (lua_isstring(L, index)) { - body = lua_tostring(L, index); - ++index; - } - } - if (lua_istable(L, index)) { - if (boost::optional value = Lua::getStringField(L, index, "to")) { - to = *value; - } - - if (boost::optional value = Lua::getStringField(L, index, "body")) { - body = value; - } - - if (boost::optional value = Lua::getStringField(L, index, "type")) { - type = MessageConvertor::convertMessageTypeFromString(*value); - } - - if (boost::optional value = Lua::getStringField(L, index, "subject")) { - subject = value; - } - - payloads = getPayloadsFromTable(L, index); - } - - if (!to.isValid()) { - throw Lua::Exception("Missing 'to'"); - } - if ((!body || body->empty()) && !subject && payloads.empty()) { - throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'"); - } - Message::ref message = boost::make_shared(); - message->setTo(to); - if (body && !body->empty()) { - message->setBody(*body); - } - if (subject) { - message->setSubject(*subject); - } - message->addPayloads(payloads.begin(), payloads.end()); - message->setType(type); - getClient(L)->getClient()->sendMessage(message); - return 0; + Sluift::globals.eventLoop.runOnce(); + JID to; + boost::optional body; + boost::optional subject; + std::vector > payloads; + int index = 2; + Message::Type type = Message::Chat; + if (lua_isstring(L, index)) { + to = std::string(lua_tostring(L, index)); + ++index; + if (lua_isstring(L, index)) { + body = lua_tostring(L, index); + ++index; + } + } + if (lua_istable(L, index)) { + if (boost::optional value = Lua::getStringField(L, index, "to")) { + to = *value; + } + + if (boost::optional value = Lua::getStringField(L, index, "body")) { + body = value; + } + + if (boost::optional value = Lua::getStringField(L, index, "type")) { + type = MessageConvertor::convertMessageTypeFromString(*value); + } + + if (boost::optional value = Lua::getStringField(L, index, "subject")) { + subject = value; + } + + payloads = getPayloadsFromTable(L, index); + } + + if (!to.isValid()) { + throw Lua::Exception("Missing 'to'"); + } + if ((!body || body->empty()) && !subject && payloads.empty()) { + throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'"); + } + Message::ref message = boost::make_shared(); + message->setTo(to); + if (body && !body->empty()) { + message->setBody(*body); + } + if (subject) { + message->setSubject(*subject); + } + message->addPayloads(payloads.begin(), payloads.end()); + message->setType(type); + getClient(L)->getClient()->sendMessage(message); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, send_presence, - "Send presence.", - - "self\n" - "body the text of the presence. Can alternatively be specified using the `status` option\n", - - "to the JID to send the message to\n" - "status the text of the presence\n" - "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n" - "priority the priority of the presence\n" - "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n" - "payloads payloads to add to the presence\n" + Client, send_presence, + "Send presence.", + + "self\n" + "body the text of the presence. Can alternatively be specified using the `status` option\n", + + "to the JID to send the message to\n" + "status the text of the presence\n" + "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n" + "priority the priority of the presence\n" + "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n" + "payloads payloads to add to the presence\n" ) { - Sluift::globals.eventLoop.runOnce(); - boost::shared_ptr presence = boost::make_shared(); - - int index = 2; - if (lua_isstring(L, index)) { - presence->setStatus(lua_tostring(L, index)); - ++index; - } - if (lua_istable(L, index)) { - if (boost::optional value = Lua::getStringField(L, index, "to")) { - presence->setTo(*value); - } - if (boost::optional value = Lua::getStringField(L, index, "status")) { - presence->setStatus(*value); - } - if (boost::optional value = Lua::getIntField(L, index, "priority")) { - presence->setPriority(*value); - } - if (boost::optional value = Lua::getStringField(L, index, "type")) { - presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value)); - } - if (boost::optional value = Lua::getStringField(L, index, "show")) { - presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value)); - } - std::vector< boost::shared_ptr > payloads = getPayloadsFromTable(L, index); - presence->addPayloads(payloads.begin(), payloads.end()); - } - - getClient(L)->getClient()->getPresenceSender()->sendPresence(presence); - lua_pushvalue(L, 1); - return 0; + Sluift::globals.eventLoop.runOnce(); + boost::shared_ptr presence = boost::make_shared(); + + int index = 2; + if (lua_isstring(L, index)) { + presence->setStatus(lua_tostring(L, index)); + ++index; + } + if (lua_istable(L, index)) { + if (boost::optional value = Lua::getStringField(L, index, "to")) { + presence->setTo(*value); + } + if (boost::optional value = Lua::getStringField(L, index, "status")) { + presence->setStatus(*value); + } + if (boost::optional value = Lua::getIntField(L, index, "priority")) { + presence->setPriority(*value); + } + if (boost::optional value = Lua::getStringField(L, index, "type")) { + presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value)); + } + if (boost::optional value = Lua::getStringField(L, index, "show")) { + presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value)); + } + std::vector< boost::shared_ptr > payloads = getPayloadsFromTable(L, index); + presence->addPayloads(payloads.begin(), payloads.end()); + } + + getClient(L)->getClient()->getPresenceSender()->sendPresence(presence); + lua_pushvalue(L, 1); + return 0; } static int sendQuery(lua_State* L, IQ::Type type) { - SluiftClient* client = getClient(L); + SluiftClient* client = getClient(L); - JID to; - if (boost::optional toString = Lua::getStringField(L, 2, "to")) { - to = JID(*toString); - } + JID to; + if (boost::optional toString = Lua::getStringField(L, 2, "to")) { + to = JID(*toString); + } - int timeout = getGlobalTimeout(L); - if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { - timeout = *timeoutInt; - } + int timeout = getGlobalTimeout(L); + if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { + timeout = *timeoutInt; + } - boost::shared_ptr payload; - lua_getfield(L, 2, "query"); - payload = getPayload(L, -1); - lua_pop(L, 1); + boost::shared_ptr payload; + lua_getfield(L, 2, "query"); + payload = getPayload(L, -1); + lua_pop(L, 1); - return client->sendRequest( - boost::make_shared< GenericRequest >(type, to, payload, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L); + return client->sendRequest( + boost::make_shared< GenericRequest >(type, to, payload, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L); } #define DISPATCH_PUBSUB_PAYLOAD(payloadType, container, response) \ - else if (boost::shared_ptr p = boost::dynamic_pointer_cast(payload)) { \ - return client->sendPubSubRequest(type, to, p, timeout).convertToLuaResult(L); \ - } + else if (boost::shared_ptr p = boost::dynamic_pointer_cast(payload)) { \ + return client->sendPubSubRequest(type, to, p, timeout).convertToLuaResult(L); \ + } SLUIFT_LUA_FUNCTION(Client, query_pubsub) { - SluiftClient* client = getClient(L); + SluiftClient* client = getClient(L); - JID to; - if (boost::optional toString = Lua::getStringField(L, 2, "to")) { - to = JID(*toString); - } + JID to; + if (boost::optional toString = Lua::getStringField(L, 2, "to")) { + to = JID(*toString); + } - int timeout = getGlobalTimeout(L); - if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { - timeout = *timeoutInt; - } + int timeout = getGlobalTimeout(L); + if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { + timeout = *timeoutInt; + } - IQ::Type type; - if (boost::optional queryType = Lua::getStringField(L, 2, "type")) { - type = IQConvertor::convertIQTypeFromString(*queryType); - } - else { - throw Lua::Exception("Missing query type"); - } + IQ::Type type; + if (boost::optional queryType = Lua::getStringField(L, 2, "type")) { + type = IQConvertor::convertIQTypeFromString(*queryType); + } + else { + throw Lua::Exception("Missing query type"); + } - lua_getfield(L, 2, "query"); - if (!lua_istable(L, -1)) { - throw Lua::Exception("Missing/incorrect query"); - } - boost::shared_ptr payload = getPayload(L, -1); + lua_getfield(L, 2, "query"); + if (!lua_istable(L, -1)) { + throw Lua::Exception("Missing/incorrect query"); + } + boost::shared_ptr payload = getPayload(L, -1); - if (false) { } - SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(DISPATCH_PUBSUB_PAYLOAD) - else { - throw Lua::Exception("Incorrect PubSub payload"); - } + if (false) { } + SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE(DISPATCH_PUBSUB_PAYLOAD) + else { + throw Lua::Exception("Incorrect PubSub payload"); + } } SLUIFT_LUA_FUNCTION(Client, get) { - return sendQuery(L, IQ::Get); + return sendQuery(L, IQ::Get); } SLUIFT_LUA_FUNCTION(Client, set) { - return sendQuery(L, IQ::Set); + return sendQuery(L, IQ::Set); } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, send, - "Sends a raw string", + Client, send, + "Sends a raw string", - "self\n" - "data the string to send\n", + "self\n" + "data the string to send\n", - "" + "" ) { - Sluift::globals.eventLoop.runOnce(); + Sluift::globals.eventLoop.runOnce(); - getClient(L)->getClient()->sendData(std::string(Lua::checkString(L, 2))); - lua_pushvalue(L, 1); - return 0; + getClient(L)->getClient()->sendData(std::string(Lua::checkString(L, 2))); + lua_pushvalue(L, 1); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, set_options, + Client, set_options, - "Sets the connection options of this client.", + "Sets the connection options of this client.", - "self", + "self", - "host The host to connect to. When omitted, is determined from resolving the JID domain.\n" - "port The port to connect to. When omitted, is determined from resolving the JID domain.\n" - "ack Request acknowledgements\n" - "compress Use stream compression when available\n" - "tls Use TLS when available\n" - "bosh_url Connect using the specified BOSH URL\n" - "allow_plain_without_tls Allow PLAIN authentication without a TLS encrypted connection\n" + "host The host to connect to. When omitted, is determined from resolving the JID domain.\n" + "port The port to connect to. When omitted, is determined from resolving the JID domain.\n" + "ack Request acknowledgements\n" + "compress Use stream compression when available\n" + "tls Use TLS when available\n" + "bosh_url Connect using the specified BOSH URL\n" + "allow_plain_without_tls Allow PLAIN authentication without a TLS encrypted connection\n" ) { - SluiftClient* client = getClient(L); - Lua::checkType(L, 2, LUA_TTABLE); - lua_getfield(L, 2, "host"); - if (!lua_isnil(L, -1)) { - client->getOptions().manualHostname = lua_tostring(L, -1); - } - lua_getfield(L, 2, "port"); - if (!lua_isnil(L, -1)) { - client->getOptions().manualPort = boost::numeric_cast(lua_tointeger(L, -1)); - } - lua_getfield(L, 2, "ack"); - if (!lua_isnil(L, -1)) { - client->getOptions().useAcks = lua_toboolean(L, -1); - } - lua_getfield(L, 2, "compress"); - if (!lua_isnil(L, -1)) { - client->getOptions().useStreamCompression = lua_toboolean(L, -1); - } - lua_getfield(L, 2, "tls"); - if (!lua_isnil(L, -1)) { - bool useTLS = lua_toboolean(L, -1); - client->getOptions().useTLS = (useTLS ? ClientOptions::UseTLSWhenAvailable : ClientOptions::NeverUseTLS); - } - lua_getfield(L, 2, "bosh_url"); - if (!lua_isnil(L, -1)) { - client->getOptions().boshURL = URL::fromString(lua_tostring(L, -1)); - } - lua_getfield(L, 2, "allow_plain_without_tls"); - if (!lua_isnil(L, -1)) { - client->getOptions().allowPLAINWithoutTLS = lua_toboolean(L, -1); - } - lua_pushvalue(L, 1); - return 0; + SluiftClient* client = getClient(L); + Lua::checkType(L, 2, LUA_TTABLE); + lua_getfield(L, 2, "host"); + if (!lua_isnil(L, -1)) { + client->getOptions().manualHostname = lua_tostring(L, -1); + } + lua_getfield(L, 2, "port"); + if (!lua_isnil(L, -1)) { + client->getOptions().manualPort = boost::numeric_cast(lua_tointeger(L, -1)); + } + lua_getfield(L, 2, "ack"); + if (!lua_isnil(L, -1)) { + client->getOptions().useAcks = lua_toboolean(L, -1); + } + lua_getfield(L, 2, "compress"); + if (!lua_isnil(L, -1)) { + client->getOptions().useStreamCompression = lua_toboolean(L, -1); + } + lua_getfield(L, 2, "tls"); + if (!lua_isnil(L, -1)) { + bool useTLS = lua_toboolean(L, -1); + client->getOptions().useTLS = (useTLS ? ClientOptions::UseTLSWhenAvailable : ClientOptions::NeverUseTLS); + } + lua_getfield(L, 2, "bosh_url"); + if (!lua_isnil(L, -1)) { + client->getOptions().boshURL = URL::fromString(lua_tostring(L, -1)); + } + lua_getfield(L, 2, "allow_plain_without_tls"); + if (!lua_isnil(L, -1)) { + client->getOptions().allowPLAINWithoutTLS = lua_toboolean(L, -1); + } + lua_pushvalue(L, 1); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, get_options, - "Returns a table with all the connection options of this client.", - "self\n", - "" + Client, get_options, + "Returns a table with all the connection options of this client.", + "self\n", + "" ) { - Sluift::globals.eventLoop.runOnce(); - - SluiftClient* client = getClient(L); - Lua::Table optionsTable = boost::assign::map_list_of - ("host", boost::make_shared(client->getOptions().manualHostname)) - ("port", boost::make_shared(client->getOptions().manualPort)) - ("ack", boost::make_shared(client->getOptions().useAcks)) - ("compress", boost::make_shared(client->getOptions().useStreamCompression)) - ("tls", boost::make_shared(client->getOptions().useTLS == ClientOptions::NeverUseTLS ? false : true)) - ("bosh_url", boost::make_shared(client->getOptions().boshURL.toString())) - ("allow_plain_without_tls", boost::make_shared(client->getOptions().allowPLAINWithoutTLS)); - pushValue(L, optionsTable); - Lua::registerTableToString(L, -1); - return 1; + Sluift::globals.eventLoop.runOnce(); + + SluiftClient* client = getClient(L); + Lua::Table optionsTable = boost::assign::map_list_of + ("host", boost::make_shared(client->getOptions().manualHostname)) + ("port", boost::make_shared(client->getOptions().manualPort)) + ("ack", boost::make_shared(client->getOptions().useAcks)) + ("compress", boost::make_shared(client->getOptions().useStreamCompression)) + ("tls", boost::make_shared(client->getOptions().useTLS == ClientOptions::NeverUseTLS ? false : true)) + ("bosh_url", boost::make_shared(client->getOptions().boshURL.toString())) + ("allow_plain_without_tls", boost::make_shared(client->getOptions().allowPLAINWithoutTLS)); + pushValue(L, optionsTable); + Lua::registerTableToString(L, -1); + return 1; } static void pushEvent(lua_State* L, const SluiftClient::Event& event) { - switch (event.type) { - case SluiftClient::Event::MessageType: { - Message::ref message = boost::dynamic_pointer_cast(event.stanza); - Lua::Table result = boost::assign::map_list_of - ("type", boost::make_shared(std::string("message"))) - ("from", boost::make_shared(message->getFrom().toString())) - ("body", boost::make_shared(message->getBody().get_value_or(""))) - ("message_type", boost::make_shared(MessageConvertor::convertMessageTypeToString(message->getType()))); - Lua::pushValue(L, result); - addPayloadsToTable(L, message->getPayloads()); - Lua::registerTableToString(L, -1); - break; - } - case SluiftClient::Event::PresenceType: { - Presence::ref presence = boost::dynamic_pointer_cast(event.stanza); - Lua::Table result = boost::assign::map_list_of - ("type", boost::make_shared(std::string("presence"))) - ("from", boost::make_shared(presence->getFrom().toString())) - ("status", boost::make_shared(presence->getStatus())) - ("presence_type", boost::make_shared(PresenceConvertor::convertPresenceTypeToString(presence->getType()))); - Lua::pushValue(L, result); - addPayloadsToTable(L, presence->getPayloads()); - Lua::registerTableToString(L, -1); - break; - } - case SluiftClient::Event::PubSubEventType: { - Sluift::globals.elementConvertor.convertToLua(L, event.pubsubEvent); - lua_pushstring(L, "pubsub"); - lua_setfield(L, -2, "type"); - lua_pushstring(L, event.from.toString().c_str()); - lua_setfield(L, -2, "from"); - - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "process_pubsub_event"); - lua_pushvalue(L, -3); - lua_call(L, 1, 0); - lua_pop(L, 1); - } - } + switch (event.type) { + case SluiftClient::Event::MessageType: { + Message::ref message = boost::dynamic_pointer_cast(event.stanza); + Lua::Table result = boost::assign::map_list_of + ("type", boost::make_shared(std::string("message"))) + ("from", boost::make_shared(message->getFrom().toString())) + ("body", boost::make_shared(message->getBody().get_value_or(""))) + ("message_type", boost::make_shared(MessageConvertor::convertMessageTypeToString(message->getType()))); + Lua::pushValue(L, result); + addPayloadsToTable(L, message->getPayloads()); + Lua::registerTableToString(L, -1); + break; + } + case SluiftClient::Event::PresenceType: { + Presence::ref presence = boost::dynamic_pointer_cast(event.stanza); + Lua::Table result = boost::assign::map_list_of + ("type", boost::make_shared(std::string("presence"))) + ("from", boost::make_shared(presence->getFrom().toString())) + ("status", boost::make_shared(presence->getStatus())) + ("presence_type", boost::make_shared(PresenceConvertor::convertPresenceTypeToString(presence->getType()))); + Lua::pushValue(L, result); + addPayloadsToTable(L, presence->getPayloads()); + Lua::registerTableToString(L, -1); + break; + } + case SluiftClient::Event::PubSubEventType: { + Sluift::globals.elementConvertor.convertToLua(L, event.pubsubEvent); + lua_pushstring(L, "pubsub"); + lua_setfield(L, -2, "type"); + lua_pushstring(L, event.from.toString().c_str()); + lua_setfield(L, -2, "from"); + + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "process_pubsub_event"); + lua_pushvalue(L, -3); + lua_call(L, 1, 0); + lua_pop(L, 1); + } + } } struct CallUnaryLuaPredicateOnEvent { - CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) { - } - - bool operator()(const SluiftClient::Event& event) { - lua_pushvalue(L, index); - pushEvent(L, event); - if (lua_pcall(L, 1, 1, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - bool result = lua_toboolean(L, -1); - lua_pop(L, 1); - return result; - } - - lua_State* L; - int index; + CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) { + } + + bool operator()(const SluiftClient::Event& event) { + lua_pushvalue(L, index); + pushEvent(L, event); + if (lua_pcall(L, 1, 1, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + bool result = lua_toboolean(L, -1); + lua_pop(L, 1); + return result; + } + + lua_State* L; + int index; }; SLUIFT_LUA_FUNCTION(Client, get_next_event) { - Sluift::globals.eventLoop.runOnce(); - SluiftClient* client = getClient(L); - - int timeout = getGlobalTimeout(L); - boost::optional type; - int condition = 0; - if (lua_istable(L, 2)) { - if (boost::optional typeString = Lua::getStringField(L, 2, "type")) { - if (*typeString == "message") { - type = SluiftClient::Event::MessageType; - } - else if (*typeString == "presence") { - type = SluiftClient::Event::PresenceType; - } - else if (*typeString == "pubsub") { - type = SluiftClient::Event::PubSubEventType; - } - } - if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { - timeout = *timeoutInt; - } - lua_getfield(L, 2, "if"); - if (lua_isfunction(L, -1)) { - condition = Lua::absoluteOffset(L, -1); - } - } - - boost::optional event; - if (condition) { - event = client->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition)); - } - else if (type) { - event = client->getNextEvent( - timeout, lambda::bind(&SluiftClient::Event::type, lambda::_1) == *type); - } - else { - event = client->getNextEvent(timeout); - } - - if (event) { - pushEvent(L, *event); - } - else { - lua_pushnil(L); - } - return 1; + Sluift::globals.eventLoop.runOnce(); + SluiftClient* client = getClient(L); + + int timeout = getGlobalTimeout(L); + boost::optional type; + int condition = 0; + if (lua_istable(L, 2)) { + if (boost::optional typeString = Lua::getStringField(L, 2, "type")) { + if (*typeString == "message") { + type = SluiftClient::Event::MessageType; + } + else if (*typeString == "presence") { + type = SluiftClient::Event::PresenceType; + } + else if (*typeString == "pubsub") { + type = SluiftClient::Event::PubSubEventType; + } + } + if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { + timeout = *timeoutInt; + } + lua_getfield(L, 2, "if"); + if (lua_isfunction(L, -1)) { + condition = Lua::absoluteOffset(L, -1); + } + } + + boost::optional event; + if (condition) { + event = client->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition)); + } + else if (type) { + event = client->getNextEvent( + timeout, lambda::bind(&SluiftClient::Event::type, lambda::_1) == *type); + } + else { + event = client->getNextEvent(timeout); + } + + if (event) { + pushEvent(L, *event); + } + else { + lua_pushnil(L); + } + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, add_contact, - "Add a contact to the contact list.", - "self\n", - "jid The JID of the contact to add\n" - "name The name to use in the contact list\n" - "groups An array of group names to add the contact to\n") { - Sluift::globals.eventLoop.runOnce(); - SluiftClient* client = getClient(L); - RosterItemPayload item; - int timeout = getGlobalTimeout(L); - - if (lua_type(L, 2) == LUA_TTABLE) { - lua_getfield(L, 2, "jid"); - const char* rawJID = lua_tostring(L, -1); - if (rawJID) { - item.setJID(std::string(rawJID)); - } - lua_getfield(L, 2, "name"); - const char* rawName = lua_tostring(L, -1); - if (rawName) { - item.setName(rawName); - } - lua_getfield(L, 2, "groups"); - if (!lua_isnil(L, -1)) { - if (lua_type(L, -1) == LUA_TTABLE) { - for (size_t i = 1; i <= lua_objlen(L, -1); ++i) { - lua_rawgeti(L, -1, boost::numeric_cast(i)); - const char* rawGroup = lua_tostring(L, -1); - if (rawGroup) { - item.addGroup(rawGroup); - } - lua_pop(L, 1); - } - } - else { - throw Lua::Exception("Groups should be a table"); - } - } - } - else { - item.setJID(Lua::checkString(L, 2)); - } - - client->getRoster(timeout); - if (!client->getClient()->getRoster()->containsJID(item.getJID())) { - RosterPayload::ref roster = boost::make_shared(); - roster->addItem(item); - - Sluift::Response response = client->sendVoidRequest( - SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout); - if (response.error) { - return response.convertToLuaResult(L); - } - } - client->getClient()->getSubscriptionManager()->requestSubscription(item.getJID()); - lua_pushboolean(L, true); - return 1; + Client, add_contact, + "Add a contact to the contact list.", + "self\n", + "jid The JID of the contact to add\n" + "name The name to use in the contact list\n" + "groups An array of group names to add the contact to\n") { + Sluift::globals.eventLoop.runOnce(); + SluiftClient* client = getClient(L); + RosterItemPayload item; + int timeout = getGlobalTimeout(L); + + if (lua_type(L, 2) == LUA_TTABLE) { + lua_getfield(L, 2, "jid"); + const char* rawJID = lua_tostring(L, -1); + if (rawJID) { + item.setJID(std::string(rawJID)); + } + lua_getfield(L, 2, "name"); + const char* rawName = lua_tostring(L, -1); + if (rawName) { + item.setName(rawName); + } + lua_getfield(L, 2, "groups"); + if (!lua_isnil(L, -1)) { + if (lua_type(L, -1) == LUA_TTABLE) { + for (size_t i = 1; i <= lua_objlen(L, -1); ++i) { + lua_rawgeti(L, -1, boost::numeric_cast(i)); + const char* rawGroup = lua_tostring(L, -1); + if (rawGroup) { + item.addGroup(rawGroup); + } + lua_pop(L, 1); + } + } + else { + throw Lua::Exception("Groups should be a table"); + } + } + } + else { + item.setJID(Lua::checkString(L, 2)); + } + + client->getRoster(timeout); + if (!client->getClient()->getRoster()->containsJID(item.getJID())) { + RosterPayload::ref roster = boost::make_shared(); + roster->addItem(item); + + Sluift::Response response = client->sendVoidRequest( + SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout); + if (response.error) { + return response.convertToLuaResult(L); + } + } + client->getClient()->getSubscriptionManager()->requestSubscription(item.getJID()); + lua_pushboolean(L, true); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, remove_contact, - "Remove a contact from the contact list.", - "self\n" - "jid the JID of the contact to remove\n", - "" + Client, remove_contact, + "Remove a contact from the contact list.", + "self\n" + "jid the JID of the contact to remove\n", + "" ) { - Sluift::globals.eventLoop.runOnce(); - SluiftClient* client = getClient(L); - JID jid(Lua::checkString(L, 2)); - int timeout = getGlobalTimeout(L); + Sluift::globals.eventLoop.runOnce(); + SluiftClient* client = getClient(L); + JID jid(Lua::checkString(L, 2)); + int timeout = getGlobalTimeout(L); - RosterPayload::ref roster = boost::make_shared(); - roster->addItem(RosterItemPayload(JID(Lua::checkString(L, 2)), "", RosterItemPayload::Remove)); - - return client->sendVoidRequest( - SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L); + RosterPayload::ref roster = boost::make_shared(); + roster->addItem(RosterItemPayload(JID(Lua::checkString(L, 2)), "", RosterItemPayload::Remove)); + + return client->sendVoidRequest( + SetRosterRequest::create(roster, client->getClient()->getIQRouter()), timeout).convertToLuaResult(L); } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, confirm_subscription, - "Confirm subscription of a contact.", - "self\n" - "jid the JID of the contact to confirm the subscription of\n", - "" + Client, confirm_subscription, + "Confirm subscription of a contact.", + "self\n" + "jid the JID of the contact to confirm the subscription of\n", + "" ) { - Sluift::globals.eventLoop.runOnce(); - SluiftClient* client = getClient(L); - JID jid(Lua::checkString(L, 2)); - client->getClient()->getSubscriptionManager()->confirmSubscription(jid); - return 0; + Sluift::globals.eventLoop.runOnce(); + SluiftClient* client = getClient(L); + JID jid(Lua::checkString(L, 2)); + client->getClient()->getSubscriptionManager()->confirmSubscription(jid); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, cancel_subscription, - "Cancel the subscription of a contact.", - "self\n" - "jid the JID of the contact to cancel the subscription of\n", - "" + Client, cancel_subscription, + "Cancel the subscription of a contact.", + "self\n" + "jid the JID of the contact to cancel the subscription of\n", + "" ) { - Sluift::globals.eventLoop.runOnce(); - SluiftClient* client = getClient(L); - JID jid(Lua::checkString(L, 2)); - client->getClient()->getSubscriptionManager()->cancelSubscription(jid); - return 0; + Sluift::globals.eventLoop.runOnce(); + SluiftClient* client = getClient(L); + JID jid(Lua::checkString(L, 2)); + client->getClient()->getSubscriptionManager()->cancelSubscription(jid); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, set_disco_info, - "Sets the service discovery information for this client", - "self\n" - "disco_info A structured representation of the service discovery information\n", - "" + Client, set_disco_info, + "Sets the service discovery information for this client", + "self\n" + "disco_info A structured representation of the service discovery information\n", + "" ) { - SluiftClient* client = getClient(L); - if (!lua_istable(L, 2)) { - throw Lua::Exception("Missing disco info"); - } - if (boost::shared_ptr discoInfo = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "disco_info"))) { - client->getClient()->getDiscoManager()->setDiscoInfo(*discoInfo); - } - else { - throw Lua::Exception("Illegal disco info"); - } - return 0; + SluiftClient* client = getClient(L); + if (!lua_istable(L, 2)) { + throw Lua::Exception("Missing disco info"); + } + if (boost::shared_ptr discoInfo = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "disco_info"))) { + client->getClient()->getDiscoManager()->setDiscoInfo(*discoInfo); + } + else { + throw Lua::Exception("Illegal disco info"); + } + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, set_caps_node, - "Sets the caps node of this client", - "self\n" - "node The caps node (e.g. 'http://swift.im/sluift')\n", - "" + Client, set_caps_node, + "Sets the caps node of this client", + "self\n" + "node The caps node (e.g. 'http://swift.im/sluift')\n", + "" ) { - SluiftClient* client = getClient(L); - std::string node(Lua::checkString(L, 2)); - client->getClient()->getDiscoManager()->setCapsNode(Lua::checkString(L, 2)); - return 0; + SluiftClient* client = getClient(L); + std::string node(Lua::checkString(L, 2)); + client->getClient()->getDiscoManager()->setCapsNode(Lua::checkString(L, 2)); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, set_certificate, - "Sets a client certificate to use for strong authentication with the server.", - "self\n" - "file PKCS #12 file\n" - "pwd passphrase for the certificate private key\n", - "" + Client, set_certificate, + "Sets a client certificate to use for strong authentication with the server.", + "self\n" + "file PKCS #12 file\n" + "pwd passphrase for the certificate private key\n", + "" ) { - std::string file; - std::string pwd; - int index = 2; - if (!lua_isnoneornil(L, index)) { - file = Lua::checkString(L, index); - ++index; - if (!lua_isnoneornil(L, index)) { - pwd = Lua::checkString(L, index); - ++index; - } - } - if (file.empty()) { - getClient(L)->getClient()->setCertificate(CertificateWithKey::ref()); - } else { - getClient(L)->getClient()->setCertificate(boost::make_shared(file, createSafeByteArray(pwd))); - } - return 0; + std::string file; + std::string pwd; + int index = 2; + if (!lua_isnoneornil(L, index)) { + file = Lua::checkString(L, index); + ++index; + if (!lua_isnoneornil(L, index)) { + pwd = Lua::checkString(L, index); + ++index; + } + } + if (file.empty()) { + getClient(L)->getClient()->setCertificate(CertificateWithKey::ref()); + } else { + getClient(L)->getClient()->setCertificate(boost::make_shared(file, createSafeByteArray(pwd))); + } + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Client, jid, - "Returns the JID of this client", - "self\n", - "" + Client, jid, + "Returns the JID of this client", + "self\n", + "" ) { - SluiftClient* client = getClient(L); - lua_pushstring(L, client->getClient()->getJID().toString().c_str()); - return 1; + SluiftClient* client = getClient(L); + lua_pushstring(L, client->getClient()->getJID().toString().c_str()); + return 1; } SLUIFT_LUA_FUNCTION(Client, __gc) { - SluiftClient* client = getClient(L); - delete client; - return 0; + SluiftClient* client = getClient(L); + delete client; + return 0; } diff --git a/Sluift/component.cpp b/Sluift/component.cpp index af0b66e..f8184c7 100644 --- a/Sluift/component.cpp +++ b/Sluift/component.cpp @@ -47,423 +47,423 @@ using namespace Swift; namespace lambda = boost::lambda; static inline SluiftComponent* getComponent(lua_State* L) { - return *Lua::checkUserData(L, 1); + return *Lua::checkUserData(L, 1); } static inline int getGlobalTimeout(lua_State* L) { - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex); - lua_getfield(L, -1, "timeout"); - int result = boost::numeric_cast(lua_tointeger(L, -1)); - lua_pop(L, 2); - return result; + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex); + lua_getfield(L, -1, "timeout"); + int result = boost::numeric_cast(lua_tointeger(L, -1)); + lua_pop(L, 2); + return result; } static void addPayloadsToTable(lua_State* L, const std::vector >& payloads) { - if (!payloads.empty()) { - lua_createtable(L, boost::numeric_cast(payloads.size()), 0); - for (size_t i = 0; i < payloads.size(); ++i) { - Sluift::globals.elementConvertor.convertToLua(L, payloads[i]); - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - Lua::registerGetByTypeIndex(L, -1); - lua_setfield(L, -2, "payloads"); - } + if (!payloads.empty()) { + lua_createtable(L, boost::numeric_cast(payloads.size()), 0); + for (size_t i = 0; i < payloads.size(); ++i) { + Sluift::globals.elementConvertor.convertToLua(L, payloads[i]); + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + Lua::registerGetByTypeIndex(L, -1); + lua_setfield(L, -2, "payloads"); + } } static boost::shared_ptr getPayload(lua_State* L, int index) { - if (lua_type(L, index) == LUA_TTABLE) { - return boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLua(L, index)); - } - else if (lua_type(L, index) == LUA_TSTRING) { - return boost::make_shared(Lua::checkString(L, index)); - } - else { - return boost::shared_ptr(); - } + if (lua_type(L, index) == LUA_TTABLE) { + return boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLua(L, index)); + } + else if (lua_type(L, index) == LUA_TSTRING) { + return boost::make_shared(Lua::checkString(L, index)); + } + else { + return boost::shared_ptr(); + } } static std::vector< boost::shared_ptr > getPayloadsFromTable(lua_State* L, int index) { - index = Lua::absoluteOffset(L, index); - std::vector< boost::shared_ptr > result; - lua_getfield(L, index, "payloads"); - if (lua_istable(L, -1)) { - for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { - boost::shared_ptr payload = getPayload(L, -1); - if (payload) { - result.push_back(payload); - } - } - } - lua_pop(L, 1); - return result; + index = Lua::absoluteOffset(L, index); + std::vector< boost::shared_ptr > result; + lua_getfield(L, index, "payloads"); + if (lua_istable(L, -1)) { + for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { + boost::shared_ptr payload = getPayload(L, -1); + if (payload) { + result.push_back(payload); + } + } + } + lua_pop(L, 1); + return result; } SLUIFT_LUA_FUNCTION(Component, async_connect) { - SluiftComponent* component = getComponent(L); - - std::string host; - int port = 0; - if (lua_istable(L, 2)) { - if (boost::optional hostString = Lua::getStringField(L, 2, "host")) { - host = *hostString; - } - if (boost::optional portInt = Lua::getIntField(L, 2, "port")) { - port = *portInt; - } - } - component->connect(host, port); - return 0; + SluiftComponent* component = getComponent(L); + + std::string host; + int port = 0; + if (lua_istable(L, 2)) { + if (boost::optional hostString = Lua::getStringField(L, 2, "host")) { + host = *hostString; + } + if (boost::optional portInt = Lua::getIntField(L, 2, "port")) { + port = *portInt; + } + } + component->connect(host, port); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, set_trace_enabled, - "Enable/disable tracing of the data sent/received.\n\n.", - "self\n" - "enable a boolean specifying whether to enable/disable tracing", - "" + Component, set_trace_enabled, + "Enable/disable tracing of the data sent/received.\n\n.", + "self\n" + "enable a boolean specifying whether to enable/disable tracing", + "" ) { - getComponent(L)->setTraceEnabled(lua_toboolean(L, 1)); - return 0; + getComponent(L)->setTraceEnabled(lua_toboolean(L, 1)); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, wait_connected, - "Block until the component is connected.\n\nThis is useful after an `async_connect`.", - "self", - "" + Component, wait_connected, + "Block until the component is connected.\n\nThis is useful after an `async_connect`.", + "self", + "" ) { - getComponent(L)->waitConnected(getGlobalTimeout(L)); - return 0; + getComponent(L)->waitConnected(getGlobalTimeout(L)); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, is_connected, - "Checks whether this component is still connected.\n\nReturns a boolean.", - "self\n", - "" + Component, is_connected, + "Checks whether this component is still connected.\n\nReturns a boolean.", + "self\n", + "" ) { - lua_pushboolean(L, getComponent(L)->isConnected()); - return 1; + lua_pushboolean(L, getComponent(L)->isConnected()); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, disconnect, - "Disconnect from the server", - "self\n", - "" + Component, disconnect, + "Disconnect from the server", + "self\n", + "" ) { - Sluift::globals.eventLoop.runOnce(); - getComponent(L)->disconnect(); - return 0; + Sluift::globals.eventLoop.runOnce(); + getComponent(L)->disconnect(); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, set_version, + Component, set_version, - "Sets the published version of this component.", + "Sets the published version of this component.", - "self", + "self", - "name the name of the component software\n" - "version the version identifier of this component\n" - "os the OS this component is running on\n" + "name the name of the component software\n" + "version the version identifier of this component\n" + "os the OS this component is running on\n" ) { - Sluift::globals.eventLoop.runOnce(); - SluiftComponent* component = getComponent(L); - if (boost::shared_ptr version = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) { - component->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS()); - } - return 0; + Sluift::globals.eventLoop.runOnce(); + SluiftComponent* component = getComponent(L); + if (boost::shared_ptr version = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLuaUntyped(L, 2, "software_version"))) { + component->setSoftwareVersion(version->getName(), version->getVersion(), version->getOS()); + } + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, send_message, - "Send a message.", - "self\n" - "to the JID to send the message to\n" - "body the body of the message. Can alternatively be specified using the `body` option\n", - - "to the JID to send the message to\n" - "body the body of the message\n" - "subject the subject of the MUC room to set\n" - "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n" - "payloads payloads to add to the message\n" + Component, send_message, + "Send a message.", + "self\n" + "to the JID to send the message to\n" + "body the body of the message. Can alternatively be specified using the `body` option\n", + + "to the JID to send the message to\n" + "body the body of the message\n" + "subject the subject of the MUC room to set\n" + "type the type of message to send (`normal`, `chat`, `error`, `groupchat`, `headline`)\n" + "payloads payloads to add to the message\n" ) { - Sluift::globals.eventLoop.runOnce(); - JID to; - boost::optional from; - boost::optional body; - boost::optional subject; - std::vector > payloads; - int index = 2; - Message::Type type = Message::Chat; - if (lua_isstring(L, index)) { - to = std::string(lua_tostring(L, index)); - ++index; - if (lua_isstring(L, index)) { - body = lua_tostring(L, index); - ++index; - } - } - if (lua_istable(L, index)) { - if (boost::optional value = Lua::getStringField(L, index, "to")) { - to = *value; - } - - if (boost::optional value = Lua::getStringField(L, index, "from")) { - from = value; - } - - if (boost::optional value = Lua::getStringField(L, index, "body")) { - body = value; - } - - if (boost::optional value = Lua::getStringField(L, index, "type")) { - type = MessageConvertor::convertMessageTypeFromString(*value); - } - - if (boost::optional value = Lua::getStringField(L, index, "subject")) { - subject = value; - } - - payloads = getPayloadsFromTable(L, index); - } - - if (!to.isValid()) { - throw Lua::Exception("Missing 'to'"); - } - if ((!body || body->empty()) && !subject && payloads.empty()) { - throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'"); - } - Message::ref message = boost::make_shared(); - message->setTo(to); - if (from && !from->empty()) { - message->setFrom(*from); - } - if (body && !body->empty()) { - message->setBody(*body); - } - if (subject) { - message->setSubject(*subject); - } - message->addPayloads(payloads.begin(), payloads.end()); - message->setType(type); - getComponent(L)->getComponent()->sendMessage(message); - return 0; + Sluift::globals.eventLoop.runOnce(); + JID to; + boost::optional from; + boost::optional body; + boost::optional subject; + std::vector > payloads; + int index = 2; + Message::Type type = Message::Chat; + if (lua_isstring(L, index)) { + to = std::string(lua_tostring(L, index)); + ++index; + if (lua_isstring(L, index)) { + body = lua_tostring(L, index); + ++index; + } + } + if (lua_istable(L, index)) { + if (boost::optional value = Lua::getStringField(L, index, "to")) { + to = *value; + } + + if (boost::optional value = Lua::getStringField(L, index, "from")) { + from = value; + } + + if (boost::optional value = Lua::getStringField(L, index, "body")) { + body = value; + } + + if (boost::optional value = Lua::getStringField(L, index, "type")) { + type = MessageConvertor::convertMessageTypeFromString(*value); + } + + if (boost::optional value = Lua::getStringField(L, index, "subject")) { + subject = value; + } + + payloads = getPayloadsFromTable(L, index); + } + + if (!to.isValid()) { + throw Lua::Exception("Missing 'to'"); + } + if ((!body || body->empty()) && !subject && payloads.empty()) { + throw Lua::Exception("Missing any of 'body', 'subject' or 'payloads'"); + } + Message::ref message = boost::make_shared(); + message->setTo(to); + if (from && !from->empty()) { + message->setFrom(*from); + } + if (body && !body->empty()) { + message->setBody(*body); + } + if (subject) { + message->setSubject(*subject); + } + message->addPayloads(payloads.begin(), payloads.end()); + message->setType(type); + getComponent(L)->getComponent()->sendMessage(message); + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, send_presence, - "Send presence.", - - "self\n" - "body the text of the presence. Can alternatively be specified using the `status` option\n", - - "to the JID to send the message to\n" - "from the JID to send the message from\n" - "status the text of the presence\n" - "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n" - "priority the priority of the presence\n" - "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n" - "payloads payloads to add to the presence\n" + Component, send_presence, + "Send presence.", + + "self\n" + "body the text of the presence. Can alternatively be specified using the `status` option\n", + + "to the JID to send the message to\n" + "from the JID to send the message from\n" + "status the text of the presence\n" + "show the availability of the presence (`online`, `ffc`, `away`, `xa`, `dnd`)\n" + "priority the priority of the presence\n" + "type the type of message to send (`available`, `error`, `probe`, `subscribe`, `subscribed`, `unavailable`, `unsubscribe`, `unsubscribed`)\n" + "payloads payloads to add to the presence\n" ) { - Sluift::globals.eventLoop.runOnce(); - boost::shared_ptr presence = boost::make_shared(); - - int index = 2; - if (lua_isstring(L, index)) { - presence->setStatus(lua_tostring(L, index)); - ++index; - } - if (lua_istable(L, index)) { - if (boost::optional value = Lua::getStringField(L, index, "to")) { - presence->setTo(*value); - } - if (boost::optional value = Lua::getStringField(L, index, "from")) { - presence->setFrom(*value); - } - if (boost::optional value = Lua::getStringField(L, index, "status")) { - presence->setStatus(*value); - } - if (boost::optional value = Lua::getIntField(L, index, "priority")) { - presence->setPriority(*value); - } - if (boost::optional value = Lua::getStringField(L, index, "type")) { - presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value)); - } - if (boost::optional value = Lua::getStringField(L, index, "show")) { - presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value)); - } - std::vector< boost::shared_ptr > payloads = getPayloadsFromTable(L, index); - presence->addPayloads(payloads.begin(), payloads.end()); - } - - getComponent(L)->getComponent()->sendPresence(presence); - lua_pushvalue(L, 1); - return 0; + Sluift::globals.eventLoop.runOnce(); + boost::shared_ptr presence = boost::make_shared(); + + int index = 2; + if (lua_isstring(L, index)) { + presence->setStatus(lua_tostring(L, index)); + ++index; + } + if (lua_istable(L, index)) { + if (boost::optional value = Lua::getStringField(L, index, "to")) { + presence->setTo(*value); + } + if (boost::optional value = Lua::getStringField(L, index, "from")) { + presence->setFrom(*value); + } + if (boost::optional value = Lua::getStringField(L, index, "status")) { + presence->setStatus(*value); + } + if (boost::optional value = Lua::getIntField(L, index, "priority")) { + presence->setPriority(*value); + } + if (boost::optional value = Lua::getStringField(L, index, "type")) { + presence->setType(PresenceConvertor::convertPresenceTypeFromString(*value)); + } + if (boost::optional value = Lua::getStringField(L, index, "show")) { + presence->setShow(StatusShowConvertor::convertStatusShowTypeFromString(*value)); + } + std::vector< boost::shared_ptr > payloads = getPayloadsFromTable(L, index); + presence->addPayloads(payloads.begin(), payloads.end()); + } + + getComponent(L)->getComponent()->sendPresence(presence); + lua_pushvalue(L, 1); + return 0; } static int sendQuery(lua_State* L, IQ::Type type) { - SluiftComponent* component = getComponent(L); - - JID to; - if (boost::optional toString = Lua::getStringField(L, 2, "to")) { - to = JID(*toString); - } - - JID from; - if (boost::optional fromString = Lua::getStringField(L, 2, "from")) { - from = JID(*fromString); - } - - int timeout = getGlobalTimeout(L); - if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { - timeout = *timeoutInt; - } - - boost::shared_ptr payload; - lua_getfield(L, 2, "query"); - payload = getPayload(L, -1); - lua_pop(L, 1); - - return component->sendRequest( - boost::make_shared< GenericRequest >(type, from, to, payload, component->getComponent()->getIQRouter()), timeout).convertToLuaResult(L); + SluiftComponent* component = getComponent(L); + + JID to; + if (boost::optional toString = Lua::getStringField(L, 2, "to")) { + to = JID(*toString); + } + + JID from; + if (boost::optional fromString = Lua::getStringField(L, 2, "from")) { + from = JID(*fromString); + } + + int timeout = getGlobalTimeout(L); + if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { + timeout = *timeoutInt; + } + + boost::shared_ptr payload; + lua_getfield(L, 2, "query"); + payload = getPayload(L, -1); + lua_pop(L, 1); + + return component->sendRequest( + boost::make_shared< GenericRequest >(type, from, to, payload, component->getComponent()->getIQRouter()), timeout).convertToLuaResult(L); } SLUIFT_LUA_FUNCTION(Component, get) { - return sendQuery(L, IQ::Get); + return sendQuery(L, IQ::Get); } SLUIFT_LUA_FUNCTION(Component, set) { - return sendQuery(L, IQ::Set); + return sendQuery(L, IQ::Set); } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, send, - "Sends a raw string", + Component, send, + "Sends a raw string", - "self\n" - "data the string to send\n", + "self\n" + "data the string to send\n", - "" + "" ) { - Sluift::globals.eventLoop.runOnce(); + Sluift::globals.eventLoop.runOnce(); - getComponent(L)->getComponent()->sendData(std::string(Lua::checkString(L, 2))); - lua_pushvalue(L, 1); - return 0; + getComponent(L)->getComponent()->sendData(std::string(Lua::checkString(L, 2))); + lua_pushvalue(L, 1); + return 0; } static void pushEvent(lua_State* L, const SluiftComponent::Event& event) { - switch (event.type) { - case SluiftComponent::Event::MessageType: { - Message::ref message = boost::dynamic_pointer_cast(event.stanza); - Lua::Table result = boost::assign::map_list_of - ("type", boost::make_shared(std::string("message"))) - ("from", boost::make_shared(message->getFrom().toString())) - ("to", boost::make_shared(message->getTo().toString())) - ("body", boost::make_shared(message->getBody().get_value_or(""))) - ("message_type", boost::make_shared(MessageConvertor::convertMessageTypeToString(message->getType()))); - Lua::pushValue(L, result); - addPayloadsToTable(L, message->getPayloads()); - Lua::registerTableToString(L, -1); - break; - } - case SluiftComponent::Event::PresenceType: { - Presence::ref presence = boost::dynamic_pointer_cast(event.stanza); - Lua::Table result = boost::assign::map_list_of - ("type", boost::make_shared(std::string("presence"))) - ("from", boost::make_shared(presence->getFrom().toString())) - ("to", boost::make_shared(presence->getTo().toString())) - ("status", boost::make_shared(presence->getStatus())) - ("presence_type", boost::make_shared(PresenceConvertor::convertPresenceTypeToString(presence->getType()))); - Lua::pushValue(L, result); - addPayloadsToTable(L, presence->getPayloads()); - Lua::registerTableToString(L, -1); - break; - } - } + switch (event.type) { + case SluiftComponent::Event::MessageType: { + Message::ref message = boost::dynamic_pointer_cast(event.stanza); + Lua::Table result = boost::assign::map_list_of + ("type", boost::make_shared(std::string("message"))) + ("from", boost::make_shared(message->getFrom().toString())) + ("to", boost::make_shared(message->getTo().toString())) + ("body", boost::make_shared(message->getBody().get_value_or(""))) + ("message_type", boost::make_shared(MessageConvertor::convertMessageTypeToString(message->getType()))); + Lua::pushValue(L, result); + addPayloadsToTable(L, message->getPayloads()); + Lua::registerTableToString(L, -1); + break; + } + case SluiftComponent::Event::PresenceType: { + Presence::ref presence = boost::dynamic_pointer_cast(event.stanza); + Lua::Table result = boost::assign::map_list_of + ("type", boost::make_shared(std::string("presence"))) + ("from", boost::make_shared(presence->getFrom().toString())) + ("to", boost::make_shared(presence->getTo().toString())) + ("status", boost::make_shared(presence->getStatus())) + ("presence_type", boost::make_shared(PresenceConvertor::convertPresenceTypeToString(presence->getType()))); + Lua::pushValue(L, result); + addPayloadsToTable(L, presence->getPayloads()); + Lua::registerTableToString(L, -1); + break; + } + } } struct CallUnaryLuaPredicateOnEvent { - CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) { - } - - bool operator()(const SluiftComponent::Event& event) { - lua_pushvalue(L, index); - pushEvent(L, event); - if (lua_pcall(L, 1, 1, 0) != 0) { - throw Lua::Exception(lua_tostring(L, -1)); - } - bool result = lua_toboolean(L, -1); - lua_pop(L, 1); - return result; - } - - lua_State* L; - int index; + CallUnaryLuaPredicateOnEvent(lua_State* L, int index) : L(L), index(index) { + } + + bool operator()(const SluiftComponent::Event& event) { + lua_pushvalue(L, index); + pushEvent(L, event); + if (lua_pcall(L, 1, 1, 0) != 0) { + throw Lua::Exception(lua_tostring(L, -1)); + } + bool result = lua_toboolean(L, -1); + lua_pop(L, 1); + return result; + } + + lua_State* L; + int index; }; SLUIFT_LUA_FUNCTION(Component, get_next_event) { - Sluift::globals.eventLoop.runOnce(); - SluiftComponent* component = getComponent(L); - - int timeout = getGlobalTimeout(L); - boost::optional type; - int condition = 0; - if (lua_istable(L, 2)) { - if (boost::optional typeString = Lua::getStringField(L, 2, "type")) { - if (*typeString == "message") { - type = SluiftComponent::Event::MessageType; - } - else if (*typeString == "presence") { - type = SluiftComponent::Event::PresenceType; - } - } - if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { - timeout = *timeoutInt; - } - lua_getfield(L, 2, "if"); - if (lua_isfunction(L, -1)) { - condition = Lua::absoluteOffset(L, -1); - } - } - - boost::optional event; - if (condition) { - event = component->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition)); - } - else if (type) { - event = component->getNextEvent( - timeout, lambda::bind(&SluiftComponent::Event::type, lambda::_1) == *type); - } - else { - event = component->getNextEvent(timeout); - } - - if (event) { - pushEvent(L, *event); - } - else { - lua_pushnil(L); - } - return 1; + Sluift::globals.eventLoop.runOnce(); + SluiftComponent* component = getComponent(L); + + int timeout = getGlobalTimeout(L); + boost::optional type; + int condition = 0; + if (lua_istable(L, 2)) { + if (boost::optional typeString = Lua::getStringField(L, 2, "type")) { + if (*typeString == "message") { + type = SluiftComponent::Event::MessageType; + } + else if (*typeString == "presence") { + type = SluiftComponent::Event::PresenceType; + } + } + if (boost::optional timeoutInt = Lua::getIntField(L, 2, "timeout")) { + timeout = *timeoutInt; + } + lua_getfield(L, 2, "if"); + if (lua_isfunction(L, -1)) { + condition = Lua::absoluteOffset(L, -1); + } + } + + boost::optional event; + if (condition) { + event = component->getNextEvent(timeout, CallUnaryLuaPredicateOnEvent(L, condition)); + } + else if (type) { + event = component->getNextEvent( + timeout, lambda::bind(&SluiftComponent::Event::type, lambda::_1) == *type); + } + else { + event = component->getNextEvent(timeout); + } + + if (event) { + pushEvent(L, *event); + } + else { + lua_pushnil(L); + } + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Component, jid, - "Returns the JID of this component", - "self\n", - "" + Component, jid, + "Returns the JID of this component", + "self\n", + "" ) { - SluiftComponent* component = getComponent(L); - lua_pushstring(L, component->getComponent()->getJID().toString().c_str()); - return 1; + SluiftComponent* component = getComponent(L); + lua_pushstring(L, component->getComponent()->getJID().toString().c_str()); + return 1; } SLUIFT_LUA_FUNCTION(Component, __gc) { - SluiftComponent* component = getComponent(L); - delete component; - return 0; + SluiftComponent* component = getComponent(L); + delete component; + return 0; } diff --git a/Sluift/globals.h b/Sluift/globals.h index e414eb0..f92beeb 100644 --- a/Sluift/globals.h +++ b/Sluift/globals.h @@ -9,7 +9,7 @@ #include namespace Swift { - namespace Sluift { - extern SluiftGlobals globals; - } + namespace Sluift { + extern SluiftGlobals globals; + } } diff --git a/Sluift/main.cpp b/Sluift/main.cpp index 425f7fa..6953ca6 100644 --- a/Sluift/main.cpp +++ b/Sluift/main.cpp @@ -34,155 +34,155 @@ using namespace Swift; #endif static const std::string SLUIFT_WELCOME_STRING( - "== Sluift XMPP Console (" SLUIFT_VERSION_STRING ")\nPress Ctrl-" EXIT_KEY " to exit. Type help() for help."); + "== Sluift XMPP Console (" SLUIFT_VERSION_STRING ")\nPress Ctrl-" EXIT_KEY " to exit. Type help() for help."); static const luaL_Reg defaultLibraries[] = { - {"", luaopen_base}, - {LUA_LOADLIBNAME, luaopen_package}, - {LUA_TABLIBNAME, luaopen_table}, - {LUA_IOLIBNAME, luaopen_io}, - {LUA_OSLIBNAME, luaopen_os}, - {LUA_STRLIBNAME, luaopen_string}, - {LUA_MATHLIBNAME, luaopen_math}, - {LUA_DBLIBNAME, luaopen_debug}, - {"sluift", luaopen_sluift}, - {NULL, NULL} + {"", luaopen_base}, + {LUA_LOADLIBNAME, luaopen_package}, + {LUA_TABLIBNAME, luaopen_table}, + {LUA_IOLIBNAME, luaopen_io}, + {LUA_OSLIBNAME, luaopen_os}, + {LUA_STRLIBNAME, luaopen_string}, + {LUA_MATHLIBNAME, luaopen_math}, + {LUA_DBLIBNAME, luaopen_debug}, + {"sluift", luaopen_sluift}, + {NULL, NULL} }; static void handleInterruptSignal(int) { - Sluift::globals.interruptRequested = 1; + Sluift::globals.interruptRequested = 1; } static void checkResult(lua_State* L, int result) { - if (result && !lua_isnil(L, -1)) { - const char* errorMessage = lua_tostring(L, -1); - throw std::runtime_error(errorMessage ? errorMessage : "Unknown error"); - } + if (result && !lua_isnil(L, -1)) { + const char* errorMessage = lua_tostring(L, -1); + throw std::runtime_error(errorMessage ? errorMessage : "Unknown error"); + } } static void initialize(lua_State* L) { - lua_gc(L, LUA_GCSTOP, 0); - for (const luaL_Reg* lib = defaultLibraries; lib->func; lib++) { + lua_gc(L, LUA_GCSTOP, 0); + for (const luaL_Reg* lib = defaultLibraries; lib->func; lib++) { #if LUA_VERSION_NUM >= 502 - luaL_requiref(L, lib->name, lib->func, 1); - lua_pop(L, 1); + luaL_requiref(L, lib->name, lib->func, 1); + lua_pop(L, 1); #else - lua_pushcfunction(L, lib->func); - lua_pushstring(L, lib->name); - lua_call(L, 1, 0); + lua_pushcfunction(L, lib->func); + lua_pushstring(L, lib->name); + lua_call(L, 1, 0); #endif - } - lua_gc(L, LUA_GCRESTART, 0); + } + lua_gc(L, LUA_GCRESTART, 0); } static void runScript(lua_State* L, const std::string& script, const std::vector& scriptArguments) { - // Create arguments table - lua_createtable(L, boost::numeric_cast(scriptArguments.size()), 0); - for (size_t i = 0; i < scriptArguments.size(); ++i) { - lua_pushstring(L, scriptArguments[i].c_str()); - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - lua_setglobal(L, "arg"); - - // Load file - checkResult(L, luaL_loadfile(L, script.c_str())); - foreach (const std::string& scriptArgument, scriptArguments) { - lua_pushstring(L, scriptArgument.c_str()); - } - checkResult(L, Console::call(L, boost::numeric_cast(scriptArguments.size()), false)); + // Create arguments table + lua_createtable(L, boost::numeric_cast(scriptArguments.size()), 0); + for (size_t i = 0; i < scriptArguments.size(); ++i) { + lua_pushstring(L, scriptArguments[i].c_str()); + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + lua_setglobal(L, "arg"); + + // Load file + checkResult(L, luaL_loadfile(L, script.c_str())); + foreach (const std::string& scriptArgument, scriptArguments) { + lua_pushstring(L, scriptArgument.c_str()); + } + checkResult(L, Console::call(L, boost::numeric_cast(scriptArguments.size()), false)); } int main(int argc, char* argv[]) { - // Parse program options - boost::program_options::options_description visibleOptions("Options"); - visibleOptions.add_options() - ("help,h", "Display this help message") - ("version,v", "Display version information") - ("interactive,i", "Enter interactive mode after executing script") - ; - boost::program_options::options_description hiddenOptions("Hidden Options"); - hiddenOptions.add_options() - ("script", boost::program_options::value< std::string >(), "Script to be executed") - ("script-arguments", boost::program_options::value< std::vector >(), "Script arguments") - ; - boost::program_options::options_description options("All Options"); - options.add(visibleOptions).add(hiddenOptions); - - boost::program_options::positional_options_description positional_options; - positional_options.add("script", 1).add("script-arguments", -1); - - boost::program_options::variables_map arguments; - try { - boost::program_options::store( - boost::program_options::command_line_parser(argc, argv) - .options(options) - .positional(positional_options).run(), arguments); - } - catch (const boost::program_options::unknown_option& option) { + // Parse program options + boost::program_options::options_description visibleOptions("Options"); + visibleOptions.add_options() + ("help,h", "Display this help message") + ("version,v", "Display version information") + ("interactive,i", "Enter interactive mode after executing script") + ; + boost::program_options::options_description hiddenOptions("Hidden Options"); + hiddenOptions.add_options() + ("script", boost::program_options::value< std::string >(), "Script to be executed") + ("script-arguments", boost::program_options::value< std::vector >(), "Script arguments") + ; + boost::program_options::options_description options("All Options"); + options.add(visibleOptions).add(hiddenOptions); + + boost::program_options::positional_options_description positional_options; + positional_options.add("script", 1).add("script-arguments", -1); + + boost::program_options::variables_map arguments; + try { + boost::program_options::store( + boost::program_options::command_line_parser(argc, argv) + .options(options) + .positional(positional_options).run(), arguments); + } + catch (const boost::program_options::unknown_option& option) { #if BOOST_VERSION >= 104200 - std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl; + std::cout << "Ignoring unknown option " << option.get_option_name() << " but continuing." << std::endl; #else - std::cout << "Error: " << option.what() << " (continuing)" << std::endl; + std::cout << "Error: " << option.what() << " (continuing)" << std::endl; #endif - } - catch (const std::exception& e) { - std::cout << "Error: " << e.what() << std::endl; - return -1; - } - boost::program_options::notify(arguments); - - // Help & version - if (arguments.count("help")) { - std::cout << visibleOptions << "\n"; - return 0; - } - else if (arguments.count("version")) { - std::cout << SLUIFT_VERSION_STRING; - return 0; - } - - lua_State* L = luaL_newstate(); - initialize(L); - try { - // Run script - if (arguments.count("script")) { - std::vector scriptArguments; - if (arguments.count("script-arguments")) { - scriptArguments = arguments["script-arguments"].as< std::vector >(); - } - runScript(L, arguments["script"].as(), scriptArguments); - } - - // Run console - if (arguments.count("interactive") || arguments.count("script") == 0) { - // Set up signal handler - signal(SIGINT, handleInterruptSignal); - - // Import some useful functions into the global namespace - lua_getglobal(L, "sluift"); - std::vector globalImports = boost::assign::list_of - ("help")("with"); - foreach (const std::string& globalImport, globalImports) { - lua_getfield(L, -1, globalImport.c_str()); - lua_setglobal(L, globalImport.c_str()); - } - lua_pop(L, 1); - - std::cout << SLUIFT_WELCOME_STRING << std::endl; + } + catch (const std::exception& e) { + std::cout << "Error: " << e.what() << std::endl; + return -1; + } + boost::program_options::notify(arguments); + + // Help & version + if (arguments.count("help")) { + std::cout << visibleOptions << "\n"; + return 0; + } + else if (arguments.count("version")) { + std::cout << SLUIFT_VERSION_STRING; + return 0; + } + + lua_State* L = luaL_newstate(); + initialize(L); + try { + // Run script + if (arguments.count("script")) { + std::vector scriptArguments; + if (arguments.count("script-arguments")) { + scriptArguments = arguments["script-arguments"].as< std::vector >(); + } + runScript(L, arguments["script"].as(), scriptArguments); + } + + // Run console + if (arguments.count("interactive") || arguments.count("script") == 0) { + // Set up signal handler + signal(SIGINT, handleInterruptSignal); + + // Import some useful functions into the global namespace + lua_getglobal(L, "sluift"); + std::vector globalImports = boost::assign::list_of + ("help")("with"); + foreach (const std::string& globalImport, globalImports) { + lua_getfield(L, -1, globalImport.c_str()); + lua_setglobal(L, globalImport.c_str()); + } + lua_pop(L, 1); + + std::cout << SLUIFT_WELCOME_STRING << std::endl; #ifdef HAVE_EDITLINE - EditlineTerminal& terminal = EditlineTerminal::getInstance(); + EditlineTerminal& terminal = EditlineTerminal::getInstance(); #else - StandardTerminal terminal; + StandardTerminal terminal; #endif - Console console(L, &terminal); - console.run(); - } - } - catch (const std::exception& e) { - std::cerr << e.what() << std::endl; - lua_close(L); - return -1; - } - lua_close(L); - return 0; + Console console(L, &terminal); + console.run(); + } + } + catch (const std::exception& e) { + std::cerr << e.what() << std::endl; + lua_close(L); + return -1; + } + lua_close(L); + return 0; } diff --git a/Sluift/sluift.cpp b/Sluift/sluift.cpp index 9b82602..aff4533 100644 --- a/Sluift/sluift.cpp +++ b/Sluift/sluift.cpp @@ -44,20 +44,20 @@ using namespace Swift; namespace Swift { - namespace Sluift { - SluiftGlobals globals; - } + namespace Sluift { + SluiftGlobals globals; + } } extern "C" const char core_lua[]; extern "C" size_t core_lua_size; static inline bool getGlobalDebug(lua_State* L) { - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex); - lua_getfield(L, -1, "debug"); - int result = lua_toboolean(L, -1); - lua_pop(L, 2); - return result; + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.moduleLibIndex); + lua_getfield(L, -1, "debug"); + int result = lua_toboolean(L, -1); + lua_pop(L, 2); + return result; } @@ -66,157 +66,157 @@ static inline bool getGlobalDebug(lua_State* L) { ******************************************************************************/ SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, new_client, + Sluift, new_client, - "Creates a new client.\n\nReturns a @{Client} object.\n", + "Creates a new client.\n\nReturns a @{Client} object.\n", - "jid The JID to connect as\n" - "passphrase The passphrase to use\n", + "jid The JID to connect as\n" + "passphrase The passphrase to use\n", - "" + "" ) { - Lua::checkString(L, 1); - JID jid(std::string(Lua::checkString(L, 1))); - std::string password(Lua::checkString(L, 2)); + Lua::checkString(L, 1); + JID jid(std::string(Lua::checkString(L, 1))); + std::string password(Lua::checkString(L, 2)); - SluiftClient** client = reinterpret_cast(lua_newuserdata(L, sizeof(SluiftClient*))); + SluiftClient** client = reinterpret_cast(lua_newuserdata(L, sizeof(SluiftClient*))); - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "Client"); - lua_setmetatable(L, -3); - lua_pop(L, 1); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "Client"); + lua_setmetatable(L, -3); + lua_pop(L, 1); - *client = new SluiftClient(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop); - (*client)->setTraceEnabled(getGlobalDebug(L)); - return 1; + *client = new SluiftClient(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop); + (*client)->setTraceEnabled(getGlobalDebug(L)); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, new_component, + Sluift, new_component, - "Creates a new component.\n\nReturns a @{Component} object.\n", + "Creates a new component.\n\nReturns a @{Component} object.\n", - "jid The JID to connect as\n" - "passphrase The passphrase to use\n", + "jid The JID to connect as\n" + "passphrase The passphrase to use\n", - "" + "" ) { - Lua::checkString(L, 1); - JID jid(std::string(Lua::checkString(L, 1))); - std::string password(Lua::checkString(L, 2)); + Lua::checkString(L, 1); + JID jid(std::string(Lua::checkString(L, 1))); + std::string password(Lua::checkString(L, 2)); - SluiftComponent** component = reinterpret_cast(lua_newuserdata(L, sizeof(SluiftComponent*))); + SluiftComponent** component = reinterpret_cast(lua_newuserdata(L, sizeof(SluiftComponent*))); - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - lua_getfield(L, -1, "Component"); - lua_setmetatable(L, -3); - lua_pop(L, 1); + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + lua_getfield(L, -1, "Component"); + lua_setmetatable(L, -3); + lua_pop(L, 1); - *component = new SluiftComponent(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop); - (*component)->setTraceEnabled(getGlobalDebug(L)); - return 1; + *component = new SluiftComponent(jid, password, &Sluift::globals.networkFactories, &Sluift::globals.eventLoop); + (*component)->setTraceEnabled(getGlobalDebug(L)); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, sha1, - "Compute the SHA-1 hash of given data", - "data the data to hash", - "" + Sluift, sha1, + "Compute the SHA-1 hash of given data", + "data the data to hash", + "" ) { - static boost::shared_ptr crypto(PlatformCryptoProvider::create()); - if (!lua_isstring(L, 1)) { - throw Lua::Exception("Expected string"); - } - size_t len; - const char* data = lua_tolstring(L, 1, &len); - ByteArray result = crypto->getSHA1Hash(createByteArray(data, len)); - lua_pushlstring(L, reinterpret_cast(vecptr(result)), result.size()); - return 1; + static boost::shared_ptr crypto(PlatformCryptoProvider::create()); + if (!lua_isstring(L, 1)) { + throw Lua::Exception("Expected string"); + } + size_t len; + const char* data = lua_tolstring(L, 1, &len); + ByteArray result = crypto->getSHA1Hash(createByteArray(data, len)); + lua_pushlstring(L, reinterpret_cast(vecptr(result)), result.size()); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, sleep, - "Sleeps for the given time.", - "milliseconds the amount of milliseconds to sleep", - "" + Sluift, sleep, + "Sleeps for the given time.", + "milliseconds the amount of milliseconds to sleep", + "" ) { - Sluift::globals.eventLoop.runOnce(); - int timeout = Lua::checkIntNumber(L, 1); - Watchdog watchdog(timeout, Sluift::globals.networkFactories.getTimerFactory()); - while (!watchdog.getTimedOut()) { - Swift::sleep(boost::numeric_cast(std::min(100, timeout))); - Sluift::globals.eventLoop.runOnce(); - } - return 0; + Sluift::globals.eventLoop.runOnce(); + int timeout = Lua::checkIntNumber(L, 1); + Watchdog watchdog(timeout, Sluift::globals.networkFactories.getTimerFactory()); + while (!watchdog.getTimedOut()) { + Swift::sleep(boost::numeric_cast(std::min(100, timeout))); + Sluift::globals.eventLoop.runOnce(); + } + return 0; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, new_uuid, - "Generates a new UUID", "", "" + Sluift, new_uuid, + "Generates a new UUID", "", "" ) { - lua_pushstring(L, IDGenerator().generateID().c_str()); - return 1; + lua_pushstring(L, IDGenerator().generateID().c_str()); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, from_xml, - "Convert a raw XML string into a structured representation.", - "string the string to convert", - "" + Sluift, from_xml, + "Convert a raw XML string into a structured representation.", + "string the string to convert", + "" ) { - PayloadsParserTester parser; - if (!parser.parse(Lua::checkString(L, 1))) { - throw Lua::Exception("Error in XML"); - } - return Sluift::globals.elementConvertor.convertToLua(L, parser.getPayload()); + PayloadsParserTester parser; + if (!parser.parse(Lua::checkString(L, 1))) { + throw Lua::Exception("Error in XML"); + } + return Sluift::globals.elementConvertor.convertToLua(L, parser.getPayload()); } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, to_xml, - "Convert a structured element into XML.", - "element the element to convert", - "" + Sluift, to_xml, + "Convert a structured element into XML.", + "element the element to convert", + "" ) { - static FullPayloadSerializerCollection serializers; - boost::shared_ptr payload = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLua(L, 1)); - if (!payload) { - throw Lua::Exception("Unrecognized XML"); - } - PayloadSerializer* serializer = serializers.getPayloadSerializer(payload); - if (!payload) { - throw Lua::Exception("Unrecognized XML"); - } - lua_pushstring(L, serializer->serialize(payload).c_str()); - return 1; + static FullPayloadSerializerCollection serializers; + boost::shared_ptr payload = boost::dynamic_pointer_cast(Sluift::globals.elementConvertor.convertFromLua(L, 1)); + if (!payload) { + throw Lua::Exception("Unrecognized XML"); + } + PayloadSerializer* serializer = serializers.getPayloadSerializer(payload); + if (!payload) { + throw Lua::Exception("Unrecognized XML"); + } + lua_pushstring(L, serializer->serialize(payload).c_str()); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, hexify, - "Convert binary data into hexadecimal format.", - "data the data to convert", - "" + Sluift, hexify, + "Convert binary data into hexadecimal format.", + "data the data to convert", + "" ) { - if (!lua_isstring(L, 1)) { - throw Lua::Exception("Expected string"); - } - size_t len; - const char* data = lua_tolstring(L, 1, &len); - lua_pushstring(L, Hexify::hexify(createByteArray(data, len)).c_str()); - return 1; + if (!lua_isstring(L, 1)) { + throw Lua::Exception("Expected string"); + } + size_t len; + const char* data = lua_tolstring(L, 1, &len); + lua_pushstring(L, Hexify::hexify(createByteArray(data, len)).c_str()); + return 1; } SLUIFT_LUA_FUNCTION_WITH_HELP( - Sluift, unhexify, - "Convert hexadecimal data into binary data.", - "data the data in hexadecimal format", - "" + Sluift, unhexify, + "Convert hexadecimal data into binary data.", + "data the data in hexadecimal format", + "" ) { - if (!lua_isstring(L, 1)) { - throw Lua::Exception("Expected string"); - } - ByteArray result = Hexify::unhexify(lua_tostring(L, 1)); - lua_pushlstring(L, reinterpret_cast(vecptr(result)), result.size()); - return 1; + if (!lua_isstring(L, 1)) { + throw Lua::Exception("Expected string"); + } + ByteArray result = Hexify::unhexify(lua_tostring(L, 1)); + lua_pushlstring(L, reinterpret_cast(vecptr(result)), result.size()); + return 1; } /******************************************************************************* @@ -224,34 +224,34 @@ SLUIFT_LUA_FUNCTION_WITH_HELP( ******************************************************************************/ SLUIFT_LUA_FUNCTION_WITH_HELP( - Crypto, new_certificate, - "Creates a new X.509 certificate from DER data.\n", + Crypto, new_certificate, + "Creates a new X.509 certificate from DER data.\n", - "der the DER-encoded certificate data", + "der the DER-encoded certificate data", - "") { - ByteArray certData(Lua::checkByteArray(L, 1)); - Certificate::ref cert(Sluift::globals.tlsFactories.getCertificateFactory()->createCertificateFromDER(certData)); - lua_createtable(L, 0, 0); - lua_pushstring(L, cert->getSubjectName().c_str()); - lua_setfield(L, -2, "subject_name"); - lua_pushstring(L, Certificate::getSHA1Fingerprint(cert, Sluift::globals.networkFactories.getCryptoProvider()).c_str()); - lua_setfield(L, -2, "sha1_fingerprint"); + "") { + ByteArray certData(Lua::checkByteArray(L, 1)); + Certificate::ref cert(Sluift::globals.tlsFactories.getCertificateFactory()->createCertificateFromDER(certData)); + lua_createtable(L, 0, 0); + lua_pushstring(L, cert->getSubjectName().c_str()); + lua_setfield(L, -2, "subject_name"); + lua_pushstring(L, Certificate::getSHA1Fingerprint(cert, Sluift::globals.networkFactories.getCryptoProvider()).c_str()); + lua_setfield(L, -2, "sha1_fingerprint"); - Lua::pushStringArray(L, cert->getCommonNames()); - lua_setfield(L, -2, "common_names"); + Lua::pushStringArray(L, cert->getCommonNames()); + lua_setfield(L, -2, "common_names"); - Lua::pushStringArray(L, cert->getSRVNames()); - lua_setfield(L, -2, "srv_names"); + Lua::pushStringArray(L, cert->getSRVNames()); + lua_setfield(L, -2, "srv_names"); - Lua::pushStringArray(L, cert->getDNSNames()); - lua_setfield(L, -2, "dns_names"); + Lua::pushStringArray(L, cert->getDNSNames()); + lua_setfield(L, -2, "dns_names"); - Lua::pushStringArray(L, cert->getXMPPAddresses()); - lua_setfield(L, -2, "xmpp_addresses"); + Lua::pushStringArray(L, cert->getXMPPAddresses()); + lua_setfield(L, -2, "xmpp_addresses"); - Lua::registerTableToString(L, -1); - return 1; + Lua::registerTableToString(L, -1); + return 1; } /******************************************************************************* @@ -259,30 +259,30 @@ SLUIFT_LUA_FUNCTION_WITH_HELP( ******************************************************************************/ SLUIFT_LUA_FUNCTION(FS, list) { - boost::filesystem::path dir(std::string(Lua::checkString(L, 1))); - if (!boost::filesystem::exists(dir) || !boost::filesystem::is_directory(dir)) { - lua_pushnil(L); - lua_pushstring(L, "Argument is not an existing directory"); - return 2; - } - - boost::filesystem::directory_iterator i(dir); - std::vector items( - i, boost::filesystem::directory_iterator()); - - lua_createtable(L, boost::numeric_cast(items.size()), 0); - for (size_t i = 0; i < items.size(); ++i) { - lua_pushstring(L, items[i].string().c_str()); - lua_rawseti(L, -2, boost::numeric_cast(i+1)); - } - Lua::registerTableToString(L, -1); - return 1; + boost::filesystem::path dir(std::string(Lua::checkString(L, 1))); + if (!boost::filesystem::exists(dir) || !boost::filesystem::is_directory(dir)) { + lua_pushnil(L); + lua_pushstring(L, "Argument is not an existing directory"); + return 2; + } + + boost::filesystem::directory_iterator i(dir); + std::vector items( + i, boost::filesystem::directory_iterator()); + + lua_createtable(L, boost::numeric_cast(items.size()), 0); + for (size_t i = 0; i < items.size(); ++i) { + lua_pushstring(L, items[i].string().c_str()); + lua_rawseti(L, -2, boost::numeric_cast(i+1)); + } + Lua::registerTableToString(L, -1); + return 1; } SLUIFT_LUA_FUNCTION(FS, is_file) { - boost::filesystem::path file(std::string(Lua::checkString(L, 1))); - lua_pushboolean(L, boost::filesystem::is_regular_file(file)); - return 1; + boost::filesystem::path file(std::string(Lua::checkString(L, 1))); + lua_pushboolean(L, boost::filesystem::is_regular_file(file)); + return 1; } @@ -291,32 +291,32 @@ SLUIFT_LUA_FUNCTION(FS, is_file) { ******************************************************************************/ SLUIFT_LUA_FUNCTION(JID, to_bare) { - JID jid(std::string(Lua::checkString(L, 1))); - lua_pushstring(L, jid.toBare().toString().c_str()); - return 1; + JID jid(std::string(Lua::checkString(L, 1))); + lua_pushstring(L, jid.toBare().toString().c_str()); + return 1; } SLUIFT_LUA_FUNCTION(JID, node) { - JID jid(std::string(Lua::checkString(L, 1))); - lua_pushstring(L, jid.getNode().c_str()); - return 1; + JID jid(std::string(Lua::checkString(L, 1))); + lua_pushstring(L, jid.getNode().c_str()); + return 1; } SLUIFT_LUA_FUNCTION(JID, domain) { - JID jid(std::string(Lua::checkString(L, 1))); - lua_pushstring(L, jid.getDomain().c_str()); - return 1; + JID jid(std::string(Lua::checkString(L, 1))); + lua_pushstring(L, jid.getDomain().c_str()); + return 1; } SLUIFT_LUA_FUNCTION(JID, resource) { - JID jid(std::string(Lua::checkString(L, 1))); - lua_pushstring(L, jid.getResource().c_str()); - return 1; + JID jid(std::string(Lua::checkString(L, 1))); + lua_pushstring(L, jid.getResource().c_str()); + return 1; } SLUIFT_LUA_FUNCTION(JID, escape_node) { - lua_pushstring(L, JID::getEscapedNode(Lua::checkString(L, 1)).c_str()); - return 1; + lua_pushstring(L, JID::getEscapedNode(Lua::checkString(L, 1)).c_str()); + return 1; } /******************************************************************************* @@ -324,22 +324,22 @@ SLUIFT_LUA_FUNCTION(JID, escape_node) { ******************************************************************************/ SLUIFT_LUA_FUNCTION(Base64, encode) { - if (!lua_isstring(L, 1)) { - throw Lua::Exception("Expected string"); - } - size_t len; - const char* data = lua_tolstring(L, 1, &len); - lua_pushstring(L, Base64::encode(createByteArray(data, len)).c_str()); - return 1; + if (!lua_isstring(L, 1)) { + throw Lua::Exception("Expected string"); + } + size_t len; + const char* data = lua_tolstring(L, 1, &len); + lua_pushstring(L, Base64::encode(createByteArray(data, len)).c_str()); + return 1; } SLUIFT_LUA_FUNCTION(Base64, decode) { - if (!lua_isstring(L, 1)) { - throw Lua::Exception("Expected string"); - } - ByteArray result = Base64::decode(lua_tostring(L, 1)); - lua_pushlstring(L, reinterpret_cast(vecptr(result)), result.size()); - return 1; + if (!lua_isstring(L, 1)) { + throw Lua::Exception("Expected string"); + } + ByteArray result = Base64::decode(lua_tostring(L, 1)); + lua_pushlstring(L, reinterpret_cast(vecptr(result)), result.size()); + return 1; } /******************************************************************************* @@ -347,43 +347,43 @@ SLUIFT_LUA_FUNCTION(Base64, decode) { ******************************************************************************/ SLUIFT_LUA_FUNCTION(IDN, encode) { - IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter(); - boost::optional encoded = converter->getIDNAEncoded(Lua::checkString(L, 1)); - if (!encoded) { - lua_pushnil(L); - lua_pushstring(L, "Error encoding domain name"); - return 2; - } - lua_pushstring(L, encoded->c_str()); - return 1; + IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter(); + boost::optional encoded = converter->getIDNAEncoded(Lua::checkString(L, 1)); + if (!encoded) { + lua_pushnil(L); + lua_pushstring(L, "Error encoding domain name"); + return 2; + } + lua_pushstring(L, encoded->c_str()); + return 1; } SLUIFT_LUA_FUNCTION(IDN, stringprep) { - IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter(); - IDNConverter::StringPrepProfile profile; - std::string profileString = Lua::checkString(L, 2); - if (profileString == "nameprep") { - profile = IDNConverter::NamePrep; - } - else if (profileString == "xmpp_nodeprep") { - profile = IDNConverter::XMPPNodePrep; - } - else if (profileString == "xmpp_resourceprep") { - profile = IDNConverter::XMPPResourcePrep; - } - else if (profileString == "saslprep") { - profile = IDNConverter::SASLPrep; - } - else { - throw Lua::Exception("Invalid profile"); - } - try { - lua_pushstring(L, converter->getStringPrepared(Lua::checkString(L, 1), profile).c_str()); - } - catch (const std::exception&) { - throw Lua::Exception("Error"); - } - return 1; + IDNConverter* converter = Sluift::globals.networkFactories.getIDNConverter(); + IDNConverter::StringPrepProfile profile; + std::string profileString = Lua::checkString(L, 2); + if (profileString == "nameprep") { + profile = IDNConverter::NamePrep; + } + else if (profileString == "xmpp_nodeprep") { + profile = IDNConverter::XMPPNodePrep; + } + else if (profileString == "xmpp_resourceprep") { + profile = IDNConverter::XMPPResourcePrep; + } + else if (profileString == "saslprep") { + profile = IDNConverter::SASLPrep; + } + else { + throw Lua::Exception("Invalid profile"); + } + try { + lua_pushstring(L, converter->getStringPrepared(Lua::checkString(L, 1), profile).c_str()); + } + catch (const std::exception&) { + throw Lua::Exception("Error"); + } + return 1; } /******************************************************************************* @@ -392,26 +392,26 @@ SLUIFT_LUA_FUNCTION(IDN, stringprep) { #ifdef HAVE_ITUNES SLUIFT_LUA_FUNCTION(iTunes, get_current_track) { - boost::optional track = Sluift::globals.iTunes.getCurrentTrack(); - if (!track) { - return 0; - } - lua_createtable(L, 0, 0); - lua_pushstring(L, track->artist.c_str()); - lua_setfield(L, -2, "artist"); - lua_pushstring(L, track->name.c_str()); - lua_setfield(L, -2, "name"); - lua_pushstring(L, track->album.c_str()); - lua_setfield(L, -2, "album"); - lua_pushinteger(L, track->trackNumber); - lua_setfield(L, -2, "track_number"); - lua_pushnumber(L, track->duration); - lua_setfield(L, -2, "duration"); - lua_pushinteger(L, track->rating); - lua_setfield(L, -2, "rating"); - Lua::registerTableToString(L, -1); - Lua::registerTableEquals(L, -1); - return 1; + boost::optional track = Sluift::globals.iTunes.getCurrentTrack(); + if (!track) { + return 0; + } + lua_createtable(L, 0, 0); + lua_pushstring(L, track->artist.c_str()); + lua_setfield(L, -2, "artist"); + lua_pushstring(L, track->name.c_str()); + lua_setfield(L, -2, "name"); + lua_pushstring(L, track->album.c_str()); + lua_setfield(L, -2, "album"); + lua_pushinteger(L, track->trackNumber); + lua_setfield(L, -2, "track_number"); + lua_pushnumber(L, track->duration); + lua_setfield(L, -2, "duration"); + lua_pushinteger(L, track->rating); + lua_setfield(L, -2, "rating"); + Lua::registerTableToString(L, -1); + Lua::registerTableEquals(L, -1); + return 1; } #endif @@ -422,81 +422,81 @@ SLUIFT_LUA_FUNCTION(iTunes, get_current_track) { static const luaL_Reg sluift_functions[] = { {NULL, NULL} }; SLUIFT_API int luaopen_sluift(lua_State* L) { - // Initialize & store the module table - luaL_register(L, lua_tostring(L, 1), sluift_functions); - lua_pushinteger(L, -1); - lua_setfield(L, -2, "timeout"); - lua_pushboolean(L, 0); - lua_setfield(L, -2, "debug"); - - lua_pushvalue(L, -1); - Sluift::globals.moduleLibIndex = luaL_ref(L, LUA_REGISTRYINDEX); - - // Load core lib code - if (luaL_loadbuffer(L, core_lua, core_lua_size, "core.lua") != 0) { - lua_error(L); - } - lua_pushvalue(L, -2); - lua_call(L, 1, 1); - Sluift::globals.coreLibIndex = luaL_ref(L, LUA_REGISTRYINDEX); - - // Register functions - Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, "Sluift"); - Lua::FunctionRegistry::getInstance().createFunctionTable(L, "JID"); - lua_setfield(L, -2, "jid"); - Lua::FunctionRegistry::getInstance().createFunctionTable(L, "Base64"); - lua_setfield(L, -2, "base64"); - Lua::FunctionRegistry::getInstance().createFunctionTable(L, "IDN"); - lua_setfield(L, -2, "idn"); - Lua::FunctionRegistry::getInstance().createFunctionTable(L, "Crypto"); - lua_setfield(L, -2, "crypto"); - Lua::FunctionRegistry::getInstance().createFunctionTable(L, "FS"); - lua_setfield(L, -2, "fs"); + // Initialize & store the module table + luaL_register(L, lua_tostring(L, 1), sluift_functions); + lua_pushinteger(L, -1); + lua_setfield(L, -2, "timeout"); + lua_pushboolean(L, 0); + lua_setfield(L, -2, "debug"); + + lua_pushvalue(L, -1); + Sluift::globals.moduleLibIndex = luaL_ref(L, LUA_REGISTRYINDEX); + + // Load core lib code + if (luaL_loadbuffer(L, core_lua, core_lua_size, "core.lua") != 0) { + lua_error(L); + } + lua_pushvalue(L, -2); + lua_call(L, 1, 1); + Sluift::globals.coreLibIndex = luaL_ref(L, LUA_REGISTRYINDEX); + + // Register functions + Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, "Sluift"); + Lua::FunctionRegistry::getInstance().createFunctionTable(L, "JID"); + lua_setfield(L, -2, "jid"); + Lua::FunctionRegistry::getInstance().createFunctionTable(L, "Base64"); + lua_setfield(L, -2, "base64"); + Lua::FunctionRegistry::getInstance().createFunctionTable(L, "IDN"); + lua_setfield(L, -2, "idn"); + Lua::FunctionRegistry::getInstance().createFunctionTable(L, "Crypto"); + lua_setfield(L, -2, "crypto"); + Lua::FunctionRegistry::getInstance().createFunctionTable(L, "FS"); + lua_setfield(L, -2, "fs"); #ifdef HAVE_ITUNES - Lua::FunctionRegistry::getInstance().createFunctionTable(L, "iTunes"); - lua_setfield(L, -2, "itunes"); + Lua::FunctionRegistry::getInstance().createFunctionTable(L, "iTunes"); + lua_setfield(L, -2, "itunes"); #endif - // Register convenience functions - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - std::vector coreLibExports = boost::assign::list_of - ("tprint")("disco")("help")("get_help")("copy")("with")("read_file")("create_form"); - foreach (const std::string& coreLibExport, coreLibExports) { - lua_getfield(L, -1, coreLibExport.c_str()); - lua_setfield(L, -3, coreLibExport.c_str()); - } - lua_pop(L, 1); - - // Load client metatable - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - std::vector tables = boost::assign::list_of("Client"); - foreach(const std::string& table, tables) { - lua_getfield(L, -1, table.c_str()); - Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table); - lua_pop(L, 1); - } - lua_pop(L, 1); - - // Load component metatable - lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); - std::vector comp_tables = boost::assign::list_of("Component"); - foreach(const std::string& table, comp_tables) { - lua_getfield(L, -1, table.c_str()); - Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table); - lua_pop(L, 1); - } - lua_pop(L, 1); - - // Register documentation for all elements - foreach (boost::shared_ptr convertor, Sluift::globals.elementConvertor.getConvertors()) { - boost::optional documentation = convertor->getDocumentation(); - if (documentation) { - Lua::registerClassHelp(L, documentation->className, documentation->description); - } - } - - // Register global documentation - Lua::registerExtraHelp(L, -1, "sluift"); - - return 1; + // Register convenience functions + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + std::vector coreLibExports = boost::assign::list_of + ("tprint")("disco")("help")("get_help")("copy")("with")("read_file")("create_form"); + foreach (const std::string& coreLibExport, coreLibExports) { + lua_getfield(L, -1, coreLibExport.c_str()); + lua_setfield(L, -3, coreLibExport.c_str()); + } + lua_pop(L, 1); + + // Load client metatable + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + std::vector tables = boost::assign::list_of("Client"); + foreach(const std::string& table, tables) { + lua_getfield(L, -1, table.c_str()); + Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table); + lua_pop(L, 1); + } + lua_pop(L, 1); + + // Load component metatable + lua_rawgeti(L, LUA_REGISTRYINDEX, Sluift::globals.coreLibIndex); + std::vector comp_tables = boost::assign::list_of("Component"); + foreach(const std::string& table, comp_tables) { + lua_getfield(L, -1, table.c_str()); + Lua::FunctionRegistry::getInstance().addFunctionsToTable(L, table); + lua_pop(L, 1); + } + lua_pop(L, 1); + + // Register documentation for all elements + foreach (boost::shared_ptr convertor, Sluift::globals.elementConvertor.getConvertors()) { + boost::optional documentation = convertor->getDocumentation(); + if (documentation) { + Lua::registerClassHelp(L, documentation->className, documentation->description); + } + } + + // Register global documentation + Lua::registerExtraHelp(L, -1, "sluift"); + + return 1; } diff --git a/Sluift/tokenize.cpp b/Sluift/tokenize.cpp index e0252f7..ff162d6 100644 --- a/Sluift/tokenize.cpp +++ b/Sluift/tokenize.cpp @@ -13,75 +13,75 @@ using namespace Swift; namespace { - struct LuaTokenizeFunctor { - void reset() { - } + struct LuaTokenizeFunctor { + void reset() { + } - template - bool operator()(InputIterator& next, InputIterator& end, Token& result) { - while (next != end && std::isspace(*next)) { - ++next; - } - if (next == end) { - return false; - } + template + bool operator()(InputIterator& next, InputIterator& end, Token& result) { + while (next != end && std::isspace(*next)) { + ++next; + } + if (next == end) { + return false; + } - std::vector token; - char c = *next++; - token.push_back(c); + std::vector token; + char c = *next++; + token.push_back(c); - // String literal - if (c == '\'' || c == '"') { - char quote = c; - bool inEscape = false; - for (; next != end; ++next) { - c = *next; - token.push_back(c); - if (inEscape) { - inEscape = false; - } - else if (c == '\\') { - inEscape = true; - } - else if (c == quote) { - break; - } - } - if (next != end) { - ++next; - } - } - // Identifier - else if (std::isalpha(c) || c == '_') { - while (next != end && (std::isalpha(*next) || *next == '_' || std::isdigit(*next))) { - token.push_back(*next); - ++next; - } - } - // Digit - else if (std::isdigit(c)) { - while (next != end && !std::isspace(*next)) { - token.push_back(*next); - ++next; - } - } - // Dots - else if (c == '.') { - while (next != end && *next == '.') { - token.push_back(*next); - ++next; - } - } - - result = Token(&token[0], token.size()); - return true; - } - }; + // String literal + if (c == '\'' || c == '"') { + char quote = c; + bool inEscape = false; + for (; next != end; ++next) { + c = *next; + token.push_back(c); + if (inEscape) { + inEscape = false; + } + else if (c == '\\') { + inEscape = true; + } + else if (c == quote) { + break; + } + } + if (next != end) { + ++next; + } + } + // Identifier + else if (std::isalpha(c) || c == '_') { + while (next != end && (std::isalpha(*next) || *next == '_' || std::isdigit(*next))) { + token.push_back(*next); + ++next; + } + } + // Digit + else if (std::isdigit(c)) { + while (next != end && !std::isspace(*next)) { + token.push_back(*next); + ++next; + } + } + // Dots + else if (c == '.') { + while (next != end && *next == '.') { + token.push_back(*next); + ++next; + } + } + + result = Token(&token[0], token.size()); + return true; + } + }; } std::vector Lua::tokenize(const std::string& input) { - boost::tokenizer tokenizer(input); - return std::vector(tokenizer.begin(), tokenizer.end()); + boost::tokenizer tokenizer(input); + return std::vector(tokenizer.begin(), tokenizer.end()); } diff --git a/Sluift/tokenize.h b/Sluift/tokenize.h index 842f1d3..33ea435 100644 --- a/Sluift/tokenize.h +++ b/Sluift/tokenize.h @@ -10,7 +10,7 @@ #include namespace Swift { - namespace Lua { - std::vector tokenize(const std::string&); - } + namespace Lua { + std::vector tokenize(const std::string&); + } } diff --git a/SwifTools/Application/ApplicationPathProvider.cpp b/SwifTools/Application/ApplicationPathProvider.cpp index ebe9654..3a86f28 100644 --- a/SwifTools/Application/ApplicationPathProvider.cpp +++ b/SwifTools/Application/ApplicationPathProvider.cpp @@ -22,29 +22,29 @@ ApplicationPathProvider::~ApplicationPathProvider() { } boost::filesystem::path ApplicationPathProvider::getProfileDir(const std::string& profile) const { - boost::filesystem::path result(getHomeDir() / profile); - try { - boost::filesystem::create_directory(result); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } - return result; + boost::filesystem::path result(getHomeDir() / profile); + try { + boost::filesystem::create_directory(result); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } + return result; } boost::filesystem::path ApplicationPathProvider::getResourcePath(const std::string& resource) const { - std::vector resourcePaths = getResourceDirs(); - foreach(const boost::filesystem::path& resourcePath, resourcePaths) { - boost::filesystem::path r(resourcePath / resource); - if (boost::filesystem::exists(r)) { - return r; - } - } - return boost::filesystem::path(); + std::vector resourcePaths = getResourceDirs(); + foreach(const boost::filesystem::path& resourcePath, resourcePaths) { + boost::filesystem::path r(resourcePath / resource); + if (boost::filesystem::exists(r)) { + return r; + } + } + return boost::filesystem::path(); } boost::filesystem::path ApplicationPathProvider::getExecutableDir() const { - return Paths::getExecutablePath(); + return Paths::getExecutablePath(); } } diff --git a/SwifTools/Application/ApplicationPathProvider.h b/SwifTools/Application/ApplicationPathProvider.h index aba9687..399ac5d 100644 --- a/SwifTools/Application/ApplicationPathProvider.h +++ b/SwifTools/Application/ApplicationPathProvider.h @@ -12,24 +12,24 @@ #include namespace Swift { - class ApplicationPathProvider { - public: - ApplicationPathProvider(const std::string& applicationName); - virtual ~ApplicationPathProvider(); + class ApplicationPathProvider { + public: + ApplicationPathProvider(const std::string& applicationName); + virtual ~ApplicationPathProvider(); - virtual boost::filesystem::path getHomeDir() const = 0; - virtual boost::filesystem::path getDataDir() const = 0; - boost::filesystem::path getExecutableDir() const; - boost::filesystem::path getProfileDir(const std::string& profile) const; - boost::filesystem::path getResourcePath(const std::string& resource) const; + virtual boost::filesystem::path getHomeDir() const = 0; + virtual boost::filesystem::path getDataDir() const = 0; + boost::filesystem::path getExecutableDir() const; + boost::filesystem::path getProfileDir(const std::string& profile) const; + boost::filesystem::path getResourcePath(const std::string& resource) const; - protected: - virtual std::vector getResourceDirs() const = 0; - const std::string& getApplicationName() const { - return applicationName; - } + protected: + virtual std::vector getResourceDirs() const = 0; + const std::string& getApplicationName() const { + return applicationName; + } - private: - std::string applicationName; - }; + private: + std::string applicationName; + }; } diff --git a/SwifTools/Application/CocoaApplication.h b/SwifTools/Application/CocoaApplication.h index 2653aca..a3e281c 100644 --- a/SwifTools/Application/CocoaApplication.h +++ b/SwifTools/Application/CocoaApplication.h @@ -7,13 +7,13 @@ #pragma once namespace Swift { - class CocoaApplication { - public: - CocoaApplication(); - ~CocoaApplication(); + class CocoaApplication { + public: + CocoaApplication(); + ~CocoaApplication(); - private: - class Private; - Private* d; - }; + private: + class Private; + Private* d; + }; } diff --git a/SwifTools/Application/CocoaApplication.mm b/SwifTools/Application/CocoaApplication.mm index cbb5f2e..f879014 100644 --- a/SwifTools/Application/CocoaApplication.mm +++ b/SwifTools/Application/CocoaApplication.mm @@ -6,19 +6,19 @@ namespace Swift { class CocoaApplication::Private { - public: - NSAutoreleasePool* autoReleasePool_; + public: + NSAutoreleasePool* autoReleasePool_; }; CocoaApplication::CocoaApplication() { - d = new CocoaApplication::Private(); - NSApplicationLoad(); - d->autoReleasePool_ = [[NSAutoreleasePool alloc] init]; + d = new CocoaApplication::Private(); + NSApplicationLoad(); + d->autoReleasePool_ = [[NSAutoreleasePool alloc] init]; } CocoaApplication::~CocoaApplication() { - [d->autoReleasePool_ release]; - delete d; + [d->autoReleasePool_ release]; + delete d; } } diff --git a/SwifTools/Application/MacOSXApplicationPathProvider.cpp b/SwifTools/Application/MacOSXApplicationPathProvider.cpp index 2c35cbe..086bbaa 100644 --- a/SwifTools/Application/MacOSXApplicationPathProvider.cpp +++ b/SwifTools/Application/MacOSXApplicationPathProvider.cpp @@ -13,23 +13,23 @@ namespace Swift { MacOSXApplicationPathProvider::MacOSXApplicationPathProvider(const std::string& name) : ApplicationPathProvider(name) { - resourceDirs.push_back(getExecutableDir() / "../Resources"); - resourceDirs.push_back(getExecutableDir() / "../resources"); // Development + resourceDirs.push_back(getExecutableDir() / "../Resources"); + resourceDirs.push_back(getExecutableDir() / "../resources"); // Development } boost::filesystem::path MacOSXApplicationPathProvider::getDataDir() const { - boost::filesystem::path result(getHomeDir() / "Library/Application Support" / getApplicationName()); - try { - boost::filesystem::create_directory(result); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } - return result; + boost::filesystem::path result(getHomeDir() / "Library/Application Support" / getApplicationName()); + try { + boost::filesystem::create_directory(result); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } + return result; } boost::filesystem::path MacOSXApplicationPathProvider::getHomeDir() const { - return boost::filesystem::path(getenv("HOME")); + return boost::filesystem::path(getenv("HOME")); } } diff --git a/SwifTools/Application/MacOSXApplicationPathProvider.h b/SwifTools/Application/MacOSXApplicationPathProvider.h index 93797bc..9d8f619 100644 --- a/SwifTools/Application/MacOSXApplicationPathProvider.h +++ b/SwifTools/Application/MacOSXApplicationPathProvider.h @@ -9,18 +9,18 @@ #include namespace Swift { - class MacOSXApplicationPathProvider : public ApplicationPathProvider { - public: - MacOSXApplicationPathProvider(const std::string& name); + class MacOSXApplicationPathProvider : public ApplicationPathProvider { + public: + MacOSXApplicationPathProvider(const std::string& name); - virtual boost::filesystem::path getHomeDir() const; - boost::filesystem::path getDataDir() const; + virtual boost::filesystem::path getHomeDir() const; + boost::filesystem::path getDataDir() const; - virtual std::vector getResourceDirs() const { - return resourceDirs; - } + virtual std::vector getResourceDirs() const { + return resourceDirs; + } - private: - std::vector resourceDirs; - }; + private: + std::vector resourceDirs; + }; } diff --git a/SwifTools/Application/PlatformApplicationPathProvider.h b/SwifTools/Application/PlatformApplicationPathProvider.h index d9400a4..5de91fe 100644 --- a/SwifTools/Application/PlatformApplicationPathProvider.h +++ b/SwifTools/Application/PlatformApplicationPathProvider.h @@ -11,16 +11,16 @@ #if defined(SWIFTEN_PLATFORM_MACOSX) #include namespace Swift { - typedef MacOSXApplicationPathProvider PlatformApplicationPathProvider; + typedef MacOSXApplicationPathProvider PlatformApplicationPathProvider; } #elif defined(SWIFTEN_PLATFORM_WIN32) #include namespace Swift { - typedef WindowsApplicationPathProvider PlatformApplicationPathProvider; + typedef WindowsApplicationPathProvider PlatformApplicationPathProvider; } #else #include namespace Swift { - typedef UnixApplicationPathProvider PlatformApplicationPathProvider; + typedef UnixApplicationPathProvider PlatformApplicationPathProvider; } #endif diff --git a/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp b/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp index df59505..433b379 100644 --- a/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp +++ b/SwifTools/Application/UnitTest/ApplicationPathProviderTest.cpp @@ -18,37 +18,37 @@ using namespace Swift; class ApplicationPathProviderTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ApplicationPathProviderTest); - CPPUNIT_TEST(testGetDataDir); - CPPUNIT_TEST(testGetExecutableDir); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - testling_ = new PlatformApplicationPathProvider("SwiftTest"); - } - - void tearDown() { - delete testling_; - } - - void testGetDataDir() { - boost::filesystem::path dir = testling_->getDataDir(); - - CPPUNIT_ASSERT(boost::filesystem::exists(dir)); - CPPUNIT_ASSERT(boost::filesystem::is_directory(dir)); - - boost::filesystem::remove(dir); - } - - void testGetExecutableDir() { - boost::filesystem::path dir = testling_->getExecutableDir(); - CPPUNIT_ASSERT(boost::filesystem::is_directory(dir)); - CPPUNIT_ASSERT(boost::ends_with(pathToString(dir), "UnitTest")); - } - - private: - ApplicationPathProvider* testling_; + CPPUNIT_TEST_SUITE(ApplicationPathProviderTest); + CPPUNIT_TEST(testGetDataDir); + CPPUNIT_TEST(testGetExecutableDir); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + testling_ = new PlatformApplicationPathProvider("SwiftTest"); + } + + void tearDown() { + delete testling_; + } + + void testGetDataDir() { + boost::filesystem::path dir = testling_->getDataDir(); + + CPPUNIT_ASSERT(boost::filesystem::exists(dir)); + CPPUNIT_ASSERT(boost::filesystem::is_directory(dir)); + + boost::filesystem::remove(dir); + } + + void testGetExecutableDir() { + boost::filesystem::path dir = testling_->getExecutableDir(); + CPPUNIT_ASSERT(boost::filesystem::is_directory(dir)); + CPPUNIT_ASSERT(boost::ends_with(pathToString(dir), "UnitTest")); + } + + private: + ApplicationPathProvider* testling_; }; CPPUNIT_TEST_SUITE_REGISTRATION(ApplicationPathProviderTest); diff --git a/SwifTools/Application/UnixApplicationPathProvider.cpp b/SwifTools/Application/UnixApplicationPathProvider.cpp index 0708bb2..c561d72 100644 --- a/SwifTools/Application/UnixApplicationPathProvider.cpp +++ b/SwifTools/Application/UnixApplicationPathProvider.cpp @@ -20,45 +20,45 @@ namespace Swift { UnixApplicationPathProvider::UnixApplicationPathProvider(const std::string& name) : ApplicationPathProvider(name) { - resourceDirs.push_back(getExecutableDir() / "../resources"); // Development - resourceDirs.push_back(getExecutableDir() / ".." / "share" / boost::to_lower_copy(getApplicationName())); // Local install - char* xdgDataDirs = getenv("XDG_DATA_DIRS"); - if (xdgDataDirs) { - std::vector dataDirs = String::split(xdgDataDirs, ':'); - if (!dataDirs.empty()) { - foreach(const std::string& dir, dataDirs) { - resourceDirs.push_back(boost::filesystem::path(dir) / "swift"); - } - return; - } - } - resourceDirs.push_back("/usr/local/share/" + boost::to_lower_copy(getApplicationName())); - resourceDirs.push_back("/usr/share/" + boost::to_lower_copy(getApplicationName())); + resourceDirs.push_back(getExecutableDir() / "../resources"); // Development + resourceDirs.push_back(getExecutableDir() / ".." / "share" / boost::to_lower_copy(getApplicationName())); // Local install + char* xdgDataDirs = getenv("XDG_DATA_DIRS"); + if (xdgDataDirs) { + std::vector dataDirs = String::split(xdgDataDirs, ':'); + if (!dataDirs.empty()) { + foreach(const std::string& dir, dataDirs) { + resourceDirs.push_back(boost::filesystem::path(dir) / "swift"); + } + return; + } + } + resourceDirs.push_back("/usr/local/share/" + boost::to_lower_copy(getApplicationName())); + resourceDirs.push_back("/usr/share/" + boost::to_lower_copy(getApplicationName())); } boost::filesystem::path UnixApplicationPathProvider::getHomeDir() const { - char* home = getenv("HOME"); - return home ? boost::filesystem::path(home) : boost::filesystem::path(); + char* home = getenv("HOME"); + return home ? boost::filesystem::path(home) : boost::filesystem::path(); } boost::filesystem::path UnixApplicationPathProvider::getDataDir() const { - char* xdgDataHome = getenv("XDG_DATA_HOME"); - std::string dataDir; - if (xdgDataHome) { - dataDir = std::string(xdgDataHome); - } + char* xdgDataHome = getenv("XDG_DATA_HOME"); + std::string dataDir; + if (xdgDataHome) { + dataDir = std::string(xdgDataHome); + } - boost::filesystem::path dataPath = (dataDir.empty() ? - getHomeDir() / ".local" / "share" - : boost::filesystem::path(dataDir)) / boost::to_lower_copy(getApplicationName()); + boost::filesystem::path dataPath = (dataDir.empty() ? + getHomeDir() / ".local" / "share" + : boost::filesystem::path(dataDir)) / boost::to_lower_copy(getApplicationName()); - try { - boost::filesystem::create_directories(dataPath); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } - return dataPath; + try { + boost::filesystem::create_directories(dataPath); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } + return dataPath; } } diff --git a/SwifTools/Application/UnixApplicationPathProvider.h b/SwifTools/Application/UnixApplicationPathProvider.h index 96f4955..9e27a93 100644 --- a/SwifTools/Application/UnixApplicationPathProvider.h +++ b/SwifTools/Application/UnixApplicationPathProvider.h @@ -9,19 +9,19 @@ #include namespace Swift { - class UnixApplicationPathProvider : public ApplicationPathProvider { - public: - UnixApplicationPathProvider(const std::string& name); + class UnixApplicationPathProvider : public ApplicationPathProvider { + public: + UnixApplicationPathProvider(const std::string& name); - virtual boost::filesystem::path getHomeDir() const; - boost::filesystem::path getDataDir() const; + virtual boost::filesystem::path getHomeDir() const; + boost::filesystem::path getDataDir() const; - virtual std::vector getResourceDirs() const { - return resourceDirs; - } + virtual std::vector getResourceDirs() const { + return resourceDirs; + } - private: - std::vector resourceDirs; - }; + private: + std::vector resourceDirs; + }; } diff --git a/SwifTools/Application/WindowsApplicationPathProvider.cpp b/SwifTools/Application/WindowsApplicationPathProvider.cpp index 0b0c9cf..e90214c 100644 --- a/SwifTools/Application/WindowsApplicationPathProvider.cpp +++ b/SwifTools/Application/WindowsApplicationPathProvider.cpp @@ -15,24 +15,24 @@ namespace Swift { WindowsApplicationPathProvider::WindowsApplicationPathProvider(const std::string& name) : ApplicationPathProvider(name) { - resourceDirs.push_back(getExecutableDir()); - resourceDirs.push_back(getExecutableDir() / "../resources"); // Development + resourceDirs.push_back(getExecutableDir()); + resourceDirs.push_back(getExecutableDir() / "../resources"); // Development } boost::filesystem::path WindowsApplicationPathProvider::getDataDir() const { - wchar_t* appDirRaw = _wgetenv(L"APPDATA"); - assert(appDirRaw); - boost::filesystem::path result( - boost::filesystem::path(appDirRaw) / getApplicationName()); - boost::filesystem::create_directory(result); - return result; + wchar_t* appDirRaw = _wgetenv(L"APPDATA"); + assert(appDirRaw); + boost::filesystem::path result( + boost::filesystem::path(appDirRaw) / getApplicationName()); + boost::filesystem::create_directory(result); + return result; } boost::filesystem::path WindowsApplicationPathProvider::getHomeDir() const { - //FIXME: This should be My Documents - wchar_t* homeDirRaw = _wgetenv(L"USERPROFILE"); - assert(homeDirRaw); - return boost::filesystem::path(homeDirRaw); + //FIXME: This should be My Documents + wchar_t* homeDirRaw = _wgetenv(L"USERPROFILE"); + assert(homeDirRaw); + return boost::filesystem::path(homeDirRaw); } diff --git a/SwifTools/Application/WindowsApplicationPathProvider.h b/SwifTools/Application/WindowsApplicationPathProvider.h index 6d0f5bd..bf8dada 100644 --- a/SwifTools/Application/WindowsApplicationPathProvider.h +++ b/SwifTools/Application/WindowsApplicationPathProvider.h @@ -9,18 +9,18 @@ #include namespace Swift { - class WindowsApplicationPathProvider : public ApplicationPathProvider { - public: - WindowsApplicationPathProvider(const std::string& name); + class WindowsApplicationPathProvider : public ApplicationPathProvider { + public: + WindowsApplicationPathProvider(const std::string& name); - boost::filesystem::path getDataDir() const; - boost::filesystem::path getHomeDir() const; + boost::filesystem::path getDataDir() const; + boost::filesystem::path getHomeDir() const; - virtual std::vector getResourceDirs() const { - return resourceDirs; - } + virtual std::vector getResourceDirs() const { + return resourceDirs; + } - private: - std::vector resourceDirs; - }; + private: + std::vector resourceDirs; + }; } diff --git a/SwifTools/AutoUpdater/AutoUpdater.h b/SwifTools/AutoUpdater/AutoUpdater.h index 12abc22..dec85c9 100644 --- a/SwifTools/AutoUpdater/AutoUpdater.h +++ b/SwifTools/AutoUpdater/AutoUpdater.h @@ -7,10 +7,10 @@ #pragma once namespace Swift { - class AutoUpdater { - public: - virtual ~AutoUpdater(); + class AutoUpdater { + public: + virtual ~AutoUpdater(); - virtual void checkForUpdates() = 0; - }; + virtual void checkForUpdates() = 0; + }; } diff --git a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp index 424c6e0..f693224 100644 --- a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp +++ b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.cpp @@ -16,18 +16,18 @@ namespace Swift { bool PlatformAutoUpdaterFactory::isSupported() const { #ifdef HAVE_SPARKLE - return true; + return true; #else - return false; + return false; #endif } AutoUpdater* PlatformAutoUpdaterFactory::createAutoUpdater(const std::string& appcastURL) { #ifdef HAVE_SPARKLE - return new SparkleAutoUpdater(appcastURL); + return new SparkleAutoUpdater(appcastURL); #else - (void) appcastURL; - return NULL; + (void) appcastURL; + return NULL; #endif } diff --git a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h index 24a2f21..9942d6a 100644 --- a/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h +++ b/SwifTools/AutoUpdater/PlatformAutoUpdaterFactory.h @@ -7,12 +7,12 @@ #include namespace Swift { - class AutoUpdater; + class AutoUpdater; - class PlatformAutoUpdaterFactory { - public: - bool isSupported() const; + class PlatformAutoUpdaterFactory { + public: + bool isSupported() const; - AutoUpdater* createAutoUpdater(const std::string& appcastURL); - }; + AutoUpdater* createAutoUpdater(const std::string& appcastURL); + }; } diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdater.h b/SwifTools/AutoUpdater/SparkleAutoUpdater.h index 351d075..95ca35e 100644 --- a/SwifTools/AutoUpdater/SparkleAutoUpdater.h +++ b/SwifTools/AutoUpdater/SparkleAutoUpdater.h @@ -11,15 +11,15 @@ #include namespace Swift { - class SparkleAutoUpdater : public AutoUpdater { - public: - SparkleAutoUpdater(const std::string& url); - ~SparkleAutoUpdater(); + class SparkleAutoUpdater : public AutoUpdater { + public: + SparkleAutoUpdater(const std::string& url); + ~SparkleAutoUpdater(); - void checkForUpdates(); - - private: - class Private; - Private* d; - }; + void checkForUpdates(); + + private: + class Private; + Private* d; + }; } diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm index c35abc8..bcd1388 100644 --- a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm +++ b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm @@ -6,29 +6,29 @@ namespace Swift { class SparkleAutoUpdater::Private { - public: - SUUpdater* updater; + public: + SUUpdater* updater; }; SparkleAutoUpdater::SparkleAutoUpdater(const std::string& url) { - d = new Private; + d = new Private; - d->updater = [SUUpdater sharedUpdater]; - [d->updater retain]; - [d->updater setAutomaticallyChecksForUpdates: true]; + d->updater = [SUUpdater sharedUpdater]; + [d->updater retain]; + [d->updater setAutomaticallyChecksForUpdates: true]; - NSURL* nsurl = [NSURL URLWithString: - [NSString stringWithUTF8String: url.c_str()]]; - [d->updater setFeedURL: nsurl]; + NSURL* nsurl = [NSURL URLWithString: + [NSString stringWithUTF8String: url.c_str()]]; + [d->updater setFeedURL: nsurl]; } SparkleAutoUpdater::~SparkleAutoUpdater() { - [d->updater release]; - delete d; + [d->updater release]; + delete d; } void SparkleAutoUpdater::checkForUpdates() { - [d->updater checkForUpdatesInBackground]; + [d->updater checkForUpdatesInBackground]; } } diff --git a/SwifTools/Cocoa/CocoaAction.mm b/SwifTools/Cocoa/CocoaAction.mm index 6daba2e..341da2c 100644 --- a/SwifTools/Cocoa/CocoaAction.mm +++ b/SwifTools/Cocoa/CocoaAction.mm @@ -7,24 +7,24 @@ #include @implementation CocoaAction { - boost::function* function; + boost::function* function; } - (id) initWithFunction: (boost::function*) f { - if ((self = [super init])) { - function = f; - } - return self; + if ((self = [super init])) { + function = f; + } + return self; } - (void) dealloc { - delete function; - [super dealloc]; + delete function; + [super dealloc]; } - (void) doAction: (id) sender { - (void) sender; - (*function)(); + (void) sender; + (*function)(); } @end diff --git a/SwifTools/Cocoa/CocoaUtil.h b/SwifTools/Cocoa/CocoaUtil.h index 83d95b6..8c4dd64 100644 --- a/SwifTools/Cocoa/CocoaUtil.h +++ b/SwifTools/Cocoa/CocoaUtil.h @@ -11,37 +11,37 @@ namespace { inline std::string ns2StdString(NSString* _Nullable nsString); inline std::string ns2StdString(NSString* _Nullable nsString) { - std::string stdString; - if (nsString != nil) { - stdString = std::string([nsString cStringUsingEncoding:NSUTF8StringEncoding]); - } - return stdString; + std::string stdString; + if (nsString != nil) { + stdString = std::string([nsString cStringUsingEncoding:NSUTF8StringEncoding]); + } + return stdString; } inline NSString* _Nonnull std2NSString(const std::string& stdString); inline NSString* _Nonnull std2NSString(const std::string& stdString) { - NSString* _Nullable nsString = [NSString stringWithUTF8String:stdString.c_str()]; - if (nsString == nil) { - nsString = @""; - } - // At this point nsString is guaranteed to be not null/nil. - return static_cast(nsString); + NSString* _Nullable nsString = [NSString stringWithUTF8String:stdString.c_str()]; + if (nsString == nil) { + nsString = @""; + } + // At this point nsString is guaranteed to be not null/nil. + return static_cast(nsString); } } // Intrusive pointer for NSObjects -namespace boost { - inline void intrusive_ptr_add_ref(NSObject* _Nonnull object) { - [object retain]; - } - - inline void intrusive_ptr_release(NSObject* _Nonnull object) { - [object release]; - } +namespace boost { + inline void intrusive_ptr_add_ref(NSObject* _Nonnull object) { + [object retain]; + } + + inline void intrusive_ptr_release(NSObject* _Nonnull object) { + [object release]; + } } -// Including intrusive_ptr after ref/release methods to avoid compilation +// Including intrusive_ptr after ref/release methods to avoid compilation // errors with CLang #include diff --git a/SwifTools/CrashReporter.cpp b/SwifTools/CrashReporter.cpp index 35db605..b401e76 100644 --- a/SwifTools/CrashReporter.cpp +++ b/SwifTools/CrashReporter.cpp @@ -24,46 +24,46 @@ #if defined(SWIFTEN_PLATFORM_WINDOWS) static bool handleDump(const wchar_t* /* dir */, const wchar_t* /* id*/, void* /* context */, EXCEPTION_POINTERS*, MDRawAssertionInfo*, bool /* succeeded */) { - return false; + return false; } #else static bool handleDump(const char* /* dir */, const char* /* id*/, void* /* context */, bool /* succeeded */) { - return false; + return false; } #endif namespace Swift { struct CrashReporter::Private { - boost::shared_ptr handler; + boost::shared_ptr handler; }; CrashReporter::CrashReporter(const boost::filesystem::path& path) { - // Create the path that will contain the crash dumps - if (!boost::filesystem::exists(path)) { - try { - boost::filesystem::create_directories(path); - } - catch (const boost::filesystem::filesystem_error& e) { - SWIFT_LOG(error) << "ERROR: " << e.what() << std::endl; - } - } + // Create the path that will contain the crash dumps + if (!boost::filesystem::exists(path)) { + try { + boost::filesystem::create_directories(path); + } + catch (const boost::filesystem::filesystem_error& e) { + SWIFT_LOG(error) << "ERROR: " << e.what() << std::endl; + } + } - p = boost::make_shared(); + p = boost::make_shared(); #if defined(SWIFTEN_PLATFORM_WINDOWS) - // FIXME: Need UTF8 conversion from string to wstring - std::string pathString = pathToString(path); - p->handler = boost::shared_ptr( - // Not using make_shared, because 'handleDump' seems to have problems with VC2010 - new google_breakpad::ExceptionHandler( - std::wstring(pathString.begin(), pathString.end()), - (google_breakpad::ExceptionHandler::FilterCallback) 0, - handleDump, - (void*) 0, - google_breakpad::ExceptionHandler::HANDLER_ALL)); + // FIXME: Need UTF8 conversion from string to wstring + std::string pathString = pathToString(path); + p->handler = boost::shared_ptr( + // Not using make_shared, because 'handleDump' seems to have problems with VC2010 + new google_breakpad::ExceptionHandler( + std::wstring(pathString.begin(), pathString.end()), + (google_breakpad::ExceptionHandler::FilterCallback) 0, + handleDump, + (void*) 0, + google_breakpad::ExceptionHandler::HANDLER_ALL)); // Turning it off for Mac, because it doesn't really help us //#elif defined(SWIFTEN_PLATFORM_MACOSX) -// p->handler = boost::make_shared(pathToString(path), (google_breakpad::ExceptionHandler::FilterCallback) 0, handleDump, (void*) 0, true, (const char*) 0); +// p->handler = boost::make_shared(pathToString(path), (google_breakpad::ExceptionHandler::FilterCallback) 0, handleDump, (void*) 0, true, (const char*) 0); #endif } @@ -73,7 +73,7 @@ CrashReporter::CrashReporter(const boost::filesystem::path& path) { // Dummy implementation namespace Swift { - CrashReporter::CrashReporter(const boost::filesystem::path&) {} + CrashReporter::CrashReporter(const boost::filesystem::path&) {} } #endif diff --git a/SwifTools/CrashReporter.h b/SwifTools/CrashReporter.h index cce6c43..ee71223 100644 --- a/SwifTools/CrashReporter.h +++ b/SwifTools/CrashReporter.h @@ -12,12 +12,12 @@ #include namespace Swift { - class CrashReporter { - public: - CrashReporter(const boost::filesystem::path& path); + class CrashReporter { + public: + CrashReporter(const boost::filesystem::path& path); - private: - struct Private; - boost::shared_ptr p; - }; + private: + struct Private; + boost::shared_ptr p; + }; } diff --git a/SwifTools/Dock/Dock.h b/SwifTools/Dock/Dock.h index cf7ee5f..6120445 100644 --- a/SwifTools/Dock/Dock.h +++ b/SwifTools/Dock/Dock.h @@ -7,12 +7,12 @@ #pragma once namespace Swift { - - class Dock { - public: - virtual ~Dock(); - virtual void setNumberOfPendingMessages(int i) = 0; - }; + class Dock { + public: + virtual ~Dock(); + + virtual void setNumberOfPendingMessages(int i) = 0; + }; } diff --git a/SwifTools/Dock/MacOSXDock.h b/SwifTools/Dock/MacOSXDock.h index 60347fb..6b33506 100644 --- a/SwifTools/Dock/MacOSXDock.h +++ b/SwifTools/Dock/MacOSXDock.h @@ -9,13 +9,13 @@ #include namespace Swift { - - class CocoaApplication; - class MacOSXDock : public Dock { - public: - MacOSXDock(CocoaApplication* application); + class CocoaApplication; - virtual void setNumberOfPendingMessages(int i); - }; + class MacOSXDock : public Dock { + public: + MacOSXDock(CocoaApplication* application); + + virtual void setNumberOfPendingMessages(int i); + }; } diff --git a/SwifTools/Dock/MacOSXDock.mm b/SwifTools/Dock/MacOSXDock.mm index f231e9a..5c7207c 100644 --- a/SwifTools/Dock/MacOSXDock.mm +++ b/SwifTools/Dock/MacOSXDock.mm @@ -19,11 +19,11 @@ MacOSXDock::MacOSXDock(CocoaApplication*) { } void MacOSXDock::setNumberOfPendingMessages(int i) { - std::string label(i > 0 ? boost::lexical_cast(i) : ""); - NSString *labelString = [[NSString alloc] initWithUTF8String: label.c_str()]; - [[NSApp dockTile] setBadgeLabel: labelString]; - [labelString release]; - [NSApp requestUserAttention: NSInformationalRequest]; + std::string label(i > 0 ? boost::lexical_cast(i) : ""); + NSString *labelString = [[NSString alloc] initWithUTF8String: label.c_str()]; + [[NSApp dockTile] setBadgeLabel: labelString]; + [labelString release]; + [NSApp requestUserAttention: NSInformationalRequest]; } } diff --git a/SwifTools/Dock/NullDock.h b/SwifTools/Dock/NullDock.h index e4433f6..9f3c554 100644 --- a/SwifTools/Dock/NullDock.h +++ b/SwifTools/Dock/NullDock.h @@ -9,11 +9,11 @@ #include namespace Swift { - class NullDock : public Dock { - public: - NullDock() {} + class NullDock : public Dock { + public: + NullDock() {} - virtual void setNumberOfPendingMessages(int) { - } - }; + virtual void setNumberOfPendingMessages(int) { + } + }; } diff --git a/SwifTools/Dock/WindowsDock.h b/SwifTools/Dock/WindowsDock.h index 07b0eff..fc10a48 100644 --- a/SwifTools/Dock/WindowsDock.h +++ b/SwifTools/Dock/WindowsDock.h @@ -14,30 +14,30 @@ #include namespace Swift { - class WindowsDock : public Dock { - public: - WindowsDock(QSystemTrayIcon* tray, Notifier* notifier) : tray(tray), notifier(notifier) {} - - virtual void setNumberOfPendingMessages(int i) { - if (notifier->isAvailable()) { - return; - } - - if (i > 0) { - std::string message = boost::lexical_cast(i) + " new message"; - if (i > 1) { - message += "s"; - } - message += " received."; - tray->showMessage("New messages", message.c_str(), QSystemTrayIcon::NoIcon); - } - else { - tray->showMessage("", "", QSystemTrayIcon::NoIcon, 0); - } - } - - private: - QSystemTrayIcon* tray; - Notifier* notifier; - }; + class WindowsDock : public Dock { + public: + WindowsDock(QSystemTrayIcon* tray, Notifier* notifier) : tray(tray), notifier(notifier) {} + + virtual void setNumberOfPendingMessages(int i) { + if (notifier->isAvailable()) { + return; + } + + if (i > 0) { + std::string message = boost::lexical_cast(i) + " new message"; + if (i > 1) { + message += "s"; + } + message += " received."; + tray->showMessage("New messages", message.c_str(), QSystemTrayIcon::NoIcon); + } + else { + tray->showMessage("", "", QSystemTrayIcon::NoIcon, 0); + } + } + + private: + QSystemTrayIcon* tray; + Notifier* notifier; + }; } diff --git a/SwifTools/HunspellChecker.cpp b/SwifTools/HunspellChecker.cpp index 2fe7a21..fb1a5d6 100644 --- a/SwifTools/HunspellChecker.cpp +++ b/SwifTools/HunspellChecker.cpp @@ -21,44 +21,44 @@ namespace Swift { HunspellChecker::HunspellChecker(const char* affix_path, const char* dictionary_path) { - speller_ = new Hunspell(affix_path, dictionary_path); + speller_ = new Hunspell(affix_path, dictionary_path); } HunspellChecker::~HunspellChecker() { - delete speller_; + delete speller_; } bool HunspellChecker::isCorrect(const std::string& word) { - return speller_->spell(word.c_str()); + return speller_->spell(word.c_str()); } void HunspellChecker::getSuggestions(const std::string& word, std::vector& list) { - char **suggestList = NULL; - int words_returned = 0; - if (!word.empty()) { - words_returned = speller_->suggest(&suggestList, word.c_str()); - if (suggestList != NULL) { - for (int i = 0; i < words_returned; ++i) { - list.push_back(suggestList[i]); - free(suggestList[i]); - } - free(suggestList); - } - } + char **suggestList = NULL; + int words_returned = 0; + if (!word.empty()) { + words_returned = speller_->suggest(&suggestList, word.c_str()); + if (suggestList != NULL) { + for (int i = 0; i < words_returned; ++i) { + list.push_back(suggestList[i]); + free(suggestList[i]); + } + free(suggestList); + } + } } void HunspellChecker::checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) { - if (!fragment.empty()) { - parser_->check(fragment, misspelledPositions); - for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end();) { - if (isCorrect(fragment.substr(boost::get<0>(*it), boost::get<1>(*it) - boost::get<0>(*it)))) { - it = misspelledPositions.erase(it); - } - else { - ++it; - } - } - } + if (!fragment.empty()) { + parser_->check(fragment, misspelledPositions); + for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end();) { + if (isCorrect(fragment.substr(boost::get<0>(*it), boost::get<1>(*it) - boost::get<0>(*it)))) { + it = misspelledPositions.erase(it); + } + else { + ++it; + } + } + } } } diff --git a/SwifTools/HunspellChecker.h b/SwifTools/HunspellChecker.h index 689e0e7..076b468 100644 --- a/SwifTools/HunspellChecker.h +++ b/SwifTools/HunspellChecker.h @@ -22,14 +22,14 @@ class Hunspell; namespace Swift { - class HunspellChecker : public SpellChecker { - public: - HunspellChecker(const char* affix_path, const char* dict_path); - virtual ~HunspellChecker(); - virtual bool isCorrect(const std::string& word); - virtual void getSuggestions(const std::string& word, std::vector& list); - virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions); - private: - Hunspell* speller_; - }; + class HunspellChecker : public SpellChecker { + public: + HunspellChecker(const char* affix_path, const char* dict_path); + virtual ~HunspellChecker(); + virtual bool isCorrect(const std::string& word); + virtual void getSuggestions(const std::string& word, std::vector& list); + virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions); + private: + Hunspell* speller_; + }; } diff --git a/SwifTools/Idle/ActualIdleDetector.cpp b/SwifTools/Idle/ActualIdleDetector.cpp index dac4a5e..2a16fca 100644 --- a/SwifTools/Idle/ActualIdleDetector.cpp +++ b/SwifTools/Idle/ActualIdleDetector.cpp @@ -16,20 +16,20 @@ namespace Swift { ActualIdleDetector::ActualIdleDetector(IdleQuerier* querier, TimerFactory* timerFactory, int refreshRateMilliseconds) : querier(querier) { - timer = timerFactory->createTimer(refreshRateMilliseconds); - timer->onTick.connect(boost::bind(&ActualIdleDetector::handleTimerTick, this)); - timer->start(); + timer = timerFactory->createTimer(refreshRateMilliseconds); + timer->onTick.connect(boost::bind(&ActualIdleDetector::handleTimerTick, this)); + timer->start(); } ActualIdleDetector::~ActualIdleDetector() { - timer->onTick.disconnect(boost::bind(&ActualIdleDetector::handleTimerTick, this)); - timer->stop(); + timer->onTick.disconnect(boost::bind(&ActualIdleDetector::handleTimerTick, this)); + timer->stop(); } void ActualIdleDetector::handleTimerTick() { - timer->stop(); - setIdle(querier->getIdleTimeSeconds() >= getIdleTimeSeconds()); - timer->start(); + timer->stop(); + setIdle(querier->getIdleTimeSeconds() >= getIdleTimeSeconds()); + timer->start(); } } diff --git a/SwifTools/Idle/ActualIdleDetector.h b/SwifTools/Idle/ActualIdleDetector.h index 739a005..194606f 100644 --- a/SwifTools/Idle/ActualIdleDetector.h +++ b/SwifTools/Idle/ActualIdleDetector.h @@ -11,20 +11,20 @@ #include namespace Swift { - class IdleQuerier; - class TimerFactory; - class Timer; + class IdleQuerier; + class TimerFactory; + class Timer; - class ActualIdleDetector : public IdleDetector, public boost::bsignals::trackable { - public: - ActualIdleDetector(IdleQuerier*, TimerFactory*, int refreshRateMilliseconds); - ~ActualIdleDetector(); + class ActualIdleDetector : public IdleDetector, public boost::bsignals::trackable { + public: + ActualIdleDetector(IdleQuerier*, TimerFactory*, int refreshRateMilliseconds); + ~ActualIdleDetector(); - private: - void handleTimerTick(); + private: + void handleTimerTick(); - private: - IdleQuerier* querier; - boost::shared_ptr timer; - }; + private: + IdleQuerier* querier; + boost::shared_ptr timer; + }; } diff --git a/SwifTools/Idle/DummyIdleQuerier.h b/SwifTools/Idle/DummyIdleQuerier.h index 068d9ad..d3f5177 100644 --- a/SwifTools/Idle/DummyIdleQuerier.h +++ b/SwifTools/Idle/DummyIdleQuerier.h @@ -9,12 +9,12 @@ #include namespace Swift { - class DummyIdleQuerier : public IdleQuerier { - public: - DummyIdleQuerier() {} + class DummyIdleQuerier : public IdleQuerier { + public: + DummyIdleQuerier() {} - virtual int getIdleTimeSeconds() { - return 0; - } - }; + virtual int getIdleTimeSeconds() { + return 0; + } + }; } diff --git a/SwifTools/Idle/IdleDetector.h b/SwifTools/Idle/IdleDetector.h index 7819f54..88a1c4c 100644 --- a/SwifTools/Idle/IdleDetector.h +++ b/SwifTools/Idle/IdleDetector.h @@ -11,34 +11,34 @@ #include namespace Swift { - class IdleDetector { - public: - IdleDetector() : idle(false), idleTimeSeconds(300) {} - virtual ~IdleDetector(); - - void setIdleTimeSeconds(int time) { - idleTimeSeconds = time; - } - - int getIdleTimeSeconds() const { - return idleTimeSeconds; - } - - virtual bool isIdle() const { - return idle; - } - - boost::signal onIdleChanged; - - void setIdle(bool b) { - if (b != idle) { - idle = b; - onIdleChanged(b); - } - } - - private: - bool idle; - int idleTimeSeconds; - }; + class IdleDetector { + public: + IdleDetector() : idle(false), idleTimeSeconds(300) {} + virtual ~IdleDetector(); + + void setIdleTimeSeconds(int time) { + idleTimeSeconds = time; + } + + int getIdleTimeSeconds() const { + return idleTimeSeconds; + } + + virtual bool isIdle() const { + return idle; + } + + boost::signal onIdleChanged; + + void setIdle(bool b) { + if (b != idle) { + idle = b; + onIdleChanged(b); + } + } + + private: + bool idle; + int idleTimeSeconds; + }; } diff --git a/SwifTools/Idle/IdleQuerier.h b/SwifTools/Idle/IdleQuerier.h index ba4879d..e0de8be 100644 --- a/SwifTools/Idle/IdleQuerier.h +++ b/SwifTools/Idle/IdleQuerier.h @@ -7,10 +7,10 @@ #pragma once namespace Swift { - class IdleQuerier { - public: - virtual ~IdleQuerier(); + class IdleQuerier { + public: + virtual ~IdleQuerier(); - virtual int getIdleTimeSeconds() = 0; - }; + virtual int getIdleTimeSeconds() = 0; + }; } diff --git a/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp b/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp index 365ed1a..a0b78e6 100644 --- a/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp +++ b/SwifTools/Idle/IdleQuerierTest/IdleQuerierTest.cpp @@ -14,11 +14,11 @@ using namespace Swift; int main() { - PlatformIdleQuerier querier; - while (true) { - std::cout << "Idle time: " << querier.getIdleTimeSeconds() << std::endl; - Swift::sleep(1000); - } - assert(false); - return 0; + PlatformIdleQuerier querier; + while (true) { + std::cout << "Idle time: " << querier.getIdleTimeSeconds() << std::endl; + Swift::sleep(1000); + } + assert(false); + return 0; } diff --git a/SwifTools/Idle/MacOSXIdleQuerier.cpp b/SwifTools/Idle/MacOSXIdleQuerier.cpp index f7d4199..6d6780b 100644 --- a/SwifTools/Idle/MacOSXIdleQuerier.cpp +++ b/SwifTools/Idle/MacOSXIdleQuerier.cpp @@ -16,20 +16,20 @@ namespace Swift { MacOSXIdleQuerier::MacOSXIdleQuerier() : ioService(0) { - mach_port_t masterPort; - IOMasterPort(MACH_PORT_NULL, &masterPort); - ioService = IOServiceGetMatchingService(masterPort, IOServiceMatching("IOHIDSystem")); - assert(ioService); + mach_port_t masterPort; + IOMasterPort(MACH_PORT_NULL, &masterPort); + ioService = IOServiceGetMatchingService(masterPort, IOServiceMatching("IOHIDSystem")); + assert(ioService); } int MacOSXIdleQuerier::getIdleTimeSeconds() { - CFTypeRef property = IORegistryEntryCreateCFProperty(ioService, CFSTR("HIDIdleTime"), kCFAllocatorDefault, 0); - uint64_t idle = 0; - bool result = CFNumberGetValue((CFNumberRef)property, kCFNumberSInt64Type, &idle); - assert(result); - (void) result; - CFRelease(property); - return boost::numeric_cast(idle / 1000000000); + CFTypeRef property = IORegistryEntryCreateCFProperty(ioService, CFSTR("HIDIdleTime"), kCFAllocatorDefault, 0); + uint64_t idle = 0; + bool result = CFNumberGetValue((CFNumberRef)property, kCFNumberSInt64Type, &idle); + assert(result); + (void) result; + CFRelease(property); + return boost::numeric_cast(idle / 1000000000); } } diff --git a/SwifTools/Idle/MacOSXIdleQuerier.h b/SwifTools/Idle/MacOSXIdleQuerier.h index 7f70e88..8ff747c 100644 --- a/SwifTools/Idle/MacOSXIdleQuerier.h +++ b/SwifTools/Idle/MacOSXIdleQuerier.h @@ -11,13 +11,13 @@ #include namespace Swift { - class MacOSXIdleQuerier : public IdleQuerier { - public: - MacOSXIdleQuerier(); + class MacOSXIdleQuerier : public IdleQuerier { + public: + MacOSXIdleQuerier(); - virtual int getIdleTimeSeconds(); + virtual int getIdleTimeSeconds(); - private: - io_service_t ioService; - }; + private: + io_service_t ioService; + }; } diff --git a/SwifTools/Idle/PlatformIdleQuerier.cpp b/SwifTools/Idle/PlatformIdleQuerier.cpp index bf8f778..5855749 100644 --- a/SwifTools/Idle/PlatformIdleQuerier.cpp +++ b/SwifTools/Idle/PlatformIdleQuerier.cpp @@ -24,21 +24,21 @@ namespace Swift { PlatformIdleQuerier::PlatformIdleQuerier() : querier(NULL) { #if defined(SWIFTEN_PLATFORM_MACOSX) #if defined(HAVE_IOKIT) && !defined(SWIFTEN_PLATFORM_IPHONE) - querier = new MacOSXIdleQuerier(); + querier = new MacOSXIdleQuerier(); #else - querier = new DummyIdleQuerier(); + querier = new DummyIdleQuerier(); #endif #elif defined(SWIFTEN_PLATFORM_WINDOWS) - querier = new WindowsIdleQuerier(); + querier = new WindowsIdleQuerier(); #elif defined(HAVE_XSS) - querier = new XSSIdleQuerier(); + querier = new XSSIdleQuerier(); #else - querier = new DummyIdleQuerier(); + querier = new DummyIdleQuerier(); #endif } PlatformIdleQuerier::~PlatformIdleQuerier() { - delete querier; + delete querier; } } diff --git a/SwifTools/Idle/PlatformIdleQuerier.h b/SwifTools/Idle/PlatformIdleQuerier.h index 676dad0..1221ada 100644 --- a/SwifTools/Idle/PlatformIdleQuerier.h +++ b/SwifTools/Idle/PlatformIdleQuerier.h @@ -9,16 +9,16 @@ #include namespace Swift { - class PlatformIdleQuerier : public IdleQuerier { - public: - PlatformIdleQuerier(); - ~PlatformIdleQuerier(); + class PlatformIdleQuerier : public IdleQuerier { + public: + PlatformIdleQuerier(); + ~PlatformIdleQuerier(); - virtual int getIdleTimeSeconds() { - return querier->getIdleTimeSeconds(); - } + virtual int getIdleTimeSeconds() { + return querier->getIdleTimeSeconds(); + } - private: - IdleQuerier* querier; - }; + private: + IdleQuerier* querier; + }; } diff --git a/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp b/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp index c97705e..8af66fc 100644 --- a/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp +++ b/SwifTools/Idle/UnitTest/ActualIdleDetectorTest.cpp @@ -19,154 +19,154 @@ using namespace Swift; class ActualIdleDetectorTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ActualIdleDetectorTest); - CPPUNIT_TEST(testDestructor); - CPPUNIT_TEST(testHandleTick_Idle); - CPPUNIT_TEST(testHandleTick_Idle_AlreadyIdle); - CPPUNIT_TEST(testHandleTick_NotIdle); - CPPUNIT_TEST(testHandleTick_NotIdle_AlreadyNotIdle); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - querier = new MockIdleQuerier(); - timerFactory = new MockTimerFactory(); - idleEvents.clear(); - } - - void tearDown() { - delete timerFactory; - delete querier; - } - - void testDestructor() { - ActualIdleDetector* testling = createDetector(); - testling->setIdleTimeSeconds(15); - delete testling; - - querier->idleTime = 15; - timerFactory->updateTime(15000); - - CPPUNIT_ASSERT_EQUAL(0, static_cast(idleEvents.size())); - } - - void testHandleTick_Idle() { - std::auto_ptr testling(createDetector()); - testling->setIdleTimeSeconds(15); - querier->idleTime = 15; - - timerFactory->updateTime(15000); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(idleEvents.size())); - CPPUNIT_ASSERT(idleEvents[0]); - } - - void testHandleTick_Idle_AlreadyIdle() { - std::auto_ptr testling(createDetector()); - testling->setIdleTimeSeconds(15); - querier->idleTime = 15; - timerFactory->updateTime(15000); - - querier->idleTime = 30; - timerFactory->updateTime(30000); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(idleEvents.size())); - CPPUNIT_ASSERT(idleEvents[0]); - } - - void testHandleTick_NotIdle() { - std::auto_ptr testling(createDetector()); - testling->setIdleTimeSeconds(15); - querier->idleTime = 15; - timerFactory->updateTime(15000); - - querier->idleTime = 5; - timerFactory->updateTime(30000); - - CPPUNIT_ASSERT_EQUAL(2, static_cast(idleEvents.size())); - CPPUNIT_ASSERT(idleEvents[0]); - CPPUNIT_ASSERT(!idleEvents[1]); - } - - void testHandleTick_NotIdle_AlreadyNotIdle() { - std::auto_ptr testling(createDetector()); - testling->setIdleTimeSeconds(15); - querier->idleTime = 5; - - timerFactory->updateTime(15000); - - CPPUNIT_ASSERT_EQUAL(0, static_cast(idleEvents.size())); - } - - private: - ActualIdleDetector* createDetector() { - ActualIdleDetector* detector = new ActualIdleDetector(querier, timerFactory, 10); - detector->onIdleChanged.connect(boost::bind(&ActualIdleDetectorTest::handleIdle, this, _1)); - return detector; - } - - void handleIdle(bool b) { - idleEvents.push_back(b); - } - - private: - struct MockIdleQuerier : public IdleQuerier { - MockIdleQuerier() : idleTime(0) {} - virtual int getIdleTimeSeconds() { return idleTime; } - int idleTime; - }; - - struct MockTimer : public Timer { - MockTimer(int interval) : interval(interval), running(false), lastTime(0) {} - - virtual void start() { - running = true; - } - - virtual void stop() { - running = false; - } - - virtual void updateTime(int currentTime) { - if (lastTime == currentTime) { - return; - } - if (running) { - int time = lastTime; - while (time <= currentTime) { - onTick(); - time += interval; - } - } - lastTime = currentTime; - } - - int interval; - bool running; - int lastTime; - }; - - struct MockTimerFactory : public TimerFactory { - MockTimerFactory() {} - - void updateTime(int milliseconds) { - foreach(boost::shared_ptr timer, timers) { - timer->updateTime(milliseconds); - } - } - - boost::shared_ptr createTimer(int milliseconds) { - boost::shared_ptr timer(new MockTimer(milliseconds)); - timers.push_back(timer); - return timer; - } - - std::vector > timers; - }; - - MockIdleQuerier* querier; - MockTimerFactory* timerFactory; - std::vector idleEvents; + CPPUNIT_TEST_SUITE(ActualIdleDetectorTest); + CPPUNIT_TEST(testDestructor); + CPPUNIT_TEST(testHandleTick_Idle); + CPPUNIT_TEST(testHandleTick_Idle_AlreadyIdle); + CPPUNIT_TEST(testHandleTick_NotIdle); + CPPUNIT_TEST(testHandleTick_NotIdle_AlreadyNotIdle); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + querier = new MockIdleQuerier(); + timerFactory = new MockTimerFactory(); + idleEvents.clear(); + } + + void tearDown() { + delete timerFactory; + delete querier; + } + + void testDestructor() { + ActualIdleDetector* testling = createDetector(); + testling->setIdleTimeSeconds(15); + delete testling; + + querier->idleTime = 15; + timerFactory->updateTime(15000); + + CPPUNIT_ASSERT_EQUAL(0, static_cast(idleEvents.size())); + } + + void testHandleTick_Idle() { + std::auto_ptr testling(createDetector()); + testling->setIdleTimeSeconds(15); + querier->idleTime = 15; + + timerFactory->updateTime(15000); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(idleEvents.size())); + CPPUNIT_ASSERT(idleEvents[0]); + } + + void testHandleTick_Idle_AlreadyIdle() { + std::auto_ptr testling(createDetector()); + testling->setIdleTimeSeconds(15); + querier->idleTime = 15; + timerFactory->updateTime(15000); + + querier->idleTime = 30; + timerFactory->updateTime(30000); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(idleEvents.size())); + CPPUNIT_ASSERT(idleEvents[0]); + } + + void testHandleTick_NotIdle() { + std::auto_ptr testling(createDetector()); + testling->setIdleTimeSeconds(15); + querier->idleTime = 15; + timerFactory->updateTime(15000); + + querier->idleTime = 5; + timerFactory->updateTime(30000); + + CPPUNIT_ASSERT_EQUAL(2, static_cast(idleEvents.size())); + CPPUNIT_ASSERT(idleEvents[0]); + CPPUNIT_ASSERT(!idleEvents[1]); + } + + void testHandleTick_NotIdle_AlreadyNotIdle() { + std::auto_ptr testling(createDetector()); + testling->setIdleTimeSeconds(15); + querier->idleTime = 5; + + timerFactory->updateTime(15000); + + CPPUNIT_ASSERT_EQUAL(0, static_cast(idleEvents.size())); + } + + private: + ActualIdleDetector* createDetector() { + ActualIdleDetector* detector = new ActualIdleDetector(querier, timerFactory, 10); + detector->onIdleChanged.connect(boost::bind(&ActualIdleDetectorTest::handleIdle, this, _1)); + return detector; + } + + void handleIdle(bool b) { + idleEvents.push_back(b); + } + + private: + struct MockIdleQuerier : public IdleQuerier { + MockIdleQuerier() : idleTime(0) {} + virtual int getIdleTimeSeconds() { return idleTime; } + int idleTime; + }; + + struct MockTimer : public Timer { + MockTimer(int interval) : interval(interval), running(false), lastTime(0) {} + + virtual void start() { + running = true; + } + + virtual void stop() { + running = false; + } + + virtual void updateTime(int currentTime) { + if (lastTime == currentTime) { + return; + } + if (running) { + int time = lastTime; + while (time <= currentTime) { + onTick(); + time += interval; + } + } + lastTime = currentTime; + } + + int interval; + bool running; + int lastTime; + }; + + struct MockTimerFactory : public TimerFactory { + MockTimerFactory() {} + + void updateTime(int milliseconds) { + foreach(boost::shared_ptr timer, timers) { + timer->updateTime(milliseconds); + } + } + + boost::shared_ptr createTimer(int milliseconds) { + boost::shared_ptr timer(new MockTimer(milliseconds)); + timers.push_back(timer); + return timer; + } + + std::vector > timers; + }; + + MockIdleQuerier* querier; + MockTimerFactory* timerFactory; + std::vector idleEvents; }; CPPUNIT_TEST_SUITE_REGISTRATION(ActualIdleDetectorTest); diff --git a/SwifTools/Idle/WindowsIdleQuerier.cpp b/SwifTools/Idle/WindowsIdleQuerier.cpp index ef1738b..f766436 100644 --- a/SwifTools/Idle/WindowsIdleQuerier.cpp +++ b/SwifTools/Idle/WindowsIdleQuerier.cpp @@ -14,14 +14,14 @@ WindowsIdleQuerier::WindowsIdleQuerier() { } int WindowsIdleQuerier::getIdleTimeSeconds() { - LASTINPUTINFO info; - info.cbSize = sizeof(info); - if (GetLastInputInfo(&info)) { - return (GetTickCount() - info.dwTime) / 1000; - } - else { - return 0; - } + LASTINPUTINFO info; + info.cbSize = sizeof(info); + if (GetLastInputInfo(&info)) { + return (GetTickCount() - info.dwTime) / 1000; + } + else { + return 0; + } } } diff --git a/SwifTools/Idle/WindowsIdleQuerier.h b/SwifTools/Idle/WindowsIdleQuerier.h index 557ecab..198c6e9 100644 --- a/SwifTools/Idle/WindowsIdleQuerier.h +++ b/SwifTools/Idle/WindowsIdleQuerier.h @@ -9,10 +9,10 @@ #include namespace Swift { - class WindowsIdleQuerier : public IdleQuerier { - public: - WindowsIdleQuerier(); + class WindowsIdleQuerier : public IdleQuerier { + public: + WindowsIdleQuerier(); - virtual int getIdleTimeSeconds(); - }; + virtual int getIdleTimeSeconds(); + }; } diff --git a/SwifTools/Idle/XSSIdleQuerier.cpp b/SwifTools/Idle/XSSIdleQuerier.cpp index 883f76f..03c5330 100644 --- a/SwifTools/Idle/XSSIdleQuerier.cpp +++ b/SwifTools/Idle/XSSIdleQuerier.cpp @@ -14,31 +14,31 @@ namespace Swift { XSSIdleQuerier::XSSIdleQuerier() : display(NULL), info(NULL) { - display = XOpenDisplay(NULL); - assert(display); - rootWindow = DefaultRootWindow(display); - int event, error; - available = XScreenSaverQueryExtension(display, &event, &error); - if (available) { - info = XScreenSaverAllocInfo(); - } - else { - std::cerr << "Warning: XScreenSaver extension not found. Idle time detection will not work." << std::endl; - } + display = XOpenDisplay(NULL); + assert(display); + rootWindow = DefaultRootWindow(display); + int event, error; + available = XScreenSaverQueryExtension(display, &event, &error); + if (available) { + info = XScreenSaverAllocInfo(); + } + else { + std::cerr << "Warning: XScreenSaver extension not found. Idle time detection will not work." << std::endl; + } } XSSIdleQuerier::~XSSIdleQuerier() { - XFree(info); + XFree(info); } int XSSIdleQuerier::getIdleTimeSeconds() { - if (available) { - XScreenSaverQueryInfo(display, rootWindow, info); - return info->idle / 1000; - } - else { - return 0; - } + if (available) { + XScreenSaverQueryInfo(display, rootWindow, info); + return info->idle / 1000; + } + else { + return 0; + } } } diff --git a/SwifTools/Idle/XSSIdleQuerier.h b/SwifTools/Idle/XSSIdleQuerier.h index ae5a502..225f781 100644 --- a/SwifTools/Idle/XSSIdleQuerier.h +++ b/SwifTools/Idle/XSSIdleQuerier.h @@ -12,17 +12,17 @@ #include namespace Swift { - class XSSIdleQuerier : public IdleQuerier { - public: - XSSIdleQuerier(); - ~XSSIdleQuerier(); + class XSSIdleQuerier : public IdleQuerier { + public: + XSSIdleQuerier(); + ~XSSIdleQuerier(); - virtual int getIdleTimeSeconds(); + virtual int getIdleTimeSeconds(); - private: - Display* display; - Window rootWindow; - bool available; - XScreenSaverInfo* info; - }; + private: + Display* display; + Window rootWindow; + bool available; + XScreenSaverInfo* info; + }; } diff --git a/SwifTools/LastLineTracker.cpp b/SwifTools/LastLineTracker.cpp index 9428ff4..b9f1aa3 100644 --- a/SwifTools/LastLineTracker.cpp +++ b/SwifTools/LastLineTracker.cpp @@ -15,22 +15,22 @@ using namespace Swift; LastLineTracker::LastLineTracker() { - lastFocus = true; - shouldMove = false; + lastFocus = true; + shouldMove = false; } void LastLineTracker::setHasFocus(bool focus) { - if (!focus && lastFocus) { - shouldMove = true; - lastFocus = focus; - return; - } - shouldMove = false; - lastFocus = focus; + if (!focus && lastFocus) { + shouldMove = true; + lastFocus = focus; + return; + } + shouldMove = false; + lastFocus = focus; } bool LastLineTracker::getShouldMoveLastLine() { - bool ret = shouldMove; - shouldMove = false; - return ret; + bool ret = shouldMove; + shouldMove = false; + return ret; } diff --git a/SwifTools/LastLineTracker.h b/SwifTools/LastLineTracker.h index b7c9a3b..7156ec3 100644 --- a/SwifTools/LastLineTracker.h +++ b/SwifTools/LastLineTracker.h @@ -7,13 +7,13 @@ #pragma once namespace Swift { - class LastLineTracker { - public: - LastLineTracker(); - void setHasFocus(bool focus); - bool getShouldMoveLastLine(); - private: - bool lastFocus; - bool shouldMove; - }; + class LastLineTracker { + public: + LastLineTracker(); + void setHasFocus(bool focus); + bool getShouldMoveLastLine(); + private: + bool lastFocus; + bool shouldMove; + }; } diff --git a/SwifTools/Linkify.cpp b/SwifTools/Linkify.cpp index 324d145..b1557e5 100644 --- a/SwifTools/Linkify.cpp +++ b/SwifTools/Linkify.cpp @@ -16,89 +16,89 @@ namespace Swift { static boost::regex linkifyRegexp("^(https?://|xmpp:).*"); std::string Linkify::linkify(const std::string& input) { - std::ostringstream result; - std::vector currentURL; - bool inURL = false; - for (size_t i = 0; i < input.size(); ++i) { - char c = input[i]; - if (inURL) { - if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) { - currentURL.push_back(c); - } - else { - std::string url(¤tURL[0], currentURL.size()); - result << "" << url << ""; - currentURL.clear(); - inURL = false; - result << c; - } - } - else { - if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) { - currentURL.push_back(c); - inURL = true; - } - else { - result << c; - } - } - } - if (!currentURL.empty()) { - std::string url(¤tURL[0], currentURL.size()); - result << "" << url << ""; - } - return std::string(result.str()); + std::ostringstream result; + std::vector currentURL; + bool inURL = false; + for (size_t i = 0; i < input.size(); ++i) { + char c = input[i]; + if (inURL) { + if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) { + currentURL.push_back(c); + } + else { + std::string url(¤tURL[0], currentURL.size()); + result << "" << url << ""; + currentURL.clear(); + inURL = false; + result << c; + } + } + else { + if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) { + currentURL.push_back(c); + inURL = true; + } + else { + result << c; + } + } + } + if (!currentURL.empty()) { + std::string url(¤tURL[0], currentURL.size()); + result << "" << url << ""; + } + return std::string(result.str()); } std::pair, size_t> Linkify::splitLink(const std::string& input) { - std::vector result; - std::pair, size_t> pair; - std::vector currentURL; - bool inURL = false; - size_t urlStartsAt = 0; - for (size_t i = 0; i < input.size(); ++i) { - char c = input[i]; - if (inURL) { - if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) { - // Keep parsing - } - else { - std::string url(input.substr(urlStartsAt, i - urlStartsAt)); - result.push_back(url); - inURL = false; - size_t remaining = input.size() - i; - if (remaining > 0) { - result.push_back(input.substr(i, remaining)); - } - pair.first = result; - pair.second = urlStartsAt == 0 ? 0 : 1; - return pair; - } - } - else { - if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) { - urlStartsAt = i; - inURL = true; - if (i > 0) { - result.push_back(input.substr(0, i)); - } - } - else { - // Just keep swimming - } - } - } - if (urlStartsAt > 0 || inURL) { - std::string url(input.substr(urlStartsAt, input.size() - urlStartsAt)); - result.push_back(url); - pair.first = result; - pair.second = urlStartsAt == 0 ? 0 : 1; - } - else { - pair.first.push_back(input); - pair.second = 1; - } - return pair; + std::vector result; + std::pair, size_t> pair; + std::vector currentURL; + bool inURL = false; + size_t urlStartsAt = 0; + for (size_t i = 0; i < input.size(); ++i) { + char c = input[i]; + if (inURL) { + if (c != ' ' && c != '\t' && c != '\n' && !(c == '*' && i == input.size() - 1 && input[0] == '*')) { + // Keep parsing + } + else { + std::string url(input.substr(urlStartsAt, i - urlStartsAt)); + result.push_back(url); + inURL = false; + size_t remaining = input.size() - i; + if (remaining > 0) { + result.push_back(input.substr(i, remaining)); + } + pair.first = result; + pair.second = urlStartsAt == 0 ? 0 : 1; + return pair; + } + } + else { + if (boost::regex_match(input.substr(i, 8), linkifyRegexp)) { + urlStartsAt = i; + inURL = true; + if (i > 0) { + result.push_back(input.substr(0, i)); + } + } + else { + // Just keep swimming + } + } + } + if (urlStartsAt > 0 || inURL) { + std::string url(input.substr(urlStartsAt, input.size() - urlStartsAt)); + result.push_back(url); + pair.first = result; + pair.second = urlStartsAt == 0 ? 0 : 1; + } + else { + pair.first.push_back(input); + pair.second = 1; + } + return pair; } } diff --git a/SwifTools/Linkify.h b/SwifTools/Linkify.h index 98d55d6..64c92dc 100644 --- a/SwifTools/Linkify.h +++ b/SwifTools/Linkify.h @@ -10,18 +10,18 @@ #include namespace Swift { - namespace Linkify { - std::string linkify(const std::string&); - /** - * Parse the string for a URI. The string will be split by the URI, and the segments plus index of the URI returned. - * If no URI is found the index will be result.size() (i.e. an invalid index) - * - * Examples: - * "not a URI" -> <<"not a URI">, -1> - * "http://swift.im" -> <<"http://swift.im">, 0 - * " See http://swift.im" -> <<" See ", "http://swift.im">, 1> - * "Right, http://swift.im it is" -> <<"Right, ", "http://swift.im", " it is">, 1> - */ - std::pair, size_t> splitLink(const std::string& text); - } + namespace Linkify { + std::string linkify(const std::string&); + /** + * Parse the string for a URI. The string will be split by the URI, and the segments plus index of the URI returned. + * If no URI is found the index will be result.size() (i.e. an invalid index) + * + * Examples: + * "not a URI" -> <<"not a URI">, -1> + * "http://swift.im" -> <<"http://swift.im">, 0 + * " See http://swift.im" -> <<" See ", "http://swift.im">, 1> + * "Right, http://swift.im it is" -> <<"Right, ", "http://swift.im", " it is">, 1> + */ + std::pair, size_t> splitLink(const std::string& text); + } } diff --git a/SwifTools/MacOSXChecker.h b/SwifTools/MacOSXChecker.h index 0bc7356..be9a32a 100644 --- a/SwifTools/MacOSXChecker.h +++ b/SwifTools/MacOSXChecker.h @@ -19,12 +19,12 @@ #include namespace Swift { - class MacOSXChecker : public SpellChecker { - public: - MacOSXChecker(); - virtual ~MacOSXChecker(); - virtual bool isCorrect(const std::string& word); - virtual void getSuggestions(const std::string& word, std::vector& list); - virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions); - }; + class MacOSXChecker : public SpellChecker { + public: + MacOSXChecker(); + virtual ~MacOSXChecker(); + virtual bool isCorrect(const std::string& word); + virtual void getSuggestions(const std::string& word, std::vector& list); + virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions); + }; } diff --git a/SwifTools/MacOSXChecker.mm b/SwifTools/MacOSXChecker.mm index eefea97..5f4f9c3 100644 --- a/SwifTools/MacOSXChecker.mm +++ b/SwifTools/MacOSXChecker.mm @@ -21,43 +21,43 @@ namespace Swift { MacOSXChecker::MacOSXChecker() { - NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; - [spellChecker setAutomaticallyIdentifiesLanguages:YES]; + NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; + [spellChecker setAutomaticallyIdentifiesLanguages:YES]; } MacOSXChecker::~MacOSXChecker() { } bool MacOSXChecker::isCorrect(const std::string& /*word*/) { - // No content since it doesn't seem to be used anywhere. - return false; + // No content since it doesn't seem to be used anywhere. + return false; } void MacOSXChecker::getSuggestions(const std::string& word, std::vector& list) { - NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; - NSString* wordString = [[NSString alloc] initWithUTF8String: word.c_str()]; - NSArray* suggestions = [spellChecker guessesForWordRange:NSMakeRange(0, [wordString length]) inString:wordString language:nil inSpellDocumentWithTag:0]; - for(unsigned int i = 0; i < [suggestions count]; ++i) { - list.push_back(std::string([[suggestions objectAtIndex:i] UTF8String])); - } - [wordString release]; + NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; + NSString* wordString = [[NSString alloc] initWithUTF8String: word.c_str()]; + NSArray* suggestions = [spellChecker guessesForWordRange:NSMakeRange(0, [wordString length]) inString:wordString language:nil inSpellDocumentWithTag:0]; + for(unsigned int i = 0; i < [suggestions count]; ++i) { + list.push_back(std::string([[suggestions objectAtIndex:i] UTF8String])); + } + [wordString release]; } void MacOSXChecker::checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) { - NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; - size_t nextLocation = 0; - NSRange range; - NSString *fragmentString = [[NSString alloc] initWithUTF8String: fragment.c_str()]; - do { - range = [spellChecker checkSpellingOfString:fragmentString startingAt:static_cast(nextLocation)]; - if (range.location != NSNotFound) { - if (range.location < nextLocation) - break; - misspelledPositions.push_back(PositionPair(static_cast(range.location), static_cast(range.location + range.length))); - nextLocation = range.location + range.length + 1; - } - } while (range.location != NSNotFound); - [fragmentString release]; + NSSpellChecker* spellChecker = [NSSpellChecker sharedSpellChecker]; + size_t nextLocation = 0; + NSRange range; + NSString *fragmentString = [[NSString alloc] initWithUTF8String: fragment.c_str()]; + do { + range = [spellChecker checkSpellingOfString:fragmentString startingAt:static_cast(nextLocation)]; + if (range.location != NSNotFound) { + if (range.location < nextLocation) + break; + misspelledPositions.push_back(PositionPair(static_cast(range.location), static_cast(range.location + range.length))); + nextLocation = range.location + range.length + 1; + } + } while (range.location != NSNotFound); + [fragmentString release]; } } diff --git a/SwifTools/Notifier/GNTPNotifier.cpp b/SwifTools/Notifier/GNTPNotifier.cpp index 01e8726..62203b4 100644 --- a/SwifTools/Notifier/GNTPNotifier.cpp +++ b/SwifTools/Notifier/GNTPNotifier.cpp @@ -21,67 +21,67 @@ namespace Swift { GNTPNotifier::GNTPNotifier(const std::string& name, const boost::filesystem::path& icon, ConnectionFactory* connectionFactory) : name(name), icon(icon), connectionFactory(connectionFactory), initialized(false), registered(false) { - // Registration message - std::ostringstream message; - message << "GNTP/1.0 REGISTER NONE\r\n"; - message << "Application-Name: " << name << "\r\n"; - message << "Application-Icon: file://" << pathToString(icon) << "\r\n"; - message << "Notifications-Count: " << getAllTypes().size() << "\r\n"; - std::vector defaultTypes = getDefaultTypes(); - std::vector allTypes = getAllTypes(); - foreach(Notifier::Type type, allTypes) { - message << "\r\n"; - message << "Notification-Name: " << typeToString(type) << "\r\n"; - message << "Notification-Enabled: " << (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end() ? "false" : "true") << "\r\n"; - } - message << "\r\n"; + // Registration message + std::ostringstream message; + message << "GNTP/1.0 REGISTER NONE\r\n"; + message << "Application-Name: " << name << "\r\n"; + message << "Application-Icon: file://" << pathToString(icon) << "\r\n"; + message << "Notifications-Count: " << getAllTypes().size() << "\r\n"; + std::vector defaultTypes = getDefaultTypes(); + std::vector allTypes = getAllTypes(); + foreach(Notifier::Type type, allTypes) { + message << "\r\n"; + message << "Notification-Name: " << typeToString(type) << "\r\n"; + message << "Notification-Enabled: " << (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end() ? "false" : "true") << "\r\n"; + } + message << "\r\n"; - send(message.str()); + send(message.str()); } GNTPNotifier::~GNTPNotifier() { } void GNTPNotifier::send(const std::string& message) { - if (currentConnection) { - return; - } - currentMessage = message; - currentConnection = connectionFactory->createConnection(); - currentConnection->onConnectFinished.connect(boost::bind(&GNTPNotifier::handleConnectFinished, this, _1)); - currentConnection->onDataRead.connect(boost::bind(&GNTPNotifier::handleDataRead, this, _1)); - currentConnection->connect(HostAddressPort(HostAddress("127.0.0.1"), 23053)); + if (currentConnection) { + return; + } + currentMessage = message; + currentConnection = connectionFactory->createConnection(); + currentConnection->onConnectFinished.connect(boost::bind(&GNTPNotifier::handleConnectFinished, this, _1)); + currentConnection->onDataRead.connect(boost::bind(&GNTPNotifier::handleDataRead, this, _1)); + currentConnection->connect(HostAddressPort(HostAddress("127.0.0.1"), 23053)); } void GNTPNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function) { - if (registered) { - std::ostringstream message; - message << "GNTP/1.0 NOTIFY NONE\r\n"; - message << "Application-Name: " << name << "\r\n"; - message << "Notification-Name: " << typeToString(type) << "\r\n"; - message << "Notification-Title: " << subject << "\r\n"; - message << "Notification-Text: " << description << "\r\n"; - message << "Notification-Icon: " << pathToString(picture) << "\r\n"; - message << "\r\n"; - send(message.str()); - } + if (registered) { + std::ostringstream message; + message << "GNTP/1.0 NOTIFY NONE\r\n"; + message << "Application-Name: " << name << "\r\n"; + message << "Notification-Name: " << typeToString(type) << "\r\n"; + message << "Notification-Title: " << subject << "\r\n"; + message << "Notification-Text: " << description << "\r\n"; + message << "Notification-Icon: " << pathToString(picture) << "\r\n"; + message << "\r\n"; + send(message.str()); + } } void GNTPNotifier::handleConnectFinished(bool error) { - if (!initialized) { - initialized = true; - registered = !error; - } + if (!initialized) { + initialized = true; + registered = !error; + } - if (!error) { - currentConnection->write(currentMessage.c_str()); - } + if (!error) { + currentConnection->write(currentMessage.c_str()); + } } void GNTPNotifier::handleDataRead(const ByteArray&) { - currentConnection->onDataRead.disconnect(boost::bind(&GNTPNotifier::handleDataRead, this, _1)); - currentConnection->onConnectFinished.disconnect(boost::bind(&GNTPNotifier::handleConnectFinished, this, _1)); - currentConnection.reset(); + currentConnection->onDataRead.disconnect(boost::bind(&GNTPNotifier::handleDataRead, this, _1)); + currentConnection->onConnectFinished.disconnect(boost::bind(&GNTPNotifier::handleConnectFinished, this, _1)); + currentConnection.reset(); } } diff --git a/SwifTools/Notifier/GNTPNotifier.h b/SwifTools/Notifier/GNTPNotifier.h index 92ff5a3..44811e7 100644 --- a/SwifTools/Notifier/GNTPNotifier.h +++ b/SwifTools/Notifier/GNTPNotifier.h @@ -13,27 +13,27 @@ #include namespace Swift { - class ConnectionFactory; - - class GNTPNotifier : public Notifier { - public: - GNTPNotifier(const std::string& name, const boost::filesystem::path& icon, ConnectionFactory* connectionFactory); - ~GNTPNotifier(); - - virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); - - private: - void handleConnectFinished(bool error); - void handleDataRead(const ByteArray& data); - void send(const std::string& message); - - private: - std::string name; - boost::filesystem::path icon; - ConnectionFactory* connectionFactory; - bool initialized; - bool registered; - std::string currentMessage; - Connection::ref currentConnection; - }; + class ConnectionFactory; + + class GNTPNotifier : public Notifier { + public: + GNTPNotifier(const std::string& name, const boost::filesystem::path& icon, ConnectionFactory* connectionFactory); + ~GNTPNotifier(); + + virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); + + private: + void handleConnectFinished(bool error); + void handleDataRead(const ByteArray& data); + void send(const std::string& message); + + private: + std::string name; + boost::filesystem::path icon; + ConnectionFactory* connectionFactory; + bool initialized; + bool registered; + std::string currentMessage; + Connection::ref currentConnection; + }; } diff --git a/SwifTools/Notifier/GrowlNotifier.h b/SwifTools/Notifier/GrowlNotifier.h index 9c90471..b4c4eba 100644 --- a/SwifTools/Notifier/GrowlNotifier.h +++ b/SwifTools/Notifier/GrowlNotifier.h @@ -11,31 +11,31 @@ #include namespace Swift { - /** - * Preconditions for using growlnotifier: - * - Must be part a bundle. - * - The Carbon/Cocoa application loop must be running (e.g. through QApplication) - * such that notifications are coming through. - */ - class GrowlNotifier : public Notifier { - public: - GrowlNotifier(const std::string& name); - ~GrowlNotifier(); - - virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); - virtual bool isExternallyConfigured() const; - - // Called by the delegate. Don't call. - void handleNotificationClicked(void* data); - void handleNotificationTimedOut(void* data); - - virtual void purgeCallbacks(); - - private: - void clearPendingNotifications(); - - private: - class Private; - boost::shared_ptr p; - }; + /** + * Preconditions for using growlnotifier: + * - Must be part a bundle. + * - The Carbon/Cocoa application loop must be running (e.g. through QApplication) + * such that notifications are coming through. + */ + class GrowlNotifier : public Notifier { + public: + GrowlNotifier(const std::string& name); + ~GrowlNotifier(); + + virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); + virtual bool isExternallyConfigured() const; + + // Called by the delegate. Don't call. + void handleNotificationClicked(void* data); + void handleNotificationTimedOut(void* data); + + virtual void purgeCallbacks(); + + private: + void clearPendingNotifications(); + + private: + class Private; + boost::shared_ptr p; + }; } diff --git a/SwifTools/Notifier/GrowlNotifier.mm b/SwifTools/Notifier/GrowlNotifier.mm index d5bdf6f..e9ffff7 100644 --- a/SwifTools/Notifier/GrowlNotifier.mm +++ b/SwifTools/Notifier/GrowlNotifier.mm @@ -17,101 +17,101 @@ #pragma GCC diagnostic ignored "-Wold-style-cast" namespace { - struct Context { - Context(const boost::function& callback) : callback(new boost::function(callback)) {} + struct Context { + Context(const boost::function& callback) : callback(new boost::function(callback)) {} - boost::function* callback; - }; + boost::function* callback; + }; } namespace Swift { class GrowlNotifier::Private { - public: - std::set pendingNotifications; - boost::intrusive_ptr delegate; + public: + std::set pendingNotifications; + boost::intrusive_ptr delegate; }; GrowlNotifier::GrowlNotifier(const std::string& name) { - p = boost::make_shared(); - p->delegate = boost::intrusive_ptr([[GrowlNotifierDelegate alloc] init], false); - p->delegate.get().notifier = this; - p->delegate.get().name = std2NSString(name); - - NSMutableArray* allNotifications = [[NSMutableArray alloc] init]; - foreach(Type type, getAllTypes()) { - [allNotifications addObject: std2NSString(typeToString(type))]; - } - - NSMutableArray* defaultNotifications = [[NSMutableArray alloc] init]; - foreach(Type type, getDefaultTypes()) { - [defaultNotifications addObject: std2NSString(typeToString(type))]; - } - - p->delegate.get().registrationDictionary = [[[NSDictionary alloc] - initWithObjects: [NSArray arrayWithObjects: allNotifications, defaultNotifications, nil] - forKeys: [NSArray arrayWithObjects: GROWL_NOTIFICATIONS_ALL, GROWL_NOTIFICATIONS_DEFAULT, nil]] autorelease]; - - [allNotifications release]; - [defaultNotifications release]; - - [GrowlApplicationBridge setGrowlDelegate: p->delegate.get()]; + p = boost::make_shared(); + p->delegate = boost::intrusive_ptr([[GrowlNotifierDelegate alloc] init], false); + p->delegate.get().notifier = this; + p->delegate.get().name = std2NSString(name); + + NSMutableArray* allNotifications = [[NSMutableArray alloc] init]; + foreach(Type type, getAllTypes()) { + [allNotifications addObject: std2NSString(typeToString(type))]; + } + + NSMutableArray* defaultNotifications = [[NSMutableArray alloc] init]; + foreach(Type type, getDefaultTypes()) { + [defaultNotifications addObject: std2NSString(typeToString(type))]; + } + + p->delegate.get().registrationDictionary = [[[NSDictionary alloc] + initWithObjects: [NSArray arrayWithObjects: allNotifications, defaultNotifications, nil] + forKeys: [NSArray arrayWithObjects: GROWL_NOTIFICATIONS_ALL, GROWL_NOTIFICATIONS_DEFAULT, nil]] autorelease]; + + [allNotifications release]; + [defaultNotifications release]; + + [GrowlApplicationBridge setGrowlDelegate: p->delegate.get()]; } GrowlNotifier::~GrowlNotifier() { - [GrowlApplicationBridge setGrowlDelegate: nil]; - clearPendingNotifications(); + [GrowlApplicationBridge setGrowlDelegate: nil]; + clearPendingNotifications(); } void GrowlNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picturePath, boost::function callback) { - ByteArray picture; - readByteArrayFromFile(picture, picturePath); - - Context* context = new Context(callback); - // Growl sometimes sends timeout notifications twice for the same message. We therefore need - // to keep track of which ones have already been processed. - p->pendingNotifications.insert(context); - - [GrowlApplicationBridge - notifyWithTitle: std2NSString(subject) - description: std2NSString(description) - notificationName: std2NSString(typeToString(type)) - iconData: [NSData dataWithBytes: vecptr(picture) length: picture.size()] - priority: 0 - isSticky: NO - clickContext: [NSData dataWithBytes: &context length: sizeof(context)]]; + ByteArray picture; + readByteArrayFromFile(picture, picturePath); + + Context* context = new Context(callback); + // Growl sometimes sends timeout notifications twice for the same message. We therefore need + // to keep track of which ones have already been processed. + p->pendingNotifications.insert(context); + + [GrowlApplicationBridge + notifyWithTitle: std2NSString(subject) + description: std2NSString(description) + notificationName: std2NSString(typeToString(type)) + iconData: [NSData dataWithBytes: vecptr(picture) length: picture.size()] + priority: 0 + isSticky: NO + clickContext: [NSData dataWithBytes: &context length: sizeof(context)]]; } void GrowlNotifier::handleNotificationClicked(void* rawData) { - Context* context = *(Context**) [((NSData*) rawData) bytes]; - if (p->pendingNotifications.erase(context) > 0) { - if (!context->callback->empty()) { - (*context->callback)(); - } - delete context; - } + Context* context = *(Context**) [((NSData*) rawData) bytes]; + if (p->pendingNotifications.erase(context) > 0) { + if (!context->callback->empty()) { + (*context->callback)(); + } + delete context; + } } void GrowlNotifier::handleNotificationTimedOut(void* rawData) { - Context* context = *(Context**) [((NSData*) rawData) bytes]; - if (p->pendingNotifications.erase(context) > 0) { - delete context; - } + Context* context = *(Context**) [((NSData*) rawData) bytes]; + if (p->pendingNotifications.erase(context) > 0) { + delete context; + } } bool GrowlNotifier::isExternallyConfigured() const { - return ![GrowlApplicationBridge isMistEnabled]; + return ![GrowlApplicationBridge isMistEnabled]; } void GrowlNotifier::purgeCallbacks() { - clearPendingNotifications(); + clearPendingNotifications(); } void GrowlNotifier::clearPendingNotifications() { - foreach (Context* context, p->pendingNotifications) { - delete context; - } - p->pendingNotifications.clear(); + foreach (Context* context, p->pendingNotifications) { + delete context; + } + p->pendingNotifications.clear(); } } diff --git a/SwifTools/Notifier/GrowlNotifierDelegate.h b/SwifTools/Notifier/GrowlNotifierDelegate.h index 0640ff7..f4ce132 100644 --- a/SwifTools/Notifier/GrowlNotifierDelegate.h +++ b/SwifTools/Notifier/GrowlNotifierDelegate.h @@ -7,13 +7,13 @@ #import namespace Swift { - class GrowlNotifier; + class GrowlNotifier; } @interface GrowlNotifierDelegate : NSObject { - Swift::GrowlNotifier* notifier; - NSString* name; - NSDictionary* registrationDictionary; + Swift::GrowlNotifier* notifier; + NSString* name; + NSDictionary* registrationDictionary; } @property (nonatomic, retain) NSDictionary* registrationDictionary; diff --git a/SwifTools/Notifier/GrowlNotifierDelegate.mm b/SwifTools/Notifier/GrowlNotifierDelegate.mm index 1d934ad..77df3ab 100644 --- a/SwifTools/Notifier/GrowlNotifierDelegate.mm +++ b/SwifTools/Notifier/GrowlNotifierDelegate.mm @@ -17,19 +17,19 @@ using namespace Swift; - (NSString *) applicationNameForGrowl { - return name; + return name; } - (NSDictionary*) registrationDictionaryForGrowl { - return registrationDictionary; + return registrationDictionary; } - (void) growlNotificationWasClicked: (id) clickContext { - notifier->handleNotificationClicked(clickContext); + notifier->handleNotificationClicked(clickContext); } - (void) growlNotificationTimedOut: (id) clickContext { - notifier->handleNotificationTimedOut(clickContext); + notifier->handleNotificationTimedOut(clickContext); } @end diff --git a/SwifTools/Notifier/LoggingNotifier.h b/SwifTools/Notifier/LoggingNotifier.h index d50cb2d..e12500b 100644 --- a/SwifTools/Notifier/LoggingNotifier.h +++ b/SwifTools/Notifier/LoggingNotifier.h @@ -11,23 +11,23 @@ #include namespace Swift { - class LoggingNotifier : public Notifier { - public: - virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) { - notifications.push_back(Notification(type, subject, description, picture, callback)); - } + class LoggingNotifier : public Notifier { + public: + virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) { + notifications.push_back(Notification(type, subject, description, picture, callback)); + } - struct Notification { - Notification(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) : type(type), subject(subject), description(description), picture(picture), callback(callback) {} - Type type; - std::string subject; - std::string description; - boost::filesystem::path picture; - boost::function callback; - }; + struct Notification { + Notification(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) : type(type), subject(subject), description(description), picture(picture), callback(callback) {} + Type type; + std::string subject; + std::string description; + boost::filesystem::path picture; + boost::function callback; + }; - virtual void purgeCallbacks() {} + virtual void purgeCallbacks() {} - std::vector notifications; - }; + std::vector notifications; + }; } diff --git a/SwifTools/Notifier/NotificationCenterNotifier.h b/SwifTools/Notifier/NotificationCenterNotifier.h index 0d43c5b..75b4df7 100644 --- a/SwifTools/Notifier/NotificationCenterNotifier.h +++ b/SwifTools/Notifier/NotificationCenterNotifier.h @@ -18,21 +18,21 @@ namespace Swift { */ class NotificationCenterNotifier : public Notifier { public: - NotificationCenterNotifier(); - virtual ~NotificationCenterNotifier(); + NotificationCenterNotifier(); + virtual ~NotificationCenterNotifier(); - virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); - virtual void purgeCallbacks(); + virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); + virtual void purgeCallbacks(); - /** - * @brief The handleUserNotificationActivated is called by the delegate, when a user activates/clicks on a notification. - * @param identifier The std::string UUID identifiying the notification. - */ - void handleUserNotificationActivated(const std::string& identifier); + /** + * @brief The handleUserNotificationActivated is called by the delegate, when a user activates/clicks on a notification. + * @param identifier The std::string UUID identifiying the notification. + */ + void handleUserNotificationActivated(const std::string& identifier); private: - class Private; - boost::shared_ptr p; + class Private; + boost::shared_ptr p; }; } diff --git a/SwifTools/Notifier/NotificationCenterNotifier.mm b/SwifTools/Notifier/NotificationCenterNotifier.mm index 01e6368..57b9a4b 100644 --- a/SwifTools/Notifier/NotificationCenterNotifier.mm +++ b/SwifTools/Notifier/NotificationCenterNotifier.mm @@ -19,78 +19,78 @@ #include namespace { - struct Context { - Context(const boost::function& callback) : callback(new boost::function(callback)) { - } + struct Context { + Context(const boost::function& callback) : callback(new boost::function(callback)) { + } - ~Context() { - delete callback; - } + ~Context() { + delete callback; + } - boost::function* callback; - }; + boost::function* callback; + }; } namespace Swift { class NotificationCenterNotifier::Private { - public: - std::map > callbacksForNotifications; - boost::intrusive_ptr delegate; + public: + std::map > callbacksForNotifications; + boost::intrusive_ptr delegate; }; NotificationCenterNotifier::NotificationCenterNotifier() { - p = boost::make_shared(); - p->delegate = boost::intrusive_ptr([[NotificationCenterNotifierDelegate alloc] init], false); - [p->delegate.get() setNotifier: this]; + p = boost::make_shared(); + p->delegate = boost::intrusive_ptr([[NotificationCenterNotifierDelegate alloc] init], false); + [p->delegate.get() setNotifier: this]; - [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: p->delegate.get()]; + [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: p->delegate.get()]; } NotificationCenterNotifier::~NotificationCenterNotifier() { - [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: nil]; - p->callbacksForNotifications.clear(); + [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: nil]; + p->callbacksForNotifications.clear(); } void NotificationCenterNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) { - std::vector defaultTypes = getDefaultTypes(); - if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) { - return; - } - NSImage* image = [[NSImage alloc] initWithContentsOfFile: std2NSString(picture.string())]; - NSUserNotification* notification = [[NSUserNotification alloc] init]; - [notification setTitle:std2NSString(typeToString(type))]; - [notification setSubtitle:std2NSString(subject)]; - [notification setInformativeText:std2NSString(description)]; - [notification setContentImage: image]; - [image release]; - - // The OS X Notification Center API does not allow to attach custom data, like a pointer to a callback function, - // to the NSUserNotification object. Therefore we maintain a mapping from a NSUserNotification instance's identification - // to their respective callbacks. - [notification setIdentifier:[[NSUUID UUID] UUIDString]]; - - /// \todo Currently the elements are only removed on application exit. Ideally the notifications not required anymore - /// are removed from the map; e.g. when visiting a chat view, all notifications from that view can be removed from - /// the map and the NSUserNotificationCenter. - p->callbacksForNotifications[ns2StdString(notification.identifier)] = boost::make_shared(callback); - [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification]; - [notification release]; + std::vector defaultTypes = getDefaultTypes(); + if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) { + return; + } + NSImage* image = [[NSImage alloc] initWithContentsOfFile: std2NSString(picture.string())]; + NSUserNotification* notification = [[NSUserNotification alloc] init]; + [notification setTitle:std2NSString(typeToString(type))]; + [notification setSubtitle:std2NSString(subject)]; + [notification setInformativeText:std2NSString(description)]; + [notification setContentImage: image]; + [image release]; + + // The OS X Notification Center API does not allow to attach custom data, like a pointer to a callback function, + // to the NSUserNotification object. Therefore we maintain a mapping from a NSUserNotification instance's identification + // to their respective callbacks. + [notification setIdentifier:[[NSUUID UUID] UUIDString]]; + + /// \todo Currently the elements are only removed on application exit. Ideally the notifications not required anymore + /// are removed from the map; e.g. when visiting a chat view, all notifications from that view can be removed from + /// the map and the NSUserNotificationCenter. + p->callbacksForNotifications[ns2StdString(notification.identifier)] = boost::make_shared(callback); + [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification]; + [notification release]; } void NotificationCenterNotifier::purgeCallbacks() { - p->callbacksForNotifications.clear(); + p->callbacksForNotifications.clear(); } void NotificationCenterNotifier::handleUserNotificationActivated(const std::string& identifier) { - if (p->callbacksForNotifications.find(identifier) != p->callbacksForNotifications.end()) { - if (!(*p->callbacksForNotifications[identifier]->callback).empty()) { - (*p->callbacksForNotifications[identifier]->callback)(); - } - } - else { - SWIFT_LOG(warning) << "Missing callback entry for activated notification. The activate notification may come from another instance." << std::endl; - } + if (p->callbacksForNotifications.find(identifier) != p->callbacksForNotifications.end()) { + if (!(*p->callbacksForNotifications[identifier]->callback).empty()) { + (*p->callbacksForNotifications[identifier]->callback)(); + } + } + else { + SWIFT_LOG(warning) << "Missing callback entry for activated notification. The activate notification may come from another instance." << std::endl; + } } } diff --git a/SwifTools/Notifier/NotificationCenterNotifierDelegate.h b/SwifTools/Notifier/NotificationCenterNotifierDelegate.h index ea8fae0..f09c09f 100644 --- a/SwifTools/Notifier/NotificationCenterNotifierDelegate.h +++ b/SwifTools/Notifier/NotificationCenterNotifierDelegate.h @@ -9,7 +9,7 @@ #import namespace Swift { - class NotificationCenterNotifier; + class NotificationCenterNotifier; } @interface NotificationCenterNotifierDelegate : NSObject { diff --git a/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm b/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm index 2b1c2a4..84ec943 100644 --- a/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm +++ b/SwifTools/Notifier/NotificationCenterNotifierDelegate.mm @@ -18,9 +18,9 @@ using namespace Swift; @synthesize notifier; - (void)userNotificationCenter:(NSUserNotificationCenter *) center didActivateNotification:(NSUserNotification *)notification { - (void)center; - std::string identifier = ns2StdString(notification.identifier); - notifier->handleUserNotificationActivated(identifier); + (void)center; + std::string identifier = ns2StdString(notification.identifier); + notifier->handleUserNotificationActivated(identifier); } @end diff --git a/SwifTools/Notifier/Notifier.cpp b/SwifTools/Notifier/Notifier.cpp index b8fd1a0..314d39c 100644 --- a/SwifTools/Notifier/Notifier.cpp +++ b/SwifTools/Notifier/Notifier.cpp @@ -15,32 +15,32 @@ Notifier::~Notifier() { } std::string Notifier::typeToString(Type type) { - switch (type) { - case ContactAvailable: return "Contact Becomes Available"; - case ContactUnavailable: return "Contact Becomes Unavailable"; - case ContactStatusChange: return "Contact Changes Status"; - case IncomingMessage: return "Incoming Message"; - case SystemMessage: return "System Message"; - } - assert(false); - return ""; + switch (type) { + case ContactAvailable: return "Contact Becomes Available"; + case ContactUnavailable: return "Contact Becomes Unavailable"; + case ContactStatusChange: return "Contact Changes Status"; + case IncomingMessage: return "Incoming Message"; + case SystemMessage: return "System Message"; + } + assert(false); + return ""; } std::vector Notifier::getAllTypes() { - std::vector result; - result.push_back(ContactAvailable); - result.push_back(ContactUnavailable); - result.push_back(ContactStatusChange); - result.push_back(IncomingMessage); - result.push_back(SystemMessage); - return result; + std::vector result; + result.push_back(ContactAvailable); + result.push_back(ContactUnavailable); + result.push_back(ContactStatusChange); + result.push_back(IncomingMessage); + result.push_back(SystemMessage); + return result; } std::vector Notifier::getDefaultTypes() { - std::vector result; - result.push_back(IncomingMessage); - result.push_back(SystemMessage); - return result; + std::vector result; + result.push_back(IncomingMessage); + result.push_back(SystemMessage); + return result; } } diff --git a/SwifTools/Notifier/Notifier.h b/SwifTools/Notifier/Notifier.h index b099701..afd596b 100644 --- a/SwifTools/Notifier/Notifier.h +++ b/SwifTools/Notifier/Notifier.h @@ -13,39 +13,39 @@ #include namespace Swift { - class Notifier { - public: - virtual ~Notifier(); - - enum Type { ContactAvailable, ContactUnavailable, ContactStatusChange, IncomingMessage, SystemMessage }; - - /** - * Picture is a PNG image. - */ - virtual void showMessage( - Type type, - const std::string& subject, - const std::string& description, - const boost::filesystem::path& picture, - boost::function callback) = 0; - - virtual bool isAvailable() const { - return true; - } - - virtual bool isExternallyConfigured() const { - return false; - } - - /** Remove any pending callbacks. */ - virtual void purgeCallbacks() = 0; - - protected: - std::string typeToString(Type type); - static std::vector getAllTypes(); - static std::vector getDefaultTypes(); - - static const int DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS; - static const int DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS; - }; + class Notifier { + public: + virtual ~Notifier(); + + enum Type { ContactAvailable, ContactUnavailable, ContactStatusChange, IncomingMessage, SystemMessage }; + + /** + * Picture is a PNG image. + */ + virtual void showMessage( + Type type, + const std::string& subject, + const std::string& description, + const boost::filesystem::path& picture, + boost::function callback) = 0; + + virtual bool isAvailable() const { + return true; + } + + virtual bool isExternallyConfigured() const { + return false; + } + + /** Remove any pending callbacks. */ + virtual void purgeCallbacks() = 0; + + protected: + std::string typeToString(Type type); + static std::vector getAllTypes(); + static std::vector getDefaultTypes(); + + static const int DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS; + static const int DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS; + }; } diff --git a/SwifTools/Notifier/NullNotifier.h b/SwifTools/Notifier/NullNotifier.h index 1f6d7d9..8945a53 100644 --- a/SwifTools/Notifier/NullNotifier.h +++ b/SwifTools/Notifier/NullNotifier.h @@ -9,11 +9,11 @@ #include namespace Swift { - class NullNotifier : public Notifier { - public: - virtual void showMessage(Type, const std::string&, const std::string&, const boost::filesystem::path&, boost::function) { - } - virtual void purgeCallbacks() { - } - }; + class NullNotifier : public Notifier { + public: + virtual void showMessage(Type, const std::string&, const std::string&, const boost::filesystem::path&, boost::function) { + } + virtual void purgeCallbacks() { + } + }; } diff --git a/SwifTools/Notifier/SnarlNotifier.cpp b/SwifTools/Notifier/SnarlNotifier.cpp index b4e5ef3..e3977a7 100644 --- a/SwifTools/Notifier/SnarlNotifier.cpp +++ b/SwifTools/Notifier/SnarlNotifier.cpp @@ -18,56 +18,56 @@ namespace Swift { SnarlNotifier::SnarlNotifier(const std::string& name, Win32NotifierWindow* window, const boost::filesystem::path& icon) : window(window), available(false) { - window->onMessageReceived.connect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1)); - available = snarl.RegisterApp(name.c_str(), name.c_str(), icon.string().c_str(), window->getID(), SWIFT_SNARLNOTIFIER_MESSAGE_ID); - foreach(Notifier::Type type, getAllTypes()) { - snarl.AddClass(typeToString(type).c_str(), typeToString(type).c_str()); - } + window->onMessageReceived.connect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1)); + available = snarl.RegisterApp(name.c_str(), name.c_str(), icon.string().c_str(), window->getID(), SWIFT_SNARLNOTIFIER_MESSAGE_ID); + foreach(Notifier::Type type, getAllTypes()) { + snarl.AddClass(typeToString(type).c_str(), typeToString(type).c_str()); + } } SnarlNotifier::~SnarlNotifier() { - snarl.UnregisterApp(); - window->onMessageReceived.disconnect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1)); - if (!notifications.empty()) { - std::cerr << "Warning: " << notifications.size() << " Snarl notifications pending" << std::endl; - } + snarl.UnregisterApp(); + window->onMessageReceived.disconnect(boost::bind(&SnarlNotifier::handleMessageReceived, this, _1)); + if (!notifications.empty()) { + std::cerr << "Warning: " << notifications.size() << " Snarl notifications pending" << std::endl; + } } bool SnarlNotifier::isAvailable() const { - return available; + return available; } void SnarlNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) { - int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS; - int notificationID = snarl.EZNotify( - typeToString(type).c_str(), - subject.c_str(), - description.c_str(), - timeout, - picture.string().c_str()); - if (notificationID > 0) { - notifications.insert(std::make_pair(notificationID, callback)); - } + int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS; + int notificationID = snarl.EZNotify( + typeToString(type).c_str(), + subject.c_str(), + description.c_str(), + timeout, + picture.string().c_str()); + if (notificationID > 0) { + notifications.insert(std::make_pair(notificationID, callback)); + } } void SnarlNotifier::handleMessageReceived(MSG* message) { - if (message->message == SWIFT_SNARLNOTIFIER_MESSAGE_ID) { - int action = message->wParam; - if (action == Snarl::V41::SnarlEnums::NotificationTimedOut || action == Snarl::V41::SnarlEnums::NotificationAck || action == Snarl::V41::SnarlEnums::NotificationClosed) { - int notificationID = message->lParam; - NotificationsMap::iterator i = notifications.find(notificationID); - if (i != notifications.end()) { - if (action == Snarl::V41::SnarlEnums::NotificationAck && !i->second.empty()) { - i->second(); - } - notifications.erase(i); - } - else { - std::cerr << "Warning: Orphaned Snarl notification received"; - } - } - } + if (message->message == SWIFT_SNARLNOTIFIER_MESSAGE_ID) { + int action = message->wParam; + if (action == Snarl::V41::SnarlEnums::NotificationTimedOut || action == Snarl::V41::SnarlEnums::NotificationAck || action == Snarl::V41::SnarlEnums::NotificationClosed) { + int notificationID = message->lParam; + NotificationsMap::iterator i = notifications.find(notificationID); + if (i != notifications.end()) { + if (action == Snarl::V41::SnarlEnums::NotificationAck && !i->second.empty()) { + i->second(); + } + notifications.erase(i); + } + else { + std::cerr << "Warning: Orphaned Snarl notification received"; + } + } + } } } diff --git a/SwifTools/Notifier/SnarlNotifier.h b/SwifTools/Notifier/SnarlNotifier.h index b8b9a48..5006185 100644 --- a/SwifTools/Notifier/SnarlNotifier.h +++ b/SwifTools/Notifier/SnarlNotifier.h @@ -13,28 +13,28 @@ #include namespace Swift { - class Win32NotifierWindow; - - class SnarlNotifier : public Notifier { - public: - SnarlNotifier(const std::string& name, Win32NotifierWindow* window, const boost::filesystem::path& icon); - ~SnarlNotifier(); - - virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); - virtual bool isAvailable() const; - - virtual void purgeCallbacks() { - notifications.clear(); - } - - private: - void handleMessageReceived(MSG* message); - - private: - Snarl::V41::SnarlInterface snarl; - Win32NotifierWindow* window; - bool available; - typedef std::map > NotificationsMap; - NotificationsMap notifications; - }; + class Win32NotifierWindow; + + class SnarlNotifier : public Notifier { + public: + SnarlNotifier(const std::string& name, Win32NotifierWindow* window, const boost::filesystem::path& icon); + ~SnarlNotifier(); + + virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback); + virtual bool isAvailable() const; + + virtual void purgeCallbacks() { + notifications.clear(); + } + + private: + void handleMessageReceived(MSG* message); + + private: + Snarl::V41::SnarlInterface snarl; + Win32NotifierWindow* window; + bool available; + typedef std::map > NotificationsMap; + NotificationsMap notifications; + }; } diff --git a/SwifTools/Notifier/TogglableNotifier.h b/SwifTools/Notifier/TogglableNotifier.h index 5580322..c537a6f 100644 --- a/SwifTools/Notifier/TogglableNotifier.h +++ b/SwifTools/Notifier/TogglableNotifier.h @@ -9,54 +9,54 @@ #include namespace Swift { - class TogglableNotifier : public Notifier { - public: - TogglableNotifier(Notifier* notifier) : notifier(notifier), persistentEnabled(true), temporarilyDisabled(false) { - } - - /** - * Set a long-term (usually user-set) enabled. - * This may be temporarily overriden by the application, e.g. if the - * user is marked DND. - */ - void setPersistentEnabled(bool b) { - persistentEnabled = b; - } - - /** - * Set a temporary override to stop notifications without changing the - * long-term state. e.g. if the user goes DND, but the persistent - * enabled shouldn't be lost when they become available again. - */ - void setTemporarilyDisabled(bool b) { - temporarilyDisabled = b; - } - - /** - * Get the result of applying the temporary override to the persistent - * enabledness. - */ - bool getCurrentlyEnabled() const { - return persistentEnabled && !temporarilyDisabled; - } - - virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) { - if (getCurrentlyEnabled() || notifier->isExternallyConfigured()) { - notifier->showMessage(type, subject, description, picture, callback); - } - } - - virtual bool isExternallyConfigured() const { - return notifier->isExternallyConfigured(); - } - - virtual void purgeCallbacks() { - notifier->purgeCallbacks(); - } - - private: - Notifier* notifier; - bool persistentEnabled; - bool temporarilyDisabled; - }; + class TogglableNotifier : public Notifier { + public: + TogglableNotifier(Notifier* notifier) : notifier(notifier), persistentEnabled(true), temporarilyDisabled(false) { + } + + /** + * Set a long-term (usually user-set) enabled. + * This may be temporarily overriden by the application, e.g. if the + * user is marked DND. + */ + void setPersistentEnabled(bool b) { + persistentEnabled = b; + } + + /** + * Set a temporary override to stop notifications without changing the + * long-term state. e.g. if the user goes DND, but the persistent + * enabled shouldn't be lost when they become available again. + */ + void setTemporarilyDisabled(bool b) { + temporarilyDisabled = b; + } + + /** + * Get the result of applying the temporary override to the persistent + * enabledness. + */ + bool getCurrentlyEnabled() const { + return persistentEnabled && !temporarilyDisabled; + } + + virtual void showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function callback) { + if (getCurrentlyEnabled() || notifier->isExternallyConfigured()) { + notifier->showMessage(type, subject, description, picture, callback); + } + } + + virtual bool isExternallyConfigured() const { + return notifier->isExternallyConfigured(); + } + + virtual void purgeCallbacks() { + notifier->purgeCallbacks(); + } + + private: + Notifier* notifier; + bool persistentEnabled; + bool temporarilyDisabled; + }; } diff --git a/SwifTools/Notifier/Win32NotifierWindow.h b/SwifTools/Notifier/Win32NotifierWindow.h index 8e67146..3f03825 100644 --- a/SwifTools/Notifier/Win32NotifierWindow.h +++ b/SwifTools/Notifier/Win32NotifierWindow.h @@ -11,12 +11,12 @@ #include namespace Swift { - class Win32NotifierWindow { - public: - virtual ~Win32NotifierWindow() {} + class Win32NotifierWindow { + public: + virtual ~Win32NotifierWindow() {} - virtual HWND getID() const = 0; + virtual HWND getID() const = 0; - boost::signal onMessageReceived; - }; + boost::signal onMessageReceived; + }; } diff --git a/SwifTools/SpellChecker.h b/SwifTools/SpellChecker.h index e161d20..415d3f6 100644 --- a/SwifTools/SpellChecker.h +++ b/SwifTools/SpellChecker.h @@ -20,18 +20,18 @@ #include namespace Swift { - class SpellChecker { - public: - SpellChecker() { - parser_ = new SpellParser(); - } - virtual ~SpellChecker() { - delete parser_; - } - virtual bool isCorrect(const std::string& word) = 0; - virtual void getSuggestions(const std::string& word, std::vector& list) = 0; - virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) = 0; - protected: - SpellParser *parser_; - }; + class SpellChecker { + public: + SpellChecker() { + parser_ = new SpellParser(); + } + virtual ~SpellChecker() { + delete parser_; + } + virtual bool isCorrect(const std::string& word) = 0; + virtual void getSuggestions(const std::string& word, std::vector& list) = 0; + virtual void checkFragment(const std::string& fragment, PositionPairList& misspelledPositions) = 0; + protected: + SpellParser *parser_; + }; } diff --git a/SwifTools/SpellCheckerFactory.cpp b/SwifTools/SpellCheckerFactory.cpp index 428e1a5..e53447e 100644 --- a/SwifTools/SpellCheckerFactory.cpp +++ b/SwifTools/SpellCheckerFactory.cpp @@ -24,17 +24,17 @@ SpellCheckerFactory::SpellCheckerFactory() { #ifdef HAVE_HUNSPELL SpellChecker* SpellCheckerFactory::createSpellChecker(const std::string& dictFile) { - std::string affixFile(dictFile); - boost::replace_all(affixFile, ".dic", ".aff"); - if ((boost::filesystem::exists(dictFile)) && (boost::filesystem::exists(affixFile))) { - return new HunspellChecker(affixFile.c_str(), dictFile.c_str()); - } - // If dictionaries don't exist disable the checker - return NULL; + std::string affixFile(dictFile); + boost::replace_all(affixFile, ".dic", ".aff"); + if ((boost::filesystem::exists(dictFile)) && (boost::filesystem::exists(affixFile))) { + return new HunspellChecker(affixFile.c_str(), dictFile.c_str()); + } + // If dictionaries don't exist disable the checker + return NULL; } #elif defined(SWIFTEN_PLATFORM_MACOSX) SpellChecker* SpellCheckerFactory::createSpellChecker(const std::string& /*dictFile*/) { - return new MacOSXChecker(); + return new MacOSXChecker(); } #endif diff --git a/SwifTools/SpellCheckerFactory.h b/SwifTools/SpellCheckerFactory.h index 91118f9..a0de98c 100644 --- a/SwifTools/SpellCheckerFactory.h +++ b/SwifTools/SpellCheckerFactory.h @@ -15,10 +15,10 @@ #endif namespace Swift { - class SpellChecker; - class SpellCheckerFactory { - public: - SpellCheckerFactory(); - SpellChecker* createSpellChecker(const std::string& dictFile); - }; + class SpellChecker; + class SpellCheckerFactory { + public: + SpellCheckerFactory(); + SpellChecker* createSpellChecker(const std::string& dictFile); + }; } diff --git a/SwifTools/SpellParser.cpp b/SwifTools/SpellParser.cpp index e60486f..5bafa6e 100644 --- a/SwifTools/SpellParser.cpp +++ b/SwifTools/SpellParser.cpp @@ -26,51 +26,51 @@ namespace Swift { template struct word_count_tokens : lex::lexer { - word_count_tokens() - { - // define tokens (regular expresions) to match strings - // order is important - this->self.add - ("w{3}.[^ ]+", ID_WWW) - ("http:\\/\\/[^ ]+", ID_HTTP) - ("\\w{1,}['?|\\-?]?\\w{1,}", ID_WORD) - (".", ID_CHAR); - } + word_count_tokens() + { + // define tokens (regular expresions) to match strings + // order is important + this->self.add + ("w{3}.[^ ]+", ID_WWW) + ("http:\\/\\/[^ ]+", ID_HTTP) + ("\\w{1,}['?|\\-?]?\\w{1,}", ID_WORD) + (".", ID_CHAR); + } }; struct counter { - typedef bool result_type; - // the function operator gets called for each of the matched tokens - template - bool operator()(Token const& t, PositionPairList& wordPositions, std::size_t& position) const - { - switch (t.id()) { - case ID_WWW: - position += boost::numeric_cast(t.value().size()); - break; - case ID_HTTP: - position += boost::numeric_cast(t.value().size()); - break; - case ID_WORD: // matched a word - wordPositions.push_back(boost::tuples::make_tuple(position, position + boost::numeric_cast(t.value().size()))); - position += boost::numeric_cast(t.value().size()); - break; - case ID_CHAR: // match a simple char - ++position; - break; - } - return true; // always continue to tokenize - } + typedef bool result_type; + // the function operator gets called for each of the matched tokens + template + bool operator()(Token const& t, PositionPairList& wordPositions, std::size_t& position) const + { + switch (t.id()) { + case ID_WWW: + position += boost::numeric_cast(t.value().size()); + break; + case ID_HTTP: + position += boost::numeric_cast(t.value().size()); + break; + case ID_WORD: // matched a word + wordPositions.push_back(boost::tuples::make_tuple(position, position + boost::numeric_cast(t.value().size()))); + position += boost::numeric_cast(t.value().size()); + break; + case ID_CHAR: // match a simple char + ++position; + break; + } + return true; // always continue to tokenize + } }; void SpellParser::check(const std::string& fragment, PositionPairList& wordPositions) { - std::size_t position = 0; - // create the token definition instance needed to invoke the lexical analyzer - word_count_tokens > word_count_functor; - char const* first = fragment.c_str(); - char const* last = &first[fragment.size()]; - lex::tokenize(first, last, word_count_functor, boost::bind(counter(), _1, boost::ref(wordPositions), boost::ref(position))); + std::size_t position = 0; + // create the token definition instance needed to invoke the lexical analyzer + word_count_tokens > word_count_functor; + char const* first = fragment.c_str(); + char const* last = &first[fragment.size()]; + lex::tokenize(first, last, word_count_functor, boost::bind(counter(), _1, boost::ref(wordPositions), boost::ref(position))); } } diff --git a/SwifTools/SpellParser.h b/SwifTools/SpellParser.h index b37cb48..5b057c9 100644 --- a/SwifTools/SpellParser.h +++ b/SwifTools/SpellParser.h @@ -18,19 +18,19 @@ #include namespace Swift { - enum token_ids - { - ID_WWW = 1, - ID_HTTP = 2, - ID_WORD = 3, - ID_CHAR = 4 - }; + enum token_ids + { + ID_WWW = 1, + ID_HTTP = 2, + ID_WORD = 3, + ID_CHAR = 4 + }; - typedef boost::tuple PositionPair; - typedef std::vector PositionPairList; + typedef boost::tuple PositionPair; + typedef std::vector PositionPairList; - class SpellParser{ - public: - void check(const std::string& fragment, PositionPairList& wordPositions); - }; + class SpellParser{ + public: + void check(const std::string& fragment, PositionPairList& wordPositions); + }; } diff --git a/SwifTools/TabComplete.cpp b/SwifTools/TabComplete.cpp index 4796f1b..f158ffa 100644 --- a/SwifTools/TabComplete.cpp +++ b/SwifTools/TabComplete.cpp @@ -15,42 +15,42 @@ namespace Swift { void TabComplete::addWord(const std::string& word) { - words_.erase(std::remove(words_.begin(), words_.end(), word), words_.end()); - words_.insert(words_.begin(), word); - if (boost::starts_with(boost::to_lower_copy(word), lastShort_)) { - lastCompletionCandidates_.insert(lastCompletionCandidates_.begin(), word); - } + words_.erase(std::remove(words_.begin(), words_.end(), word), words_.end()); + words_.insert(words_.begin(), word); + if (boost::starts_with(boost::to_lower_copy(word), lastShort_)) { + lastCompletionCandidates_.insert(lastCompletionCandidates_.begin(), word); + } } void TabComplete::removeWord(const std::string& word) { - words_.erase(std::remove(words_.begin(), words_.end(), word), words_.end()); - lastCompletionCandidates_.erase(std::remove(lastCompletionCandidates_.begin(), lastCompletionCandidates_.end(), word), lastCompletionCandidates_.end()); + words_.erase(std::remove(words_.begin(), words_.end(), word), words_.end()); + lastCompletionCandidates_.erase(std::remove(lastCompletionCandidates_.begin(), lastCompletionCandidates_.end(), word), lastCompletionCandidates_.end()); } std::string TabComplete::completeWord(const std::string& word) { - if (word == lastCompletion_) { - if (!lastCompletionCandidates_.empty()) { - size_t match = 0; - for (match = 0; match < lastCompletionCandidates_.size(); match++) { - if (lastCompletionCandidates_[match] == lastCompletion_) { - break; - } - } - size_t nextIndex = match + 1; - nextIndex = nextIndex >= lastCompletionCandidates_.size() ? 0 : nextIndex; - lastCompletion_ = lastCompletionCandidates_[nextIndex]; - } - } else { - lastShort_ = boost::to_lower_copy(word); - lastCompletionCandidates_.clear(); - foreach (std::string candidate, words_) { - if (boost::starts_with(boost::to_lower_copy(candidate), boost::to_lower_copy(word))) { - lastCompletionCandidates_.push_back(candidate); - } - } - lastCompletion_ = !lastCompletionCandidates_.empty() ? lastCompletionCandidates_[0] : word; - } - return lastCompletion_; + if (word == lastCompletion_) { + if (!lastCompletionCandidates_.empty()) { + size_t match = 0; + for (match = 0; match < lastCompletionCandidates_.size(); match++) { + if (lastCompletionCandidates_[match] == lastCompletion_) { + break; + } + } + size_t nextIndex = match + 1; + nextIndex = nextIndex >= lastCompletionCandidates_.size() ? 0 : nextIndex; + lastCompletion_ = lastCompletionCandidates_[nextIndex]; + } + } else { + lastShort_ = boost::to_lower_copy(word); + lastCompletionCandidates_.clear(); + foreach (std::string candidate, words_) { + if (boost::starts_with(boost::to_lower_copy(candidate), boost::to_lower_copy(word))) { + lastCompletionCandidates_.push_back(candidate); + } + } + lastCompletion_ = !lastCompletionCandidates_.empty() ? lastCompletionCandidates_[0] : word; + } + return lastCompletion_; } } diff --git a/SwifTools/TabComplete.h b/SwifTools/TabComplete.h index a1bdc40..ac1e07e 100644 --- a/SwifTools/TabComplete.h +++ b/SwifTools/TabComplete.h @@ -10,15 +10,15 @@ #include namespace Swift { - class TabComplete { - public: - void addWord(const std::string& word); - void removeWord(const std::string& word); - std::string completeWord(const std::string& word); - private: - std::vector words_; - std::string lastCompletion_; - std::string lastShort_; - std::vector lastCompletionCandidates_; - }; + class TabComplete { + public: + void addWord(const std::string& word); + void removeWord(const std::string& word); + std::string completeWord(const std::string& word); + private: + std::vector words_; + std::string lastCompletion_; + std::string lastShort_; + std::vector lastCompletionCandidates_; + }; } diff --git a/SwifTools/URIHandler/MacOSXURIHandler.h b/SwifTools/URIHandler/MacOSXURIHandler.h index 274f76d..afa4c6c 100644 --- a/SwifTools/URIHandler/MacOSXURIHandler.h +++ b/SwifTools/URIHandler/MacOSXURIHandler.h @@ -9,16 +9,16 @@ #include namespace Swift { - class MacOSXURIHandler : public URIHandler { - public: - MacOSXURIHandler(); - virtual ~MacOSXURIHandler(); + class MacOSXURIHandler : public URIHandler { + public: + MacOSXURIHandler(); + virtual ~MacOSXURIHandler(); - virtual void start(); - virtual void stop(); + virtual void start(); + virtual void stop(); - private: - class Private; - Private* p; - }; + private: + class Private; + Private* p; + }; } diff --git a/SwifTools/URIHandler/MacOSXURIHandler.mm b/SwifTools/URIHandler/MacOSXURIHandler.mm index 482be8f..6285e12 100644 --- a/SwifTools/URIHandler/MacOSXURIHandler.mm +++ b/SwifTools/URIHandler/MacOSXURIHandler.mm @@ -21,47 +21,47 @@ using namespace Swift; @end @implementation MacOSXURIEventHandler - { - URIHandler* handler; - } - - - (id) initWithHandler: (URIHandler*) h { - if ((self = [super init])) { - handler = h; - } - return self; - } - - - (void) getUrl: (NSAppleEventDescriptor*) event withReplyEvent: (NSAppleEventDescriptor*) replyEvent { - (void) replyEvent; - NSString* url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; - handler->onURI(std::string([url UTF8String])); - } + { + URIHandler* handler; + } + + - (id) initWithHandler: (URIHandler*) h { + if ((self = [super init])) { + handler = h; + } + return self; + } + + - (void) getUrl: (NSAppleEventDescriptor*) event withReplyEvent: (NSAppleEventDescriptor*) replyEvent { + (void) replyEvent; + NSString* url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; + handler->onURI(std::string([url UTF8String])); + } @end class MacOSXURIHandler::Private { - public: - MacOSXURIEventHandler* eventHandler; + public: + MacOSXURIEventHandler* eventHandler; }; MacOSXURIHandler::MacOSXURIHandler() { - p = new Private(); - p->eventHandler = [[MacOSXURIEventHandler alloc] initWithHandler: this]; + p = new Private(); + p->eventHandler = [[MacOSXURIEventHandler alloc] initWithHandler: this]; } MacOSXURIHandler::~MacOSXURIHandler() { - [p->eventHandler release]; - delete p; + [p->eventHandler release]; + delete p; } void MacOSXURIHandler::start() { - [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->eventHandler andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; + [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->eventHandler andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; - // Register ourselves as default URI handler - //NSString* bundleID = [[NSBundle mainBundle] bundleIdentifier]; - //LSSetDefaultHandlerForURLScheme((CFStringRef)@"xmpp", (CFStringRef)bundleID); + // Register ourselves as default URI handler + //NSString* bundleID = [[NSBundle mainBundle] bundleIdentifier]; + //LSSetDefaultHandlerForURLScheme((CFStringRef)@"xmpp", (CFStringRef)bundleID); } void MacOSXURIHandler::stop() { - [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL]; + [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kInternetEventClass andEventID:kAEGetURL]; } diff --git a/SwifTools/URIHandler/NullURIHandler.h b/SwifTools/URIHandler/NullURIHandler.h index 646fab7..99c01e8 100644 --- a/SwifTools/URIHandler/NullURIHandler.h +++ b/SwifTools/URIHandler/NullURIHandler.h @@ -9,12 +9,12 @@ #include namespace Swift { - class NullURIHandler : public URIHandler { - public: - virtual void start() { - } + class NullURIHandler : public URIHandler { + public: + virtual void start() { + } - virtual void stop() { - } - }; + virtual void stop() { + } + }; } diff --git a/SwifTools/URIHandler/URIHandler.h b/SwifTools/URIHandler/URIHandler.h index 84bb368..0f85e64 100644 --- a/SwifTools/URIHandler/URIHandler.h +++ b/SwifTools/URIHandler/URIHandler.h @@ -11,11 +11,11 @@ #include namespace Swift { - class URIHandler { - public: - URIHandler(); - virtual ~URIHandler(); + class URIHandler { + public: + URIHandler(); + virtual ~URIHandler(); - boost::signal onURI; - }; + boost::signal onURI; + }; } diff --git a/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp b/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp index 0cafefb..aa0570c 100644 --- a/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp +++ b/SwifTools/URIHandler/UnitTest/XMPPURITest.cpp @@ -12,180 +12,180 @@ using namespace Swift; class XMPPURITest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(XMPPURITest); - CPPUNIT_TEST(testFromString_Authority); - CPPUNIT_TEST(testFromString_AuthorityWithPath); - CPPUNIT_TEST(testFromString_AuthorityWithFragment); - CPPUNIT_TEST(testFromString_AuthorityWithPathAndFragment); - CPPUNIT_TEST(testFromString_AuthorityWithIntlChars); - CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParameters); - CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParameters); - CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParametersWithFragment); - CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParametersWithFragment); - CPPUNIT_TEST(testFromString_Path); - CPPUNIT_TEST(testFromString_PathWithFragment); - CPPUNIT_TEST(testFromString_PathWithIntlChars); - CPPUNIT_TEST(testFromString_PathWithInvalidEscapedChar); - CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar); - CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar2); - CPPUNIT_TEST(testFromString_PathWithQueryWithoutParameters); - CPPUNIT_TEST(testFromString_PathWithQueryWithParameters); - CPPUNIT_TEST(testFromString_PathWithQueryWithoutParametersWithFragment); - CPPUNIT_TEST(testFromString_PathWithQueryWithParametersWithFragment); - CPPUNIT_TEST(testFromString_NoPrefix); - CPPUNIT_TEST_SUITE_END(); - - public: - void testFromString_Authority() { - XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com"); - - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); - } - - void testFromString_AuthorityWithPath() { - XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com"); - - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); - CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); - } - - void testFromString_AuthorityWithFragment() { - XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com#myfragment"); - - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); - CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); - } - - void testFromString_AuthorityWithPathAndFragment() { - XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com#myfragment"); - - CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); - CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); - CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); - } - - void testFromString_AuthorityWithIntlChars() { - XMPPURI testling = XMPPURI::fromString("xmpp://nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com"); - - CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getAuthority()); - } - - void testFromString_AuthorityWithQueryWithoutParameters() { - XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message"); - - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - } - - void testFromString_AuthorityWithQueryWithParameters() { - XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message"); - - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); - CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); - } - - void testFromString_AuthorityWithQueryWithoutParametersWithFragment() { - XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message#myfragment"); - - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); - } - - void testFromString_AuthorityWithQueryWithParametersWithFragment() { - XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment"); - - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); - CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); - CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); - } - - void testFromString_Path() { - XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com"); - - CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); - } - - void testFromString_PathWithFragment() { - XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com#myfragment"); - - CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); - CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); - } - - void testFromString_PathWithIntlChars() { - XMPPURI testling = XMPPURI::fromString("xmpp:nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com"); + CPPUNIT_TEST_SUITE(XMPPURITest); + CPPUNIT_TEST(testFromString_Authority); + CPPUNIT_TEST(testFromString_AuthorityWithPath); + CPPUNIT_TEST(testFromString_AuthorityWithFragment); + CPPUNIT_TEST(testFromString_AuthorityWithPathAndFragment); + CPPUNIT_TEST(testFromString_AuthorityWithIntlChars); + CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParameters); + CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParameters); + CPPUNIT_TEST(testFromString_AuthorityWithQueryWithoutParametersWithFragment); + CPPUNIT_TEST(testFromString_AuthorityWithQueryWithParametersWithFragment); + CPPUNIT_TEST(testFromString_Path); + CPPUNIT_TEST(testFromString_PathWithFragment); + CPPUNIT_TEST(testFromString_PathWithIntlChars); + CPPUNIT_TEST(testFromString_PathWithInvalidEscapedChar); + CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar); + CPPUNIT_TEST(testFromString_PathWithIncompleteEscapedChar2); + CPPUNIT_TEST(testFromString_PathWithQueryWithoutParameters); + CPPUNIT_TEST(testFromString_PathWithQueryWithParameters); + CPPUNIT_TEST(testFromString_PathWithQueryWithoutParametersWithFragment); + CPPUNIT_TEST(testFromString_PathWithQueryWithParametersWithFragment); + CPPUNIT_TEST(testFromString_NoPrefix); + CPPUNIT_TEST_SUITE_END(); + + public: + void testFromString_Authority() { + XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com"); + + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); + } + + void testFromString_AuthorityWithPath() { + XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com"); + + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); + CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); + } + + void testFromString_AuthorityWithFragment() { + XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com#myfragment"); + + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); + CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); + } + + void testFromString_AuthorityWithPathAndFragment() { + XMPPURI testling = XMPPURI::fromString("xmpp://foo@bar.com/baz@example.com#myfragment"); + + CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com"), testling.getAuthority()); + CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); + CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); + } + + void testFromString_AuthorityWithIntlChars() { + XMPPURI testling = XMPPURI::fromString("xmpp://nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com"); + + CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getAuthority()); + } + + void testFromString_AuthorityWithQueryWithoutParameters() { + XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message"); + + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + } + + void testFromString_AuthorityWithQueryWithParameters() { + XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message"); + + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); + CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); + } + + void testFromString_AuthorityWithQueryWithoutParametersWithFragment() { + XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message#myfragment"); + + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); + } + + void testFromString_AuthorityWithQueryWithParametersWithFragment() { + XMPPURI testling = XMPPURI::fromString("xmpp://test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment"); + + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getAuthority()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); + CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); + CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); + } + + void testFromString_Path() { + XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com"); + + CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); + } + + void testFromString_PathWithFragment() { + XMPPURI testling = XMPPURI::fromString("xmpp:baz@example.com#myfragment"); + + CPPUNIT_ASSERT_EQUAL(JID("baz@example.com"), testling.getPath()); + CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); + } + + void testFromString_PathWithIntlChars() { + XMPPURI testling = XMPPURI::fromString("xmpp:nasty!%23$%25()*+,-.;=%3F%5B%5C%5D%5E_%60%7B%7C%7D~node@example.com"); - CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getPath()); - } + CPPUNIT_ASSERT_EQUAL(JID("nasty!#$%()*+,-.;=?[\\]^_`{|}~node@example.com"), testling.getPath()); + } - void testFromString_PathWithInvalidEscapedChar() { - XMPPURI testling = XMPPURI::fromString("xmpp:test%%@example.com"); + void testFromString_PathWithInvalidEscapedChar() { + XMPPURI testling = XMPPURI::fromString("xmpp:test%%@example.com"); - CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath()); - } + CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath()); + } - void testFromString_PathWithIncompleteEscapedChar() { - XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%"); + void testFromString_PathWithIncompleteEscapedChar() { + XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%"); - CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath()); - } + CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath()); + } - void testFromString_PathWithIncompleteEscapedChar2() { - XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%1"); + void testFromString_PathWithIncompleteEscapedChar2() { + XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com%1"); - CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath()); - } + CPPUNIT_ASSERT_EQUAL(JID(), testling.getPath()); + } - void testFromString_PathWithQueryWithoutParameters() { - XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message"); + void testFromString_PathWithQueryWithoutParameters() { + XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message"); - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - } + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + } - void testFromString_PathWithQueryWithParameters() { - XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message"); + void testFromString_PathWithQueryWithParameters() { + XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message"); - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); - CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); - } + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); + CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); + } - void testFromString_PathWithQueryWithoutParametersWithFragment() { - XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message#myfragment"); + void testFromString_PathWithQueryWithoutParametersWithFragment() { + XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message#myfragment"); - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); - } + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); + } - void testFromString_PathWithQueryWithParametersWithFragment() { - XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment"); + void testFromString_PathWithQueryWithParametersWithFragment() { + XMPPURI testling = XMPPURI::fromString("xmpp:test@example.com?message;subject=Test%20Message;body=Here%27s%20a%20test%20message#myfragment"); - CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); - CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); - CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); - CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); - CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); - } + CPPUNIT_ASSERT_EQUAL(JID("test@example.com"), testling.getPath()); + CPPUNIT_ASSERT_EQUAL(std::string("message"), testling.getQueryType()); + CPPUNIT_ASSERT_EQUAL(std::string("Test Message"), get(testling.getQueryParameters(), "subject")); + CPPUNIT_ASSERT_EQUAL(std::string("Here's a test message"), get(testling.getQueryParameters(), "body")); + CPPUNIT_ASSERT_EQUAL(std::string("myfragment"), testling.getFragment()); + } - void testFromString_NoPrefix() { - XMPPURI testling = XMPPURI::fromString("baz@example.com"); + void testFromString_NoPrefix() { + XMPPURI testling = XMPPURI::fromString("baz@example.com"); - CPPUNIT_ASSERT(testling.isNull()); - } + CPPUNIT_ASSERT(testling.isNull()); + } - private: - std::string get(const std::map& m, const std::string& k) { - std::map::const_iterator i = m.find(k); - return i == m.end() ? "" : i->second; - } + private: + std::string get(const std::map& m, const std::string& k) { + std::map::const_iterator i = m.find(k); + return i == m.end() ? "" : i->second; + } }; CPPUNIT_TEST_SUITE_REGISTRATION(XMPPURITest); diff --git a/SwifTools/URIHandler/XMPPURI.cpp b/SwifTools/URIHandler/XMPPURI.cpp index 38fc72d..8b8b81c 100644 --- a/SwifTools/URIHandler/XMPPURI.cpp +++ b/SwifTools/URIHandler/XMPPURI.cpp @@ -26,77 +26,77 @@ XMPPURI::XMPPURI() { } XMPPURI XMPPURI::fromString(const std::string& s) { - XMPPURI result; - if (boost::starts_with(s, "xmpp:")) { - std::string uri = s.substr(5, s.npos); - bool parsePath = true; - bool parseQuery = true; - bool parseFragment = true; + XMPPURI result; + if (boost::starts_with(s, "xmpp:")) { + std::string uri = s.substr(5, s.npos); + bool parsePath = true; + bool parseQuery = true; + bool parseFragment = true; - // Parse authority - if (boost::starts_with(uri, "//")) { - size_t i = uri.find_first_of("/#?", 2); - result.setAuthority(JID(URL::unescape(uri.substr(2, i - 2)))); - if (i == uri.npos) { - uri = ""; - parsePath = parseQuery = parseFragment = false; - } - else { - if (uri[i] == '?') { - parsePath = false; - } - else if (uri[i] == '#') { - parseQuery = parsePath = false; - } - uri = uri.substr(i + 1, uri.npos); - } - } + // Parse authority + if (boost::starts_with(uri, "//")) { + size_t i = uri.find_first_of("/#?", 2); + result.setAuthority(JID(URL::unescape(uri.substr(2, i - 2)))); + if (i == uri.npos) { + uri = ""; + parsePath = parseQuery = parseFragment = false; + } + else { + if (uri[i] == '?') { + parsePath = false; + } + else if (uri[i] == '#') { + parseQuery = parsePath = false; + } + uri = uri.substr(i + 1, uri.npos); + } + } - // Parse path - if (parsePath) { - size_t i = uri.find_first_of("#?"); - result.setPath(JID(URL::unescape(uri.substr(0, i)))); - if (i == uri.npos) { - uri = ""; - parseQuery = parseFragment = false; - } - else { - if (uri[i] == '#') { - parseQuery = false; - } - uri = uri.substr(i + 1, uri.npos); - } - } + // Parse path + if (parsePath) { + size_t i = uri.find_first_of("#?"); + result.setPath(JID(URL::unescape(uri.substr(0, i)))); + if (i == uri.npos) { + uri = ""; + parseQuery = parseFragment = false; + } + else { + if (uri[i] == '#') { + parseQuery = false; + } + uri = uri.substr(i + 1, uri.npos); + } + } - // Parse query - if (parseQuery) { - size_t end = uri.find_first_of("#"); - std::string query = uri.substr(0, end); - bool haveType = false; - typedef boost::split_iterator split_iterator; - for (split_iterator it = boost::make_split_iterator(query, boost::first_finder(";")); it != split_iterator(); ++it) { - if (haveType) { - std::vector keyValue; - boost::split(keyValue, *it, boost::is_any_of("=")); - if (keyValue.size() == 1) { - result.addQueryParameter(URL::unescape(keyValue[0]), ""); - } - else if (keyValue.size() >= 2) { - result.addQueryParameter(URL::unescape(keyValue[0]), URL::unescape(keyValue[1])); - } - } - else { - result.setQueryType(URL::unescape(boost::copy_range(*it))); - haveType = true; - } - } - uri = (end == uri.npos ? "" : uri.substr(end + 1, uri.npos)); - } + // Parse query + if (parseQuery) { + size_t end = uri.find_first_of("#"); + std::string query = uri.substr(0, end); + bool haveType = false; + typedef boost::split_iterator split_iterator; + for (split_iterator it = boost::make_split_iterator(query, boost::first_finder(";")); it != split_iterator(); ++it) { + if (haveType) { + std::vector keyValue; + boost::split(keyValue, *it, boost::is_any_of("=")); + if (keyValue.size() == 1) { + result.addQueryParameter(URL::unescape(keyValue[0]), ""); + } + else if (keyValue.size() >= 2) { + result.addQueryParameter(URL::unescape(keyValue[0]), URL::unescape(keyValue[1])); + } + } + else { + result.setQueryType(URL::unescape(boost::copy_range(*it))); + haveType = true; + } + } + uri = (end == uri.npos ? "" : uri.substr(end + 1, uri.npos)); + } - // Parse fragment - if (parseFragment) { - result.setFragment(URL::unescape(uri)); - } - } - return result; + // Parse fragment + if (parseFragment) { + result.setFragment(URL::unescape(uri)); + } + } + return result; } diff --git a/SwifTools/URIHandler/XMPPURI.h b/SwifTools/URIHandler/XMPPURI.h index 275f99a..a8c9f95 100644 --- a/SwifTools/URIHandler/XMPPURI.h +++ b/SwifTools/URIHandler/XMPPURI.h @@ -12,62 +12,62 @@ #include namespace Swift { - // TODO: Implement using Base/URI - class XMPPURI { - public: - XMPPURI(); - - const JID& getAuthority() const { - return authority; - } - - void setAuthority(const JID& j) { - authority = j; - } - - const JID& getPath() const { - return path; - } - - void setPath(const JID& j) { - path = j; - } - - const std::string& getQueryType() const { - return queryType; - } - - void setQueryType(const std::string& q) { - queryType = q; - } - - const std::map& getQueryParameters() const { - return queryParameters; - } - - void addQueryParameter(const std::string& key, const std::string& path) { - queryParameters[key] = path; - } - - const std::string& getFragment() const { - return fragment; - } - - void setFragment(const std::string& f) { - fragment = f; - } - - bool isNull() const { - return !authority.isValid() && !path.isValid(); - } - - static XMPPURI fromString(const std::string&); - - private: - JID authority; - JID path; - std::string fragment; - std::string queryType; - std::map queryParameters; - }; + // TODO: Implement using Base/URI + class XMPPURI { + public: + XMPPURI(); + + const JID& getAuthority() const { + return authority; + } + + void setAuthority(const JID& j) { + authority = j; + } + + const JID& getPath() const { + return path; + } + + void setPath(const JID& j) { + path = j; + } + + const std::string& getQueryType() const { + return queryType; + } + + void setQueryType(const std::string& q) { + queryType = q; + } + + const std::map& getQueryParameters() const { + return queryParameters; + } + + void addQueryParameter(const std::string& key, const std::string& path) { + queryParameters[key] = path; + } + + const std::string& getFragment() const { + return fragment; + } + + void setFragment(const std::string& f) { + fragment = f; + } + + bool isNull() const { + return !authority.isValid() && !path.isValid(); + } + + static XMPPURI fromString(const std::string&); + + private: + JID authority; + JID path; + std::string fragment; + std::string queryType; + std::map queryParameters; + }; } diff --git a/SwifTools/UnitTest/LastLineTrackerTest.cpp b/SwifTools/UnitTest/LastLineTrackerTest.cpp index 97790e5..0fc77b6 100644 --- a/SwifTools/UnitTest/LastLineTrackerTest.cpp +++ b/SwifTools/UnitTest/LastLineTrackerTest.cpp @@ -12,53 +12,53 @@ using namespace Swift; class LastLineTrackerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LastLineTrackerTest); - CPPUNIT_TEST(testFocusNormal); - CPPUNIT_TEST(testFocusOut); - CPPUNIT_TEST(testFocusOtherTab); - CPPUNIT_TEST(testRepeatedFocusOut); - CPPUNIT_TEST(testRepeatedFocusIn); - CPPUNIT_TEST_SUITE_END(); - public: - LastLineTrackerTest () { - } - void testFocusNormal() { - LastLineTracker testling; - testling.setHasFocus(true); - CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); - } - void testFocusOut() { - LastLineTracker testling; - testling.setHasFocus(false); - CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); - CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); - CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); - } - void testFocusOtherTab() { - LastLineTracker testling; - testling.setHasFocus(true); - testling.setHasFocus(false); - CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); - CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); - } + CPPUNIT_TEST_SUITE(LastLineTrackerTest); + CPPUNIT_TEST(testFocusNormal); + CPPUNIT_TEST(testFocusOut); + CPPUNIT_TEST(testFocusOtherTab); + CPPUNIT_TEST(testRepeatedFocusOut); + CPPUNIT_TEST(testRepeatedFocusIn); + CPPUNIT_TEST_SUITE_END(); + public: + LastLineTrackerTest () { + } + void testFocusNormal() { + LastLineTracker testling; + testling.setHasFocus(true); + CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); + } + void testFocusOut() { + LastLineTracker testling; + testling.setHasFocus(false); + CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); + CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); + CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); + } + void testFocusOtherTab() { + LastLineTracker testling; + testling.setHasFocus(true); + testling.setHasFocus(false); + CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); + CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); + } - void testRepeatedFocusOut() { - LastLineTracker testling; - testling.setHasFocus(true); - CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); - testling.setHasFocus(false); - CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); - testling.setHasFocus(false); - CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); - } - void testRepeatedFocusIn() { - LastLineTracker testling; - testling.setHasFocus(false); - CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); - testling.setHasFocus(true); - testling.setHasFocus(false); - CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); - } + void testRepeatedFocusOut() { + LastLineTracker testling; + testling.setHasFocus(true); + CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); + testling.setHasFocus(false); + CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); + testling.setHasFocus(false); + CPPUNIT_ASSERT_EQUAL(false, testling.getShouldMoveLastLine()); + } + void testRepeatedFocusIn() { + LastLineTracker testling; + testling.setHasFocus(false); + CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); + testling.setHasFocus(true); + testling.setHasFocus(false); + CPPUNIT_ASSERT_EQUAL(true, testling.getShouldMoveLastLine()); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(LastLineTrackerTest); diff --git a/SwifTools/UnitTest/LinkifyTest.cpp b/SwifTools/UnitTest/LinkifyTest.cpp index 663581d..69a0e23 100644 --- a/SwifTools/UnitTest/LinkifyTest.cpp +++ b/SwifTools/UnitTest/LinkifyTest.cpp @@ -12,230 +12,230 @@ using namespace Swift; class LinkifyTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LinkifyTest); - CPPUNIT_TEST(testLinkify_URLWithResource); - CPPUNIT_TEST(testLinkify_HTTPSURLWithResource); - CPPUNIT_TEST(testLinkify_URLWithEmptyResource); - CPPUNIT_TEST(testLinkify_BareURL); - CPPUNIT_TEST(testLinkify_URLSurroundedByWhitespace); - CPPUNIT_TEST(testLinkify_MultipleURLs); - CPPUNIT_TEST(testLinkify_CamelCase); - CPPUNIT_TEST(testLinkify_HierarchicalResource); - CPPUNIT_TEST(testLinkify_Anchor); - CPPUNIT_TEST(testLinkify_Plus); - CPPUNIT_TEST(testLinkify_Tilde); - CPPUNIT_TEST(testLinkify_Equal); - CPPUNIT_TEST(testLinkify_Authentication); - CPPUNIT_TEST(testLinkify_At); - CPPUNIT_TEST(testLinkify_Amps); - CPPUNIT_TEST(testLinkify_UnicodeCharacter); - CPPUNIT_TEST(testLinkify_NewLine); - CPPUNIT_TEST(testLinkify_Tab); - CPPUNIT_TEST(testLinkify_Action); - - CPPUNIT_TEST(testLinkify_SplitNone); - CPPUNIT_TEST(testLinkify_SplitAll); - CPPUNIT_TEST(testLinkify_SplitFirst); - CPPUNIT_TEST(testLinkify_SplitSecond); - CPPUNIT_TEST(testLinkify_SplitMiddle); - CPPUNIT_TEST_SUITE_END(); - - public: - void testLinkify_URLWithResource() { - std::string result = Linkify::linkify("http://swift.im/blog"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://swift.im/blog"), - result); - } - - void testLinkify_HTTPSURLWithResource() { - std::string result = Linkify::linkify("https://swift.im/blog"); - - CPPUNIT_ASSERT_EQUAL( - std::string("https://swift.im/blog"), - result); - } - - void testLinkify_URLWithEmptyResource() { - std::string result = Linkify::linkify("http://swift.im/"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://swift.im/"), - result); - } - - - void testLinkify_BareURL() { - std::string result = Linkify::linkify("http://swift.im"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://swift.im"), - result); - } - - void testLinkify_URLSurroundedByWhitespace() { - std::string result = Linkify::linkify("Foo http://swift.im/blog Bar"); - - CPPUNIT_ASSERT_EQUAL( - std::string("Foo http://swift.im/blog Bar"), - result); - } - - void testLinkify_MultipleURLs() { - std::string result = Linkify::linkify("Foo http://swift.im/blog Bar http://el-tramo.be/about Baz"); - - CPPUNIT_ASSERT_EQUAL( - std::string("Foo http://swift.im/blog Bar http://el-tramo.be/about Baz"), - result); - } - - void testLinkify_CamelCase() { - std::string result = Linkify::linkify("http://fOo.cOm/bAz"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://fOo.cOm/bAz"), - result); - } - - void testLinkify_HierarchicalResource() { - std::string result = Linkify::linkify("http://foo.com/bar/baz/"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://foo.com/bar/baz/"), - result); - } - - void testLinkify_Anchor() { - std::string result = Linkify::linkify("http://foo.com/bar#baz"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://foo.com/bar#baz"), - result); - } - - void testLinkify_Plus() { - std::string result = Linkify::linkify("http://foo.com/bar+baz"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://foo.com/bar+baz"), - result); - } - - void testLinkify_Tilde() { - std::string result = Linkify::linkify("http://foo.com/~kev/"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://foo.com/~kev/"), - result); - } - - void testLinkify_Equal() { - std::string result = Linkify::linkify("http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0"), - result); - } - - void testLinkify_Authentication() { - std::string result = Linkify::linkify("http://bob:bla@swift.im/foo/bar"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://bob:bla@swift.im/foo/bar"), - result); - } - - void testLinkify_At() { - std::string result = Linkify::linkify("http://swift.im/foo@bar"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://swift.im/foo@bar"), - result); - } - - void testLinkify_Amps() { - std::string result = Linkify::linkify("http://swift.im/foo&bar&baz"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://swift.im/foo&bar&baz"), - result); - } - - void testLinkify_UnicodeCharacter() { - std::string result = Linkify::linkify("http://\xe2\x98\x83.net"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://\xe2\x98\x83.net"), - result); - } - - void testLinkify_NewLine() { - std::string result = Linkify::linkify("http://swift.im\nfoo"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://swift.im\nfoo"), - result); - } - - void testLinkify_Tab() { - std::string result = Linkify::linkify("http://swift.im\tfoo"); - - CPPUNIT_ASSERT_EQUAL( - std::string("http://swift.im\tfoo"), - result); - } - - void testLinkify_Action() { - std::string result = Linkify::linkify("*http://swift.im*"); - - CPPUNIT_ASSERT_EQUAL( - std::string("*http://swift.im*"), - result); - } - - void checkResult(const std::string& testling, size_t expectedIndex, std::string expectedSplit[]) { - std::pair, size_t> result = Linkify::splitLink(testling); - CPPUNIT_ASSERT_EQUAL(expectedIndex, result.second); - for (size_t i = 0; i < result.first.size(); i++) { - CPPUNIT_ASSERT_EQUAL(expectedSplit[i], result.first[i]); - } - } - - void testLinkify_SplitNone() { - std::string testling = "http this ain't"; - size_t expectedIndex = 1; - std::string expectedSplit[] = {"http this ain't"}; - checkResult(testling, expectedIndex, expectedSplit); - } - - void testLinkify_SplitAll() { - std::string testling = "http://swift.im"; - size_t expectedIndex = 0; - std::string expectedSplit[] = {"http://swift.im"}; - checkResult(testling, expectedIndex, expectedSplit); - } - - void testLinkify_SplitFirst() { - std::string testling = "http://swift.im is a link"; - size_t expectedIndex = 0; - std::string expectedSplit[] = {"http://swift.im", " is a link"}; - checkResult(testling, expectedIndex, expectedSplit); - } - - void testLinkify_SplitSecond() { - std::string testling = "this is a link: http://swift.im"; - size_t expectedIndex = 1; - std::string expectedSplit[] = {"this is a link: ", "http://swift.im"}; - checkResult(testling, expectedIndex, expectedSplit); - } - - void testLinkify_SplitMiddle() { - std::string testling = "Shove a link like http://swift.im in the middle"; - size_t expectedIndex = 1; - std::string expectedSplit[] = {"Shove a link like ","http://swift.im", " in the middle"}; - checkResult(testling, expectedIndex, expectedSplit); - } + CPPUNIT_TEST_SUITE(LinkifyTest); + CPPUNIT_TEST(testLinkify_URLWithResource); + CPPUNIT_TEST(testLinkify_HTTPSURLWithResource); + CPPUNIT_TEST(testLinkify_URLWithEmptyResource); + CPPUNIT_TEST(testLinkify_BareURL); + CPPUNIT_TEST(testLinkify_URLSurroundedByWhitespace); + CPPUNIT_TEST(testLinkify_MultipleURLs); + CPPUNIT_TEST(testLinkify_CamelCase); + CPPUNIT_TEST(testLinkify_HierarchicalResource); + CPPUNIT_TEST(testLinkify_Anchor); + CPPUNIT_TEST(testLinkify_Plus); + CPPUNIT_TEST(testLinkify_Tilde); + CPPUNIT_TEST(testLinkify_Equal); + CPPUNIT_TEST(testLinkify_Authentication); + CPPUNIT_TEST(testLinkify_At); + CPPUNIT_TEST(testLinkify_Amps); + CPPUNIT_TEST(testLinkify_UnicodeCharacter); + CPPUNIT_TEST(testLinkify_NewLine); + CPPUNIT_TEST(testLinkify_Tab); + CPPUNIT_TEST(testLinkify_Action); + + CPPUNIT_TEST(testLinkify_SplitNone); + CPPUNIT_TEST(testLinkify_SplitAll); + CPPUNIT_TEST(testLinkify_SplitFirst); + CPPUNIT_TEST(testLinkify_SplitSecond); + CPPUNIT_TEST(testLinkify_SplitMiddle); + CPPUNIT_TEST_SUITE_END(); + + public: + void testLinkify_URLWithResource() { + std::string result = Linkify::linkify("http://swift.im/blog"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://swift.im/blog"), + result); + } + + void testLinkify_HTTPSURLWithResource() { + std::string result = Linkify::linkify("https://swift.im/blog"); + + CPPUNIT_ASSERT_EQUAL( + std::string("https://swift.im/blog"), + result); + } + + void testLinkify_URLWithEmptyResource() { + std::string result = Linkify::linkify("http://swift.im/"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://swift.im/"), + result); + } + + + void testLinkify_BareURL() { + std::string result = Linkify::linkify("http://swift.im"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://swift.im"), + result); + } + + void testLinkify_URLSurroundedByWhitespace() { + std::string result = Linkify::linkify("Foo http://swift.im/blog Bar"); + + CPPUNIT_ASSERT_EQUAL( + std::string("Foo http://swift.im/blog Bar"), + result); + } + + void testLinkify_MultipleURLs() { + std::string result = Linkify::linkify("Foo http://swift.im/blog Bar http://el-tramo.be/about Baz"); + + CPPUNIT_ASSERT_EQUAL( + std::string("Foo http://swift.im/blog Bar http://el-tramo.be/about Baz"), + result); + } + + void testLinkify_CamelCase() { + std::string result = Linkify::linkify("http://fOo.cOm/bAz"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://fOo.cOm/bAz"), + result); + } + + void testLinkify_HierarchicalResource() { + std::string result = Linkify::linkify("http://foo.com/bar/baz/"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://foo.com/bar/baz/"), + result); + } + + void testLinkify_Anchor() { + std::string result = Linkify::linkify("http://foo.com/bar#baz"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://foo.com/bar#baz"), + result); + } + + void testLinkify_Plus() { + std::string result = Linkify::linkify("http://foo.com/bar+baz"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://foo.com/bar+baz"), + result); + } + + void testLinkify_Tilde() { + std::string result = Linkify::linkify("http://foo.com/~kev/"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://foo.com/~kev/"), + result); + } + + void testLinkify_Equal() { + std::string result = Linkify::linkify("http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=xmpp+definitive+guide&x=0&y=0"), + result); + } + + void testLinkify_Authentication() { + std::string result = Linkify::linkify("http://bob:bla@swift.im/foo/bar"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://bob:bla@swift.im/foo/bar"), + result); + } + + void testLinkify_At() { + std::string result = Linkify::linkify("http://swift.im/foo@bar"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://swift.im/foo@bar"), + result); + } + + void testLinkify_Amps() { + std::string result = Linkify::linkify("http://swift.im/foo&bar&baz"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://swift.im/foo&bar&baz"), + result); + } + + void testLinkify_UnicodeCharacter() { + std::string result = Linkify::linkify("http://\xe2\x98\x83.net"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://\xe2\x98\x83.net"), + result); + } + + void testLinkify_NewLine() { + std::string result = Linkify::linkify("http://swift.im\nfoo"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://swift.im\nfoo"), + result); + } + + void testLinkify_Tab() { + std::string result = Linkify::linkify("http://swift.im\tfoo"); + + CPPUNIT_ASSERT_EQUAL( + std::string("http://swift.im\tfoo"), + result); + } + + void testLinkify_Action() { + std::string result = Linkify::linkify("*http://swift.im*"); + + CPPUNIT_ASSERT_EQUAL( + std::string("*http://swift.im*"), + result); + } + + void checkResult(const std::string& testling, size_t expectedIndex, std::string expectedSplit[]) { + std::pair, size_t> result = Linkify::splitLink(testling); + CPPUNIT_ASSERT_EQUAL(expectedIndex, result.second); + for (size_t i = 0; i < result.first.size(); i++) { + CPPUNIT_ASSERT_EQUAL(expectedSplit[i], result.first[i]); + } + } + + void testLinkify_SplitNone() { + std::string testling = "http this ain't"; + size_t expectedIndex = 1; + std::string expectedSplit[] = {"http this ain't"}; + checkResult(testling, expectedIndex, expectedSplit); + } + + void testLinkify_SplitAll() { + std::string testling = "http://swift.im"; + size_t expectedIndex = 0; + std::string expectedSplit[] = {"http://swift.im"}; + checkResult(testling, expectedIndex, expectedSplit); + } + + void testLinkify_SplitFirst() { + std::string testling = "http://swift.im is a link"; + size_t expectedIndex = 0; + std::string expectedSplit[] = {"http://swift.im", " is a link"}; + checkResult(testling, expectedIndex, expectedSplit); + } + + void testLinkify_SplitSecond() { + std::string testling = "this is a link: http://swift.im"; + size_t expectedIndex = 1; + std::string expectedSplit[] = {"this is a link: ", "http://swift.im"}; + checkResult(testling, expectedIndex, expectedSplit); + } + + void testLinkify_SplitMiddle() { + std::string testling = "Shove a link like http://swift.im in the middle"; + size_t expectedIndex = 1; + std::string expectedSplit[] = {"Shove a link like ","http://swift.im", " in the middle"}; + checkResult(testling, expectedIndex, expectedSplit); + } }; diff --git a/SwifTools/UnitTest/SpellParserTest.cpp b/SwifTools/UnitTest/SpellParserTest.cpp index 3747eb1..da233e5 100644 --- a/SwifTools/UnitTest/SpellParserTest.cpp +++ b/SwifTools/UnitTest/SpellParserTest.cpp @@ -20,38 +20,38 @@ using namespace Swift; class SpellParserTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SpellParserTest); - CPPUNIT_TEST(testSimpleCheckFragment); - CPPUNIT_TEST(testWWWCheckFragment); - CPPUNIT_TEST_SUITE_END(); - public: - SpellParserTest() { - parser_ = new SpellParser(); - }; - void tearDown() { - position_.clear(); - } - void testSimpleCheckFragment() { - parser_->check("fragment test", position_); - int size = position_.size(); - CPPUNIT_ASSERT_EQUAL(2, size); - CPPUNIT_ASSERT_EQUAL(0, boost::get<0>(position_.front())); - CPPUNIT_ASSERT_EQUAL(8, boost::get<1>(position_.front())); - CPPUNIT_ASSERT_EQUAL(9, boost::get<0>(position_.back())); - CPPUNIT_ASSERT_EQUAL(13, boost::get<1>(position_.back())); - } - void testWWWCheckFragment() { - parser_->check("www.link.com fragment test", position_); - int size = position_.size(); - CPPUNIT_ASSERT_EQUAL(2, size); - CPPUNIT_ASSERT_EQUAL(13, boost::get<0>(position_.front())); - CPPUNIT_ASSERT_EQUAL(21, boost::get<1>(position_.front())); - CPPUNIT_ASSERT_EQUAL(22, boost::get<0>(position_.back())); - CPPUNIT_ASSERT_EQUAL(26, boost::get<1>(position_.back())); - } - private: - SpellParser *parser_; - PositionPairList position_; + CPPUNIT_TEST_SUITE(SpellParserTest); + CPPUNIT_TEST(testSimpleCheckFragment); + CPPUNIT_TEST(testWWWCheckFragment); + CPPUNIT_TEST_SUITE_END(); + public: + SpellParserTest() { + parser_ = new SpellParser(); + }; + void tearDown() { + position_.clear(); + } + void testSimpleCheckFragment() { + parser_->check("fragment test", position_); + int size = position_.size(); + CPPUNIT_ASSERT_EQUAL(2, size); + CPPUNIT_ASSERT_EQUAL(0, boost::get<0>(position_.front())); + CPPUNIT_ASSERT_EQUAL(8, boost::get<1>(position_.front())); + CPPUNIT_ASSERT_EQUAL(9, boost::get<0>(position_.back())); + CPPUNIT_ASSERT_EQUAL(13, boost::get<1>(position_.back())); + } + void testWWWCheckFragment() { + parser_->check("www.link.com fragment test", position_); + int size = position_.size(); + CPPUNIT_ASSERT_EQUAL(2, size); + CPPUNIT_ASSERT_EQUAL(13, boost::get<0>(position_.front())); + CPPUNIT_ASSERT_EQUAL(21, boost::get<1>(position_.front())); + CPPUNIT_ASSERT_EQUAL(22, boost::get<0>(position_.back())); + CPPUNIT_ASSERT_EQUAL(26, boost::get<1>(position_.back())); + } + private: + SpellParser *parser_; + PositionPairList position_; }; CPPUNIT_TEST_SUITE_REGISTRATION(SpellParserTest); diff --git a/SwifTools/UnitTest/TabCompleteTest.cpp b/SwifTools/UnitTest/TabCompleteTest.cpp index 2642410..56c91a8 100644 --- a/SwifTools/UnitTest/TabCompleteTest.cpp +++ b/SwifTools/UnitTest/TabCompleteTest.cpp @@ -12,254 +12,254 @@ using namespace Swift; class TabCompleteTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(TabCompleteTest); - CPPUNIT_TEST(testEmpty); - CPPUNIT_TEST(testNoMatch); - CPPUNIT_TEST(testOneMatch); - CPPUNIT_TEST(testTwoMatch); - CPPUNIT_TEST(testChangeMatch); - CPPUNIT_TEST(testRemoveDuringComplete); - CPPUNIT_TEST(testAddDuringComplete); - CPPUNIT_TEST(testSwiftRoomSample); - CPPUNIT_TEST_SUITE_END(); - + CPPUNIT_TEST_SUITE(TabCompleteTest); + CPPUNIT_TEST(testEmpty); + CPPUNIT_TEST(testNoMatch); + CPPUNIT_TEST(testOneMatch); + CPPUNIT_TEST(testTwoMatch); + CPPUNIT_TEST(testChangeMatch); + CPPUNIT_TEST(testRemoveDuringComplete); + CPPUNIT_TEST(testAddDuringComplete); + CPPUNIT_TEST(testSwiftRoomSample); + CPPUNIT_TEST_SUITE_END(); + public: - TabCompleteTest() {} - - void setUp() { - completer_ = TabComplete(); - } - - void testEmpty() { - std::string blah("Blah"); - CPPUNIT_ASSERT_EQUAL( - blah, - completer_.completeWord(blah)); - CPPUNIT_ASSERT_EQUAL( - blah, - completer_.completeWord(blah)); - } - - void testNoMatch() { - completer_.addWord("Bleh"); - std::string blah("Blah"); - CPPUNIT_ASSERT_EQUAL( - blah, - completer_.completeWord(blah)); - CPPUNIT_ASSERT_EQUAL( - blah, - completer_.completeWord(blah)); - } - - void testOneMatch() { - std::string short1("Bl"); - std::string long1("Blehling"); - completer_.addWord(long1); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(short1)); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(long1)); - } - - void testTwoMatch() { - std::string short1("Hur"); - std::string long1("Hurgle"); - std::string long2("Hurdler"); - completer_.addWord(long1); - completer_.addWord("Blah"); - completer_.addWord(long2); - completer_.addWord("Bleh"); - CPPUNIT_ASSERT_EQUAL( - long2, - completer_.completeWord(short1)); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(long2)); - CPPUNIT_ASSERT_EQUAL( - long2, - completer_.completeWord(long1)); - } - - void testChangeMatch() { - std::string short1("Hur"); - std::string short2("Rub"); - std::string long1("Hurgle"); - std::string long2("Rubbish"); - completer_.addWord(long2); - completer_.addWord("Blah"); - completer_.addWord(long1); - completer_.addWord("Bleh"); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(short1)); - CPPUNIT_ASSERT_EQUAL( - long2, - completer_.completeWord(short2)); - CPPUNIT_ASSERT_EQUAL( - long2, - completer_.completeWord(long2)); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(short1)); - } - - void testRemoveDuringComplete() { - std::string short1("Kev"); - std::string long1("Kevin"); - std::string long2("Kevlar"); - completer_.addWord(long1); - completer_.addWord("Blah"); - completer_.addWord(long2); - completer_.addWord("Bleh"); - CPPUNIT_ASSERT_EQUAL( - long2, - completer_.completeWord(short1)); - completer_.removeWord(long2); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(long2)); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(long1)); - } - - void testAddDuringComplete() { - std::string short1("Rem"); - std::string long1("Remko"); - std::string long2("Remove"); - std::string long3("Remedial"); - completer_.addWord(long1); - completer_.addWord("Blah"); - completer_.addWord(long2); - completer_.addWord("Bleh"); - CPPUNIT_ASSERT_EQUAL( - long2, - completer_.completeWord(short1)); - completer_.addWord(long3); - CPPUNIT_ASSERT_EQUAL( - long1, - completer_.completeWord(long2)); - CPPUNIT_ASSERT_EQUAL( - long3, - completer_.completeWord(long1)); - } - - void testSwiftRoomSample() { - std::string t("t"); - std::string Anpan("Anpan"); - std::string cdubouloz("cdubouloz"); - std::string Tobias("Tobias"); - std::string Zash("Zash"); - std::string lastsky("lastsky"); - std::string Steve("Steve Kille"); - std::string Flo("Flo"); - std::string Test("Test"); - std::string test("test"); - completer_.addWord(Anpan); - completer_.addWord(cdubouloz); - completer_.addWord(Tobias); - completer_.addWord(lastsky); - completer_.addWord(Steve); - completer_.addWord(Flo); - completer_.addWord(Zash); - - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(Tobias)); - - completer_.addWord(Test); - - CPPUNIT_ASSERT_EQUAL( - Test, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(Test)); - CPPUNIT_ASSERT_EQUAL( - Test, - completer_.completeWord(Tobias)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(Test)); - - completer_.addWord(Zash); - completer_.addWord(Zash); - completer_.addWord(Zash); - completer_.addWord(Zash); - - completer_.removeWord(Test); - - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(Tobias)); - - completer_.addWord(test); - - completer_.addWord(Zash); - completer_.addWord(Zash); - completer_.addWord(Zash); - completer_.addWord(Zash); - - - CPPUNIT_ASSERT_EQUAL( - test, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(test)); - CPPUNIT_ASSERT_EQUAL( - test, - completer_.completeWord(Tobias)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(test)); - - completer_.removeWord(test); - - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(Tobias)); - - completer_.removeWord(Tobias); - CPPUNIT_ASSERT_EQUAL( - t, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - t, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - t, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - t, - completer_.completeWord(t)); - - completer_.addWord(Tobias); - - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(t)); - CPPUNIT_ASSERT_EQUAL( - Tobias, - completer_.completeWord(Tobias)); - - } + TabCompleteTest() {} + + void setUp() { + completer_ = TabComplete(); + } + + void testEmpty() { + std::string blah("Blah"); + CPPUNIT_ASSERT_EQUAL( + blah, + completer_.completeWord(blah)); + CPPUNIT_ASSERT_EQUAL( + blah, + completer_.completeWord(blah)); + } + + void testNoMatch() { + completer_.addWord("Bleh"); + std::string blah("Blah"); + CPPUNIT_ASSERT_EQUAL( + blah, + completer_.completeWord(blah)); + CPPUNIT_ASSERT_EQUAL( + blah, + completer_.completeWord(blah)); + } + + void testOneMatch() { + std::string short1("Bl"); + std::string long1("Blehling"); + completer_.addWord(long1); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(short1)); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(long1)); + } + + void testTwoMatch() { + std::string short1("Hur"); + std::string long1("Hurgle"); + std::string long2("Hurdler"); + completer_.addWord(long1); + completer_.addWord("Blah"); + completer_.addWord(long2); + completer_.addWord("Bleh"); + CPPUNIT_ASSERT_EQUAL( + long2, + completer_.completeWord(short1)); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(long2)); + CPPUNIT_ASSERT_EQUAL( + long2, + completer_.completeWord(long1)); + } + + void testChangeMatch() { + std::string short1("Hur"); + std::string short2("Rub"); + std::string long1("Hurgle"); + std::string long2("Rubbish"); + completer_.addWord(long2); + completer_.addWord("Blah"); + completer_.addWord(long1); + completer_.addWord("Bleh"); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(short1)); + CPPUNIT_ASSERT_EQUAL( + long2, + completer_.completeWord(short2)); + CPPUNIT_ASSERT_EQUAL( + long2, + completer_.completeWord(long2)); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(short1)); + } + + void testRemoveDuringComplete() { + std::string short1("Kev"); + std::string long1("Kevin"); + std::string long2("Kevlar"); + completer_.addWord(long1); + completer_.addWord("Blah"); + completer_.addWord(long2); + completer_.addWord("Bleh"); + CPPUNIT_ASSERT_EQUAL( + long2, + completer_.completeWord(short1)); + completer_.removeWord(long2); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(long2)); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(long1)); + } + + void testAddDuringComplete() { + std::string short1("Rem"); + std::string long1("Remko"); + std::string long2("Remove"); + std::string long3("Remedial"); + completer_.addWord(long1); + completer_.addWord("Blah"); + completer_.addWord(long2); + completer_.addWord("Bleh"); + CPPUNIT_ASSERT_EQUAL( + long2, + completer_.completeWord(short1)); + completer_.addWord(long3); + CPPUNIT_ASSERT_EQUAL( + long1, + completer_.completeWord(long2)); + CPPUNIT_ASSERT_EQUAL( + long3, + completer_.completeWord(long1)); + } + + void testSwiftRoomSample() { + std::string t("t"); + std::string Anpan("Anpan"); + std::string cdubouloz("cdubouloz"); + std::string Tobias("Tobias"); + std::string Zash("Zash"); + std::string lastsky("lastsky"); + std::string Steve("Steve Kille"); + std::string Flo("Flo"); + std::string Test("Test"); + std::string test("test"); + completer_.addWord(Anpan); + completer_.addWord(cdubouloz); + completer_.addWord(Tobias); + completer_.addWord(lastsky); + completer_.addWord(Steve); + completer_.addWord(Flo); + completer_.addWord(Zash); + + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(Tobias)); + + completer_.addWord(Test); + + CPPUNIT_ASSERT_EQUAL( + Test, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(Test)); + CPPUNIT_ASSERT_EQUAL( + Test, + completer_.completeWord(Tobias)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(Test)); + + completer_.addWord(Zash); + completer_.addWord(Zash); + completer_.addWord(Zash); + completer_.addWord(Zash); + + completer_.removeWord(Test); + + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(Tobias)); + + completer_.addWord(test); + + completer_.addWord(Zash); + completer_.addWord(Zash); + completer_.addWord(Zash); + completer_.addWord(Zash); + + + CPPUNIT_ASSERT_EQUAL( + test, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(test)); + CPPUNIT_ASSERT_EQUAL( + test, + completer_.completeWord(Tobias)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(test)); + + completer_.removeWord(test); + + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(Tobias)); + + completer_.removeWord(Tobias); + CPPUNIT_ASSERT_EQUAL( + t, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + t, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + t, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + t, + completer_.completeWord(t)); + + completer_.addWord(Tobias); + + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(t)); + CPPUNIT_ASSERT_EQUAL( + Tobias, + completer_.completeWord(Tobias)); + + } private: - TabComplete completer_; + TabComplete completer_; }; CPPUNIT_TEST_SUITE_REGISTRATION(TabCompleteTest); diff --git a/Swift/Controllers/AdHocController.cpp b/Swift/Controllers/AdHocController.cpp index 38b0fc5..4b93f2b 100644 --- a/Swift/Controllers/AdHocController.cpp +++ b/Swift/Controllers/AdHocController.cpp @@ -13,21 +13,21 @@ namespace Swift { AdHocController::AdHocController(AdHocCommandWindowFactory* factory, boost::shared_ptr command) { - window_ = factory->createAdHocCommandWindow(command); - window_->onClosing.connect(boost::bind(&AdHocController::handleWindowClosed, this)); + window_ = factory->createAdHocCommandWindow(command); + window_->onClosing.connect(boost::bind(&AdHocController::handleWindowClosed, this)); } AdHocController::~AdHocController() { - window_->onClosing.disconnect(boost::bind(&AdHocController::handleWindowClosed, this)); - delete window_; + window_->onClosing.disconnect(boost::bind(&AdHocController::handleWindowClosed, this)); + delete window_; } void AdHocController::se