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::setOnline(bool online) { - window_->setOnline(online); + window_->setOnline(online); } void AdHocController::handleWindowClosed() { - onDeleting(); + onDeleting(); } } diff --git a/Swift/Controllers/AdHocController.h b/Swift/Controllers/AdHocController.h index e2b93df..4694991 100644 --- a/Swift/Controllers/AdHocController.h +++ b/Swift/Controllers/AdHocController.h @@ -17,13 +17,13 @@ class AdHocCommandWindow; class AdHocController { public: - AdHocController(AdHocCommandWindowFactory* factory, boost::shared_ptr command); - ~AdHocController(); - boost::signal onDeleting; - void setOnline(bool online); + AdHocController(AdHocCommandWindowFactory* factory, boost::shared_ptr command); + ~AdHocController(); + boost::signal onDeleting; + void setOnline(bool online); private: - void handleWindowClosed(); - AdHocCommandWindow* window_; + void handleWindowClosed(); + AdHocCommandWindow* window_; }; } diff --git a/Swift/Controllers/AdHocManager.cpp b/Swift/Controllers/AdHocManager.cpp index 4733b57..1dcefbd 100644 --- a/Swift/Controllers/AdHocManager.cpp +++ b/Swift/Controllers/AdHocManager.cpp @@ -23,73 +23,73 @@ namespace Swift { AdHocManager::AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow) : jid_(jid) { - iqRouter_ = iqRouter; - uiEventStream_ = uiEventStream; - mainWindow_ = mainWindow; - factory_ = factory; + iqRouter_ = iqRouter; + uiEventStream_ = uiEventStream; + mainWindow_ = mainWindow; + factory_ = factory; - uiEventStream_->onUIEvent.connect(boost::bind(&AdHocManager::handleUIEvent, this, _1)); + uiEventStream_->onUIEvent.connect(boost::bind(&AdHocManager::handleUIEvent, this, _1)); } AdHocManager::~AdHocManager() { - uiEventStream_->onUIEvent.disconnect(boost::bind(&AdHocManager::handleUIEvent, this, _1)); - for (size_t i = 0; i < controllers_.size(); ++i) { - controllers_[i]->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controllers_[i])); - } + uiEventStream_->onUIEvent.disconnect(boost::bind(&AdHocManager::handleUIEvent, this, _1)); + for (size_t i = 0; i < controllers_.size(); ++i) { + controllers_[i]->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controllers_[i])); + } } void AdHocManager::removeController(boost::shared_ptr controller) { - controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller)); - controllers_.erase(std::find(controllers_.begin(), controllers_.end(), controller)); + controller->onDeleting.disconnect(boost::bind(&AdHocManager::removeController, this, controller)); + controllers_.erase(std::find(controllers_.begin(), controllers_.end(), controller)); } void AdHocManager::setServerDiscoInfo(boost::shared_ptr info) { - if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::CommandsFeature)) { - if (discoItemsRequest_) { - discoItemsRequest_->onResponse.disconnect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2)); - discoItemsRequest_.reset(); - } - discoItemsRequest_ = GetDiscoItemsRequest::create(JID(jid_.getDomain()), DiscoInfo::CommandsFeature, iqRouter_); - discoItemsRequest_->onResponse.connect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2)); - discoItemsRequest_->send(); - } else { - mainWindow_->setAvailableAdHocCommands(std::vector()); - } + if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::CommandsFeature)) { + if (discoItemsRequest_) { + discoItemsRequest_->onResponse.disconnect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2)); + discoItemsRequest_.reset(); + } + discoItemsRequest_ = GetDiscoItemsRequest::create(JID(jid_.getDomain()), DiscoInfo::CommandsFeature, iqRouter_); + discoItemsRequest_->onResponse.connect(boost::bind(&AdHocManager::handleServerDiscoItemsResponse, this, _1, _2)); + discoItemsRequest_->send(); + } else { + mainWindow_->setAvailableAdHocCommands(std::vector()); + } } void AdHocManager::setOnline(bool online) { - foreach (boost::shared_ptr controller, controllers_) { - controller->setOnline(online); - } + foreach (boost::shared_ptr controller, controllers_) { + controller->setOnline(online); + } } void AdHocManager::handleServerDiscoItemsResponse(boost::shared_ptr items, ErrorPayload::ref error) { - std::vector commands; - if (!error) { - foreach (DiscoItems::Item item, items->getItems()) { - if (item.getNode() != "http://isode.com/xmpp/commands#test") { - commands.push_back(item); - } - } - } - mainWindow_->setAvailableAdHocCommands(commands); + std::vector commands; + if (!error) { + foreach (DiscoItems::Item item, items->getItems()) { + if (item.getNode() != "http://isode.com/xmpp/commands#test") { + commands.push_back(item); + } + } + } + mainWindow_->setAvailableAdHocCommands(commands); } void AdHocManager::handleUIEvent(boost::shared_ptr event) { - boost::shared_ptr adHocEvent = boost::dynamic_pointer_cast(event); - if (adHocEvent) { - boost::shared_ptr command = boost::make_shared(adHocEvent->getCommand().getJID(), adHocEvent->getCommand().getNode(), iqRouter_); - boost::shared_ptr controller = boost::make_shared(factory_, command); - controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller)); - controllers_.push_back(controller); - } - boost::shared_ptr adHocJIDEvent = boost::dynamic_pointer_cast(event); - if (!!adHocJIDEvent) { - boost::shared_ptr command = boost::make_shared(adHocJIDEvent->getJID(), adHocJIDEvent->getNode(), iqRouter_); - boost::shared_ptr controller = boost::make_shared(factory_, command); - controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller)); - controllers_.push_back(controller); - } + boost::shared_ptr adHocEvent = boost::dynamic_pointer_cast(event); + if (adHocEvent) { + boost::shared_ptr command = boost::make_shared(adHocEvent->getCommand().getJID(), adHocEvent->getCommand().getNode(), iqRouter_); + boost::shared_ptr controller = boost::make_shared(factory_, command); + controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller)); + controllers_.push_back(controller); + } + boost::shared_ptr adHocJIDEvent = boost::dynamic_pointer_cast(event); + if (!!adHocJIDEvent) { + boost::shared_ptr command = boost::make_shared(adHocJIDEvent->getJID(), adHocJIDEvent->getNode(), iqRouter_); + boost::shared_ptr controller = boost::make_shared(factory_, command); + controller->onDeleting.connect(boost::bind(&AdHocManager::removeController, this, controller)); + controllers_.push_back(controller); + } } } diff --git a/Swift/Controllers/AdHocManager.h b/Swift/Controllers/AdHocManager.h index 00289b0..73c057c 100644 --- a/Swift/Controllers/AdHocManager.h +++ b/Swift/Controllers/AdHocManager.h @@ -23,22 +23,22 @@ class UIEventStream; class AdHocCommandWindowFactory; class AdHocManager { public: - AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow); - ~AdHocManager(); - void removeController(boost::shared_ptr contoller); - void setServerDiscoInfo(boost::shared_ptr info); - void setOnline(bool online); + AdHocManager(const JID& jid, AdHocCommandWindowFactory* factory, IQRouter* iqRouter, UIEventStream* uiEventStream, MainWindow* mainWindow); + ~AdHocManager(); + void removeController(boost::shared_ptr contoller); + void setServerDiscoInfo(boost::shared_ptr info); + void setOnline(bool online); private: - void handleServerDiscoItemsResponse(boost::shared_ptr, ErrorPayload::ref error); - void handleUIEvent(boost::shared_ptr event); - boost::signal onControllerComplete; - JID jid_; - IQRouter* iqRouter_; - UIEventStream* uiEventStream_; - MainWindow* mainWindow_; - AdHocCommandWindowFactory* factory_; - GetDiscoItemsRequest::ref discoItemsRequest_; - std::vector > controllers_; + void handleServerDiscoItemsResponse(boost::shared_ptr, ErrorPayload::ref error); + void handleUIEvent(boost::shared_ptr event); + boost::signal onControllerComplete; + JID jid_; + IQRouter* iqRouter_; + UIEventStream* uiEventStream_; + MainWindow* mainWindow_; + AdHocCommandWindowFactory* factory_; + GetDiscoItemsRequest::ref discoItemsRequest_; + std::vector > controllers_; }; } diff --git a/Swift/Controllers/BlockListController.cpp b/Swift/Controllers/BlockListController.cpp index 2c8d401..6fbf6b3 100644 --- a/Swift/Controllers/BlockListController.cpp +++ b/Swift/Controllers/BlockListController.cpp @@ -28,159 +28,159 @@ namespace Swift { BlockListController::BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController) : blockListManager_(blockListManager), blockListEditorWidgetFactory_(blockListEditorWidgetFactory), blockListEditorWidget_(0), eventController_(eventController), remainingRequests_(0), uiEventStream_(uiEventStream) { - uiEventStream->onUIEvent.connect(boost::bind(&BlockListController::handleUIEvent, this, _1)); - blockListManager_->getBlockList()->onItemAdded.connect(boost::bind(&BlockListController::handleBlockListChanged, this)); - blockListManager_->getBlockList()->onItemRemoved.connect(boost::bind(&BlockListController::handleBlockListChanged, this)); + uiEventStream->onUIEvent.connect(boost::bind(&BlockListController::handleUIEvent, this, _1)); + blockListManager_->getBlockList()->onItemAdded.connect(boost::bind(&BlockListController::handleBlockListChanged, this)); + blockListManager_->getBlockList()->onItemRemoved.connect(boost::bind(&BlockListController::handleBlockListChanged, this)); } BlockListController::~BlockListController() { - uiEventStream_->onUIEvent.disconnect(boost::bind(&BlockListController::handleUIEvent, this, _1)); - blockListManager_->getBlockList()->onItemAdded.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this)); - blockListManager_->getBlockList()->onItemRemoved.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this)); + uiEventStream_->onUIEvent.disconnect(boost::bind(&BlockListController::handleUIEvent, this, _1)); + blockListManager_->getBlockList()->onItemAdded.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this)); + blockListManager_->getBlockList()->onItemRemoved.disconnect(boost::bind(&BlockListController::handleBlockListChanged, this)); } void BlockListController::blockListDifferences(const std::vector &newBlockList, std::vector &jidsToUnblock, std::vector &jidsToBlock) const { - foreach (const JID& jid, blockListBeforeEdit) { - if (std::find(newBlockList.begin(), newBlockList.end(), jid) == newBlockList.end()) { - jidsToUnblock.push_back(jid); - } - } - - foreach (const JID& jid, newBlockList) { - if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) { - jidsToBlock.push_back(jid); - } - } + foreach (const JID& jid, blockListBeforeEdit) { + if (std::find(newBlockList.begin(), newBlockList.end(), jid) == newBlockList.end()) { + jidsToUnblock.push_back(jid); + } + } + + foreach (const JID& jid, newBlockList) { + if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) { + jidsToBlock.push_back(jid); + } + } } void BlockListController::handleUIEvent(boost::shared_ptr rawEvent) { - // handle UI dialog - boost::shared_ptr requestDialogEvent = boost::dynamic_pointer_cast(rawEvent); - if (requestDialogEvent != NULL) { - if (blockListEditorWidget_ == NULL) { - blockListEditorWidget_ = blockListEditorWidgetFactory_->createBlockListEditorWidget(); - blockListEditorWidget_->onSetNewBlockList.connect(boost::bind(&BlockListController::handleSetNewBlockList, this, _1)); - } - blockListBeforeEdit = blockListManager_->getBlockList()->getItems(); - blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit); - blockListEditorWidget_->setError(""); - blockListEditorWidget_->show(); - return; - } - - // handle block state change - boost::shared_ptr changeStateEvent = boost::dynamic_pointer_cast(rawEvent); - if (changeStateEvent != NULL) { - if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Blocked) { - GenericRequest::ref blockRequest = blockListManager_->createBlockJIDRequest(changeStateEvent->getContact()); - blockRequest->onResponse.connect(boost::bind(&BlockListController::handleBlockResponse, this, blockRequest, _1, _2, std::vector(1, changeStateEvent->getContact()), false)); - blockRequest->send(); - } else if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Unblocked) { - GenericRequest::ref unblockRequest = blockListManager_->createUnblockJIDRequest(changeStateEvent->getContact()); - unblockRequest->onResponse.connect(boost::bind(&BlockListController::handleUnblockResponse, this, unblockRequest, _1, _2, std::vector(1, changeStateEvent->getContact()), false)); - unblockRequest->send(); - } - return; - } + // handle UI dialog + boost::shared_ptr requestDialogEvent = boost::dynamic_pointer_cast(rawEvent); + if (requestDialogEvent != NULL) { + if (blockListEditorWidget_ == NULL) { + blockListEditorWidget_ = blockListEditorWidgetFactory_->createBlockListEditorWidget(); + blockListEditorWidget_->onSetNewBlockList.connect(boost::bind(&BlockListController::handleSetNewBlockList, this, _1)); + } + blockListBeforeEdit = blockListManager_->getBlockList()->getItems(); + blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit); + blockListEditorWidget_->setError(""); + blockListEditorWidget_->show(); + return; + } + + // handle block state change + boost::shared_ptr changeStateEvent = boost::dynamic_pointer_cast(rawEvent); + if (changeStateEvent != NULL) { + if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Blocked) { + GenericRequest::ref blockRequest = blockListManager_->createBlockJIDRequest(changeStateEvent->getContact()); + blockRequest->onResponse.connect(boost::bind(&BlockListController::handleBlockResponse, this, blockRequest, _1, _2, std::vector(1, changeStateEvent->getContact()), false)); + blockRequest->send(); + } else if (changeStateEvent->getBlockState() == RequestChangeBlockStateUIEvent::Unblocked) { + GenericRequest::ref unblockRequest = blockListManager_->createUnblockJIDRequest(changeStateEvent->getContact()); + unblockRequest->onResponse.connect(boost::bind(&BlockListController::handleUnblockResponse, this, unblockRequest, _1, _2, std::vector(1, changeStateEvent->getContact()), false)); + unblockRequest->send(); + } + return; + } } void BlockListController::handleBlockResponse(GenericRequest::ref request, boost::shared_ptr, ErrorPayload::ref error, const std::vector& jids, bool originEditor) { - if (error) { - std::string errorMessage; - // FIXME: Handle reporting of list of JIDs in a translatable way. - errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to block %1%.")) % jids.at(0).toString()); - if (!error->getText().empty()) { - errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText()); - } - if (blockListEditorWidget_ && originEditor) { - blockListEditorWidget_->setError(errorMessage); - blockListEditorWidget_->setBusy(false); - } - else { - eventController_->handleIncomingEvent(boost::make_shared(request->getReceiver(), errorMessage)); - } - } - if (originEditor) { - remainingRequests_--; - if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) { - blockListEditorWidget_->setBusy(false); - blockListEditorWidget_->hide(); - } - } + if (error) { + std::string errorMessage; + // FIXME: Handle reporting of list of JIDs in a translatable way. + errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to block %1%.")) % jids.at(0).toString()); + if (!error->getText().empty()) { + errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText()); + } + if (blockListEditorWidget_ && originEditor) { + blockListEditorWidget_->setError(errorMessage); + blockListEditorWidget_->setBusy(false); + } + else { + eventController_->handleIncomingEvent(boost::make_shared(request->getReceiver(), errorMessage)); + } + } + if (originEditor) { + remainingRequests_--; + if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) { + blockListEditorWidget_->setBusy(false); + blockListEditorWidget_->hide(); + } + } } void BlockListController::handleUnblockResponse(GenericRequest::ref request, boost::shared_ptr, ErrorPayload::ref error, const std::vector& jids, bool originEditor) { - if (error) { - std::string errorMessage; - // FIXME: Handle reporting of list of JIDs in a translatable way. - errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to unblock %1%.")) % jids.at(0).toString()); - if (!error->getText().empty()) { - errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText()); - } - if (blockListEditorWidget_ && originEditor) { - blockListEditorWidget_->setError(errorMessage); - blockListEditorWidget_->setBusy(false); - } - else { - eventController_->handleIncomingEvent(boost::make_shared(request->getReceiver(), errorMessage)); - } - } - if (originEditor) { - remainingRequests_--; - if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) { - blockListEditorWidget_->setBusy(false); - blockListEditorWidget_->hide(); - } - } + if (error) { + std::string errorMessage; + // FIXME: Handle reporting of list of JIDs in a translatable way. + errorMessage = str(format(QT_TRANSLATE_NOOP("", "Failed to unblock %1%.")) % jids.at(0).toString()); + if (!error->getText().empty()) { + errorMessage = str(format(QT_TRANSLATE_NOOP("", "%1%: %2%.")) % errorMessage % error->getText()); + } + if (blockListEditorWidget_ && originEditor) { + blockListEditorWidget_->setError(errorMessage); + blockListEditorWidget_->setBusy(false); + } + else { + eventController_->handleIncomingEvent(boost::make_shared(request->getReceiver(), errorMessage)); + } + } + if (originEditor) { + remainingRequests_--; + if (blockListEditorWidget_ && (remainingRequests_ == 0) && !error) { + blockListEditorWidget_->setBusy(false); + blockListEditorWidget_->hide(); + } + } } void BlockListController::handleSetNewBlockList(const std::vector &newBlockList) { - std::vector jidsToBlock; - std::vector jidsToUnblock; - - blockListDifferences(newBlockList, jidsToUnblock, jidsToBlock); - - if (!jidsToBlock.empty()) { - remainingRequests_++; - GenericRequest::ref blockRequest = blockListManager_->createBlockJIDsRequest(jidsToBlock); - blockRequest->onResponse.connect(boost::bind(&BlockListController::handleBlockResponse, this, blockRequest, _1, _2, jidsToBlock, true)); - blockRequest->send(); - } - if (!jidsToUnblock.empty()) { - remainingRequests_++; - GenericRequest::ref unblockRequest = blockListManager_->createUnblockJIDsRequest(jidsToUnblock); - unblockRequest->onResponse.connect(boost::bind(&BlockListController::handleUnblockResponse, this, unblockRequest, _1, _2, jidsToUnblock, true)); - unblockRequest->send(); - } - if (!jidsToBlock.empty() || !jidsToUnblock.empty()) { - assert(blockListEditorWidget_); - blockListEditorWidget_->setBusy(true); - blockListEditorWidget_->setError(""); - } else { - blockListEditorWidget_->hide(); - } + std::vector jidsToBlock; + std::vector jidsToUnblock; + + blockListDifferences(newBlockList, jidsToUnblock, jidsToBlock); + + if (!jidsToBlock.empty()) { + remainingRequests_++; + GenericRequest::ref blockRequest = blockListManager_->createBlockJIDsRequest(jidsToBlock); + blockRequest->onResponse.connect(boost::bind(&BlockListController::handleBlockResponse, this, blockRequest, _1, _2, jidsToBlock, true)); + blockRequest->send(); + } + if (!jidsToUnblock.empty()) { + remainingRequests_++; + GenericRequest::ref unblockRequest = blockListManager_->createUnblockJIDsRequest(jidsToUnblock); + unblockRequest->onResponse.connect(boost::bind(&BlockListController::handleUnblockResponse, this, unblockRequest, _1, _2, jidsToUnblock, true)); + unblockRequest->send(); + } + if (!jidsToBlock.empty() || !jidsToUnblock.empty()) { + assert(blockListEditorWidget_); + blockListEditorWidget_->setBusy(true); + blockListEditorWidget_->setError(""); + } else { + blockListEditorWidget_->hide(); + } } void BlockListController::handleBlockListChanged() { - if (blockListEditorWidget_) { - std::vector jidsToBlock; - std::vector jidsToUnblock; + if (blockListEditorWidget_) { + std::vector jidsToBlock; + std::vector jidsToUnblock; - blockListDifferences(blockListEditorWidget_->getCurrentBlockList(), jidsToUnblock, jidsToBlock); - blockListBeforeEdit = blockListManager_->getBlockList()->getItems(); + blockListDifferences(blockListEditorWidget_->getCurrentBlockList(), jidsToUnblock, jidsToBlock); + blockListBeforeEdit = blockListManager_->getBlockList()->getItems(); - foreach (const JID& jid, jidsToBlock) { - if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) { - blockListBeforeEdit.push_back(jid); - } - } + foreach (const JID& jid, jidsToBlock) { + if (std::find(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid) == blockListBeforeEdit.end()) { + blockListBeforeEdit.push_back(jid); + } + } - foreach (const JID& jid, jidsToUnblock) { - blockListBeforeEdit.erase(std::remove(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid), blockListBeforeEdit.end()); - } + foreach (const JID& jid, jidsToUnblock) { + blockListBeforeEdit.erase(std::remove(blockListBeforeEdit.begin(), blockListBeforeEdit.end(), jid), blockListBeforeEdit.end()); + } - blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit); - } + blockListEditorWidget_->setCurrentBlockList(blockListBeforeEdit); + } } } diff --git a/Swift/Controllers/BlockListController.h b/Swift/Controllers/BlockListController.h index c911344..f9ee5a6 100644 --- a/Swift/Controllers/BlockListController.h +++ b/Swift/Controllers/BlockListController.h @@ -28,29 +28,29 @@ class EventController; class BlockListController { public: - BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController); - ~BlockListController(); + BlockListController(ClientBlockListManager* blockListManager, UIEventStream* uiEventStream, BlockListEditorWidgetFactory* blockListEditorWidgetFactory, EventController* eventController); + ~BlockListController(); private: - void blockListDifferences(const std::vector &newBlockList, std::vector& jidsToUnblock, std::vector& jidsToBlock) const; + void blockListDifferences(const std::vector &newBlockList, std::vector& jidsToUnblock, std::vector& jidsToBlock) const; - void handleUIEvent(boost::shared_ptr event); + void handleUIEvent(boost::shared_ptr event); - void handleBlockResponse(GenericRequest::ref, boost::shared_ptr, ErrorPayload::ref error, const std::vector& jids, bool originEditor); - void handleUnblockResponse(GenericRequest::ref, boost::shared_ptr, ErrorPayload::ref error, const std::vector& jids, bool originEditor); + void handleBlockResponse(GenericRequest::ref, boost::shared_ptr, ErrorPayload::ref error, const std::vector& jids, bool originEditor); + void handleUnblockResponse(GenericRequest::ref, boost::shared_ptr, ErrorPayload::ref error, const std::vector& jids, bool originEditor); - void handleSetNewBlockList(const std::vector& newBlockList); + void handleSetNewBlockList(const std::vector& newBlockList); - void handleBlockListChanged(); + void handleBlockListChanged(); private: - ClientBlockListManager* blockListManager_; - BlockListEditorWidgetFactory* blockListEditorWidgetFactory_; - BlockListEditorWidget* blockListEditorWidget_; - EventController* eventController_; - std::vector blockListBeforeEdit; - int remainingRequests_; - UIEventStream* uiEventStream_; + ClientBlockListManager* blockListManager_; + BlockListEditorWidgetFactory* blockListEditorWidgetFactory_; + BlockListEditorWidget* blockListEditorWidget_; + EventController* eventController_; + std::vector blockListBeforeEdit; + int remainingRequests_; + UIEventStream* uiEventStream_; }; } diff --git a/Swift/Controllers/CertificateMemoryStorageFactory.h b/Swift/Controllers/CertificateMemoryStorageFactory.h index de9f3fe..080b157 100644 --- a/Swift/Controllers/CertificateMemoryStorageFactory.h +++ b/Swift/Controllers/CertificateMemoryStorageFactory.h @@ -10,19 +10,19 @@ #include namespace Swift { - class CertificateFactory; + class CertificateFactory; - class CertificateMemoryStorageFactory : public CertificateStorageFactory { - public: - CertificateMemoryStorageFactory() { - } + class CertificateMemoryStorageFactory : public CertificateStorageFactory { + public: + CertificateMemoryStorageFactory() { + } - virtual CertificateStorage* createCertificateStorage(const JID&) const { - return new CertificateMemoryStorage(); - } + virtual CertificateStorage* createCertificateStorage(const JID&) const { + return new CertificateMemoryStorage(); + } - private: - boost::filesystem::path basePath; - CertificateFactory* certificateFactory; - }; + private: + boost::filesystem::path basePath; + CertificateFactory* certificateFactory; + }; } diff --git a/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h b/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h index 8ea6dff..646612b 100644 --- a/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h +++ b/Swift/Controllers/Chat/AutoAcceptMUCInviteDecider.h @@ -19,36 +19,36 @@ #include namespace Swift { - class AutoAcceptMUCInviteDecider { - public: - AutoAcceptMUCInviteDecider(const JID& domain, XMPPRoster* roster, SettingsProvider* settings) : domain_(domain), roster_(roster), settings_(settings) { - } - - bool isAutoAcceptedInvite(const JID& from, MUCInvitationPayload::ref invite) { - if (!invite->getIsImpromptu()) { - return false; /* always ask the user for normal MUC invites */ - } - - if (invite->getIsContinuation()) { - return true; - } - - std::string auto_accept_mode = settings_->getSetting(SettingConstants::INVITE_AUTO_ACCEPT_MODE); - if (auto_accept_mode == "no") { - return false; - } else if (auto_accept_mode == "presence") { - return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both; - } else if (auto_accept_mode == "domain") { - return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both || from.getDomain() == domain_; - } else { - assert(false); - return false; - } - } - - private: - JID domain_; - XMPPRoster* roster_; - SettingsProvider* settings_; - }; + class AutoAcceptMUCInviteDecider { + public: + AutoAcceptMUCInviteDecider(const JID& domain, XMPPRoster* roster, SettingsProvider* settings) : domain_(domain), roster_(roster), settings_(settings) { + } + + bool isAutoAcceptedInvite(const JID& from, MUCInvitationPayload::ref invite) { + if (!invite->getIsImpromptu()) { + return false; /* always ask the user for normal MUC invites */ + } + + if (invite->getIsContinuation()) { + return true; + } + + std::string auto_accept_mode = settings_->getSetting(SettingConstants::INVITE_AUTO_ACCEPT_MODE); + if (auto_accept_mode == "no") { + return false; + } else if (auto_accept_mode == "presence") { + return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both; + } else if (auto_accept_mode == "domain") { + return roster_->getSubscriptionStateForJID(from) == RosterItemPayload::From || roster_->getSubscriptionStateForJID(from) == RosterItemPayload::Both || from.getDomain() == domain_; + } else { + assert(false); + return false; + } + } + + private: + JID domain_; + XMPPRoster* roster_; + SettingsProvider* settings_; + }; } diff --git a/Swift/Controllers/Chat/ChatController.cpp b/Swift/Controllers/Chat/ChatController.cpp index 7f62c36..5302492 100644 --- a/Swift/Controllers/Chat/ChatController.cpp +++ b/Swift/Controllers/Chat/ChatController.cpp @@ -45,489 +45,489 @@ #include namespace Swift { - + /** * The controller does not gain ownership of the stanzaChannel, nor the factory. */ ChatController::ChatController(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &contact, NickResolver* nickResolver, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool isInMUC, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, bool userWantsReceipts, SettingsProvider* settings, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider) - : ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, contact, presenceOracle, avatarManager, useDelayForLatency, eventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), eventStream_(eventStream), userWantsReceipts_(userWantsReceipts), settings_(settings), clientBlockListManager_(clientBlockListManager) { - isInMUC_ = isInMUC; - lastWasPresence_ = false; - chatStateNotifier_ = new ChatStateNotifier(stanzaChannel, contact, entityCapsProvider); - chatStateTracker_ = new ChatStateTracker(); - nickResolver_ = nickResolver; - presenceOracle_->onPresenceChange.connect(boost::bind(&ChatController::handlePresenceChange, this, _1)); - chatStateTracker_->onChatStateChange.connect(boost::bind(&ChatWindow::setContactChatState, chatWindow_, _1)); - stanzaChannel_->onStanzaAcked.connect(boost::bind(&ChatController::handleStanzaAcked, this, _1)); - nickResolver_->onNickChanged.connect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2)); - std::string nick = nickResolver_->jidToNick(toJID_); - chatWindow_->setName(nick); - std::string startMessage; - Presence::ref theirPresence; - if (isInMUC) { - startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% in chatroom %2%")) % nick % contact.toBare().toString()); - theirPresence = presenceOracle->getLastPresence(contact); - } else { - startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% - %2%")) % nick % contact.toBare().toString()); - theirPresence = contact.isBare() ? presenceOracle->getAccountPresence(contact) : presenceOracle->getLastPresence(contact); - } - Idle::ref idle; - if (theirPresence && (idle = theirPresence->getPayload())) { - startMessage += str(format(QT_TRANSLATE_NOOP("", ", who has been idle since %1%")) % dateTimeToLocalString(idle->getSince())); - } - startMessage += ": " + statusShowTypeToFriendlyName(theirPresence ? theirPresence->getShow() : StatusShow::None); - if (theirPresence && !theirPresence->getStatus().empty()) { - startMessage += " (" + theirPresence->getStatus() + ")"; - } - lastShownStatus_ = theirPresence ? theirPresence->getShow() : StatusShow::None; - chatStateNotifier_->setContactIsOnline(theirPresence && theirPresence->getType() == Presence::Available); - startMessage += "."; - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(startMessage), ChatWindow::DefaultDirection); - chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); - chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); - chatWindow_->onFileTransferStart.connect(boost::bind(&ChatController::handleFileTransferStart, this, _1, _2)); - chatWindow_->onFileTransferAccept.connect(boost::bind(&ChatController::handleFileTransferAccept, this, _1, _2)); - chatWindow_->onFileTransferCancel.connect(boost::bind(&ChatController::handleFileTransferCancel, this, _1)); - chatWindow_->onSendFileRequest.connect(boost::bind(&ChatController::handleSendFileRequest, this, _1)); - chatWindow_->onWhiteboardSessionAccept.connect(boost::bind(&ChatController::handleWhiteboardSessionAccept, this)); - chatWindow_->onWhiteboardSessionCancel.connect(boost::bind(&ChatController::handleWhiteboardSessionCancel, this)); - chatWindow_->onWhiteboardWindowShow.connect(boost::bind(&ChatController::handleWhiteboardWindowShow, this)); - chatWindow_->onBlockUserRequest.connect(boost::bind(&ChatController::handleBlockUserRequest, this)); - chatWindow_->onUnblockUserRequest.connect(boost::bind(&ChatController::handleUnblockUserRequest, this)); - chatWindow_->onInviteToChat.connect(boost::bind(&ChatController::handleInviteToChat, this, _1)); - chatWindow_->onClosed.connect(boost::bind(&ChatController::handleWindowClosed, this)); - ChatController::handleBareJIDCapsChanged(toJID_); - - settings_->onSettingChanged.connect(boost::bind(&ChatController::handleSettingChanged, this, _1)); - eventStream_->onUIEvent.connect(boost::bind(&ChatController::handleUIEvent, this, _1)); + : ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, contact, presenceOracle, avatarManager, useDelayForLatency, eventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), eventStream_(eventStream), userWantsReceipts_(userWantsReceipts), settings_(settings), clientBlockListManager_(clientBlockListManager) { + isInMUC_ = isInMUC; + lastWasPresence_ = false; + chatStateNotifier_ = new ChatStateNotifier(stanzaChannel, contact, entityCapsProvider); + chatStateTracker_ = new ChatStateTracker(); + nickResolver_ = nickResolver; + presenceOracle_->onPresenceChange.connect(boost::bind(&ChatController::handlePresenceChange, this, _1)); + chatStateTracker_->onChatStateChange.connect(boost::bind(&ChatWindow::setContactChatState, chatWindow_, _1)); + stanzaChannel_->onStanzaAcked.connect(boost::bind(&ChatController::handleStanzaAcked, this, _1)); + nickResolver_->onNickChanged.connect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2)); + std::string nick = nickResolver_->jidToNick(toJID_); + chatWindow_->setName(nick); + std::string startMessage; + Presence::ref theirPresence; + if (isInMUC) { + startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% in chatroom %2%")) % nick % contact.toBare().toString()); + theirPresence = presenceOracle->getLastPresence(contact); + } else { + startMessage = str(format(QT_TRANSLATE_NOOP("", "Starting chat with %1% - %2%")) % nick % contact.toBare().toString()); + theirPresence = contact.isBare() ? presenceOracle->getAccountPresence(contact) : presenceOracle->getLastPresence(contact); + } + Idle::ref idle; + if (theirPresence && (idle = theirPresence->getPayload())) { + startMessage += str(format(QT_TRANSLATE_NOOP("", ", who has been idle since %1%")) % dateTimeToLocalString(idle->getSince())); + } + startMessage += ": " + statusShowTypeToFriendlyName(theirPresence ? theirPresence->getShow() : StatusShow::None); + if (theirPresence && !theirPresence->getStatus().empty()) { + startMessage += " (" + theirPresence->getStatus() + ")"; + } + lastShownStatus_ = theirPresence ? theirPresence->getShow() : StatusShow::None; + chatStateNotifier_->setContactIsOnline(theirPresence && theirPresence->getType() == Presence::Available); + startMessage += "."; + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(startMessage), ChatWindow::DefaultDirection); + chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); + chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); + chatWindow_->onFileTransferStart.connect(boost::bind(&ChatController::handleFileTransferStart, this, _1, _2)); + chatWindow_->onFileTransferAccept.connect(boost::bind(&ChatController::handleFileTransferAccept, this, _1, _2)); + chatWindow_->onFileTransferCancel.connect(boost::bind(&ChatController::handleFileTransferCancel, this, _1)); + chatWindow_->onSendFileRequest.connect(boost::bind(&ChatController::handleSendFileRequest, this, _1)); + chatWindow_->onWhiteboardSessionAccept.connect(boost::bind(&ChatController::handleWhiteboardSessionAccept, this)); + chatWindow_->onWhiteboardSessionCancel.connect(boost::bind(&ChatController::handleWhiteboardSessionCancel, this)); + chatWindow_->onWhiteboardWindowShow.connect(boost::bind(&ChatController::handleWhiteboardWindowShow, this)); + chatWindow_->onBlockUserRequest.connect(boost::bind(&ChatController::handleBlockUserRequest, this)); + chatWindow_->onUnblockUserRequest.connect(boost::bind(&ChatController::handleUnblockUserRequest, this)); + chatWindow_->onInviteToChat.connect(boost::bind(&ChatController::handleInviteToChat, this, _1)); + chatWindow_->onClosed.connect(boost::bind(&ChatController::handleWindowClosed, this)); + ChatController::handleBareJIDCapsChanged(toJID_); + + settings_->onSettingChanged.connect(boost::bind(&ChatController::handleSettingChanged, this, _1)); + eventStream_->onUIEvent.connect(boost::bind(&ChatController::handleUIEvent, this, _1)); } void ChatController::handleContactNickChanged(const JID& jid, const std::string& /*oldNick*/) { - if (jid.toBare() == toJID_.toBare()) { - chatWindow_->setName(nickResolver_->jidToNick(toJID_)); - } + if (jid.toBare() == toJID_.toBare()) { + chatWindow_->setName(nickResolver_->jidToNick(toJID_)); + } } ChatController::~ChatController() { - eventStream_->onUIEvent.disconnect(boost::bind(&ChatController::handleUIEvent, this, _1)); - settings_->onSettingChanged.disconnect(boost::bind(&ChatController::handleSettingChanged, this, _1)); - nickResolver_->onNickChanged.disconnect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2)); - delete chatStateNotifier_; - delete chatStateTracker_; + eventStream_->onUIEvent.disconnect(boost::bind(&ChatController::handleUIEvent, this, _1)); + settings_->onSettingChanged.disconnect(boost::bind(&ChatController::handleSettingChanged, this, _1)); + nickResolver_->onNickChanged.disconnect(boost::bind(&ChatController::handleContactNickChanged, this, _1, _2)); + delete chatStateNotifier_; + delete chatStateTracker_; } JID ChatController::getBaseJID() { - return isInMUC_ ? toJID_ : ChatControllerBase::getBaseJID(); + return isInMUC_ ? toJID_ : ChatControllerBase::getBaseJID(); } void ChatController::cancelReplaces() { - lastWasPresence_ = false; + lastWasPresence_ = false; } void ChatController::handleBareJIDCapsChanged(const JID& /*jid*/) { - FeatureOracle featureOracle(entityCapsProvider_, presenceOracle_); + FeatureOracle featureOracle(entityCapsProvider_, presenceOracle_); - chatWindow_->setCorrectionEnabled(featureOracle.isMessageCorrectionSupported(toJID_)); - chatWindow_->setFileTransferEnabled(isInMUC_ ? No : featureOracle.isFileTransferSupported(toJID_)); - contactSupportsReceipts_ = featureOracle.isMessageReceiptsSupported(toJID_); + chatWindow_->setCorrectionEnabled(featureOracle.isMessageCorrectionSupported(toJID_)); + chatWindow_->setFileTransferEnabled(isInMUC_ ? No : featureOracle.isFileTransferSupported(toJID_)); + contactSupportsReceipts_ = featureOracle.isMessageReceiptsSupported(toJID_); - checkForDisplayingDisplayReceiptsAlert(); + checkForDisplayingDisplayReceiptsAlert(); } void ChatController::setToJID(const JID& jid) { - chatStateNotifier_->setContact(jid); - ChatControllerBase::setToJID(jid); - Presence::ref presence; - if (isInMUC_) { - presence = presenceOracle_->getLastPresence(jid); - } else { - presence = jid.isBare() ? presenceOracle_->getAccountPresence(jid.toBare()) : presenceOracle_->getLastPresence(jid); - } - chatStateNotifier_->setContactIsOnline(presence && presence->getType() == Presence::Available); - handleBareJIDCapsChanged(toJID_); + chatStateNotifier_->setContact(jid); + ChatControllerBase::setToJID(jid); + Presence::ref presence; + if (isInMUC_) { + presence = presenceOracle_->getLastPresence(jid); + } else { + presence = jid.isBare() ? presenceOracle_->getAccountPresence(jid.toBare()) : presenceOracle_->getLastPresence(jid); + } + chatStateNotifier_->setContactIsOnline(presence && presence->getType() == Presence::Available); + handleBareJIDCapsChanged(toJID_); } void ChatController::setAvailableServerFeatures(boost::shared_ptr info) { - ChatControllerBase::setAvailableServerFeatures(info); - if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) { - boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); + ChatControllerBase::setAvailableServerFeatures(info); + if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) { + boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); - blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&ChatController::handleBlockingStateChanged, this)); - blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&ChatController::handleBlockingStateChanged, this)); - blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&ChatController::handleBlockingStateChanged, this)); + blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&ChatController::handleBlockingStateChanged, this)); + blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&ChatController::handleBlockingStateChanged, this)); + blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&ChatController::handleBlockingStateChanged, this)); - handleBlockingStateChanged(); - } + handleBlockingStateChanged(); + } } bool ChatController::isIncomingMessageFromMe(boost::shared_ptr) { - return false; + return false; } void ChatController::preHandleIncomingMessage(boost::shared_ptr messageEvent) { - if (messageEvent->isReadable()) { - chatWindow_->flash(); - lastWasPresence_ = false; - } - boost::shared_ptr message = messageEvent->getStanza(); - JID from = message->getFrom(); - if (!from.equals(toJID_, JID::WithResource)) { - if (toJID_.equals(from, JID::WithoutResource) && toJID_.isBare()){ - // Bind controller to a full JID if message contains body text or is a typing chat state. - ChatState::ref chatState = message->getPayload(); - if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) { - setToJID(from); - } - } - } - chatStateTracker_->handleMessageReceived(message); - chatStateNotifier_->receivedMessageFromContact(!!message->getPayload()); - - // handle XEP-0184 Message Receipts - // incomming receipts - if (boost::shared_ptr receipt = message->getPayload()) { - SWIFT_LOG(debug) << "received receipt for id: " << receipt->getReceivedID() << std::endl; - if (requestedReceipts_.find(receipt->getReceivedID()) != requestedReceipts_.end()) { - chatWindow_->setMessageReceiptState(requestedReceipts_[receipt->getReceivedID()], ChatWindow::ReceiptReceived); - requestedReceipts_.erase(receipt->getReceivedID()); - } - // incomming errors in response to send out receipts - } else if (message->getPayload() && (message->getType() == Message::Error)) { - if (requestedReceipts_.find(message->getID()) != requestedReceipts_.end()) { - chatWindow_->setMessageReceiptState(requestedReceipts_[message->getID()], ChatWindow::ReceiptFailed); - requestedReceipts_.erase(message->getID()); - } - // incoming receipt requests - } else if (message->getPayload()) { - if (receivingPresenceFromUs_) { - boost::shared_ptr receiptMessage = boost::make_shared(); - receiptMessage->setTo(toJID_); - receiptMessage->addPayload(boost::make_shared(message->getID())); - stanzaChannel_->sendMessage(receiptMessage); - } - } + if (messageEvent->isReadable()) { + chatWindow_->flash(); + lastWasPresence_ = false; + } + boost::shared_ptr message = messageEvent->getStanza(); + JID from = message->getFrom(); + if (!from.equals(toJID_, JID::WithResource)) { + if (toJID_.equals(from, JID::WithoutResource) && toJID_.isBare()){ + // Bind controller to a full JID if message contains body text or is a typing chat state. + ChatState::ref chatState = message->getPayload(); + if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) { + setToJID(from); + } + } + } + chatStateTracker_->handleMessageReceived(message); + chatStateNotifier_->receivedMessageFromContact(!!message->getPayload()); + + // handle XEP-0184 Message Receipts + // incomming receipts + if (boost::shared_ptr receipt = message->getPayload()) { + SWIFT_LOG(debug) << "received receipt for id: " << receipt->getReceivedID() << std::endl; + if (requestedReceipts_.find(receipt->getReceivedID()) != requestedReceipts_.end()) { + chatWindow_->setMessageReceiptState(requestedReceipts_[receipt->getReceivedID()], ChatWindow::ReceiptReceived); + requestedReceipts_.erase(receipt->getReceivedID()); + } + // incomming errors in response to send out receipts + } else if (message->getPayload() && (message->getType() == Message::Error)) { + if (requestedReceipts_.find(message->getID()) != requestedReceipts_.end()) { + chatWindow_->setMessageReceiptState(requestedReceipts_[message->getID()], ChatWindow::ReceiptFailed); + requestedReceipts_.erase(message->getID()); + } + // incoming receipt requests + } else if (message->getPayload()) { + if (receivingPresenceFromUs_) { + boost::shared_ptr receiptMessage = boost::make_shared(); + receiptMessage->setTo(toJID_); + receiptMessage->addPayload(boost::make_shared(message->getID())); + stanzaChannel_->sendMessage(receiptMessage); + } + } } void ChatController::postHandleIncomingMessage(boost::shared_ptr messageEvent, const ChatWindow::ChatMessage& chatMessage) { - eventController_->handleIncomingEvent(messageEvent); - if (!messageEvent->getConcluded()) { - handleHighlightActions(chatMessage); - } + eventController_->handleIncomingEvent(messageEvent); + if (!messageEvent->getConcluded()) { + handleHighlightActions(chatMessage); + } } void ChatController::preSendMessageRequest(boost::shared_ptr message) { - chatStateNotifier_->addChatStateRequest(message); - if (userWantsReceipts_ && (contactSupportsReceipts_ != No) && message) { - message->addPayload(boost::make_shared()); - } + chatStateNotifier_->addChatStateRequest(message); + if (userWantsReceipts_ && (contactSupportsReceipts_ != No) && message) { + message->addPayload(boost::make_shared()); + } } void ChatController::setContactIsReceivingPresence(bool isReceivingPresence) { - receivingPresenceFromUs_ = isReceivingPresence; + receivingPresenceFromUs_ = isReceivingPresence; } void ChatController::handleSettingChanged(const std::string& settingPath) { - if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) { - userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS); - checkForDisplayingDisplayReceiptsAlert(); - } + if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) { + userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS); + checkForDisplayingDisplayReceiptsAlert(); + } } void ChatController::checkForDisplayingDisplayReceiptsAlert() { - boost::optional newDeliverReceiptAlert; - if (userWantsReceipts_ && (contactSupportsReceipts_ == No)) { - newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat doesn't support delivery receipts.")); - } else if (userWantsReceipts_ && (contactSupportsReceipts_ == Maybe)) { - newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat may not support delivery receipts. You might not receive delivery receipts for the messages you send.")); - } else { - if (deliveryReceiptAlert_) { - chatWindow_->removeAlert(*deliveryReceiptAlert_); - deliveryReceiptAlert_.reset(); - } - } - if (newDeliverReceiptAlert) { - if (deliveryReceiptAlert_) { - chatWindow_->removeAlert(*deliveryReceiptAlert_); - } - deliveryReceiptAlert_ = newDeliverReceiptAlert; - } + boost::optional newDeliverReceiptAlert; + if (userWantsReceipts_ && (contactSupportsReceipts_ == No)) { + newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat doesn't support delivery receipts.")); + } else if (userWantsReceipts_ && (contactSupportsReceipts_ == Maybe)) { + newDeliverReceiptAlert = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "This chat may not support delivery receipts. You might not receive delivery receipts for the messages you send.")); + } else { + if (deliveryReceiptAlert_) { + chatWindow_->removeAlert(*deliveryReceiptAlert_); + deliveryReceiptAlert_.reset(); + } + } + if (newDeliverReceiptAlert) { + if (deliveryReceiptAlert_) { + chatWindow_->removeAlert(*deliveryReceiptAlert_); + } + deliveryReceiptAlert_ = newDeliverReceiptAlert; + } } void ChatController::handleBlockingStateChanged() { - boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); - if (blockList->getState() == BlockList::Available) { - if (isInMUC_ ? blockList->isBlocked(toJID_) : blockList->isBlocked(toJID_.toBare())) { - if (!blockedContactAlert_) { - blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've currently blocked this contact. To continue your conversation you have to unblock the contact first.")); - } - chatWindow_->setBlockingState(ChatWindow::IsBlocked); - - // disconnect typing events to prevent chat state notifciations to blocked contacts - chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); - chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); - } else { - if (blockedContactAlert_) { - chatWindow_->removeAlert(*blockedContactAlert_); - blockedContactAlert_.reset(); - } - chatWindow_->setBlockingState(ChatWindow::IsUnblocked); - - chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); - chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); - } - } + boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); + if (blockList->getState() == BlockList::Available) { + if (isInMUC_ ? blockList->isBlocked(toJID_) : blockList->isBlocked(toJID_.toBare())) { + if (!blockedContactAlert_) { + blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've currently blocked this contact. To continue your conversation you have to unblock the contact first.")); + } + chatWindow_->setBlockingState(ChatWindow::IsBlocked); + + // disconnect typing events to prevent chat state notifciations to blocked contacts + chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); + chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); + } else { + if (blockedContactAlert_) { + chatWindow_->removeAlert(*blockedContactAlert_); + blockedContactAlert_.reset(); + } + chatWindow_->setBlockingState(ChatWindow::IsUnblocked); + + chatWindow_->onUserTyping.connect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); + chatWindow_->onUserCancelsTyping.connect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); + } + } } void ChatController::handleBlockUserRequest() { - if (isInMUC_) { - eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Blocked, toJID_)); - } else { - eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Blocked, toJID_.toBare())); - } + if (isInMUC_) { + eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Blocked, toJID_)); + } else { + eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Blocked, toJID_.toBare())); + } } void ChatController::handleUnblockUserRequest() { - if (isInMUC_) { - eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Unblocked, toJID_)); - } else { - eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Unblocked, toJID_.toBare())); - } + if (isInMUC_) { + eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Unblocked, toJID_)); + } else { + eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Unblocked, toJID_.toBare())); + } } void ChatController::handleInviteToChat(const std::vector& droppedJIDs) { - boost::shared_ptr event(new RequestInviteToMUCUIEvent(toJID_.toBare(), droppedJIDs, RequestInviteToMUCUIEvent::Impromptu)); - eventStream_->send(event); + boost::shared_ptr event(new RequestInviteToMUCUIEvent(toJID_.toBare(), droppedJIDs, RequestInviteToMUCUIEvent::Impromptu)); + eventStream_->send(event); } void ChatController::handleWindowClosed() { - onWindowClosed(); + onWindowClosed(); } void ChatController::handleUIEvent(boost::shared_ptr event) { - boost::shared_ptr inviteEvent = boost::dynamic_pointer_cast(event); - if (inviteEvent && inviteEvent->getRoom() == toJID_.toBare()) { - onConvertToMUC(detachChatWindow(), inviteEvent->getInvites(), inviteEvent->getReason()); - } + boost::shared_ptr inviteEvent = boost::dynamic_pointer_cast(event); + if (inviteEvent && inviteEvent->getRoom() == toJID_.toBare()) { + onConvertToMUC(detachChatWindow(), inviteEvent->getInvites(), inviteEvent->getReason()); + } } void ChatController::postSendMessage(const std::string& body, boost::shared_ptr sentStanza) { - boost::shared_ptr replace = sentStanza->getPayload(); - if (replace) { - eraseIf(unackedStanzas_, PairSecondEquals, std::string>(myLastMessageUIID_)); - replaceMessage(chatMessageParser_->parseMessageBody(body, "", true), myLastMessageUIID_, boost::posix_time::microsec_clock::universal_time()); - } else { - myLastMessageUIID_ = addMessage(chatMessageParser_->parseMessageBody(body, "", true), QT_TRANSLATE_NOOP("", "me"), true, labelsEnabled_ ? chatWindow_->getSelectedSecurityLabel().getLabel() : boost::shared_ptr(), avatarManager_->getAvatarPath(selfJID_), boost::posix_time::microsec_clock::universal_time()); - } + boost::shared_ptr replace = sentStanza->getPayload(); + if (replace) { + eraseIf(unackedStanzas_, PairSecondEquals, std::string>(myLastMessageUIID_)); + replaceMessage(chatMessageParser_->parseMessageBody(body, "", true), myLastMessageUIID_, boost::posix_time::microsec_clock::universal_time()); + } else { + myLastMessageUIID_ = addMessage(chatMessageParser_->parseMessageBody(body, "", true), QT_TRANSLATE_NOOP("", "me"), true, labelsEnabled_ ? chatWindow_->getSelectedSecurityLabel().getLabel() : boost::shared_ptr(), avatarManager_->getAvatarPath(selfJID_), boost::posix_time::microsec_clock::universal_time()); + } - if (stanzaChannel_->getStreamManagementEnabled() && !myLastMessageUIID_.empty() ) { - chatWindow_->setAckState(myLastMessageUIID_, ChatWindow::Pending); - unackedStanzas_[sentStanza] = myLastMessageUIID_; - } + if (stanzaChannel_->getStreamManagementEnabled() && !myLastMessageUIID_.empty() ) { + chatWindow_->setAckState(myLastMessageUIID_, ChatWindow::Pending); + unackedStanzas_[sentStanza] = myLastMessageUIID_; + } - if (sentStanza->getPayload()) { - requestedReceipts_[sentStanza->getID()] = myLastMessageUIID_; - chatWindow_->setMessageReceiptState(myLastMessageUIID_, ChatWindow::ReceiptRequested); - } + if (sentStanza->getPayload()) { + requestedReceipts_[sentStanza->getID()] = myLastMessageUIID_; + chatWindow_->setMessageReceiptState(myLastMessageUIID_, ChatWindow::ReceiptRequested); + } - lastWasPresence_ = false; - chatStateNotifier_->userSentMessage(); + lastWasPresence_ = false; + chatStateNotifier_->userSentMessage(); } void ChatController::handleStanzaAcked(boost::shared_ptr stanza) { - std::map, std::string>::iterator unackedStanza = unackedStanzas_.find(stanza); - if (unackedStanza != unackedStanzas_.end()) { - chatWindow_->setAckState(unackedStanza->second, ChatWindow::Received); - unackedStanzas_.erase(unackedStanza); - } + std::map, std::string>::iterator unackedStanza = unackedStanzas_.find(stanza); + if (unackedStanza != unackedStanzas_.end()) { + chatWindow_->setAckState(unackedStanza->second, ChatWindow::Received); + unackedStanzas_.erase(unackedStanza); + } } void ChatController::setOnline(bool online) { - if (!online) { - std::map, std::string>::iterator it = unackedStanzas_.begin(); - for ( ; it != unackedStanzas_.end(); ++it) { - chatWindow_->setAckState(it->second, ChatWindow::Failed); - } - unackedStanzas_.clear(); + if (!online) { + std::map, std::string>::iterator it = unackedStanzas_.begin(); + for ( ; it != unackedStanzas_.end(); ++it) { + chatWindow_->setAckState(it->second, ChatWindow::Failed); + } + unackedStanzas_.clear(); - Presence::ref fakeOffline(new Presence()); - fakeOffline->setFrom(toJID_); - fakeOffline->setType(Presence::Unavailable); - chatStateTracker_->handlePresenceChange(fakeOffline); - } - ChatControllerBase::setOnline(online); + Presence::ref fakeOffline(new Presence()); + fakeOffline->setFrom(toJID_); + fakeOffline->setType(Presence::Unavailable); + chatStateTracker_->handlePresenceChange(fakeOffline); + } + ChatControllerBase::setOnline(online); } void ChatController::handleNewFileTransferController(FileTransferController* ftc) { - std::string nick = senderDisplayNameFromMessage(ftc->getOtherParty()); - std::string ftID = ftc->setChatWindow(chatWindow_, nick); - ftControllers[ftID] = ftc; - lastWasPresence_ = false; + std::string nick = senderDisplayNameFromMessage(ftc->getOtherParty()); + std::string ftID = ftc->setChatWindow(chatWindow_, nick); + ftControllers[ftID] = ftc; + lastWasPresence_ = false; } void ChatController::handleWhiteboardSessionRequest(bool senderIsSelf) { - lastWbID_ = chatWindow_->addWhiteboardRequest(senderIsSelf); + lastWbID_ = chatWindow_->addWhiteboardRequest(senderIsSelf); } void ChatController::handleWhiteboardStateChange(const ChatWindow::WhiteboardSessionState state) { - chatWindow_->setWhiteboardSessionStatus(lastWbID_, state); + chatWindow_->setWhiteboardSessionStatus(lastWbID_, state); } void ChatController::handleFileTransferCancel(std::string id) { - SWIFT_LOG(debug) << "handleFileTransferCancel(" << id << ")" << std::endl; - if (ftControllers.find(id) != ftControllers.end()) { - ftControllers[id]->cancel(); - } else { - std::cerr << "unknown file transfer UI id" << std::endl; - } + SWIFT_LOG(debug) << "handleFileTransferCancel(" << id << ")" << std::endl; + if (ftControllers.find(id) != ftControllers.end()) { + ftControllers[id]->cancel(); + } else { + std::cerr << "unknown file transfer UI id" << std::endl; + } } void ChatController::handleFileTransferStart(std::string id, std::string description) { - SWIFT_LOG(debug) << "handleFileTransferStart(" << id << ", " << description << ")" << std::endl; - if (ftControllers.find(id) != ftControllers.end()) { - ftControllers[id]->start(description); - } else { - std::cerr << "unknown file transfer UI id" << std::endl; - } + SWIFT_LOG(debug) << "handleFileTransferStart(" << id << ", " << description << ")" << std::endl; + if (ftControllers.find(id) != ftControllers.end()) { + ftControllers[id]->start(description); + } else { + std::cerr << "unknown file transfer UI id" << std::endl; + } } void ChatController::handleFileTransferAccept(std::string id, std::string filename) { - SWIFT_LOG(debug) << "handleFileTransferAccept(" << id << ", " << filename << ")" << std::endl; - if (ftControllers.find(id) != ftControllers.end()) { - ftControllers[id]->accept(filename); - } else { - std::cerr << "unknown file transfer UI id" << std::endl; - } + SWIFT_LOG(debug) << "handleFileTransferAccept(" << id << ", " << filename << ")" << std::endl; + if (ftControllers.find(id) != ftControllers.end()) { + ftControllers[id]->accept(filename); + } else { + std::cerr << "unknown file transfer UI id" << std::endl; + } } void ChatController::handleSendFileRequest(std::string filename) { - SWIFT_LOG(debug) << "ChatController::handleSendFileRequest(" << filename << ")" << std::endl; - eventStream_->send(boost::make_shared(getToJID(), filename)); + SWIFT_LOG(debug) << "ChatController::handleSendFileRequest(" << filename << ")" << std::endl; + eventStream_->send(boost::make_shared(getToJID(), filename)); } void ChatController::handleWhiteboardSessionAccept() { - eventStream_->send(boost::make_shared(toJID_)); + eventStream_->send(boost::make_shared(toJID_)); } void ChatController::handleWhiteboardSessionCancel() { - eventStream_->send(boost::make_shared(toJID_)); + eventStream_->send(boost::make_shared(toJID_)); } void ChatController::handleWhiteboardWindowShow() { - eventStream_->send(boost::make_shared(toJID_)); + eventStream_->send(boost::make_shared(toJID_)); } std::string ChatController::senderHighlightNameFromMessage(const JID& from) { - if (isInMUC_) { - return nickResolver_->jidToNick(from); - } - else { - return from.toBare().toString(); - } + if (isInMUC_) { + return nickResolver_->jidToNick(from); + } + else { + return from.toBare().toString(); + } } std::string ChatController::senderDisplayNameFromMessage(const JID& from) { - return nickResolver_->jidToNick(from); + return nickResolver_->jidToNick(from); } std::string ChatController::getStatusChangeString(boost::shared_ptr presence) { - std::string nick = senderDisplayNameFromMessage(presence->getFrom()); - std::string response; - if (!presence || presence->getType() == Presence::Unavailable || presence->getType() == Presence::Error) { - response = QT_TRANSLATE_NOOP("", "%1% has gone offline"); - } else if (presence->getType() == Presence::Available) { - StatusShow::Type show = presence->getShow(); - if (show == StatusShow::Online || show == StatusShow::FFC) { - response = QT_TRANSLATE_NOOP("", "%1% has become available"); - } else if (show == StatusShow::Away || show == StatusShow::XA) { - response = QT_TRANSLATE_NOOP("", "%1% has gone away"); - } else if (show == StatusShow::DND) { - response = QT_TRANSLATE_NOOP("", "%1% is now busy"); - } - } - Idle::ref idle; - if ((idle = presence->getPayload())) { - response += str(format(QT_TRANSLATE_NOOP("", " and has been idle since %1%")) % dateTimeToLocalString(idle->getSince())); - } - - if (!response.empty()) { - response = str(format(response) % nick); - } - - if (!presence->getStatus().empty()) { - response += " (" + presence->getStatus() + ")"; - } - return response + "."; + std::string nick = senderDisplayNameFromMessage(presence->getFrom()); + std::string response; + if (!presence || presence->getType() == Presence::Unavailable || presence->getType() == Presence::Error) { + response = QT_TRANSLATE_NOOP("", "%1% has gone offline"); + } else if (presence->getType() == Presence::Available) { + StatusShow::Type show = presence->getShow(); + if (show == StatusShow::Online || show == StatusShow::FFC) { + response = QT_TRANSLATE_NOOP("", "%1% has become available"); + } else if (show == StatusShow::Away || show == StatusShow::XA) { + response = QT_TRANSLATE_NOOP("", "%1% has gone away"); + } else if (show == StatusShow::DND) { + response = QT_TRANSLATE_NOOP("", "%1% is now busy"); + } + } + Idle::ref idle; + if ((idle = presence->getPayload())) { + response += str(format(QT_TRANSLATE_NOOP("", " and has been idle since %1%")) % dateTimeToLocalString(idle->getSince())); + } + + if (!response.empty()) { + response = str(format(response) % nick); + } + + if (!presence->getStatus().empty()) { + response += " (" + presence->getStatus() + ")"; + } + return response + "."; } void ChatController::handlePresenceChange(boost::shared_ptr newPresence) { - bool relevantPresence = false; - - if (isInMUC_) { - // For MUC participants we only have a single presence to choose one and - // even for multi-session nicknames multiple resources are not distinguishable - // to other participants. - if (toJID_.equals(newPresence->getFrom(), JID::WithResource)) { - relevantPresence = true; - } - } - else { - // For standard chats we retrieve the account presence from the PresenceOracle, - // as there can be multiple presences to choose from. - if (toJID_.equals(newPresence->getFrom(), JID::WithoutResource)) { - // Presence matches ChatController JID. - newPresence = presenceOracle_->getAccountPresence(toJID_); - relevantPresence = true; - } - } - - if (!relevantPresence) { - return; - } - - if (!newPresence) { - newPresence = boost::make_shared(); - newPresence->setType(Presence::Unavailable); - } - lastShownStatus_ = newPresence->getShow(); - - chatStateTracker_->handlePresenceChange(newPresence); - chatStateNotifier_->setContactIsOnline(newPresence->getType() == Presence::Available); - std::string newStatusChangeString = getStatusChangeString(newPresence); - if (newStatusChangeString != lastStatusChangeString_) { - if (lastWasPresence_) { - chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::UpdateTimestamp); - } else { - chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::DefaultDirection); - } - lastStatusChangeString_ = newStatusChangeString; - lastWasPresence_ = true; - } + bool relevantPresence = false; + + if (isInMUC_) { + // For MUC participants we only have a single presence to choose one and + // even for multi-session nicknames multiple resources are not distinguishable + // to other participants. + if (toJID_.equals(newPresence->getFrom(), JID::WithResource)) { + relevantPresence = true; + } + } + else { + // For standard chats we retrieve the account presence from the PresenceOracle, + // as there can be multiple presences to choose from. + if (toJID_.equals(newPresence->getFrom(), JID::WithoutResource)) { + // Presence matches ChatController JID. + newPresence = presenceOracle_->getAccountPresence(toJID_); + relevantPresence = true; + } + } + + if (!relevantPresence) { + return; + } + + if (!newPresence) { + newPresence = boost::make_shared(); + newPresence->setType(Presence::Unavailable); + } + lastShownStatus_ = newPresence->getShow(); + + chatStateTracker_->handlePresenceChange(newPresence); + chatStateNotifier_->setContactIsOnline(newPresence->getType() == Presence::Available); + std::string newStatusChangeString = getStatusChangeString(newPresence); + if (newStatusChangeString != lastStatusChangeString_) { + if (lastWasPresence_) { + chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::UpdateTimestamp); + } else { + chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(newStatusChangeString), ChatWindow::DefaultDirection); + } + lastStatusChangeString_ = newStatusChangeString; + lastWasPresence_ = true; + } } boost::optional ChatController::getMessageTimestamp(boost::shared_ptr message) const { - return message->getTimestamp(); + return message->getTimestamp(); } void ChatController::logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool /* isIncoming */) { - HistoryMessage::Type type; - if (mucRegistry_->isMUC(fromJID.toBare()) || mucRegistry_->isMUC(toJID.toBare())) { - type = HistoryMessage::PrivateMessage; - } - else { - type = HistoryMessage::Chat; - } + HistoryMessage::Type type; + if (mucRegistry_->isMUC(fromJID.toBare()) || mucRegistry_->isMUC(toJID.toBare())) { + type = HistoryMessage::PrivateMessage; + } + else { + type = HistoryMessage::Chat; + } - if (historyController_) { - historyController_->addMessage(message, fromJID, toJID, type, timeStamp); - } + if (historyController_) { + historyController_->addMessage(message, fromJID, toJID, type, timeStamp); + } } ChatWindow* ChatController::detachChatWindow() { - chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); - chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); - return ChatControllerBase::detachChatWindow(); + chatWindow_->onUserTyping.disconnect(boost::bind(&ChatStateNotifier::setUserIsTyping, chatStateNotifier_)); + chatWindow_->onUserCancelsTyping.disconnect(boost::bind(&ChatStateNotifier::userCancelledNewMessage, chatStateNotifier_)); + return ChatControllerBase::detachChatWindow(); } } diff --git a/Swift/Controllers/Chat/ChatController.h b/Swift/Controllers/Chat/ChatController.h index 6ec19df..aa2b203 100644 --- a/Swift/Controllers/Chat/ChatController.h +++ b/Swift/Controllers/Chat/ChatController.h @@ -16,101 +16,101 @@ #include namespace Swift { - class AvatarManager; - class ChatStateNotifier; - class ChatStateTracker; - class NickResolver; - class EntityCapsProvider; - class FileTransferController; - class SettingsProvider; - class HistoryController; - class HighlightManager; - class ClientBlockListManager; - class UIEvent; - - class ChatController : public ChatControllerBase { - public: - ChatController(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &contact, NickResolver* nickResolver, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool isInMUC, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, bool userWantsReceipts, SettingsProvider* settings, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider); - virtual ~ChatController(); - virtual void setToJID(const JID& jid) SWIFTEN_OVERRIDE; - virtual void setAvailableServerFeatures(boost::shared_ptr info) SWIFTEN_OVERRIDE; - virtual void setOnline(bool online) SWIFTEN_OVERRIDE; - virtual void handleNewFileTransferController(FileTransferController* ftc); - virtual void handleWhiteboardSessionRequest(bool senderIsSelf); - virtual void handleWhiteboardStateChange(const ChatWindow::WhiteboardSessionState state); - virtual void setContactIsReceivingPresence(bool /*isReceivingPresence*/) SWIFTEN_OVERRIDE; - virtual ChatWindow* detachChatWindow() SWIFTEN_OVERRIDE; - - protected: - virtual void cancelReplaces() SWIFTEN_OVERRIDE; - virtual JID getBaseJID() SWIFTEN_OVERRIDE; - virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE; - - private: - void handlePresenceChange(boost::shared_ptr newPresence); - std::string getStatusChangeString(boost::shared_ptr presence); - virtual bool isIncomingMessageFromMe(boost::shared_ptr message) SWIFTEN_OVERRIDE; - virtual void postSendMessage(const std::string &body, boost::shared_ptr sentStanza) SWIFTEN_OVERRIDE; - virtual void preHandleIncomingMessage(boost::shared_ptr messageEvent) SWIFTEN_OVERRIDE; - virtual void postHandleIncomingMessage(boost::shared_ptr messageEvent, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE; - virtual void preSendMessageRequest(boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; - virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; - virtual boost::optional getMessageTimestamp(boost::shared_ptr) const SWIFTEN_OVERRIDE; - void handleStanzaAcked(boost::shared_ptr stanza); - virtual void dayTicked() SWIFTEN_OVERRIDE { lastWasPresence_ = false; } - void handleContactNickChanged(const JID& jid, const std::string& /*oldNick*/); - virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE; - - void handleFileTransferCancel(std::string /* id */); - void handleFileTransferStart(std::string /* id */, std::string /* description */); - void handleFileTransferAccept(std::string /* id */, std::string /* filename */); - void handleSendFileRequest(std::string filename); - - void handleWhiteboardSessionAccept(); - void handleWhiteboardSessionCancel(); - void handleWhiteboardWindowShow(); - - void handleSettingChanged(const std::string& settingPath); - void checkForDisplayingDisplayReceiptsAlert(); - - void handleBlockingStateChanged(); - void handleBlockUserRequest(); - void handleUnblockUserRequest(); - - void handleInviteToChat(const std::vector& droppedJIDs); - - void handleWindowClosed(); - - void handleUIEvent(boost::shared_ptr event); - - private: - NickResolver* nickResolver_; - ChatStateNotifier* chatStateNotifier_; - ChatStateTracker* chatStateTracker_; - std::string myLastMessageUIID_; - bool isInMUC_; - bool lastWasPresence_; - std::string lastStatusChangeString_; - std::map, std::string> unackedStanzas_; - std::map requestedReceipts_; - StatusShow::Type lastShownStatus_; - UIEventStream* eventStream_; - - Tristate contactSupportsReceipts_; - bool receivingPresenceFromUs_; - bool userWantsReceipts_; - std::map ftControllers; - SettingsProvider* settings_; - std::string lastWbID_; - - ClientBlockListManager* clientBlockListManager_; - boost::bsignals::scoped_connection blockingOnStateChangedConnection_; - boost::bsignals::scoped_connection blockingOnItemAddedConnection_; - boost::bsignals::scoped_connection blockingOnItemRemovedConnection_; - - boost::optional deliveryReceiptAlert_; - boost::optional blockedContactAlert_; - }; + class AvatarManager; + class ChatStateNotifier; + class ChatStateTracker; + class NickResolver; + class EntityCapsProvider; + class FileTransferController; + class SettingsProvider; + class HistoryController; + class HighlightManager; + class ClientBlockListManager; + class UIEvent; + + class ChatController : public ChatControllerBase { + public: + ChatController(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &contact, NickResolver* nickResolver, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool isInMUC, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, bool userWantsReceipts, SettingsProvider* settings, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider); + virtual ~ChatController(); + virtual void setToJID(const JID& jid) SWIFTEN_OVERRIDE; + virtual void setAvailableServerFeatures(boost::shared_ptr info) SWIFTEN_OVERRIDE; + virtual void setOnline(bool online) SWIFTEN_OVERRIDE; + virtual void handleNewFileTransferController(FileTransferController* ftc); + virtual void handleWhiteboardSessionRequest(bool senderIsSelf); + virtual void handleWhiteboardStateChange(const ChatWindow::WhiteboardSessionState state); + virtual void setContactIsReceivingPresence(bool /*isReceivingPresence*/) SWIFTEN_OVERRIDE; + virtual ChatWindow* detachChatWindow() SWIFTEN_OVERRIDE; + + protected: + virtual void cancelReplaces() SWIFTEN_OVERRIDE; + virtual JID getBaseJID() SWIFTEN_OVERRIDE; + virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE; + + private: + void handlePresenceChange(boost::shared_ptr newPresence); + std::string getStatusChangeString(boost::shared_ptr presence); + virtual bool isIncomingMessageFromMe(boost::shared_ptr message) SWIFTEN_OVERRIDE; + virtual void postSendMessage(const std::string &body, boost::shared_ptr sentStanza) SWIFTEN_OVERRIDE; + virtual void preHandleIncomingMessage(boost::shared_ptr messageEvent) SWIFTEN_OVERRIDE; + virtual void postHandleIncomingMessage(boost::shared_ptr messageEvent, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE; + virtual void preSendMessageRequest(boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; + virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; + virtual boost::optional getMessageTimestamp(boost::shared_ptr) const SWIFTEN_OVERRIDE; + void handleStanzaAcked(boost::shared_ptr stanza); + virtual void dayTicked() SWIFTEN_OVERRIDE { lastWasPresence_ = false; } + void handleContactNickChanged(const JID& jid, const std::string& /*oldNick*/); + virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE; + + void handleFileTransferCancel(std::string /* id */); + void handleFileTransferStart(std::string /* id */, std::string /* description */); + void handleFileTransferAccept(std::string /* id */, std::string /* filename */); + void handleSendFileRequest(std::string filename); + + void handleWhiteboardSessionAccept(); + void handleWhiteboardSessionCancel(); + void handleWhiteboardWindowShow(); + + void handleSettingChanged(const std::string& settingPath); + void checkForDisplayingDisplayReceiptsAlert(); + + void handleBlockingStateChanged(); + void handleBlockUserRequest(); + void handleUnblockUserRequest(); + + void handleInviteToChat(const std::vector& droppedJIDs); + + void handleWindowClosed(); + + void handleUIEvent(boost::shared_ptr event); + + private: + NickResolver* nickResolver_; + ChatStateNotifier* chatStateNotifier_; + ChatStateTracker* chatStateTracker_; + std::string myLastMessageUIID_; + bool isInMUC_; + bool lastWasPresence_; + std::string lastStatusChangeString_; + std::map, std::string> unackedStanzas_; + std::map requestedReceipts_; + StatusShow::Type lastShownStatus_; + UIEventStream* eventStream_; + + Tristate contactSupportsReceipts_; + bool receivingPresenceFromUs_; + bool userWantsReceipts_; + std::map ftControllers; + SettingsProvider* settings_; + std::string lastWbID_; + + ClientBlockListManager* clientBlockListManager_; + boost::bsignals::scoped_connection blockingOnStateChangedConnection_; + boost::bsignals::scoped_connection blockingOnItemAddedConnection_; + boost::bsignals::scoped_connection blockingOnItemRemovedConnection_; + + boost::optional deliveryReceiptAlert_; + boost::optional blockedContactAlert_; + }; } diff --git a/Swift/Controllers/Chat/ChatControllerBase.cpp b/Swift/Controllers/Chat/ChatControllerBase.cpp index c790cce..d478e2a 100644 --- a/Swift/Controllers/Chat/ChatControllerBase.cpp +++ b/Swift/Controllers/Chat/ChatControllerBase.cpp @@ -43,378 +43,378 @@ namespace Swift { ChatControllerBase::ChatControllerBase(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &toJID, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, boost::shared_ptr chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider) : selfJID_(self), stanzaChannel_(stanzaChannel), iqRouter_(iqRouter), chatWindowFactory_(chatWindowFactory), toJID_(toJID), labelsEnabled_(false), presenceOracle_(presenceOracle), avatarManager_(avatarManager), useDelayForLatency_(useDelayForLatency), eventController_(eventController), timerFactory_(timerFactory), entityCapsProvider_(entityCapsProvider), historyController_(historyController), mucRegistry_(mucRegistry), chatMessageParser_(chatMessageParser), autoAcceptMUCInviteDecider_(autoAcceptMUCInviteDecider), eventStream_(eventStream) { - chatWindow_ = chatWindowFactory_->createChatWindow(toJID, eventStream); - chatWindow_->onAllMessagesRead.connect(boost::bind(&ChatControllerBase::handleAllMessagesRead, this)); - chatWindow_->onSendMessageRequest.connect(boost::bind(&ChatControllerBase::handleSendMessageRequest, this, _1, _2)); - chatWindow_->onLogCleared.connect(boost::bind(&ChatControllerBase::handleLogCleared, this)); - entityCapsProvider_->onCapsChanged.connect(boost::bind(&ChatControllerBase::handleCapsChanged, this, _1)); - highlighter_ = highlightManager->createHighlighter(); - ChatControllerBase::setOnline(stanzaChannel->isAvailable() && iqRouter->isAvailable()); - createDayChangeTimer(); + chatWindow_ = chatWindowFactory_->createChatWindow(toJID, eventStream); + chatWindow_->onAllMessagesRead.connect(boost::bind(&ChatControllerBase::handleAllMessagesRead, this)); + chatWindow_->onSendMessageRequest.connect(boost::bind(&ChatControllerBase::handleSendMessageRequest, this, _1, _2)); + chatWindow_->onLogCleared.connect(boost::bind(&ChatControllerBase::handleLogCleared, this)); + entityCapsProvider_->onCapsChanged.connect(boost::bind(&ChatControllerBase::handleCapsChanged, this, _1)); + highlighter_ = highlightManager->createHighlighter(); + ChatControllerBase::setOnline(stanzaChannel->isAvailable() && iqRouter->isAvailable()); + createDayChangeTimer(); } ChatControllerBase::~ChatControllerBase() { - if (dateChangeTimer_) { - dateChangeTimer_->onTick.disconnect(boost::bind(&ChatControllerBase::handleDayChangeTick, this)); - dateChangeTimer_->stop(); - } + if (dateChangeTimer_) { + dateChangeTimer_->onTick.disconnect(boost::bind(&ChatControllerBase::handleDayChangeTick, this)); + dateChangeTimer_->stop(); + } - delete highlighter_; - delete chatWindow_; + delete highlighter_; + delete chatWindow_; } void ChatControllerBase::handleLogCleared() { - cancelReplaces(); + cancelReplaces(); } ChatWindow* ChatControllerBase::detachChatWindow() { - ChatWindow* chatWindow = chatWindow_; - chatWindow_ = NULL; - return chatWindow; + ChatWindow* chatWindow = chatWindow_; + chatWindow_ = NULL; + return chatWindow; } void ChatControllerBase::handleCapsChanged(const JID& jid) { - if (jid.compare(toJID_, JID::WithoutResource) == 0) { - handleBareJIDCapsChanged(jid); - } + if (jid.compare(toJID_, JID::WithoutResource) == 0) { + handleBareJIDCapsChanged(jid); + } } void ChatControllerBase::setCanStartImpromptuChats(bool supportsImpromptu) { - if (chatWindow_) { - chatWindow_->setCanInitiateImpromptuChats(supportsImpromptu); - } + if (chatWindow_) { + chatWindow_->setCanInitiateImpromptuChats(supportsImpromptu); + } } void ChatControllerBase::createDayChangeTimer() { - if (timerFactory_) { - boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); - boost::posix_time::ptime midnight(now.date() + boost::gregorian::days(1)); - int millisecondsUntilMidnight = boost::numeric_cast((midnight - now).total_milliseconds()); - dateChangeTimer_ = timerFactory_->createTimer(millisecondsUntilMidnight); - dateChangeTimer_->onTick.connect(boost::bind(&ChatControllerBase::handleDayChangeTick, this)); - dateChangeTimer_->start(); - } + if (timerFactory_) { + boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); + boost::posix_time::ptime midnight(now.date() + boost::gregorian::days(1)); + int millisecondsUntilMidnight = boost::numeric_cast((midnight - now).total_milliseconds()); + dateChangeTimer_ = timerFactory_->createTimer(millisecondsUntilMidnight); + dateChangeTimer_->onTick.connect(boost::bind(&ChatControllerBase::handleDayChangeTick, this)); + dateChangeTimer_->start(); + } } void ChatControllerBase::handleDayChangeTick() { - dateChangeTimer_->stop(); - boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The day is now %1%")) % std::string(boost::posix_time::to_iso_extended_string(now)).substr(0,10))), ChatWindow::DefaultDirection); - dayTicked(); - createDayChangeTimer(); + dateChangeTimer_->stop(); + boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The day is now %1%")) % std::string(boost::posix_time::to_iso_extended_string(now)).substr(0,10))), ChatWindow::DefaultDirection); + dayTicked(); + createDayChangeTimer(); } void ChatControllerBase::setEnabled(bool enabled) { - chatWindow_->setOnline(enabled); - chatWindow_->setCanInitiateImpromptuChats(false); + chatWindow_->setOnline(enabled); + chatWindow_->setCanInitiateImpromptuChats(false); } void ChatControllerBase::setOnline(bool online) { - setEnabled(online); + setEnabled(online); } JID ChatControllerBase::getBaseJID() { - return JID(toJID_.toBare()); + return JID(toJID_.toBare()); } void ChatControllerBase::setAvailableServerFeatures(boost::shared_ptr info) { - if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::SecurityLabelsCatalogFeature)) { - GetSecurityLabelsCatalogRequest::ref request = GetSecurityLabelsCatalogRequest::create(getBaseJID(), iqRouter_); - request->onResponse.connect(boost::bind(&ChatControllerBase::handleSecurityLabelsCatalogResponse, this, _1, _2)); - request->send(); - } else { - chatWindow_->setSecurityLabelsEnabled(false); - labelsEnabled_ = false; - } + if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::SecurityLabelsCatalogFeature)) { + GetSecurityLabelsCatalogRequest::ref request = GetSecurityLabelsCatalogRequest::create(getBaseJID(), iqRouter_); + request->onResponse.connect(boost::bind(&ChatControllerBase::handleSecurityLabelsCatalogResponse, this, _1, _2)); + request->send(); + } else { + chatWindow_->setSecurityLabelsEnabled(false); + labelsEnabled_ = false; + } } void ChatControllerBase::handleAllMessagesRead() { - if (!unreadMessages_.empty()) { - targetedUnreadMessages_.clear(); - foreach (boost::shared_ptr stanzaEvent, unreadMessages_) { - stanzaEvent->conclude(); - } - unreadMessages_.clear(); - chatWindow_->setUnreadMessageCount(0); - onUnreadCountChanged(); - } + if (!unreadMessages_.empty()) { + targetedUnreadMessages_.clear(); + foreach (boost::shared_ptr stanzaEvent, unreadMessages_) { + stanzaEvent->conclude(); + } + unreadMessages_.clear(); + chatWindow_->setUnreadMessageCount(0); + onUnreadCountChanged(); + } } int ChatControllerBase::getUnreadCount() { - return boost::numeric_cast(targetedUnreadMessages_.size()); + return boost::numeric_cast(targetedUnreadMessages_.size()); } void ChatControllerBase::handleSendMessageRequest(const std::string &body, bool isCorrectionMessage) { - if (!stanzaChannel_->isAvailable() || body.empty()) { - return; - } - boost::shared_ptr message(new Message()); - message->setTo(toJID_); - message->setType(Swift::Message::Chat); - message->setBody(body); - if (labelsEnabled_) { - if (!isCorrectionMessage) { - lastLabel_ = chatWindow_->getSelectedSecurityLabel(); - } - SecurityLabelsCatalog::Item labelItem = lastLabel_; - if (labelItem.getLabel()) { - message->addPayload(labelItem.getLabel()); - } - } - preSendMessageRequest(message); - - boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); - if (useDelayForLatency_) { - message->addPayload(boost::make_shared(now, selfJID_)); - } - if (isCorrectionMessage) { - message->addPayload(boost::shared_ptr (new Replace(lastSentMessageStanzaID_))); - } - message->setID(lastSentMessageStanzaID_ = idGenerator_.generateID()); - stanzaChannel_->sendMessage(message); - postSendMessage(message->getBody().get(), boost::dynamic_pointer_cast(message)); - onActivity(message->getBody().get()); + if (!stanzaChannel_->isAvailable() || body.empty()) { + return; + } + boost::shared_ptr message(new Message()); + message->setTo(toJID_); + message->setType(Swift::Message::Chat); + message->setBody(body); + if (labelsEnabled_) { + if (!isCorrectionMessage) { + lastLabel_ = chatWindow_->getSelectedSecurityLabel(); + } + SecurityLabelsCatalog::Item labelItem = lastLabel_; + if (labelItem.getLabel()) { + message->addPayload(labelItem.getLabel()); + } + } + preSendMessageRequest(message); + + boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); + if (useDelayForLatency_) { + message->addPayload(boost::make_shared(now, selfJID_)); + } + if (isCorrectionMessage) { + message->addPayload(boost::shared_ptr (new Replace(lastSentMessageStanzaID_))); + } + message->setID(lastSentMessageStanzaID_ = idGenerator_.generateID()); + stanzaChannel_->sendMessage(message); + postSendMessage(message->getBody().get(), boost::dynamic_pointer_cast(message)); + onActivity(message->getBody().get()); #ifdef SWIFT_EXPERIMENTAL_HISTORY - logMessage(body, selfJID_, toJID_, now, false); + logMessage(body, selfJID_, toJID_, now, false); #endif } void ChatControllerBase::handleSecurityLabelsCatalogResponse(boost::shared_ptr catalog, ErrorPayload::ref error) { - if (catalog && !error) { - if (catalog->getItems().size() == 0) { - chatWindow_->setSecurityLabelsEnabled(false); - labelsEnabled_ = false; - } else { - labelsEnabled_ = true; - chatWindow_->setAvailableSecurityLabels(catalog->getItems()); - chatWindow_->setSecurityLabelsEnabled(true); - } - } else { - labelsEnabled_ = false; - chatWindow_->setSecurityLabelsError(); - } + if (catalog && !error) { + if (catalog->getItems().size() == 0) { + chatWindow_->setSecurityLabelsEnabled(false); + labelsEnabled_ = false; + } else { + labelsEnabled_ = true; + chatWindow_->setAvailableSecurityLabels(catalog->getItems()); + chatWindow_->setSecurityLabelsEnabled(true); + } + } else { + labelsEnabled_ = false; + chatWindow_->setSecurityLabelsError(); + } } void ChatControllerBase::showChatWindow() { - chatWindow_->show(); + chatWindow_->show(); } void ChatControllerBase::activateChatWindow() { - chatWindow_->activate(); + chatWindow_->activate(); } bool ChatControllerBase::hasOpenWindow() const { - return chatWindow_ && chatWindow_->isVisible(); + return chatWindow_ && chatWindow_->isVisible(); } ChatWindow::ChatMessage ChatControllerBase::buildChatWindowChatMessage(const std::string& message, bool senderIsSelf, const HighlightAction& fullMessageHighlightAction) { - ChatWindow::ChatMessage chatMessage; - if (boost::starts_with(message, "/me ")) { - chatMessage = chatMessageParser_->parseMessageBody(String::getSplittedAtFirst(message, ' ').second); - } - else { - chatMessage = chatMessageParser_->parseMessageBody(message, highlighter_->getNick(), senderIsSelf); - } - chatMessage.setFullMessageHighlightAction(fullMessageHighlightAction); - return chatMessage; + ChatWindow::ChatMessage chatMessage; + if (boost::starts_with(message, "/me ")) { + chatMessage = chatMessageParser_->parseMessageBody(String::getSplittedAtFirst(message, ' ').second); + } + else { + chatMessage = chatMessageParser_->parseMessageBody(message, highlighter_->getNick(), senderIsSelf); + } + chatMessage.setFullMessageHighlightAction(fullMessageHighlightAction); + return chatMessage; } void ChatControllerBase::handleHighlightActions(const ChatWindow::ChatMessage& chatMessage) { - std::set playedSounds; - if (chatMessage.getFullMessageHighlightAction().playSound()) { - highlighter_->handleHighlightAction(chatMessage.getFullMessageHighlightAction()); - playedSounds.insert(chatMessage.getFullMessageHighlightAction().getSoundFile()); - } - foreach(boost::shared_ptr part, chatMessage.getParts()) { - boost::shared_ptr highlightMessage = boost::dynamic_pointer_cast(part); - if (highlightMessage && highlightMessage->action.playSound()) { - if (playedSounds.find(highlightMessage->action.getSoundFile()) == playedSounds.end()) { - highlighter_->handleHighlightAction(highlightMessage->action); - playedSounds.insert(highlightMessage->action.getSoundFile()); - } - } - } + std::set playedSounds; + if (chatMessage.getFullMessageHighlightAction().playSound()) { + highlighter_->handleHighlightAction(chatMessage.getFullMessageHighlightAction()); + playedSounds.insert(chatMessage.getFullMessageHighlightAction().getSoundFile()); + } + foreach(boost::shared_ptr part, chatMessage.getParts()) { + boost::shared_ptr highlightMessage = boost::dynamic_pointer_cast(part); + if (highlightMessage && highlightMessage->action.playSound()) { + if (playedSounds.find(highlightMessage->action.getSoundFile()) == playedSounds.end()) { + highlighter_->handleHighlightAction(highlightMessage->action); + playedSounds.insert(highlightMessage->action.getSoundFile()); + } + } + } } std::string ChatControllerBase::addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, const boost::shared_ptr label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time) { - if (chatMessage.isMeCommand()) { - return chatWindow_->addAction(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time); - } - else { - return chatWindow_->addMessage(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time); - } + if (chatMessage.isMeCommand()) { + return chatWindow_->addAction(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time); + } + else { + return chatWindow_->addMessage(chatMessage, senderName, senderIsSelf, label, pathToString(avatarPath), time); + } } void ChatControllerBase::replaceMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& id, const boost::posix_time::ptime& time) { - if (chatMessage.isMeCommand()) { - chatWindow_->replaceWithAction(chatMessage, id, time); - } - else { - chatWindow_->replaceMessage(chatMessage, id, time); - } + if (chatMessage.isMeCommand()) { + chatWindow_->replaceWithAction(chatMessage, id, time); + } + else { + chatWindow_->replaceMessage(chatMessage, id, time); + } } bool ChatControllerBase::isFromContact(const JID& from) { - return from.toBare() == toJID_.toBare(); + return from.toBare() == toJID_.toBare(); } void ChatControllerBase::handleIncomingMessage(boost::shared_ptr messageEvent) { - preHandleIncomingMessage(messageEvent); - if (messageEvent->isReadable() && !messageEvent->getConcluded()) { - unreadMessages_.push_back(messageEvent); - if (messageEvent->targetsMe()) { - targetedUnreadMessages_.push_back(messageEvent); - } - } - - boost::shared_ptr message = messageEvent->getStanza(); - ChatWindow::ChatMessage chatMessage; - boost::optional optionalBody = message->getBody(); - std::string body = optionalBody.get_value_or(""); - if (message->isError()) { - if (!message->getTo().getResource().empty()) { - std::string errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't send message: %1%")) % getErrorMessage(message->getPayload())); - chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); - } - } - else if (messageEvent->getStanza()->getPayload()) { - handleMUCInvitation(messageEvent->getStanza()); - return; - } - else if (messageEvent->getStanza()->getPayload() && messageEvent->getStanza()->getPayload()->getInvite()) { - handleMediatedMUCInvitation(messageEvent->getStanza()); - return; - } - else { - if (!messageEvent->isReadable()) { - return; - } - showChatWindow(); - JID from = message->getFrom(); - std::vector > delayPayloads = message->getPayloads(); - for (size_t i = 0; useDelayForLatency_ && i < delayPayloads.size(); i++) { - if (!delayPayloads[i]->getFrom()) { - continue; - } - boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); - std::ostringstream s; - s << "The following message took " << (now - delayPayloads[i]->getStamp()).total_milliseconds() / 1000.0 << " seconds to be delivered from " << delayPayloads[i]->getFrom()->toString() << "."; - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(std::string(s.str())), ChatWindow::DefaultDirection); - } - boost::shared_ptr label = message->getPayload(); - - // Determine the timestamp - boost::posix_time::ptime timeStamp = boost::posix_time::microsec_clock::universal_time(); - boost::optional messageTimeStamp = getMessageTimestamp(message); - if (messageTimeStamp) { - timeStamp = *messageTimeStamp; - } - onActivity(body); - - // Highlight - HighlightAction fullMessageHighlight; - if (!isIncomingMessageFromMe(message)) { - fullMessageHighlight = highlighter_->findFirstFullMessageMatchAction(body, senderHighlightNameFromMessage(from)); - } - - boost::shared_ptr replace = message->getPayload(); - bool senderIsSelf = isIncomingMessageFromMe(message); - if (replace) { - // Should check if the user has a previous message - std::map::iterator lastMessage; - lastMessage = lastMessagesUIID_.find(from); - if (lastMessage != lastMessagesUIID_.end()) { - chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight); - replaceMessage(chatMessage, lastMessagesUIID_[from], timeStamp); - } - } - else { - chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight); - addMessageHandleIncomingMessage(from, chatMessage, senderIsSelf, label, timeStamp); - } - - logMessage(body, from, selfJID_, timeStamp, true); - } - chatWindow_->show(); - chatWindow_->setUnreadMessageCount(boost::numeric_cast(unreadMessages_.size())); - onUnreadCountChanged(); - postHandleIncomingMessage(messageEvent, chatMessage); + preHandleIncomingMessage(messageEvent); + if (messageEvent->isReadable() && !messageEvent->getConcluded()) { + unreadMessages_.push_back(messageEvent); + if (messageEvent->targetsMe()) { + targetedUnreadMessages_.push_back(messageEvent); + } + } + + boost::shared_ptr message = messageEvent->getStanza(); + ChatWindow::ChatMessage chatMessage; + boost::optional optionalBody = message->getBody(); + std::string body = optionalBody.get_value_or(""); + if (message->isError()) { + if (!message->getTo().getResource().empty()) { + std::string errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't send message: %1%")) % getErrorMessage(message->getPayload())); + chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); + } + } + else if (messageEvent->getStanza()->getPayload()) { + handleMUCInvitation(messageEvent->getStanza()); + return; + } + else if (messageEvent->getStanza()->getPayload() && messageEvent->getStanza()->getPayload()->getInvite()) { + handleMediatedMUCInvitation(messageEvent->getStanza()); + return; + } + else { + if (!messageEvent->isReadable()) { + return; + } + showChatWindow(); + JID from = message->getFrom(); + std::vector > delayPayloads = message->getPayloads(); + for (size_t i = 0; useDelayForLatency_ && i < delayPayloads.size(); i++) { + if (!delayPayloads[i]->getFrom()) { + continue; + } + boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time(); + std::ostringstream s; + s << "The following message took " << (now - delayPayloads[i]->getStamp()).total_milliseconds() / 1000.0 << " seconds to be delivered from " << delayPayloads[i]->getFrom()->toString() << "."; + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(std::string(s.str())), ChatWindow::DefaultDirection); + } + boost::shared_ptr label = message->getPayload(); + + // Determine the timestamp + boost::posix_time::ptime timeStamp = boost::posix_time::microsec_clock::universal_time(); + boost::optional messageTimeStamp = getMessageTimestamp(message); + if (messageTimeStamp) { + timeStamp = *messageTimeStamp; + } + onActivity(body); + + // Highlight + HighlightAction fullMessageHighlight; + if (!isIncomingMessageFromMe(message)) { + fullMessageHighlight = highlighter_->findFirstFullMessageMatchAction(body, senderHighlightNameFromMessage(from)); + } + + boost::shared_ptr replace = message->getPayload(); + bool senderIsSelf = isIncomingMessageFromMe(message); + if (replace) { + // Should check if the user has a previous message + std::map::iterator lastMessage; + lastMessage = lastMessagesUIID_.find(from); + if (lastMessage != lastMessagesUIID_.end()) { + chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight); + replaceMessage(chatMessage, lastMessagesUIID_[from], timeStamp); + } + } + else { + chatMessage = buildChatWindowChatMessage(body, senderIsSelf, fullMessageHighlight); + addMessageHandleIncomingMessage(from, chatMessage, senderIsSelf, label, timeStamp); + } + + logMessage(body, from, selfJID_, timeStamp, true); + } + chatWindow_->show(); + chatWindow_->setUnreadMessageCount(boost::numeric_cast(unreadMessages_.size())); + onUnreadCountChanged(); + postHandleIncomingMessage(messageEvent, chatMessage); } void ChatControllerBase::addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr label, const boost::posix_time::ptime& timeStamp) { - lastMessagesUIID_[from] = addMessage(message, senderDisplayNameFromMessage(from), senderIsSelf, label, avatarManager_->getAvatarPath(from), timeStamp); + lastMessagesUIID_[from] = addMessage(message, senderDisplayNameFromMessage(from), senderIsSelf, label, avatarManager_->getAvatarPath(from), timeStamp); } std::string ChatControllerBase::getErrorMessage(boost::shared_ptr error) { - std::string defaultMessage = QT_TRANSLATE_NOOP("", "Error sending message"); - if (!error->getText().empty()) { - return error->getText(); - } - else { - switch (error->getCondition()) { - case ErrorPayload::BadRequest: return QT_TRANSLATE_NOOP("", "Bad request"); - case ErrorPayload::Conflict: return QT_TRANSLATE_NOOP("", "Conflict"); - case ErrorPayload::FeatureNotImplemented: return QT_TRANSLATE_NOOP("", "This feature is not implemented"); - case ErrorPayload::Forbidden: return QT_TRANSLATE_NOOP("", "Forbidden"); - case ErrorPayload::Gone: return QT_TRANSLATE_NOOP("", "Recipient can no longer be contacted"); - case ErrorPayload::InternalServerError: return QT_TRANSLATE_NOOP("", "Internal server error"); - case ErrorPayload::ItemNotFound: return QT_TRANSLATE_NOOP("", "Item not found"); - case ErrorPayload::JIDMalformed: return QT_TRANSLATE_NOOP("", "JID Malformed"); - case ErrorPayload::NotAcceptable: return QT_TRANSLATE_NOOP("", "Message was rejected"); - case ErrorPayload::NotAllowed: return QT_TRANSLATE_NOOP("", "Not allowed"); - case ErrorPayload::NotAuthorized: return QT_TRANSLATE_NOOP("", "Not authorized"); - case ErrorPayload::PaymentRequired: return QT_TRANSLATE_NOOP("", "Payment is required"); - case ErrorPayload::RecipientUnavailable: return QT_TRANSLATE_NOOP("", "Recipient is unavailable"); - case ErrorPayload::Redirect: return QT_TRANSLATE_NOOP("", "Redirect"); - case ErrorPayload::RegistrationRequired: return QT_TRANSLATE_NOOP("", "Registration required"); - case ErrorPayload::RemoteServerNotFound: return QT_TRANSLATE_NOOP("", "Recipient's server not found"); - case ErrorPayload::RemoteServerTimeout: return QT_TRANSLATE_NOOP("", "Remote server timeout"); - case ErrorPayload::ResourceConstraint: return QT_TRANSLATE_NOOP("", "The server is low on resources"); - case ErrorPayload::ServiceUnavailable: return QT_TRANSLATE_NOOP("", "The service is unavailable"); - case ErrorPayload::SubscriptionRequired: return QT_TRANSLATE_NOOP("", "A subscription is required"); - case ErrorPayload::UndefinedCondition: return QT_TRANSLATE_NOOP("", "Undefined condition"); - case ErrorPayload::UnexpectedRequest: return QT_TRANSLATE_NOOP("", "Unexpected request"); - } - } - assert(false); - return defaultMessage; + std::string defaultMessage = QT_TRANSLATE_NOOP("", "Error sending message"); + if (!error->getText().empty()) { + return error->getText(); + } + else { + switch (error->getCondition()) { + case ErrorPayload::BadRequest: return QT_TRANSLATE_NOOP("", "Bad request"); + case ErrorPayload::Conflict: return QT_TRANSLATE_NOOP("", "Conflict"); + case ErrorPayload::FeatureNotImplemented: return QT_TRANSLATE_NOOP("", "This feature is not implemented"); + case ErrorPayload::Forbidden: return QT_TRANSLATE_NOOP("", "Forbidden"); + case ErrorPayload::Gone: return QT_TRANSLATE_NOOP("", "Recipient can no longer be contacted"); + case ErrorPayload::InternalServerError: return QT_TRANSLATE_NOOP("", "Internal server error"); + case ErrorPayload::ItemNotFound: return QT_TRANSLATE_NOOP("", "Item not found"); + case ErrorPayload::JIDMalformed: return QT_TRANSLATE_NOOP("", "JID Malformed"); + case ErrorPayload::NotAcceptable: return QT_TRANSLATE_NOOP("", "Message was rejected"); + case ErrorPayload::NotAllowed: return QT_TRANSLATE_NOOP("", "Not allowed"); + case ErrorPayload::NotAuthorized: return QT_TRANSLATE_NOOP("", "Not authorized"); + case ErrorPayload::PaymentRequired: return QT_TRANSLATE_NOOP("", "Payment is required"); + case ErrorPayload::RecipientUnavailable: return QT_TRANSLATE_NOOP("", "Recipient is unavailable"); + case ErrorPayload::Redirect: return QT_TRANSLATE_NOOP("", "Redirect"); + case ErrorPayload::RegistrationRequired: return QT_TRANSLATE_NOOP("", "Registration required"); + case ErrorPayload::RemoteServerNotFound: return QT_TRANSLATE_NOOP("", "Recipient's server not found"); + case ErrorPayload::RemoteServerTimeout: return QT_TRANSLATE_NOOP("", "Remote server timeout"); + case ErrorPayload::ResourceConstraint: return QT_TRANSLATE_NOOP("", "The server is low on resources"); + case ErrorPayload::ServiceUnavailable: return QT_TRANSLATE_NOOP("", "The service is unavailable"); + case ErrorPayload::SubscriptionRequired: return QT_TRANSLATE_NOOP("", "A subscription is required"); + case ErrorPayload::UndefinedCondition: return QT_TRANSLATE_NOOP("", "Undefined condition"); + case ErrorPayload::UnexpectedRequest: return QT_TRANSLATE_NOOP("", "Unexpected request"); + } + } + assert(false); + return defaultMessage; } void ChatControllerBase::handleGeneralMUCInvitation(MUCInviteEvent::ref event) { - unreadMessages_.push_back(event); - chatWindow_->show(); - chatWindow_->setUnreadMessageCount(boost::numeric_cast(unreadMessages_.size())); - onUnreadCountChanged(); - chatWindow_->addMUCInvitation(senderDisplayNameFromMessage(event->getInviter()), event->getRoomJID(), event->getReason(), event->getPassword(), event->getDirect(), event->getImpromptu()); - eventController_->handleIncomingEvent(event); + unreadMessages_.push_back(event); + chatWindow_->show(); + chatWindow_->setUnreadMessageCount(boost::numeric_cast(unreadMessages_.size())); + onUnreadCountChanged(); + chatWindow_->addMUCInvitation(senderDisplayNameFromMessage(event->getInviter()), event->getRoomJID(), event->getReason(), event->getPassword(), event->getDirect(), event->getImpromptu()); + eventController_->handleIncomingEvent(event); } void ChatControllerBase::handleMUCInvitation(Message::ref message) { - MUCInvitationPayload::ref invite = message->getPayload(); - - if (autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) { - eventStream_->send(boost::make_shared(invite->getJID(), boost::optional(), boost::optional(), false, false, true)); - } else { - MUCInviteEvent::ref inviteEvent = boost::make_shared(toJID_, invite->getJID(), invite->getReason(), invite->getPassword(), true, invite->getIsImpromptu()); - handleGeneralMUCInvitation(inviteEvent); - } + MUCInvitationPayload::ref invite = message->getPayload(); + + if (autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) { + eventStream_->send(boost::make_shared(invite->getJID(), boost::optional(), boost::optional(), false, false, true)); + } else { + MUCInviteEvent::ref inviteEvent = boost::make_shared(toJID_, invite->getJID(), invite->getReason(), invite->getPassword(), true, invite->getIsImpromptu()); + handleGeneralMUCInvitation(inviteEvent); + } } void ChatControllerBase::handleMediatedMUCInvitation(Message::ref message) { - MUCUserPayload::Invite invite = *message->getPayload()->getInvite(); - JID from = message->getFrom(); - std::string reason; - if (!invite.reason.empty()) { - reason = invite.reason; - } - std::string password; - if (message->getPayload()->getPassword()) { - password = *message->getPayload()->getPassword(); - } - - MUCInviteEvent::ref inviteEvent = boost::make_shared(invite.from, from, reason, password, false, false); - handleGeneralMUCInvitation(inviteEvent); + MUCUserPayload::Invite invite = *message->getPayload()->getInvite(); + JID from = message->getFrom(); + std::string reason; + if (!invite.reason.empty()) { + reason = invite.reason; + } + std::string password; + if (message->getPayload()->getPassword()) { + password = *message->getPayload()->getPassword(); + } + + MUCInviteEvent::ref inviteEvent = boost::make_shared(invite.from, from, reason, password, false, false); + handleGeneralMUCInvitation(inviteEvent); } } diff --git a/Swift/Controllers/Chat/ChatControllerBase.h b/Swift/Controllers/Chat/ChatControllerBase.h index 98f0ab0..bd8ba0f 100644 --- a/Swift/Controllers/Chat/ChatControllerBase.h +++ b/Swift/Controllers/Chat/ChatControllerBase.h @@ -35,107 +35,107 @@ #include namespace Swift { - class IQRouter; - class StanzaChannel; - class ChatWindowFactory; - class AvatarManager; - class UIEventStream; - class EventController; - class EntityCapsProvider; - class HighlightManager; - class Highlighter; - class ChatMessageParser; - class AutoAcceptMUCInviteDecider; + class IQRouter; + class StanzaChannel; + class ChatWindowFactory; + class AvatarManager; + class UIEventStream; + class EventController; + class EntityCapsProvider; + class HighlightManager; + class Highlighter; + class ChatMessageParser; + class AutoAcceptMUCInviteDecider; - class ChatControllerBase : public boost::bsignals::trackable { - public: - virtual ~ChatControllerBase(); - void showChatWindow(); - void activateChatWindow(); - bool hasOpenWindow() const; - virtual void setAvailableServerFeatures(boost::shared_ptr info); - void handleIncomingMessage(boost::shared_ptr message); - std::string addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time); - void replaceMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& id, const boost::posix_time::ptime& time); - virtual void setOnline(bool online); - void setEnabled(bool enabled); - virtual void setToJID(const JID& jid) {toJID_ = jid;} - /** Used for determining when something is recent.*/ - boost::signal onActivity; - boost::signal onUnreadCountChanged; - boost::signal onWindowClosed; - int getUnreadCount(); - const JID& getToJID() {return toJID_;} - void handleCapsChanged(const JID& jid); - void setCanStartImpromptuChats(bool supportsImpromptu); - virtual ChatWindow* detachChatWindow(); - boost::signal& /*invite people*/, const std::string& /*reason*/)> onConvertToMUC; + class ChatControllerBase : public boost::bsignals::trackable { + public: + virtual ~ChatControllerBase(); + void showChatWindow(); + void activateChatWindow(); + bool hasOpenWindow() const; + virtual void setAvailableServerFeatures(boost::shared_ptr info); + void handleIncomingMessage(boost::shared_ptr message); + std::string addMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const boost::filesystem::path& avatarPath, const boost::posix_time::ptime& time); + void replaceMessage(const ChatWindow::ChatMessage& chatMessage, const std::string& id, const boost::posix_time::ptime& time); + virtual void setOnline(bool online); + void setEnabled(bool enabled); + virtual void setToJID(const JID& jid) {toJID_ = jid;} + /** Used for determining when something is recent.*/ + boost::signal onActivity; + boost::signal onUnreadCountChanged; + boost::signal onWindowClosed; + int getUnreadCount(); + const JID& getToJID() {return toJID_;} + void handleCapsChanged(const JID& jid); + void setCanStartImpromptuChats(bool supportsImpromptu); + virtual ChatWindow* detachChatWindow(); + boost::signal& /*invite people*/, const std::string& /*reason*/)> onConvertToMUC; - protected: - ChatControllerBase(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &toJID, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, boost::shared_ptr chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider); + protected: + ChatControllerBase(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &toJID, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, boost::shared_ptr chatMessageParser, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider); - /** - * Pass the Message appended, and the stanza used to send it. - */ - virtual void postSendMessage(const std::string&, boost::shared_ptr) {} - virtual std::string senderDisplayNameFromMessage(const JID& from) = 0; - virtual std::string senderHighlightNameFromMessage(const JID& from) = 0; - virtual bool isIncomingMessageFromMe(boost::shared_ptr) = 0; - virtual void preHandleIncomingMessage(boost::shared_ptr) {} - virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr label, const boost::posix_time::ptime& time); - virtual void postHandleIncomingMessage(boost::shared_ptr, const ChatWindow::ChatMessage&) {} - virtual void preSendMessageRequest(boost::shared_ptr) {} - virtual bool isFromContact(const JID& from); - virtual boost::optional getMessageTimestamp(boost::shared_ptr) const = 0; - virtual void dayTicked() {} - virtual void handleBareJIDCapsChanged(const JID& jid) = 0; - std::string getErrorMessage(boost::shared_ptr); - virtual void setContactIsReceivingPresence(bool /* isReceivingPresence */) {} - virtual void cancelReplaces() = 0; - /** JID any iq for account should go to - bare except for PMs */ - virtual JID getBaseJID(); - virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) = 0; - ChatWindow::ChatMessage buildChatWindowChatMessage(const std::string& message, bool senderIsSelf, const HighlightAction& fullMessageHighlightAction); - void handleHighlightActions(const ChatWindow::ChatMessage& chatMessage); + /** + * Pass the Message appended, and the stanza used to send it. + */ + virtual void postSendMessage(const std::string&, boost::shared_ptr) {} + virtual std::string senderDisplayNameFromMessage(const JID& from) = 0; + virtual std::string senderHighlightNameFromMessage(const JID& from) = 0; + virtual bool isIncomingMessageFromMe(boost::shared_ptr) = 0; + virtual void preHandleIncomingMessage(boost::shared_ptr) {} + virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr label, const boost::posix_time::ptime& time); + virtual void postHandleIncomingMessage(boost::shared_ptr, const ChatWindow::ChatMessage&) {} + virtual void preSendMessageRequest(boost::shared_ptr) {} + virtual bool isFromContact(const JID& from); + virtual boost::optional getMessageTimestamp(boost::shared_ptr) const = 0; + virtual void dayTicked() {} + virtual void handleBareJIDCapsChanged(const JID& jid) = 0; + std::string getErrorMessage(boost::shared_ptr); + virtual void setContactIsReceivingPresence(bool /* isReceivingPresence */) {} + virtual void cancelReplaces() = 0; + /** JID any iq for account should go to - bare except for PMs */ + virtual JID getBaseJID(); + virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) = 0; + ChatWindow::ChatMessage buildChatWindowChatMessage(const std::string& message, bool senderIsSelf, const HighlightAction& fullMessageHighlightAction); + void handleHighlightActions(const ChatWindow::ChatMessage& chatMessage); - private: - IDGenerator idGenerator_; - std::string lastSentMessageStanzaID_; - void createDayChangeTimer(); + private: + IDGenerator idGenerator_; + std::string lastSentMessageStanzaID_; + void createDayChangeTimer(); - void handleSendMessageRequest(const std::string &body, bool isCorrectionMessage); - void handleAllMessagesRead(); - void handleSecurityLabelsCatalogResponse(boost::shared_ptr, ErrorPayload::ref error); - void handleDayChangeTick(); - void handleMUCInvitation(Message::ref message); - void handleMediatedMUCInvitation(Message::ref message); - void handleGeneralMUCInvitation(MUCInviteEvent::ref event); - void handleLogCleared(); + void handleSendMessageRequest(const std::string &body, bool isCorrectionMessage); + void handleAllMessagesRead(); + void handleSecurityLabelsCatalogResponse(boost::shared_ptr, ErrorPayload::ref error); + void handleDayChangeTick(); + void handleMUCInvitation(Message::ref message); + void handleMediatedMUCInvitation(Message::ref message); + void handleGeneralMUCInvitation(MUCInviteEvent::ref event); + void handleLogCleared(); - protected: - JID selfJID_; - std::vector > unreadMessages_; - std::vector > targetedUnreadMessages_; - StanzaChannel* stanzaChannel_; - IQRouter* iqRouter_; - ChatWindowFactory* chatWindowFactory_; - ChatWindow* chatWindow_; - JID toJID_; - bool labelsEnabled_; - std::map lastMessagesUIID_; - PresenceOracle* presenceOracle_; - AvatarManager* avatarManager_; - bool useDelayForLatency_; - EventController* eventController_; - boost::shared_ptr dateChangeTimer_; - TimerFactory* timerFactory_; - EntityCapsProvider* entityCapsProvider_; - SecurityLabelsCatalog::Item lastLabel_; - HistoryController* historyController_; - MUCRegistry* mucRegistry_; - Highlighter* highlighter_; - boost::shared_ptr chatMessageParser_; - AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_; - UIEventStream* eventStream_; - }; + protected: + JID selfJID_; + std::vector > unreadMessages_; + std::vector > targetedUnreadMessages_; + StanzaChannel* stanzaChannel_; + IQRouter* iqRouter_; + ChatWindowFactory* chatWindowFactory_; + ChatWindow* chatWindow_; + JID toJID_; + bool labelsEnabled_; + std::map lastMessagesUIID_; + PresenceOracle* presenceOracle_; + AvatarManager* avatarManager_; + bool useDelayForLatency_; + EventController* eventController_; + boost::shared_ptr dateChangeTimer_; + TimerFactory* timerFactory_; + EntityCapsProvider* entityCapsProvider_; + SecurityLabelsCatalog::Item lastLabel_; + HistoryController* historyController_; + MUCRegistry* mucRegistry_; + Highlighter* highlighter_; + boost::shared_ptr chatMessageParser_; + AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_; + UIEventStream* eventStream_; + }; } diff --git a/Swift/Controllers/Chat/ChatMessageParser.cpp b/Swift/Controllers/Chat/ChatMessageParser.cpp index 53c7588..08e4fcd 100644 --- a/Swift/Controllers/Chat/ChatMessageParser.cpp +++ b/Swift/Controllers/Chat/ChatMessageParser.cpp @@ -19,177 +19,177 @@ namespace Swift { - ChatMessageParser::ChatMessageParser(const std::map& emoticons, HighlightRulesListPtr highlightRules, bool mucMode) - : emoticons_(emoticons), highlightRules_(highlightRules), mucMode_(mucMode) { - } - - typedef std::pair StringPair; - - ChatWindow::ChatMessage ChatMessageParser::parseMessageBody(const std::string& body, const std::string& nick, bool senderIsSelf) { - ChatWindow::ChatMessage parsedMessage; - std::string remaining = body; - /* Parse one, URLs */ - while (!remaining.empty()) { - bool found = false; - std::pair, size_t> links = Linkify::splitLink(remaining); - remaining = ""; - for (size_t i = 0; i < links.first.size(); i++) { - const std::string& part = links.first[i]; - if (found) { - // Must be on the last part, then - remaining = part; - } - else { - if (i == links.second) { - found = true; - parsedMessage.append(boost::make_shared(part)); - } - else { - parsedMessage.append(boost::make_shared(part)); - } - } - } - } - - /* do emoticon substitution */ - parsedMessage = emoticonHighlight(parsedMessage); - - if (!senderIsSelf) { /* do not highlight our own messsages */ - /* do word-based color highlighting */ - parsedMessage = splitHighlight(parsedMessage, nick); - } - - return parsedMessage; - } - - ChatWindow::ChatMessage ChatMessageParser::emoticonHighlight(const ChatWindow::ChatMessage& message) - { - ChatWindow::ChatMessage parsedMessage = message; - - std::string regexString; - /* Parse two, emoticons */ - foreach (StringPair emoticon, emoticons_) { - /* Construct a regexp that finds an instance of any of the emoticons inside a group - * at the start or end of the line, or beside whitespace. - */ - regexString += regexString.empty() ? "" : "|"; - std::string escaped = "(" + Regex::escape(emoticon.first) + ")"; - regexString += "^" + escaped + "|"; - regexString += escaped + "$|"; - regexString += "\\s" + escaped + "|"; - regexString += escaped + "\\s"; - - } - if (!regexString.empty()) { - regexString += ""; - boost::regex emoticonRegex(regexString); - - ChatWindow::ChatMessage newMessage; - foreach (boost::shared_ptr part, parsedMessage.getParts()) { - boost::shared_ptr textPart; - if ((textPart = boost::dynamic_pointer_cast(part))) { - try { - boost::match_results match; - const std::string& text = textPart->text; - std::string::const_iterator start = text.begin(); - while (regex_search(start, text.end(), match, emoticonRegex)) { - int matchIndex = 0; - for (matchIndex = 1; matchIndex < static_cast(match.size()); matchIndex++) { - if (match[matchIndex].length() > 0) { - //This is the matching subgroup - break; - } - } - std::string::const_iterator matchStart = match[matchIndex].first; - std::string::const_iterator matchEnd = match[matchIndex].second; - if (start != matchStart) { - /* If we're skipping over plain text since the previous emoticon, record it as plain text */ - newMessage.append(boost::make_shared(std::string(start, matchStart))); - } - boost::shared_ptr emoticonPart = boost::make_shared(); - std::string matchString = match[matchIndex].str(); - std::map::const_iterator emoticonIterator = emoticons_.find(matchString); - assert (emoticonIterator != emoticons_.end()); - const StringPair& emoticon = *emoticonIterator; - emoticonPart->imagePath = emoticon.second; - emoticonPart->alternativeText = emoticon.first; - newMessage.append(emoticonPart); - start = matchEnd; - } - if (start != text.end()) { - /* If there's plain text after the last emoticon, record it */ - newMessage.append(boost::make_shared(std::string(start, text.end()))); - } - - } - catch (std::runtime_error) { - /* Basically too expensive to compute the regex results and it gave up, so pass through as text */ - newMessage.append(part); - } - } - else { - newMessage.append(part); - } - } - parsedMessage = newMessage; - - } - return parsedMessage; - } - - ChatWindow::ChatMessage ChatMessageParser::splitHighlight(const ChatWindow::ChatMessage& message, const std::string& nick) - { - ChatWindow::ChatMessage parsedMessage = message; - - for (size_t i = 0; i < highlightRules_->getSize(); ++i) { - const HighlightRule& rule = highlightRules_->getRule(i); - if (rule.getMatchMUC() && !mucMode_) { - continue; /* this rule only applies to MUC's, and this is a CHAT */ - } else if (rule.getMatchChat() && mucMode_) { - continue; /* this rule only applies to CHAT's, and this is a MUC */ - } else if (rule.getAction().getTextBackground().empty() && rule.getAction().getTextColor().empty()) { - continue; /* do not try to highlight text, if no highlight color is specified */ - } - const std::vector keywordRegex = rule.getKeywordRegex(nick); - foreach(const boost::regex& regex, keywordRegex) { - ChatWindow::ChatMessage newMessage; - foreach (boost::shared_ptr part, parsedMessage.getParts()) { - boost::shared_ptr textPart; - if ((textPart = boost::dynamic_pointer_cast(part))) { - try { - boost::match_results match; - const std::string& text = textPart->text; - std::string::const_iterator start = text.begin(); - while (regex_search(start, text.end(), match, regex)) { - std::string::const_iterator matchStart = match[0].first; - std::string::const_iterator matchEnd = match[0].second; - if (start != matchStart) { - /* If we're skipping over plain text since the previous emoticon, record it as plain text */ - newMessage.append(boost::make_shared(std::string(start, matchStart))); - } - boost::shared_ptr highlightPart = boost::make_shared(); - highlightPart->text = match.str(); - highlightPart->action = rule.getAction(); - newMessage.append(highlightPart); - start = matchEnd; - } - if (start != text.end()) { - /* If there's plain text after the last emoticon, record it */ - newMessage.append(boost::make_shared(std::string(start, text.end()))); - } - } - catch (std::runtime_error) { - /* Basically too expensive to compute the regex results and it gave up, so pass through as text */ - newMessage.append(part); - } - } else { - newMessage.append(part); - } - } - parsedMessage = newMessage; - } - } - - return parsedMessage; - } + ChatMessageParser::ChatMessageParser(const std::map& emoticons, HighlightRulesListPtr highlightRules, bool mucMode) + : emoticons_(emoticons), highlightRules_(highlightRules), mucMode_(mucMode) { + } + + typedef std::pair StringPair; + + ChatWindow::ChatMessage ChatMessageParser::parseMessageBody(const std::string& body, const std::string& nick, bool senderIsSelf) { + ChatWindow::ChatMessage parsedMessage; + std::string remaining = body; + /* Parse one, URLs */ + while (!remaining.empty()) { + bool found = false; + std::pair, size_t> links = Linkify::splitLink(remaining); + remaining = ""; + for (size_t i = 0; i < links.first.size(); i++) { + const std::string& part = links.first[i]; + if (found) { + // Must be on the last part, then + remaining = part; + } + else { + if (i == links.second) { + found = true; + parsedMessage.append(boost::make_shared(part)); + } + else { + parsedMessage.append(boost::make_shared(part)); + } + } + } + } + + /* do emoticon substitution */ + parsedMessage = emoticonHighlight(parsedMessage); + + if (!senderIsSelf) { /* do not highlight our own messsages */ + /* do word-based color highlighting */ + parsedMessage = splitHighlight(parsedMessage, nick); + } + + return parsedMessage; + } + + ChatWindow::ChatMessage ChatMessageParser::emoticonHighlight(const ChatWindow::ChatMessage& message) + { + ChatWindow::ChatMessage parsedMessage = message; + + std::string regexString; + /* Parse two, emoticons */ + foreach (StringPair emoticon, emoticons_) { + /* Construct a regexp that finds an instance of any of the emoticons inside a group + * at the start or end of the line, or beside whitespace. + */ + regexString += regexString.empty() ? "" : "|"; + std::string escaped = "(" + Regex::escape(emoticon.first) + ")"; + regexString += "^" + escaped + "|"; + regexString += escaped + "$|"; + regexString += "\\s" + escaped + "|"; + regexString += escaped + "\\s"; + + } + if (!regexString.empty()) { + regexString += ""; + boost::regex emoticonRegex(regexString); + + ChatWindow::ChatMessage newMessage; + foreach (boost::shared_ptr part, parsedMessage.getParts()) { + boost::shared_ptr textPart; + if ((textPart = boost::dynamic_pointer_cast(part))) { + try { + boost::match_results match; + const std::string& text = textPart->text; + std::string::const_iterator start = text.begin(); + while (regex_search(start, text.end(), match, emoticonRegex)) { + int matchIndex = 0; + for (matchIndex = 1; matchIndex < static_cast(match.size()); matchIndex++) { + if (match[matchIndex].length() > 0) { + //This is the matching subgroup + break; + } + } + std::string::const_iterator matchStart = match[matchIndex].first; + std::string::const_iterator matchEnd = match[matchIndex].second; + if (start != matchStart) { + /* If we're skipping over plain text since the previous emoticon, record it as plain text */ + newMessage.append(boost::make_shared(std::string(start, matchStart))); + } + boost::shared_ptr emoticonPart = boost::make_shared(); + std::string matchString = match[matchIndex].str(); + std::map::const_iterator emoticonIterator = emoticons_.find(matchString); + assert (emoticonIterator != emoticons_.end()); + const StringPair& emoticon = *emoticonIterator; + emoticonPart->imagePath = emoticon.second; + emoticonPart->alternativeText = emoticon.first; + newMessage.append(emoticonPart); + start = matchEnd; + } + if (start != text.end()) { + /* If there's plain text after the last emoticon, record it */ + newMessage.append(boost::make_shared(std::string(start, text.end()))); + } + + } + catch (std::runtime_error) { + /* Basically too expensive to compute the regex results and it gave up, so pass through as text */ + newMessage.append(part); + } + } + else { + newMessage.append(part); + } + } + parsedMessage = newMessage; + + } + return parsedMessage; + } + + ChatWindow::ChatMessage ChatMessageParser::splitHighlight(const ChatWindow::ChatMessage& message, const std::string& nick) + { + ChatWindow::ChatMessage parsedMessage = message; + + for (size_t i = 0; i < highlightRules_->getSize(); ++i) { + const HighlightRule& rule = highlightRules_->getRule(i); + if (rule.getMatchMUC() && !mucMode_) { + continue; /* this rule only applies to MUC's, and this is a CHAT */ + } else if (rule.getMatchChat() && mucMode_) { + continue; /* this rule only applies to CHAT's, and this is a MUC */ + } else if (rule.getAction().getTextBackground().empty() && rule.getAction().getTextColor().empty()) { + continue; /* do not try to highlight text, if no highlight color is specified */ + } + const std::vector keywordRegex = rule.getKeywordRegex(nick); + foreach(const boost::regex& regex, keywordRegex) { + ChatWindow::ChatMessage newMessage; + foreach (boost::shared_ptr part, parsedMessage.getParts()) { + boost::shared_ptr textPart; + if ((textPart = boost::dynamic_pointer_cast(part))) { + try { + boost::match_results match; + const std::string& text = textPart->text; + std::string::const_iterator start = text.begin(); + while (regex_search(start, text.end(), match, regex)) { + std::string::const_iterator matchStart = match[0].first; + std::string::const_iterator matchEnd = match[0].second; + if (start != matchStart) { + /* If we're skipping over plain text since the previous emoticon, record it as plain text */ + newMessage.append(boost::make_shared(std::string(start, matchStart))); + } + boost::shared_ptr highlightPart = boost::make_shared(); + highlightPart->text = match.str(); + highlightPart->action = rule.getAction(); + newMessage.append(highlightPart); + start = matchEnd; + } + if (start != text.end()) { + /* If there's plain text after the last emoticon, record it */ + newMessage.append(boost::make_shared(std::string(start, text.end()))); + } + } + catch (std::runtime_error) { + /* Basically too expensive to compute the regex results and it gave up, so pass through as text */ + newMessage.append(part); + } + } else { + newMessage.append(part); + } + } + parsedMessage = newMessage; + } + } + + return parsedMessage; + } } diff --git a/Swift/Controllers/Chat/ChatMessageParser.h b/Swift/Controllers/Chat/ChatMessageParser.h index e56d21b..4bed669 100644 --- a/Swift/Controllers/Chat/ChatMessageParser.h +++ b/Swift/Controllers/Chat/ChatMessageParser.h @@ -12,15 +12,15 @@ namespace Swift { - class ChatMessageParser { - public: - ChatMessageParser(const std::map& emoticons, HighlightRulesListPtr highlightRules, bool mucMode = false); - ChatWindow::ChatMessage parseMessageBody(const std::string& body, const std::string& nick = "", bool senderIsSelf = false); - private: - ChatWindow::ChatMessage emoticonHighlight(const ChatWindow::ChatMessage& parsedMessage); - ChatWindow::ChatMessage splitHighlight(const ChatWindow::ChatMessage& parsedMessage, const std::string& nick); - std::map emoticons_; - HighlightRulesListPtr highlightRules_; - bool mucMode_; - }; + class ChatMessageParser { + public: + ChatMessageParser(const std::map& emoticons, HighlightRulesListPtr highlightRules, bool mucMode = false); + ChatWindow::ChatMessage parseMessageBody(const std::string& body, const std::string& nick = "", bool senderIsSelf = false); + private: + ChatWindow::ChatMessage emoticonHighlight(const ChatWindow::ChatMessage& parsedMessage); + ChatWindow::ChatMessage splitHighlight(const ChatWindow::ChatMessage& parsedMessage, const std::string& nick); + std::map emoticons_; + HighlightRulesListPtr highlightRules_; + bool mucMode_; + }; } diff --git a/Swift/Controllers/Chat/ChatsManager.cpp b/Swift/Controllers/Chat/ChatsManager.cpp index 49caee4..32da58a 100644 --- a/Swift/Controllers/Chat/ChatsManager.cpp +++ b/Swift/Controllers/Chat/ChatsManager.cpp @@ -67,32 +67,32 @@ BOOST_CLASS_VERSION(Swift::ChatListWindow::Chat, 1) namespace boost { namespace serialization { - template void save(Archive& ar, const Swift::JID& jid, const unsigned int /*version*/) { - std::string jidStr = jid.toString(); - ar << jidStr; - } - - template void load(Archive& ar, Swift::JID& jid, const unsigned int /*version*/) { - std::string stringJID; - ar >> stringJID; - jid = Swift::JID(stringJID); - } - - template inline void serialize(Archive& ar, Swift::JID& t, const unsigned int file_version){ - split_free(ar, t, file_version); - } - - template void serialize(Archive& ar, Swift::ChatListWindow::Chat& chat, const unsigned int version) { - ar & chat.jid; - ar & chat.chatName; - ar & chat.activity; - ar & chat.isMUC; - ar & chat.nick; - ar & chat.impromptuJIDs; - if (version > 0) { - ar & chat.password; - } - } + template void save(Archive& ar, const Swift::JID& jid, const unsigned int /*version*/) { + std::string jidStr = jid.toString(); + ar << jidStr; + } + + template void load(Archive& ar, Swift::JID& jid, const unsigned int /*version*/) { + std::string stringJID; + ar >> stringJID; + jid = Swift::JID(stringJID); + } + + template inline void serialize(Archive& ar, Swift::JID& t, const unsigned int file_version){ + split_free(ar, t, file_version); + } + + template void serialize(Archive& ar, Swift::ChatListWindow::Chat& chat, const unsigned int version) { + ar & chat.jid; + ar & chat.chatName; + ar & chat.activity; + ar & chat.isMUC; + ar & chat.nick; + ar & chat.impromptuJIDs; + if (version > 0) { + ar & chat.password; + } + } } } @@ -104,950 +104,950 @@ typedef std::pair JIDMUCControllerPair; #define RECENT_CHATS "recent_chats" ChatsManager::ChatsManager( - JID jid, StanzaChannel* stanzaChannel, - IQRouter* iqRouter, - EventController* eventController, - ChatWindowFactory* chatWindowFactory, - JoinMUCWindowFactory* joinMUCWindowFactory, - NickResolver* nickResolver, - PresenceOracle* presenceOracle, - PresenceSender* presenceSender, - UIEventStream* uiEventStream, - ChatListWindowFactory* chatListWindowFactory, - bool useDelayForLatency, - TimerFactory* timerFactory, - MUCRegistry* mucRegistry, - EntityCapsProvider* entityCapsProvider, - MUCManager* mucManager, - MUCSearchWindowFactory* mucSearchWindowFactory, - ProfileSettingsProvider* profileSettings, - FileTransferOverview* ftOverview, - XMPPRoster* roster, - bool eagleMode, - SettingsProvider* settings, - HistoryController* historyController, - WhiteboardManager* whiteboardManager, - HighlightManager* highlightManager, - ClientBlockListManager* clientBlockListManager, - const std::map& emoticons, - VCardManager* vcardManager) : - jid_(jid), - joinMUCWindowFactory_(joinMUCWindowFactory), - useDelayForLatency_(useDelayForLatency), - mucRegistry_(mucRegistry), - entityCapsProvider_(entityCapsProvider), - mucManager(mucManager), - ftOverview_(ftOverview), - roster_(roster), - eagleMode_(eagleMode), - settings_(settings), - historyController_(historyController), - whiteboardManager_(whiteboardManager), - highlightManager_(highlightManager), - emoticons_(emoticons), - clientBlockListManager_(clientBlockListManager), - vcardManager_(vcardManager) { - timerFactory_ = timerFactory; - eventController_ = eventController; - stanzaChannel_ = stanzaChannel; - iqRouter_ = iqRouter; - chatWindowFactory_ = chatWindowFactory; - nickResolver_ = nickResolver; - presenceOracle_ = presenceOracle; - avatarManager_ = NULL; - serverDiscoInfo_ = boost::make_shared(); - presenceSender_ = presenceSender; - uiEventStream_ = uiEventStream; - mucBookmarkManager_ = NULL; - profileSettings_ = profileSettings; - presenceOracle_->onPresenceChange.connect(boost::bind(&ChatsManager::handlePresenceChange, this, _1)); - uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&ChatsManager::handleUIEvent, this, _1)); - - chatListWindow_ = chatListWindowFactory->createChatListWindow(uiEventStream_); - chatListWindow_->onMUCBookmarkActivated.connect(boost::bind(&ChatsManager::handleMUCBookmarkActivated, this, _1)); - chatListWindow_->onRecentActivated.connect(boost::bind(&ChatsManager::handleRecentActivated, this, _1)); - chatListWindow_->onClearRecentsRequested.connect(boost::bind(&ChatsManager::handleClearRecentsRequested, this)); - - joinMUCWindow_ = NULL; - mucSearchController_ = new MUCSearchController(jid_, mucSearchWindowFactory, iqRouter, profileSettings_); - mucSearchController_->onMUCSelected.connect(boost::bind(&ChatsManager::handleMUCSelectedAfterSearch, this, _1)); - ftOverview_->onNewFileTransferController.connect(boost::bind(&ChatsManager::handleNewFileTransferController, this, _1)); - whiteboardManager_->onSessionRequest.connect(boost::bind(&ChatsManager::handleWhiteboardSessionRequest, this, _1, _2)); - whiteboardManager_->onRequestAccepted.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardAccepted)); - whiteboardManager_->onSessionTerminate.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardTerminated)); - whiteboardManager_->onRequestRejected.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardRejected)); - roster_->onJIDAdded.connect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1)); - roster_->onJIDRemoved.connect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1)); - roster_->onJIDUpdated.connect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1)); - roster_->onRosterCleared.connect(boost::bind(&ChatsManager::handleRosterCleared, this)); - - settings_->onSettingChanged.connect(boost::bind(&ChatsManager::handleSettingChanged, this, _1)); - - userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS); - - setupBookmarks(); - loadRecents(); - - autoAcceptMUCInviteDecider_ = new AutoAcceptMUCInviteDecider(jid.getDomain(), roster_, settings_); + JID jid, StanzaChannel* stanzaChannel, + IQRouter* iqRouter, + EventController* eventController, + ChatWindowFactory* chatWindowFactory, + JoinMUCWindowFactory* joinMUCWindowFactory, + NickResolver* nickResolver, + PresenceOracle* presenceOracle, + PresenceSender* presenceSender, + UIEventStream* uiEventStream, + ChatListWindowFactory* chatListWindowFactory, + bool useDelayForLatency, + TimerFactory* timerFactory, + MUCRegistry* mucRegistry, + EntityCapsProvider* entityCapsProvider, + MUCManager* mucManager, + MUCSearchWindowFactory* mucSearchWindowFactory, + ProfileSettingsProvider* profileSettings, + FileTransferOverview* ftOverview, + XMPPRoster* roster, + bool eagleMode, + SettingsProvider* settings, + HistoryController* historyController, + WhiteboardManager* whiteboardManager, + HighlightManager* highlightManager, + ClientBlockListManager* clientBlockListManager, + const std::map& emoticons, + VCardManager* vcardManager) : + jid_(jid), + joinMUCWindowFactory_(joinMUCWindowFactory), + useDelayForLatency_(useDelayForLatency), + mucRegistry_(mucRegistry), + entityCapsProvider_(entityCapsProvider), + mucManager(mucManager), + ftOverview_(ftOverview), + roster_(roster), + eagleMode_(eagleMode), + settings_(settings), + historyController_(historyController), + whiteboardManager_(whiteboardManager), + highlightManager_(highlightManager), + emoticons_(emoticons), + clientBlockListManager_(clientBlockListManager), + vcardManager_(vcardManager) { + timerFactory_ = timerFactory; + eventController_ = eventController; + stanzaChannel_ = stanzaChannel; + iqRouter_ = iqRouter; + chatWindowFactory_ = chatWindowFactory; + nickResolver_ = nickResolver; + presenceOracle_ = presenceOracle; + avatarManager_ = NULL; + serverDiscoInfo_ = boost::make_shared(); + presenceSender_ = presenceSender; + uiEventStream_ = uiEventStream; + mucBookmarkManager_ = NULL; + profileSettings_ = profileSettings; + presenceOracle_->onPresenceChange.connect(boost::bind(&ChatsManager::handlePresenceChange, this, _1)); + uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&ChatsManager::handleUIEvent, this, _1)); + + chatListWindow_ = chatListWindowFactory->createChatListWindow(uiEventStream_); + chatListWindow_->onMUCBookmarkActivated.connect(boost::bind(&ChatsManager::handleMUCBookmarkActivated, this, _1)); + chatListWindow_->onRecentActivated.connect(boost::bind(&ChatsManager::handleRecentActivated, this, _1)); + chatListWindow_->onClearRecentsRequested.connect(boost::bind(&ChatsManager::handleClearRecentsRequested, this)); + + joinMUCWindow_ = NULL; + mucSearchController_ = new MUCSearchController(jid_, mucSearchWindowFactory, iqRouter, profileSettings_); + mucSearchController_->onMUCSelected.connect(boost::bind(&ChatsManager::handleMUCSelectedAfterSearch, this, _1)); + ftOverview_->onNewFileTransferController.connect(boost::bind(&ChatsManager::handleNewFileTransferController, this, _1)); + whiteboardManager_->onSessionRequest.connect(boost::bind(&ChatsManager::handleWhiteboardSessionRequest, this, _1, _2)); + whiteboardManager_->onRequestAccepted.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardAccepted)); + whiteboardManager_->onSessionTerminate.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardTerminated)); + whiteboardManager_->onRequestRejected.connect(boost::bind(&ChatsManager::handleWhiteboardStateChange, this, _1, ChatWindow::WhiteboardRejected)); + roster_->onJIDAdded.connect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1)); + roster_->onJIDRemoved.connect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1)); + roster_->onJIDUpdated.connect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1)); + roster_->onRosterCleared.connect(boost::bind(&ChatsManager::handleRosterCleared, this)); + + settings_->onSettingChanged.connect(boost::bind(&ChatsManager::handleSettingChanged, this, _1)); + + userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS); + + setupBookmarks(); + loadRecents(); + + autoAcceptMUCInviteDecider_ = new AutoAcceptMUCInviteDecider(jid.getDomain(), roster_, settings_); } ChatsManager::~ChatsManager() { - settings_->onSettingChanged.disconnect(boost::bind(&ChatsManager::handleSettingChanged, this, _1)); - roster_->onJIDAdded.disconnect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1)); - roster_->onJIDRemoved.disconnect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1)); - roster_->onJIDUpdated.disconnect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1)); - roster_->onRosterCleared.disconnect(boost::bind(&ChatsManager::handleRosterCleared, this)); - delete joinMUCWindow_; - foreach (JIDChatControllerPair controllerPair, chatControllers_) { - delete controllerPair.second; - } - foreach (JIDMUCControllerPair controllerPair, mucControllers_) { - delete controllerPair.second; - } - delete mucBookmarkManager_; - delete mucSearchController_; - delete autoAcceptMUCInviteDecider_; + settings_->onSettingChanged.disconnect(boost::bind(&ChatsManager::handleSettingChanged, this, _1)); + roster_->onJIDAdded.disconnect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1)); + roster_->onJIDRemoved.disconnect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1)); + roster_->onJIDUpdated.disconnect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1)); + roster_->onRosterCleared.disconnect(boost::bind(&ChatsManager::handleRosterCleared, this)); + delete joinMUCWindow_; + foreach (JIDChatControllerPair controllerPair, chatControllers_) { + delete controllerPair.second; + } + foreach (JIDMUCControllerPair controllerPair, mucControllers_) { + delete controllerPair.second; + } + delete mucBookmarkManager_; + delete mucSearchController_; + delete autoAcceptMUCInviteDecider_; } void ChatsManager::saveRecents() { - std::stringstream serializeStream; - boost::archive::text_oarchive oa(serializeStream); - std::vector recentsLimited = std::vector(recentChats_.begin(), recentChats_.end()); - if (recentsLimited.size() > 25) { - recentsLimited.erase(recentsLimited.begin() + 25, recentsLimited.end()); - } - if (eagleMode_) { - foreach(ChatListWindow::Chat& chat, recentsLimited) { - chat.activity = ""; - } - } - - class RemoveRecent { - public: - static bool ifPrivateMessage(const ChatListWindow::Chat& chat) { - return chat.isPrivateMessage; - } - }; - - recentsLimited.erase(std::remove_if(recentsLimited.begin(), recentsLimited.end(), RemoveRecent::ifPrivateMessage), recentsLimited.end()); - - oa << recentsLimited; - std::string serializedStr = Base64::encode(createByteArray(serializeStream.str())); - profileSettings_->storeString(RECENT_CHATS, serializedStr); + std::stringstream serializeStream; + boost::archive::text_oarchive oa(serializeStream); + std::vector recentsLimited = std::vector(recentChats_.begin(), recentChats_.end()); + if (recentsLimited.size() > 25) { + recentsLimited.erase(recentsLimited.begin() + 25, recentsLimited.end()); + } + if (eagleMode_) { + foreach(ChatListWindow::Chat& chat, recentsLimited) { + chat.activity = ""; + } + } + + class RemoveRecent { + public: + static bool ifPrivateMessage(const ChatListWindow::Chat& chat) { + return chat.isPrivateMessage; + } + }; + + recentsLimited.erase(std::remove_if(recentsLimited.begin(), recentsLimited.end(), RemoveRecent::ifPrivateMessage), recentsLimited.end()); + + oa << recentsLimited; + std::string serializedStr = Base64::encode(createByteArray(serializeStream.str())); + profileSettings_->storeString(RECENT_CHATS, serializedStr); } void ChatsManager::handleClearRecentsRequested() { - recentChats_.clear(); - saveRecents(); - handleUnreadCountChanged(NULL); + recentChats_.clear(); + saveRecents(); + handleUnreadCountChanged(NULL); } void ChatsManager::handleJIDAddedToRoster(const JID &jid) { - updatePresenceReceivingStateOnChatController(jid); + updatePresenceReceivingStateOnChatController(jid); } void ChatsManager::handleJIDRemovedFromRoster(const JID &jid) { - updatePresenceReceivingStateOnChatController(jid); + updatePresenceReceivingStateOnChatController(jid); } void ChatsManager::handleJIDUpdatedInRoster(const JID &jid) { - updatePresenceReceivingStateOnChatController(jid); + updatePresenceReceivingStateOnChatController(jid); } void ChatsManager::handleRosterCleared() { - /* Setting that all chat controllers aren't receiving presence anymore; - including MUC 1-to-1 chats due to the assumtion that this handler - is only called on log out. */ - foreach(JIDChatControllerPair pair, chatControllers_) { - pair.second->setContactIsReceivingPresence(false); - } + /* Setting that all chat controllers aren't receiving presence anymore; + including MUC 1-to-1 chats due to the assumtion that this handler + is only called on log out. */ + foreach(JIDChatControllerPair pair, chatControllers_) { + pair.second->setContactIsReceivingPresence(false); + } } void ChatsManager::updatePresenceReceivingStateOnChatController(const JID &jid) { - ChatController* controller = getChatControllerIfExists(jid); - if (controller) { - if (!mucRegistry_->isMUC(jid.toBare())) { - RosterItemPayload::Subscription subscription = roster_->getSubscriptionStateForJID(jid); - controller->setContactIsReceivingPresence(subscription == RosterItemPayload::From || subscription == RosterItemPayload::Both); - } else { - controller->setContactIsReceivingPresence(true); - } - } + ChatController* controller = getChatControllerIfExists(jid); + if (controller) { + if (!mucRegistry_->isMUC(jid.toBare())) { + RosterItemPayload::Subscription subscription = roster_->getSubscriptionStateForJID(jid); + controller->setContactIsReceivingPresence(subscription == RosterItemPayload::From || subscription == RosterItemPayload::Both); + } else { + controller->setContactIsReceivingPresence(true); + } + } } ChatListWindow::Chat ChatsManager::updateChatStatusAndAvatarHelper(const ChatListWindow::Chat& chat) const { - ChatListWindow::Chat fixedChat = chat; - if (fixedChat.isMUC) { - if (mucControllers_.find(fixedChat.jid.toBare()) != mucControllers_.end()) { - fixedChat.statusType = StatusShow::Online; - } - } else { - if (avatarManager_) { - fixedChat.avatarPath = avatarManager_->getAvatarPath(fixedChat.jid); - } - Presence::ref presence = presenceOracle_->getAccountPresence(fixedChat.jid.toBare()); - fixedChat.statusType = presence ? presence->getShow() : StatusShow::None; - } - return fixedChat; + ChatListWindow::Chat fixedChat = chat; + if (fixedChat.isMUC) { + if (mucControllers_.find(fixedChat.jid.toBare()) != mucControllers_.end()) { + fixedChat.statusType = StatusShow::Online; + } + } else { + if (avatarManager_) { + fixedChat.avatarPath = avatarManager_->getAvatarPath(fixedChat.jid); + } + Presence::ref presence = presenceOracle_->getAccountPresence(fixedChat.jid.toBare()); + fixedChat.statusType = presence ? presence->getShow() : StatusShow::None; + } + return fixedChat; } void ChatsManager::loadRecents() { - std::string recentsString(profileSettings_->getStringSetting(RECENT_CHATS)); - if (recentsString.find("\t") != std::string::npos) { - // old format - std::vector recents; - boost::split(recents, recentsString, boost::is_any_of("\n")); - int i = 0; - foreach (std::string recentString, recents) { - if (i++ > 30) { - break; - } - std::vector recent; - boost::split(recent, recentString, boost::is_any_of("\t")); - if (recent.size() < 4) { - continue; - } - JID jid(recent[0]); - if (!jid.isValid()) { - continue; - } - std::string activity(recent[1]); - bool isMUC = recent[2] == "true"; - std::string nick(recent[3]); - StatusShow::Type type = StatusShow::None; - boost::filesystem::path path; - - ChatListWindow::Chat chat(jid, nickResolver_->jidToNick(jid), activity, 0, type, path, isMUC, false, nick); - chat = updateChatStatusAndAvatarHelper(chat); - prependRecent(chat); - } - } else if (!recentsString.empty()){ - // boost searilaize based format - ByteArray debase64 = Base64::decode(recentsString); - std::vector recentChats; - std::stringstream deserializeStream(std::string(reinterpret_cast(vecptr(debase64)), debase64.size())); - try { - boost::archive::text_iarchive ia(deserializeStream); - ia >> recentChats; - } catch (const boost::archive::archive_exception& e) { - SWIFT_LOG(debug) << "Failed to load recents: " << e.what() << std::endl; - return; - } - - foreach(ChatListWindow::Chat chat, recentChats) { - chat.statusType = StatusShow::None; - chat = updateChatStatusAndAvatarHelper(chat); - prependRecent(chat); - } - } - handleUnreadCountChanged(NULL); + std::string recentsString(profileSettings_->getStringSetting(RECENT_CHATS)); + if (recentsString.find("\t") != std::string::npos) { + // old format + std::vector recents; + boost::split(recents, recentsString, boost::is_any_of("\n")); + int i = 0; + foreach (std::string recentString, recents) { + if (i++ > 30) { + break; + } + std::vector recent; + boost::split(recent, recentString, boost::is_any_of("\t")); + if (recent.size() < 4) { + continue; + } + JID jid(recent[0]); + if (!jid.isValid()) { + continue; + } + std::string activity(recent[1]); + bool isMUC = recent[2] == "true"; + std::string nick(recent[3]); + StatusShow::Type type = StatusShow::None; + boost::filesystem::path path; + + ChatListWindow::Chat chat(jid, nickResolver_->jidToNick(jid), activity, 0, type, path, isMUC, false, nick); + chat = updateChatStatusAndAvatarHelper(chat); + prependRecent(chat); + } + } else if (!recentsString.empty()){ + // boost searilaize based format + ByteArray debase64 = Base64::decode(recentsString); + std::vector recentChats; + std::stringstream deserializeStream(std::string(reinterpret_cast(vecptr(debase64)), debase64.size())); + try { + boost::archive::text_iarchive ia(deserializeStream); + ia >> recentChats; + } catch (const boost::archive::archive_exception& e) { + SWIFT_LOG(debug) << "Failed to load recents: " << e.what() << std::endl; + return; + } + + foreach(ChatListWindow::Chat chat, recentChats) { + chat.statusType = StatusShow::None; + chat = updateChatStatusAndAvatarHelper(chat); + prependRecent(chat); + } + } + handleUnreadCountChanged(NULL); } void ChatsManager::setupBookmarks() { - if (!mucBookmarkManager_) { - mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_); - mucBookmarkManager_->onBookmarksReady.connect(boost::bind(&ChatsManager::handleBookmarksReady, this)); - mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&ChatsManager::handleMUCBookmarkAdded, this, _1)); - mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&ChatsManager::handleMUCBookmarkRemoved, this, _1)); - - if (chatListWindow_) { - chatListWindow_->setBookmarksEnabled(false); - chatListWindow_->clearBookmarks(); - } - } + if (!mucBookmarkManager_) { + mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_); + mucBookmarkManager_->onBookmarksReady.connect(boost::bind(&ChatsManager::handleBookmarksReady, this)); + mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&ChatsManager::handleMUCBookmarkAdded, this, _1)); + mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&ChatsManager::handleMUCBookmarkRemoved, this, _1)); + + if (chatListWindow_) { + chatListWindow_->setBookmarksEnabled(false); + chatListWindow_->clearBookmarks(); + } + } } void ChatsManager::handleBookmarksReady() { - if (chatListWindow_) { - chatListWindow_->setBookmarksEnabled(true); - } + if (chatListWindow_) { + chatListWindow_->setBookmarksEnabled(true); + } } void ChatsManager::handleMUCBookmarkAdded(const MUCBookmark& bookmark) { - std::map::iterator it = mucControllers_.find(bookmark.getRoom()); - if (it == mucControllers_.end() && bookmark.getAutojoin()) { - handleJoinMUCRequest(bookmark.getRoom(), bookmark.getPassword(), bookmark.getNick(), false, false, false ); - } - chatListWindow_->addMUCBookmark(bookmark); + std::map::iterator it = mucControllers_.find(bookmark.getRoom()); + if (it == mucControllers_.end() && bookmark.getAutojoin()) { + handleJoinMUCRequest(bookmark.getRoom(), bookmark.getPassword(), bookmark.getNick(), false, false, false ); + } + chatListWindow_->addMUCBookmark(bookmark); } void ChatsManager::handleMUCBookmarkRemoved(const MUCBookmark& bookmark) { - chatListWindow_->removeMUCBookmark(bookmark); + chatListWindow_->removeMUCBookmark(bookmark); } ChatListWindow::Chat ChatsManager::createChatListChatItem(const JID& jid, const std::string& activity, bool privateMessage) { - int unreadCount = 0; - if (mucRegistry_->isMUC(jid)) { - MUCController* controller = mucControllers_[jid.toBare()]; - StatusShow::Type type = StatusShow::None; - std::string nick = ""; - std::string password = ""; - if (controller) { - unreadCount = controller->getUnreadCount(); - if (controller->isJoined()) { - type = StatusShow::Online; - } - nick = controller->getNick(); - - if (controller->getPassword()) { - password = *controller->getPassword(); - } - - if (controller->isImpromptu()) { - ChatListWindow::Chat chat = ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password); - std::map participants = controller->getParticipantJIDs(); - chat.impromptuJIDs = participants; - return chat; - } - } - return ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password); - } else { - ChatController* controller = getChatControllerIfExists(jid, false); - if (controller) { - unreadCount = controller->getUnreadCount(); - } - JID bareishJID = mucRegistry_->isMUC(jid.toBare()) ? jid : jid.toBare(); - Presence::ref presence = presenceOracle_->getAccountPresence(bareishJID); - StatusShow::Type type = presence ? presence->getShow() : StatusShow::None; - boost::filesystem::path avatarPath = avatarManager_ ? avatarManager_->getAvatarPath(bareishJID) : boost::filesystem::path(); - return ChatListWindow::Chat(bareishJID, nickResolver_->jidToNick(bareishJID), activity, unreadCount, type, avatarPath, false, privateMessage); - } + int unreadCount = 0; + if (mucRegistry_->isMUC(jid)) { + MUCController* controller = mucControllers_[jid.toBare()]; + StatusShow::Type type = StatusShow::None; + std::string nick = ""; + std::string password = ""; + if (controller) { + unreadCount = controller->getUnreadCount(); + if (controller->isJoined()) { + type = StatusShow::Online; + } + nick = controller->getNick(); + + if (controller->getPassword()) { + password = *controller->getPassword(); + } + + if (controller->isImpromptu()) { + ChatListWindow::Chat chat = ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password); + std::map participants = controller->getParticipantJIDs(); + chat.impromptuJIDs = participants; + return chat; + } + } + return ChatListWindow::Chat(jid, jid.toString(), activity, unreadCount, type, boost::filesystem::path(), true, privateMessage, nick, password); + } else { + ChatController* controller = getChatControllerIfExists(jid, false); + if (controller) { + unreadCount = controller->getUnreadCount(); + } + JID bareishJID = mucRegistry_->isMUC(jid.toBare()) ? jid : jid.toBare(); + Presence::ref presence = presenceOracle_->getAccountPresence(bareishJID); + StatusShow::Type type = presence ? presence->getShow() : StatusShow::None; + boost::filesystem::path avatarPath = avatarManager_ ? avatarManager_->getAvatarPath(bareishJID) : boost::filesystem::path(); + return ChatListWindow::Chat(bareishJID, nickResolver_->jidToNick(bareishJID), activity, unreadCount, type, avatarPath, false, privateMessage); + } } void ChatsManager::handleChatActivity(const JID& jid, const std::string& activity, bool isMUC) { - const bool privateMessage = mucRegistry_->isMUC(jid.toBare()) && !isMUC; - ChatListWindow::Chat chat = createChatListChatItem(jid, activity, privateMessage); - /* FIXME: handle nick changes */ - appendRecent(chat); - handleUnreadCountChanged(NULL); - saveRecents(); + const bool privateMessage = mucRegistry_->isMUC(jid.toBare()) && !isMUC; + ChatListWindow::Chat chat = createChatListChatItem(jid, activity, privateMessage); + /* FIXME: handle nick changes */ + appendRecent(chat); + handleUnreadCountChanged(NULL); + saveRecents(); } void ChatsManager::handleChatClosed(const JID& /*jid*/) { - cleanupPrivateMessageRecents(); - chatListWindow_->setRecents(recentChats_); + cleanupPrivateMessageRecents(); + chatListWindow_->setRecents(recentChats_); } void ChatsManager::handleUnreadCountChanged(ChatControllerBase* controller) { - int unreadTotal = 0; - bool controllerIsMUC = dynamic_cast(controller); - bool isPM = controller && !controllerIsMUC && mucRegistry_->isMUC(controller->getToJID().toBare()); - foreach (ChatListWindow::Chat& chatItem, recentChats_) { - bool match = false; - if (controller) { - /* Matching MUC item */ - match |= chatItem.isMUC == controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare(); - /* Matching PM */ - match |= isPM && chatItem.jid == controller->getToJID(); - /* Matching non-PM */ - match |= !isPM && !controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare(); - } - if (match) { - chatItem.setUnreadCount(controller->getUnreadCount()); - } - unreadTotal += chatItem.unreadCount; - } - chatListWindow_->setRecents(recentChats_); - chatListWindow_->setUnreadCount(unreadTotal); + int unreadTotal = 0; + bool controllerIsMUC = dynamic_cast(controller); + bool isPM = controller && !controllerIsMUC && mucRegistry_->isMUC(controller->getToJID().toBare()); + foreach (ChatListWindow::Chat& chatItem, recentChats_) { + bool match = false; + if (controller) { + /* Matching MUC item */ + match |= chatItem.isMUC == controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare(); + /* Matching PM */ + match |= isPM && chatItem.jid == controller->getToJID(); + /* Matching non-PM */ + match |= !isPM && !controllerIsMUC && chatItem.jid.toBare() == controller->getToJID().toBare(); + } + if (match) { + chatItem.setUnreadCount(controller->getUnreadCount()); + } + unreadTotal += chatItem.unreadCount; + } + chatListWindow_->setRecents(recentChats_); + chatListWindow_->setUnreadCount(unreadTotal); } boost::optional ChatsManager::removeExistingChat(const ChatListWindow::Chat& chat) { - std::list::iterator result = std::find(recentChats_.begin(), recentChats_.end(), chat); - if (result != recentChats_.end()) { - ChatListWindow::Chat existingChat = *result; - recentChats_.erase(std::remove(recentChats_.begin(), recentChats_.end(), chat), recentChats_.end()); - return boost::optional(existingChat); - } else { - return boost::optional(); - } + std::list::iterator result = std::find(recentChats_.begin(), recentChats_.end(), chat); + if (result != recentChats_.end()) { + ChatListWindow::Chat existingChat = *result; + recentChats_.erase(std::remove(recentChats_.begin(), recentChats_.end(), chat), recentChats_.end()); + return boost::optional(existingChat); + } else { + return boost::optional(); + } } void ChatsManager::cleanupPrivateMessageRecents() { - /* if we leave a MUC and close a PM, remove it's recent chat entry */ - const std::list chats = recentChats_; - foreach (const ChatListWindow::Chat& chat, chats) { - if (chat.isPrivateMessage) { - typedef std::map ControllerMap; - ControllerMap::iterator muc = mucControllers_.find(chat.jid.toBare()); - if (muc == mucControllers_.end() || !muc->second->isJoined()) { - ChatController* chatController = getChatControllerIfExists(chat.jid); - if (!chatController || !chatController->hasOpenWindow()) { - removeExistingChat(chat); - break; - } - } - } - } + /* if we leave a MUC and close a PM, remove it's recent chat entry */ + const std::list chats = recentChats_; + foreach (const ChatListWindow::Chat& chat, chats) { + if (chat.isPrivateMessage) { + typedef std::map ControllerMap; + ControllerMap::iterator muc = mucControllers_.find(chat.jid.toBare()); + if (muc == mucControllers_.end() || !muc->second->isJoined()) { + ChatController* chatController = getChatControllerIfExists(chat.jid); + if (!chatController || !chatController->hasOpenWindow()) { + removeExistingChat(chat); + break; + } + } + } + } } void ChatsManager::appendRecent(const ChatListWindow::Chat& chat) { - boost::optional oldChat = removeExistingChat(chat); - ChatListWindow::Chat mergedChat = chat; - if (oldChat && !oldChat->impromptuJIDs.empty()) { - mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end()); - } - recentChats_.push_front(mergedChat); + boost::optional oldChat = removeExistingChat(chat); + ChatListWindow::Chat mergedChat = chat; + if (oldChat && !oldChat->impromptuJIDs.empty()) { + mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end()); + } + recentChats_.push_front(mergedChat); } void ChatsManager::prependRecent(const ChatListWindow::Chat& chat) { - boost::optional oldChat = removeExistingChat(chat); - ChatListWindow::Chat mergedChat = chat; - if (oldChat && !oldChat->impromptuJIDs.empty()) { - mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end()); - } - recentChats_.push_back(mergedChat); + boost::optional oldChat = removeExistingChat(chat); + ChatListWindow::Chat mergedChat = chat; + if (oldChat && !oldChat->impromptuJIDs.empty()) { + mergedChat.impromptuJIDs.insert(oldChat->impromptuJIDs.begin(), oldChat->impromptuJIDs.end()); + } + recentChats_.push_back(mergedChat); } void ChatsManager::handleUserLeftMUC(MUCController* mucController) { - std::map::iterator it; - for (it = mucControllers_.begin(); it != mucControllers_.end(); ++it) { - if ((*it).second == mucController) { - foreach (ChatListWindow::Chat& chat, recentChats_) { - if (chat.isMUC && chat.jid == (*it).first) { - chat.statusType = StatusShow::None; - } - } - mucControllers_.erase(it); - delete mucController; - break; - } - } - cleanupPrivateMessageRecents(); - chatListWindow_->setRecents(recentChats_); + std::map::iterator it; + for (it = mucControllers_.begin(); it != mucControllers_.end(); ++it) { + if ((*it).second == mucController) { + foreach (ChatListWindow::Chat& chat, recentChats_) { + if (chat.isMUC && chat.jid == (*it).first) { + chat.statusType = StatusShow::None; + } + } + mucControllers_.erase(it); + delete mucController; + break; + } + } + cleanupPrivateMessageRecents(); + chatListWindow_->setRecents(recentChats_); } void ChatsManager::handleSettingChanged(const std::string& settingPath) { - if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) { - userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS); - return; - } + if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) { + userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS); + return; + } } void ChatsManager::finalizeImpromptuJoin(MUC::ref muc, const std::vector& jidsToInvite, const std::string& reason, const boost::optional& reuseChatJID) { - // send impromptu invites for the new MUC - std::vector missingJIDsToInvite = jidsToInvite; - - typedef std::pair StringMUCOccupantPair; - std::map occupants = muc->getOccupants(); - foreach(StringMUCOccupantPair occupant, occupants) { - boost::optional realJID = occupant.second.getRealJID(); - if (realJID) { - missingJIDsToInvite.erase(std::remove(missingJIDsToInvite.begin(), missingJIDsToInvite.end(), realJID->toBare()), missingJIDsToInvite.end()); - } - } - - if (reuseChatJID) { - muc->invitePerson(reuseChatJID.get(), reason, true, true); - } - foreach(const JID& jid, missingJIDsToInvite) { - muc->invitePerson(jid, reason, true); - } + // send impromptu invites for the new MUC + std::vector missingJIDsToInvite = jidsToInvite; + + typedef std::pair StringMUCOccupantPair; + std::map occupants = muc->getOccupants(); + foreach(StringMUCOccupantPair occupant, occupants) { + boost::optional realJID = occupant.second.getRealJID(); + if (realJID) { + missingJIDsToInvite.erase(std::remove(missingJIDsToInvite.begin(), missingJIDsToInvite.end(), realJID->toBare()), missingJIDsToInvite.end()); + } + } + + if (reuseChatJID) { + muc->invitePerson(reuseChatJID.get(), reason, true, true); + } + foreach(const JID& jid, missingJIDsToInvite) { + muc->invitePerson(jid, reason, true); + } } void ChatsManager::handleUIEvent(boost::shared_ptr event) { - boost::shared_ptr chatEvent = boost::dynamic_pointer_cast(event); - if (chatEvent) { - handleChatRequest(chatEvent->getContact()); - return; - } - boost::shared_ptr removeMUCBookmarkEvent = boost::dynamic_pointer_cast(event); - if (removeMUCBookmarkEvent) { - mucBookmarkManager_->removeBookmark(removeMUCBookmarkEvent->getBookmark()); - return; - } - boost::shared_ptr addMUCBookmarkEvent = boost::dynamic_pointer_cast(event); - if (addMUCBookmarkEvent) { - mucBookmarkManager_->addBookmark(addMUCBookmarkEvent->getBookmark()); - return; - } - - boost::shared_ptr createImpromptuMUCEvent = boost::dynamic_pointer_cast(event); - if (createImpromptuMUCEvent) { - assert(!localMUCServiceJID_.toString().empty()); - // create new muc - JID roomJID = createImpromptuMUCEvent->getRoomJID().toString().empty() ? JID(idGenerator_.generateID(), localMUCServiceJID_) : createImpromptuMUCEvent->getRoomJID(); - - // join muc - MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional(), nickResolver_->jidToNick(jid_), false, true, true); - mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, createImpromptuMUCEvent->getJIDs(), createImpromptuMUCEvent->getReason(), boost::optional())); - mucControllers_[roomJID]->activateChatWindow(); - } - - boost::shared_ptr editMUCBookmarkEvent = boost::dynamic_pointer_cast(event); - if (editMUCBookmarkEvent) { - mucBookmarkManager_->replaceBookmark(editMUCBookmarkEvent->getOldBookmark(), editMUCBookmarkEvent->getNewBookmark()); - } - else if (JoinMUCUIEvent::ref joinEvent = boost::dynamic_pointer_cast(event)) { - handleJoinMUCRequest(joinEvent->getJID(), joinEvent->getPassword(), joinEvent->getNick(), joinEvent->getShouldJoinAutomatically(), joinEvent->getCreateAsReservedRoomIfNew(), joinEvent->isImpromptu()); - mucControllers_[joinEvent->getJID()]->activateChatWindow(); - } - else if (boost::shared_ptr joinEvent = boost::dynamic_pointer_cast(event)) { - if (!joinMUCWindow_) { - joinMUCWindow_ = joinMUCWindowFactory_->createJoinMUCWindow(uiEventStream_); - joinMUCWindow_->onSearchMUC.connect(boost::bind(&ChatsManager::handleSearchMUCRequest, this)); - } - joinMUCWindow_->setMUC(joinEvent->getRoom()); - joinMUCWindow_->setNick(nickResolver_->jidToNick(jid_)); - joinMUCWindow_->show(); - } + boost::shared_ptr chatEvent = boost::dynamic_pointer_cast(event); + if (chatEvent) { + handleChatRequest(chatEvent->getContact()); + return; + } + boost::shared_ptr removeMUCBookmarkEvent = boost::dynamic_pointer_cast(event); + if (removeMUCBookmarkEvent) { + mucBookmarkManager_->removeBookmark(removeMUCBookmarkEvent->getBookmark()); + return; + } + boost::shared_ptr addMUCBookmarkEvent = boost::dynamic_pointer_cast(event); + if (addMUCBookmarkEvent) { + mucBookmarkManager_->addBookmark(addMUCBookmarkEvent->getBookmark()); + return; + } + + boost::shared_ptr createImpromptuMUCEvent = boost::dynamic_pointer_cast(event); + if (createImpromptuMUCEvent) { + assert(!localMUCServiceJID_.toString().empty()); + // create new muc + JID roomJID = createImpromptuMUCEvent->getRoomJID().toString().empty() ? JID(idGenerator_.generateID(), localMUCServiceJID_) : createImpromptuMUCEvent->getRoomJID(); + + // join muc + MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional(), nickResolver_->jidToNick(jid_), false, true, true); + mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, createImpromptuMUCEvent->getJIDs(), createImpromptuMUCEvent->getReason(), boost::optional())); + mucControllers_[roomJID]->activateChatWindow(); + } + + boost::shared_ptr editMUCBookmarkEvent = boost::dynamic_pointer_cast(event); + if (editMUCBookmarkEvent) { + mucBookmarkManager_->replaceBookmark(editMUCBookmarkEvent->getOldBookmark(), editMUCBookmarkEvent->getNewBookmark()); + } + else if (JoinMUCUIEvent::ref joinEvent = boost::dynamic_pointer_cast(event)) { + handleJoinMUCRequest(joinEvent->getJID(), joinEvent->getPassword(), joinEvent->getNick(), joinEvent->getShouldJoinAutomatically(), joinEvent->getCreateAsReservedRoomIfNew(), joinEvent->isImpromptu()); + mucControllers_[joinEvent->getJID()]->activateChatWindow(); + } + else if (boost::shared_ptr joinEvent = boost::dynamic_pointer_cast(event)) { + if (!joinMUCWindow_) { + joinMUCWindow_ = joinMUCWindowFactory_->createJoinMUCWindow(uiEventStream_); + joinMUCWindow_->onSearchMUC.connect(boost::bind(&ChatsManager::handleSearchMUCRequest, this)); + } + joinMUCWindow_->setMUC(joinEvent->getRoom()); + joinMUCWindow_->setNick(nickResolver_->jidToNick(jid_)); + joinMUCWindow_->show(); + } } void ChatsManager::markAllRecentsOffline() { - foreach (ChatListWindow::Chat& chat, recentChats_) { - chat.setStatusType(StatusShow::None); - } + foreach (ChatListWindow::Chat& chat, recentChats_) { + chat.setStatusType(StatusShow::None); + } - chatListWindow_->setRecents(recentChats_); + chatListWindow_->setRecents(recentChats_); } void ChatsManager::handleTransformChatToMUC(ChatController* chatController, ChatWindow* chatWindow, const std::vector& jidsToInvite, const std::string& reason) { - JID reuseChatInvite = chatController->getToJID(); - chatControllers_.erase(chatController->getToJID()); - delete chatController; + JID reuseChatInvite = chatController->getToJID(); + chatControllers_.erase(chatController->getToJID()); + delete chatController; - // join new impromptu muc - assert(!localMUCServiceJID_.toString().empty()); + // join new impromptu muc + assert(!localMUCServiceJID_.toString().empty()); - // create new muc - JID roomJID = JID(idGenerator_.generateID(), localMUCServiceJID_); + // create new muc + JID roomJID = JID(idGenerator_.generateID(), localMUCServiceJID_); - // join muc - MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional(), nickResolver_->jidToNick(jid_), false, true, true, chatWindow); - mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, jidsToInvite, reason, boost::optional(reuseChatInvite))); + // join muc + MUC::ref muc = handleJoinMUCRequest(roomJID, boost::optional(), nickResolver_->jidToNick(jid_), false, true, true, chatWindow); + mucControllers_[roomJID]->onImpromptuConfigCompleted.connect(boost::bind(&ChatsManager::finalizeImpromptuJoin, this, muc, jidsToInvite, reason, boost::optional(reuseChatInvite))); } /** * If a resource goes offline, release bound chatdialog to that resource. */ void ChatsManager::handlePresenceChange(boost::shared_ptr newPresence) { - if (mucRegistry_->isMUC(newPresence->getFrom().toBare())) return; - - foreach (ChatListWindow::Chat& chat, recentChats_) { - if (newPresence->getFrom().toBare() == chat.jid.toBare() && !chat.isMUC) { - Presence::ref presence = presenceOracle_->getHighestPriorityPresence(chat.jid.toBare()); - chat.setStatusType(presence ? presence->getShow() : StatusShow::None); - chatListWindow_->setRecents(recentChats_); - break; - } - } - - //if (newPresence->getType() != Presence::Unavailable) return; - JID fullJID(newPresence->getFrom()); - std::map::iterator it = chatControllers_.find(fullJID); - if (it == chatControllers_.end()) return; - JID bareJID(fullJID.toBare()); - //It doesn't make sense to have two unbound dialogs. - if (chatControllers_.find(bareJID) != chatControllers_.end()) return; - rebindControllerJID(fullJID, bareJID); + if (mucRegistry_->isMUC(newPresence->getFrom().toBare())) return; + + foreach (ChatListWindow::Chat& chat, recentChats_) { + if (newPresence->getFrom().toBare() == chat.jid.toBare() && !chat.isMUC) { + Presence::ref presence = presenceOracle_->getHighestPriorityPresence(chat.jid.toBare()); + chat.setStatusType(presence ? presence->getShow() : StatusShow::None); + chatListWindow_->setRecents(recentChats_); + break; + } + } + + //if (newPresence->getType() != Presence::Unavailable) return; + JID fullJID(newPresence->getFrom()); + std::map::iterator it = chatControllers_.find(fullJID); + if (it == chatControllers_.end()) return; + JID bareJID(fullJID.toBare()); + //It doesn't make sense to have two unbound dialogs. + if (chatControllers_.find(bareJID) != chatControllers_.end()) return; + rebindControllerJID(fullJID, bareJID); } void ChatsManager::setAvatarManager(AvatarManager* avatarManager) { - if (avatarManager_) { - avatarManager_->onAvatarChanged.disconnect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1)); - } - avatarManager_ = avatarManager; - foreach (ChatListWindow::Chat& chat, recentChats_) { - if (!chat.isMUC) { - chat.setAvatarPath(avatarManager_->getAvatarPath(chat.jid)); - } - } - avatarManager_->onAvatarChanged.connect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1)); + if (avatarManager_) { + avatarManager_->onAvatarChanged.disconnect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1)); + } + avatarManager_ = avatarManager; + foreach (ChatListWindow::Chat& chat, recentChats_) { + if (!chat.isMUC) { + chat.setAvatarPath(avatarManager_->getAvatarPath(chat.jid)); + } + } + avatarManager_->onAvatarChanged.connect(boost::bind(&ChatsManager::handleAvatarChanged, this, _1)); } void ChatsManager::handleAvatarChanged(const JID& jid) { - foreach (ChatListWindow::Chat& chat, recentChats_) { - if (!chat.isMUC && jid.toBare() == chat.jid.toBare()) { - chat.setAvatarPath(avatarManager_->getAvatarPath(jid)); - break; - } - } + foreach (ChatListWindow::Chat& chat, recentChats_) { + if (!chat.isMUC && jid.toBare() == chat.jid.toBare()) { + chat.setAvatarPath(avatarManager_->getAvatarPath(jid)); + break; + } + } } void ChatsManager::setServerDiscoInfo(boost::shared_ptr info) { - serverDiscoInfo_ = info; - foreach (JIDChatControllerPair pair, chatControllers_) { - pair.second->setAvailableServerFeatures(info); - } - foreach (JIDMUCControllerPair pair, mucControllers_) { - pair.second->setAvailableServerFeatures(info); - } + serverDiscoInfo_ = info; + foreach (JIDChatControllerPair pair, chatControllers_) { + pair.second->setAvailableServerFeatures(info); + } + foreach (JIDMUCControllerPair pair, mucControllers_) { + pair.second->setAvailableServerFeatures(info); + } } /** * This is to be called on connect/disconnect. - */ + */ void ChatsManager::setOnline(bool enabled) { - foreach (JIDChatControllerPair controllerPair, chatControllers_) { - controllerPair.second->setOnline(enabled); - } - foreach (JIDMUCControllerPair controllerPair, mucControllers_) { - controllerPair.second->setOnline(enabled); - if (enabled) { - controllerPair.second->rejoin(); - } - } - if (!enabled) { - markAllRecentsOffline(); - } else { - setupBookmarks(); - localMUCServiceJID_ = JID(); - localMUCServiceFinderWalker_ = boost::make_shared(jid_.getDomain(), iqRouter_); - localMUCServiceFinderWalker_->onServiceFound.connect(boost::bind(&ChatsManager::handleLocalServiceFound, this, _1, _2)); - localMUCServiceFinderWalker_->onWalkAborted.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this)); - localMUCServiceFinderWalker_->onWalkComplete.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this)); - localMUCServiceFinderWalker_->beginWalk(); - } - - if (chatListWindow_) { - chatListWindow_->setBookmarksEnabled(enabled); - } + foreach (JIDChatControllerPair controllerPair, chatControllers_) { + controllerPair.second->setOnline(enabled); + } + foreach (JIDMUCControllerPair controllerPair, mucControllers_) { + controllerPair.second->setOnline(enabled); + if (enabled) { + controllerPair.second->rejoin(); + } + } + if (!enabled) { + markAllRecentsOffline(); + } else { + setupBookmarks(); + localMUCServiceJID_ = JID(); + localMUCServiceFinderWalker_ = boost::make_shared(jid_.getDomain(), iqRouter_); + localMUCServiceFinderWalker_->onServiceFound.connect(boost::bind(&ChatsManager::handleLocalServiceFound, this, _1, _2)); + localMUCServiceFinderWalker_->onWalkAborted.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this)); + localMUCServiceFinderWalker_->onWalkComplete.connect(boost::bind(&ChatsManager::handleLocalServiceWalkFinished, this)); + localMUCServiceFinderWalker_->beginWalk(); + } + + if (chatListWindow_) { + chatListWindow_->setBookmarksEnabled(enabled); + } } void ChatsManager::handleChatRequest(const std::string &contact) { - ChatController* controller = getChatControllerOrFindAnother(JID(contact)); - controller->activateChatWindow(); + ChatController* controller = getChatControllerOrFindAnother(JID(contact)); + controller->activateChatWindow(); } ChatController* ChatsManager::getChatControllerOrFindAnother(const JID &contact) { - ChatController* controller = getChatControllerIfExists(contact); - if (!controller && !mucRegistry_->isMUC(contact.toBare())) { - foreach (JIDChatControllerPair pair, chatControllers_) { - if (pair.first.toBare() == contact.toBare()) { - controller = pair.second; - break; - } - } - } - return controller ? controller : createNewChatController(contact); + ChatController* controller = getChatControllerIfExists(contact); + if (!controller && !mucRegistry_->isMUC(contact.toBare())) { + foreach (JIDChatControllerPair pair, chatControllers_) { + if (pair.first.toBare() == contact.toBare()) { + controller = pair.second; + break; + } + } + } + return controller ? controller : createNewChatController(contact); } ChatController* ChatsManager::createNewChatController(const JID& contact) { - assert(chatControllers_.find(contact) == chatControllers_.end()); - boost::shared_ptr chatMessageParser = boost::make_shared(emoticons_, highlightManager_->getRules(), false); /* a message parser that knows this is a chat (not a room/MUC) */ - ChatController* controller = new ChatController(jid_, stanzaChannel_, iqRouter_, chatWindowFactory_, contact, nickResolver_, presenceOracle_, avatarManager_, mucRegistry_->isMUC(contact.toBare()), useDelayForLatency_, uiEventStream_, eventController_, timerFactory_, entityCapsProvider_, userWantsReceipts_, settings_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, autoAcceptMUCInviteDecider_); - chatControllers_[contact] = controller; - controller->setAvailableServerFeatures(serverDiscoInfo_); - controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, contact, _1, false)); - controller->onWindowClosed.connect(boost::bind(&ChatsManager::handleChatClosed, this, contact)); - controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller)); - controller->onConvertToMUC.connect(boost::bind(&ChatsManager::handleTransformChatToMUC, this, controller, _1, _2, _3)); - updatePresenceReceivingStateOnChatController(contact); - controller->setCanStartImpromptuChats(!localMUCServiceJID_.toString().empty()); - return controller; + assert(chatControllers_.find(contact) == chatControllers_.end()); + boost::shared_ptr chatMessageParser = boost::make_shared(emoticons_, highlightManager_->getRules(), false); /* a message parser that knows this is a chat (not a room/MUC) */ + ChatController* controller = new ChatController(jid_, stanzaChannel_, iqRouter_, chatWindowFactory_, contact, nickResolver_, presenceOracle_, avatarManager_, mucRegistry_->isMUC(contact.toBare()), useDelayForLatency_, uiEventStream_, eventController_, timerFactory_, entityCapsProvider_, userWantsReceipts_, settings_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, autoAcceptMUCInviteDecider_); + chatControllers_[contact] = controller; + controller->setAvailableServerFeatures(serverDiscoInfo_); + controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, contact, _1, false)); + controller->onWindowClosed.connect(boost::bind(&ChatsManager::handleChatClosed, this, contact)); + controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller)); + controller->onConvertToMUC.connect(boost::bind(&ChatsManager::handleTransformChatToMUC, this, controller, _1, _2, _3)); + updatePresenceReceivingStateOnChatController(contact); + controller->setCanStartImpromptuChats(!localMUCServiceJID_.toString().empty()); + return controller; } ChatController* ChatsManager::getChatControllerOrCreate(const JID &contact) { - ChatController* controller = getChatControllerIfExists(contact); - return controller ? controller : createNewChatController(contact); + ChatController* controller = getChatControllerIfExists(contact); + return controller ? controller : createNewChatController(contact); } ChatController* ChatsManager::getChatControllerIfExists(const JID &contact, bool rebindIfNeeded) { - if (chatControllers_.find(contact) == chatControllers_.end()) { - if (mucRegistry_->isMUC(contact.toBare())) { - return NULL; - } - //Need to look for an unbound window to bind first - JID bare(contact.toBare()); - if (chatControllers_.find(bare) != chatControllers_.end()) { - if (rebindIfNeeded) { - rebindControllerJID(bare, contact); - } - else { - return chatControllers_[bare]; - } - } else { - foreach (JIDChatControllerPair pair, chatControllers_) { - if (pair.first.toBare() == contact.toBare()) { - if (rebindIfNeeded) { - rebindControllerJID(pair.first, contact); - return chatControllers_[contact]; - } else { - return pair.second; - } - } - } - return NULL; - } - } - return chatControllers_[contact]; + if (chatControllers_.find(contact) == chatControllers_.end()) { + if (mucRegistry_->isMUC(contact.toBare())) { + return NULL; + } + //Need to look for an unbound window to bind first + JID bare(contact.toBare()); + if (chatControllers_.find(bare) != chatControllers_.end()) { + if (rebindIfNeeded) { + rebindControllerJID(bare, contact); + } + else { + return chatControllers_[bare]; + } + } else { + foreach (JIDChatControllerPair pair, chatControllers_) { + if (pair.first.toBare() == contact.toBare()) { + if (rebindIfNeeded) { + rebindControllerJID(pair.first, contact); + return chatControllers_[contact]; + } else { + return pair.second; + } + } + } + return NULL; + } + } + return chatControllers_[contact]; } void ChatsManager::rebindControllerJID(const JID& from, const JID& to) { - chatControllers_[to] = chatControllers_[from]; - chatControllers_.erase(from); - chatControllers_[to]->setToJID(to); + chatControllers_[to] = chatControllers_[from]; + chatControllers_.erase(from); + chatControllers_[to]->setToJID(to); } MUC::ref ChatsManager::handleJoinMUCRequest(const JID &mucJID, const boost::optional& password, const boost::optional& nickMaybe, bool addAutoJoin, bool createAsReservedIfNew, bool isImpromptu, ChatWindow* reuseChatwindow) { - MUC::ref muc; - if (addAutoJoin) { - MUCBookmark bookmark(mucJID, mucJID.getNode()); - bookmark.setAutojoin(true); - if (nickMaybe) { - bookmark.setNick(*nickMaybe); - } - if (password) { - bookmark.setPassword(*password); - } - mucBookmarkManager_->addBookmark(bookmark); - } - - std::map::iterator it = mucControllers_.find(mucJID); - if (it != mucControllers_.end()) { - if (stanzaChannel_->isAvailable()) { - it->second->rejoin(); - } - } else { - std::string nick = (nickMaybe && !(*nickMaybe).empty()) ? nickMaybe.get() : nickResolver_->jidToNick(jid_); - muc = mucManager->createMUC(mucJID); - if (createAsReservedIfNew) { - muc->setCreateAsReservedIfNew(); - } - if (isImpromptu) { - muc->setCreateAsReservedIfNew(); - } - - MUCController* controller = NULL; - SingleChatWindowFactoryAdapter* chatWindowFactoryAdapter = NULL; - if (reuseChatwindow) { - chatWindowFactoryAdapter = new SingleChatWindowFactoryAdapter(reuseChatwindow); - } - boost::shared_ptr chatMessageParser = boost::make_shared(emoticons_, highlightManager_->getRules(), true); /* a message parser that knows this is a room/MUC (not a chat) */ - controller = new MUCController(jid_, muc, password, nick, stanzaChannel_, iqRouter_, reuseChatwindow ? chatWindowFactoryAdapter : chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory_, eventController_, entityCapsProvider_, roster_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, isImpromptu, autoAcceptMUCInviteDecider_, vcardManager_, mucBookmarkManager_); - if (chatWindowFactoryAdapter) { - /* The adapters are only passed to chat windows, which are deleted in their - * controllers' dtor, which are deleted in ChatManager's dtor. The adapters - * are also deleted there.*/ - chatWindowFactoryAdapters_[controller] = chatWindowFactoryAdapter; - } - - mucControllers_[mucJID] = controller; - controller->setAvailableServerFeatures(serverDiscoInfo_); - controller->onUserLeft.connect(boost::bind(&ChatsManager::handleUserLeftMUC, this, controller)); - controller->onUserJoined.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), "", true)); - controller->onUserNicknameChanged.connect(boost::bind(&ChatsManager::handleUserNicknameChanged, this, controller, _1, _2)); - controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), _1, true)); - controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller)); - if (!stanzaChannel_->isAvailable()) { - /* When online, the MUC is added to the registry in MUCImpl::internalJoin. This method is not - * called when Swift is offline, so we add it here as only MUCs in the registry are rejoined - * when going back online. - */ - mucRegistry_->addMUC(mucJID.toBare()); - } - handleChatActivity(mucJID.toBare(), "", true); - } - - mucControllers_[mucJID]->showChatWindow(); - return muc; + MUC::ref muc; + if (addAutoJoin) { + MUCBookmark bookmark(mucJID, mucJID.getNode()); + bookmark.setAutojoin(true); + if (nickMaybe) { + bookmark.setNick(*nickMaybe); + } + if (password) { + bookmark.setPassword(*password); + } + mucBookmarkManager_->addBookmark(bookmark); + } + + std::map::iterator it = mucControllers_.find(mucJID); + if (it != mucControllers_.end()) { + if (stanzaChannel_->isAvailable()) { + it->second->rejoin(); + } + } else { + std::string nick = (nickMaybe && !(*nickMaybe).empty()) ? nickMaybe.get() : nickResolver_->jidToNick(jid_); + muc = mucManager->createMUC(mucJID); + if (createAsReservedIfNew) { + muc->setCreateAsReservedIfNew(); + } + if (isImpromptu) { + muc->setCreateAsReservedIfNew(); + } + + MUCController* controller = NULL; + SingleChatWindowFactoryAdapter* chatWindowFactoryAdapter = NULL; + if (reuseChatwindow) { + chatWindowFactoryAdapter = new SingleChatWindowFactoryAdapter(reuseChatwindow); + } + boost::shared_ptr chatMessageParser = boost::make_shared(emoticons_, highlightManager_->getRules(), true); /* a message parser that knows this is a room/MUC (not a chat) */ + controller = new MUCController(jid_, muc, password, nick, stanzaChannel_, iqRouter_, reuseChatwindow ? chatWindowFactoryAdapter : chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory_, eventController_, entityCapsProvider_, roster_, historyController_, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser, isImpromptu, autoAcceptMUCInviteDecider_, vcardManager_, mucBookmarkManager_); + if (chatWindowFactoryAdapter) { + /* The adapters are only passed to chat windows, which are deleted in their + * controllers' dtor, which are deleted in ChatManager's dtor. The adapters + * are also deleted there.*/ + chatWindowFactoryAdapters_[controller] = chatWindowFactoryAdapter; + } + + mucControllers_[mucJID] = controller; + controller->setAvailableServerFeatures(serverDiscoInfo_); + controller->onUserLeft.connect(boost::bind(&ChatsManager::handleUserLeftMUC, this, controller)); + controller->onUserJoined.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), "", true)); + controller->onUserNicknameChanged.connect(boost::bind(&ChatsManager::handleUserNicknameChanged, this, controller, _1, _2)); + controller->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, mucJID.toBare(), _1, true)); + controller->onUnreadCountChanged.connect(boost::bind(&ChatsManager::handleUnreadCountChanged, this, controller)); + if (!stanzaChannel_->isAvailable()) { + /* When online, the MUC is added to the registry in MUCImpl::internalJoin. This method is not + * called when Swift is offline, so we add it here as only MUCs in the registry are rejoined + * when going back online. + */ + mucRegistry_->addMUC(mucJID.toBare()); + } + handleChatActivity(mucJID.toBare(), "", true); + } + + mucControllers_[mucJID]->showChatWindow(); + return muc; } void ChatsManager::handleSearchMUCRequest() { - mucSearchController_->openSearchWindow(); + mucSearchController_->openSearchWindow(); } void ChatsManager::handleUserNicknameChanged(MUCController* mucController, const std::string& oldNickname, const std::string& newNickname) { - JID oldMUCChatJID = mucController->getToJID().withResource(oldNickname); - JID newMUCChatJID = mucController->getToJID().withResource(newNickname); - - SWIFT_LOG(debug) << "nickname change in " << mucController->getToJID().toString() << " from " << oldNickname << " to " << newNickname << std::endl; - - // get current chat controller - ChatController *chatController = getChatControllerIfExists(oldMUCChatJID); - if (chatController) { - // adjust chat controller - chatController->setToJID(newMUCChatJID); - nickResolver_->onNickChanged(newMUCChatJID, oldNickname); - chatControllers_.erase(oldMUCChatJID); - chatControllers_[newMUCChatJID] = chatController; - - chatController->onActivity.disconnect(boost::bind(&ChatsManager::handleChatActivity, this, oldMUCChatJID, _1, false)); - chatController->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, newMUCChatJID, _1, false)); - } + JID oldMUCChatJID = mucController->getToJID().withResource(oldNickname); + JID newMUCChatJID = mucController->getToJID().withResource(newNickname); + + SWIFT_LOG(debug) << "nickname change in " << mucController->getToJID().toString() << " from " << oldNickname << " to " << newNickname << std::endl; + + // get current chat controller + ChatController *chatController = getChatControllerIfExists(oldMUCChatJID); + if (chatController) { + // adjust chat controller + chatController->setToJID(newMUCChatJID); + nickResolver_->onNickChanged(newMUCChatJID, oldNickname); + chatControllers_.erase(oldMUCChatJID); + chatControllers_[newMUCChatJID] = chatController; + + chatController->onActivity.disconnect(boost::bind(&ChatsManager::handleChatActivity, this, oldMUCChatJID, _1, false)); + chatController->onActivity.connect(boost::bind(&ChatsManager::handleChatActivity, this, newMUCChatJID, _1, false)); + } } void ChatsManager::handleIncomingMessage(boost::shared_ptr message) { - JID jid = message->getFrom(); - boost::shared_ptr event(new MessageEvent(message)); - bool isInvite = !!message->getPayload(); - bool isMediatedInvite = (message->getPayload() && message->getPayload()->getInvite()); - if (isMediatedInvite) { - jid = (*message->getPayload()->getInvite()).from; - } - if (!event->isReadable() && !message->getPayload() && !message->getPayload() && !message->getPayload() && !isInvite && !isMediatedInvite && !message->hasSubject()) { - return; - } - - // Try to deliver it to a MUC - if (message->getType() == Message::Groupchat || message->getType() == Message::Error /*|| (isInvite && message->getType() == Message::Normal)*/) { - std::map::iterator i = mucControllers_.find(jid.toBare()); - if (i != mucControllers_.end()) { - i->second->handleIncomingMessage(event); - return; - } - else if (message->getType() == Message::Groupchat) { - //FIXME: Error handling - groupchat messages from an unknown muc. - return; - } - } - - // check for impromptu invite to potentially auto-accept - MUCInvitationPayload::ref invite = message->getPayload(); - if (invite && autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) { - if (invite->getIsContinuation()) { - // check for existing chat controller for the from JID - ChatController* controller = getChatControllerIfExists(jid); - if (controller) { - ChatWindow* window = controller->detachChatWindow(); - chatControllers_.erase(jid); - delete controller; - handleJoinMUCRequest(invite->getJID(), boost::optional(), boost::optional(), false, false, true, window); - return; - } - } else { - handleJoinMUCRequest(invite->getJID(), boost::optional(), boost::optional(), false, false, true); - return; - } - } - - //if not a mucroom - if (!event->isReadable() && !isInvite && !isMediatedInvite) { - /* Only route such messages if a window exists, don't open new windows for them.*/ - - // Do not bind a controller to a full JID, for delivery receipts or chat state notifications. - bool bindControllerToJID = false; - ChatState::ref chatState = message->getPayload(); - if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) { - bindControllerToJID = true; - } - - ChatController* controller = getChatControllerIfExists(jid, bindControllerToJID); - if (controller) { - controller->handleIncomingMessage(event); - } - } else { - getChatControllerOrCreate(jid)->handleIncomingMessage(event); - } + JID jid = message->getFrom(); + boost::shared_ptr event(new MessageEvent(message)); + bool isInvite = !!message->getPayload(); + bool isMediatedInvite = (message->getPayload() && message->getPayload()->getInvite()); + if (isMediatedInvite) { + jid = (*message->getPayload()->getInvite()).from; + } + if (!event->isReadable() && !message->getPayload() && !message->getPayload() && !message->getPayload() && !isInvite && !isMediatedInvite && !message->hasSubject()) { + return; + } + + // Try to deliver it to a MUC + if (message->getType() == Message::Groupchat || message->getType() == Message::Error /*|| (isInvite && message->getType() == Message::Normal)*/) { + std::map::iterator i = mucControllers_.find(jid.toBare()); + if (i != mucControllers_.end()) { + i->second->handleIncomingMessage(event); + return; + } + else if (message->getType() == Message::Groupchat) { + //FIXME: Error handling - groupchat messages from an unknown muc. + return; + } + } + + // check for impromptu invite to potentially auto-accept + MUCInvitationPayload::ref invite = message->getPayload(); + if (invite && autoAcceptMUCInviteDecider_->isAutoAcceptedInvite(message->getFrom(), invite)) { + if (invite->getIsContinuation()) { + // check for existing chat controller for the from JID + ChatController* controller = getChatControllerIfExists(jid); + if (controller) { + ChatWindow* window = controller->detachChatWindow(); + chatControllers_.erase(jid); + delete controller; + handleJoinMUCRequest(invite->getJID(), boost::optional(), boost::optional(), false, false, true, window); + return; + } + } else { + handleJoinMUCRequest(invite->getJID(), boost::optional(), boost::optional(), false, false, true); + return; + } + } + + //if not a mucroom + if (!event->isReadable() && !isInvite && !isMediatedInvite) { + /* Only route such messages if a window exists, don't open new windows for them.*/ + + // Do not bind a controller to a full JID, for delivery receipts or chat state notifications. + bool bindControllerToJID = false; + ChatState::ref chatState = message->getPayload(); + if (!message->getBody().get_value_or("").empty() || (chatState && chatState->getChatState() == ChatState::Composing)) { + bindControllerToJID = true; + } + + ChatController* controller = getChatControllerIfExists(jid, bindControllerToJID); + if (controller) { + controller->handleIncomingMessage(event); + } + } else { + getChatControllerOrCreate(jid)->handleIncomingMessage(event); + } } void ChatsManager::handleMUCSelectedAfterSearch(const JID& muc) { - if (joinMUCWindow_) { - joinMUCWindow_->setMUC(muc.toString()); - } + if (joinMUCWindow_) { + joinMUCWindow_->setMUC(muc.toString()); + } } void ChatsManager::handleMUCBookmarkActivated(const MUCBookmark& mucBookmark) { - uiEventStream_->send(boost::make_shared(mucBookmark.getRoom(), mucBookmark.getPassword(), mucBookmark.getNick())); + uiEventStream_->send(boost::make_shared(mucBookmark.getRoom(), mucBookmark.getPassword(), mucBookmark.getNick())); } void ChatsManager::handleNewFileTransferController(FileTransferController* ftc) { - ChatController* chatController = getChatControllerOrCreate(ftc->getOtherParty()); - chatController->handleNewFileTransferController(ftc); - chatController->activateChatWindow(); - if (ftc->isIncoming()) { - eventController_->handleIncomingEvent(boost::make_shared(ftc->getOtherParty())); - } + ChatController* chatController = getChatControllerOrCreate(ftc->getOtherParty()); + chatController->handleNewFileTransferController(ftc); + chatController->activateChatWindow(); + if (ftc->isIncoming()) { + eventController_->handleIncomingEvent(boost::make_shared(ftc->getOtherParty())); + } } void ChatsManager::handleWhiteboardSessionRequest(const JID& contact, bool senderIsSelf) { - ChatController* chatController = getChatControllerOrCreate(contact); - chatController->handleWhiteboardSessionRequest(senderIsSelf); - chatController->activateChatWindow(); + ChatController* chatController = getChatControllerOrCreate(contact); + chatController->handleWhiteboardSessionRequest(senderIsSelf); + chatController->activateChatWindow(); } void ChatsManager::handleWhiteboardStateChange(const JID& contact, const ChatWindow::WhiteboardSessionState state) { - ChatController* chatController = getChatControllerOrCreate(contact); - chatController->handleWhiteboardStateChange(state); - chatController->activateChatWindow(); - if (state == ChatWindow::WhiteboardAccepted) { - boost::filesystem::path path; - JID bareJID = contact.toBare(); - if (avatarManager_) { - path = avatarManager_->getAvatarPath(bareJID); - } - ChatListWindow::Chat chat(bareJID, nickResolver_->jidToNick(bareJID), "", 0, StatusShow::None, path, false); - chatListWindow_->addWhiteboardSession(chat); - } else { - chatListWindow_->removeWhiteboardSession(contact.toBare()); - } + ChatController* chatController = getChatControllerOrCreate(contact); + chatController->handleWhiteboardStateChange(state); + chatController->activateChatWindow(); + if (state == ChatWindow::WhiteboardAccepted) { + boost::filesystem::path path; + JID bareJID = contact.toBare(); + if (avatarManager_) { + path = avatarManager_->getAvatarPath(bareJID); + } + ChatListWindow::Chat chat(bareJID, nickResolver_->jidToNick(bareJID), "", 0, StatusShow::None, path, false); + chatListWindow_->addWhiteboardSession(chat); + } else { + chatListWindow_->removeWhiteboardSession(contact.toBare()); + } } void ChatsManager::handleRecentActivated(const ChatListWindow::Chat& chat) { - if (chat.isMUC && !chat.impromptuJIDs.empty()) { - typedef std::pair StringJIDPair; - std::vector inviteJIDs; - foreach(StringJIDPair pair, chat.impromptuJIDs) { - inviteJIDs.push_back(pair.second); - } - uiEventStream_->send(boost::make_shared(inviteJIDs, chat.jid, "")); - } - else if (chat.isMUC) { - /* FIXME: This means that recents requiring passwords will just flat-out not work */ - uiEventStream_->send(boost::make_shared(chat.jid, boost::optional(), chat.nick)); - } - else { - uiEventStream_->send(boost::make_shared(chat.jid)); - } + if (chat.isMUC && !chat.impromptuJIDs.empty()) { + typedef std::pair StringJIDPair; + std::vector inviteJIDs; + foreach(StringJIDPair pair, chat.impromptuJIDs) { + inviteJIDs.push_back(pair.second); + } + uiEventStream_->send(boost::make_shared(inviteJIDs, chat.jid, "")); + } + else if (chat.isMUC) { + /* FIXME: This means that recents requiring passwords will just flat-out not work */ + uiEventStream_->send(boost::make_shared(chat.jid, boost::optional(), chat.nick)); + } + else { + uiEventStream_->send(boost::make_shared(chat.jid)); + } } void ChatsManager::handleLocalServiceFound(const JID& service, boost::shared_ptr info) { - foreach (DiscoInfo::Identity identity, info->getIdentities()) { - if ((identity.getCategory() == "directory" - && identity.getType() == "chatroom") - || (identity.getCategory() == "conference" - && identity.getType() == "text")) { - localMUCServiceJID_ = service; - localMUCServiceFinderWalker_->endWalk(); - SWIFT_LOG(debug) << "Use following MUC service for impromptu chats: " << localMUCServiceJID_ << std::endl; - break; - } - } + foreach (DiscoInfo::Identity identity, info->getIdentities()) { + if ((identity.getCategory() == "directory" + && identity.getType() == "chatroom") + || (identity.getCategory() == "conference" + && identity.getType() == "text")) { + localMUCServiceJID_ = service; + localMUCServiceFinderWalker_->endWalk(); + SWIFT_LOG(debug) << "Use following MUC service for impromptu chats: " << localMUCServiceJID_ << std::endl; + break; + } + } } void ChatsManager::handleLocalServiceWalkFinished() { - bool impromptuMUCSupported = !localMUCServiceJID_.toString().empty(); - foreach (JIDChatControllerPair controllerPair, chatControllers_) { - controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported); - } - foreach (JIDMUCControllerPair controllerPair, mucControllers_) { - controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported); - } - onImpromptuMUCServiceDiscovered(impromptuMUCSupported); + bool impromptuMUCSupported = !localMUCServiceJID_.toString().empty(); + foreach (JIDChatControllerPair controllerPair, chatControllers_) { + controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported); + } + foreach (JIDMUCControllerPair controllerPair, mucControllers_) { + controllerPair.second->setCanStartImpromptuChats(impromptuMUCSupported); + } + onImpromptuMUCServiceDiscovered(impromptuMUCSupported); } std::vector ChatsManager::getRecentChats() const { - return std::vector(recentChats_.begin(), recentChats_.end()); + return std::vector(recentChats_.begin(), recentChats_.end()); } std::vector Swift::ChatsManager::getContacts(bool withMUCNicks) { - std::vector result; - foreach (ChatListWindow::Chat chat, recentChats_) { - if (!chat.isMUC) { - result.push_back(boost::make_shared(chat.chatName.empty() ? chat.jid.toString() : chat.chatName, chat.jid, chat.statusType, chat.avatarPath)); - } - } - if (withMUCNicks) { - /* collect MUC nicks */ - typedef std::map::value_type Item; - foreach (const Item& item, mucControllers_) { - JID mucJID = item.second->getToJID(); - std::map participants = item.second->getParticipantJIDs(); - typedef std::map::value_type ParticipantType; - foreach (const ParticipantType& participant, participants) { - const JID nickJID = JID(mucJID.getNode(), mucJID.getDomain(), participant.first); - Presence::ref presence = presenceOracle_->getLastPresence(nickJID); - const boost::filesystem::path avatar = avatarManager_->getAvatarPath(nickJID); - result.push_back(boost::make_shared(participant.first, JID(), presence->getShow(), avatar)); - } - } - } - return result; + std::vector result; + foreach (ChatListWindow::Chat chat, recentChats_) { + if (!chat.isMUC) { + result.push_back(boost::make_shared(chat.chatName.empty() ? chat.jid.toString() : chat.chatName, chat.jid, chat.statusType, chat.avatarPath)); + } + } + if (withMUCNicks) { + /* collect MUC nicks */ + typedef std::map::value_type Item; + foreach (const Item& item, mucControllers_) { + JID mucJID = item.second->getToJID(); + std::map participants = item.second->getParticipantJIDs(); + typedef std::map::value_type ParticipantType; + foreach (const ParticipantType& participant, participants) { + const JID nickJID = JID(mucJID.getNode(), mucJID.getDomain(), participant.first); + Presence::ref presence = presenceOracle_->getLastPresence(nickJID); + const boost::filesystem::path avatar = avatarManager_->getAvatarPath(nickJID); + result.push_back(boost::make_shared(participant.first, JID(), presence->getShow(), avatar)); + } + } + } + return result; } ChatsManager::SingleChatWindowFactoryAdapter::SingleChatWindowFactoryAdapter(ChatWindow* chatWindow) : chatWindow_(chatWindow) {} ChatsManager::SingleChatWindowFactoryAdapter::~SingleChatWindowFactoryAdapter() {} ChatWindow* ChatsManager::SingleChatWindowFactoryAdapter::createChatWindow(const JID &, UIEventStream*) { - return chatWindow_; + return chatWindow_; } } diff --git a/Swift/Controllers/Chat/ChatsManager.h b/Swift/Controllers/Chat/ChatsManager.h index 58a9017..7bba219 100644 --- a/Swift/Controllers/Chat/ChatsManager.h +++ b/Swift/Controllers/Chat/ChatsManager.h @@ -27,159 +27,159 @@ #include namespace Swift { - class EventController; - class ChatController; - class ChatControllerBase; - class MUCController; - class MUCManager; - class JoinMUCWindow; - class JoinMUCWindowFactory; - class NickResolver; - class PresenceOracle; - class AvatarManager; - class StanzaChannel; - class IQRouter; - class PresenceSender; - class MUCBookmarkManager; - class ChatListWindowFactory; - class TimerFactory; - class EntityCapsProvider; - class DirectedPresenceSender; - class MUCSearchWindowFactory; - class ProfileSettingsProvider; - class MUCSearchController; - class FileTransferOverview; - class FileTransferController; - class XMPPRoster; - class SettingsProvider; - class WhiteboardManager; - class HistoryController; - class HighlightManager; - class ClientBlockListManager; - class ChatMessageParser; - class DiscoServiceWalker; - class AutoAcceptMUCInviteDecider; - class VCardManager; - - class ChatsManager : public ContactProvider { - public: - ChatsManager(JID jid, StanzaChannel* stanzaChannel, IQRouter* iqRouter, EventController* eventController, ChatWindowFactory* chatWindowFactory, JoinMUCWindowFactory* joinMUCWindowFactory, NickResolver* nickResolver, PresenceOracle* presenceOracle, PresenceSender* presenceSender, UIEventStream* uiEventStream, ChatListWindowFactory* chatListWindowFactory, bool useDelayForLatency, TimerFactory* timerFactory, MUCRegistry* mucRegistry, EntityCapsProvider* entityCapsProvider, MUCManager* mucManager, MUCSearchWindowFactory* mucSearchWindowFactory, ProfileSettingsProvider* profileSettings, FileTransferOverview* ftOverview, XMPPRoster* roster, bool eagleMode, SettingsProvider* settings, HistoryController* historyController_, WhiteboardManager* whiteboardManager, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, const std::map& emoticons, VCardManager* vcardManager); - virtual ~ChatsManager(); - void setAvatarManager(AvatarManager* avatarManager); - void setOnline(bool enabled); - void setServerDiscoInfo(boost::shared_ptr info); - void handleIncomingMessage(boost::shared_ptr message); - std::vector getRecentChats() const; - virtual std::vector getContacts(bool withMUCNicks); - - boost::signal onImpromptuMUCServiceDiscovered; - - private: - class SingleChatWindowFactoryAdapter : public ChatWindowFactory { - public: - SingleChatWindowFactoryAdapter(ChatWindow* chatWindow); - virtual ~SingleChatWindowFactoryAdapter(); - virtual ChatWindow* createChatWindow(const JID &, UIEventStream*); - - private: - ChatWindow* chatWindow_; - }; - - private: - ChatListWindow::Chat createChatListChatItem(const JID& jid, const std::string& activity, bool privateMessage); - void handleChatRequest(const std::string& contact); - void finalizeImpromptuJoin(MUC::ref muc, const std::vector& jidsToInvite, const std::string& reason, const boost::optional& reuseChatJID = boost::optional()); - MUC::ref handleJoinMUCRequest(const JID& muc, const boost::optional& password, const boost::optional& nick, bool addAutoJoin, bool createAsReservedIfNew, bool isImpromptu, ChatWindow* reuseChatwindow = 0); - void handleSearchMUCRequest(); - void handleMUCSelectedAfterSearch(const JID&); - void rebindControllerJID(const JID& from, const JID& to); - void handlePresenceChange(boost::shared_ptr newPresence); - void handleUIEvent(boost::shared_ptr event); - void handleMUCBookmarkAdded(const MUCBookmark& bookmark); - void handleMUCBookmarkRemoved(const MUCBookmark& bookmark); - void handleUserLeftMUC(MUCController* mucController); - void handleUserNicknameChanged(MUCController* mucController, const std::string& oldNickname, const std::string& newNickname); - void handleBookmarksReady(); - void handleChatActivity(const JID& jid, const std::string& activity, bool isMUC); - void handleChatClosed(const JID& jid); - void handleNewFileTransferController(FileTransferController*); - void handleWhiteboardSessionRequest(const JID& contact, bool senderIsSelf); - void handleWhiteboardStateChange(const JID& contact, const ChatWindow::WhiteboardSessionState state); - boost::optional removeExistingChat(const ChatListWindow::Chat& chat); - void cleanupPrivateMessageRecents(); - void appendRecent(const ChatListWindow::Chat& chat); - void prependRecent(const ChatListWindow::Chat& chat); - void setupBookmarks(); - void loadRecents(); - void saveRecents(); - void handleChatMadeRecent(); - void handleMUCBookmarkActivated(const MUCBookmark&); - void handleRecentActivated(const ChatListWindow::Chat&); - void handleUnreadCountChanged(ChatControllerBase* controller); - void handleAvatarChanged(const JID& jid); - void handleClearRecentsRequested(); - void handleJIDAddedToRoster(const JID&); - void handleJIDRemovedFromRoster(const JID&); - void handleJIDUpdatedInRoster(const JID&); - void handleRosterCleared(); - void handleSettingChanged(const std::string& settingPath); - void markAllRecentsOffline(); - void handleTransformChatToMUC(ChatController* chatController, ChatWindow* chatWindow, const std::vector& jidsToInvite, const std::string& reason); - - void handleLocalServiceFound(const JID& service, boost::shared_ptr info); - void handleLocalServiceWalkFinished(); - - void updatePresenceReceivingStateOnChatController(const JID&); - ChatListWindow::Chat updateChatStatusAndAvatarHelper(const ChatListWindow::Chat& chat) const; - - - ChatController* getChatControllerOrFindAnother(const JID &contact); - ChatController* createNewChatController(const JID &contact); - ChatController* getChatControllerOrCreate(const JID &contact); - ChatController* getChatControllerIfExists(const JID &contact, bool rebindIfNeeded = true); - - private: - std::map mucControllers_; - std::map chatControllers_; - std::map chatWindowFactoryAdapters_; - EventController* eventController_; - JID jid_; - StanzaChannel* stanzaChannel_; - IQRouter* iqRouter_; - ChatWindowFactory* chatWindowFactory_; - JoinMUCWindowFactory* joinMUCWindowFactory_; - NickResolver* nickResolver_; - PresenceOracle* presenceOracle_; - AvatarManager* avatarManager_; - PresenceSender* presenceSender_; - UIEventStream* uiEventStream_; - MUCBookmarkManager* mucBookmarkManager_; - boost::shared_ptr serverDiscoInfo_; - ChatListWindow* chatListWindow_; - JoinMUCWindow* joinMUCWindow_; - boost::bsignals::scoped_connection uiEventConnection_; - bool useDelayForLatency_; - TimerFactory* timerFactory_; - MUCRegistry* mucRegistry_; - EntityCapsProvider* entityCapsProvider_; - MUCManager* mucManager; - MUCSearchController* mucSearchController_; - std::list recentChats_; - ProfileSettingsProvider* profileSettings_; - FileTransferOverview* ftOverview_; - XMPPRoster* roster_; - bool eagleMode_; - bool userWantsReceipts_; - SettingsProvider* settings_; - HistoryController* historyController_; - WhiteboardManager* whiteboardManager_; - HighlightManager* highlightManager_; - std::map emoticons_; - ClientBlockListManager* clientBlockListManager_; - JID localMUCServiceJID_; - boost::shared_ptr localMUCServiceFinderWalker_; - AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_; - IDGenerator idGenerator_; - VCardManager* vcardManager_; - }; + class EventController; + class ChatController; + class ChatControllerBase; + class MUCController; + class MUCManager; + class JoinMUCWindow; + class JoinMUCWindowFactory; + class NickResolver; + class PresenceOracle; + class AvatarManager; + class StanzaChannel; + class IQRouter; + class PresenceSender; + class MUCBookmarkManager; + class ChatListWindowFactory; + class TimerFactory; + class EntityCapsProvider; + class DirectedPresenceSender; + class MUCSearchWindowFactory; + class ProfileSettingsProvider; + class MUCSearchController; + class FileTransferOverview; + class FileTransferController; + class XMPPRoster; + class SettingsProvider; + class WhiteboardManager; + class HistoryController; + class HighlightManager; + class ClientBlockListManager; + class ChatMessageParser; + class DiscoServiceWalker; + class AutoAcceptMUCInviteDecider; + class VCardManager; + + class ChatsManager : public ContactProvider { + public: + ChatsManager(JID jid, StanzaChannel* stanzaChannel, IQRouter* iqRouter, EventController* eventController, ChatWindowFactory* chatWindowFactory, JoinMUCWindowFactory* joinMUCWindowFactory, NickResolver* nickResolver, PresenceOracle* presenceOracle, PresenceSender* presenceSender, UIEventStream* uiEventStream, ChatListWindowFactory* chatListWindowFactory, bool useDelayForLatency, TimerFactory* timerFactory, MUCRegistry* mucRegistry, EntityCapsProvider* entityCapsProvider, MUCManager* mucManager, MUCSearchWindowFactory* mucSearchWindowFactory, ProfileSettingsProvider* profileSettings, FileTransferOverview* ftOverview, XMPPRoster* roster, bool eagleMode, SettingsProvider* settings, HistoryController* historyController_, WhiteboardManager* whiteboardManager, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, const std::map& emoticons, VCardManager* vcardManager); + virtual ~ChatsManager(); + void setAvatarManager(AvatarManager* avatarManager); + void setOnline(bool enabled); + void setServerDiscoInfo(boost::shared_ptr info); + void handleIncomingMessage(boost::shared_ptr message); + std::vector getRecentChats() const; + virtual std::vector getContacts(bool withMUCNicks); + + boost::signal onImpromptuMUCServiceDiscovered; + + private: + class SingleChatWindowFactoryAdapter : public ChatWindowFactory { + public: + SingleChatWindowFactoryAdapter(ChatWindow* chatWindow); + virtual ~SingleChatWindowFactoryAdapter(); + virtual ChatWindow* createChatWindow(const JID &, UIEventStream*); + + private: + ChatWindow* chatWindow_; + }; + + private: + ChatListWindow::Chat createChatListChatItem(const JID& jid, const std::string& activity, bool privateMessage); + void handleChatRequest(const std::string& contact); + void finalizeImpromptuJoin(MUC::ref muc, const std::vector& jidsToInvite, const std::string& reason, const boost::optional& reuseChatJID = boost::optional()); + MUC::ref handleJoinMUCRequest(const JID& muc, const boost::optional& password, const boost::optional& nick, bool addAutoJoin, bool createAsReservedIfNew, bool isImpromptu, ChatWindow* reuseChatwindow = 0); + void handleSearchMUCRequest(); + void handleMUCSelectedAfterSearch(const JID&); + void rebindControllerJID(const JID& from, const JID& to); + void handlePresenceChange(boost::shared_ptr newPresence); + void handleUIEvent(boost::shared_ptr event); + void handleMUCBookmarkAdded(const MUCBookmark& bookmark); + void handleMUCBookmarkRemoved(const MUCBookmark& bookmark); + void handleUserLeftMUC(MUCController* mucController); + void handleUserNicknameChanged(MUCController* mucController, const std::string& oldNickname, const std::string& newNickname); + void handleBookmarksReady(); + void handleChatActivity(const JID& jid, const std::string& activity, bool isMUC); + void handleChatClosed(const JID& jid); + void handleNewFileTransferController(FileTransferController*); + void handleWhiteboardSessionRequest(const JID& contact, bool senderIsSelf); + void handleWhiteboardStateChange(const JID& contact, const ChatWindow::WhiteboardSessionState state); + boost::optional removeExistingChat(const ChatListWindow::Chat& chat); + void cleanupPrivateMessageRecents(); + void appendRecent(const ChatListWindow::Chat& chat); + void prependRecent(const ChatListWindow::Chat& chat); + void setupBookmarks(); + void loadRecents(); + void saveRecents(); + void handleChatMadeRecent(); + void handleMUCBookmarkActivated(const MUCBookmark&); + void handleRecentActivated(const ChatListWindow::Chat&); + void handleUnreadCountChanged(ChatControllerBase* controller); + void handleAvatarChanged(const JID& jid); + void handleClearRecentsRequested(); + void handleJIDAddedToRoster(const JID&); + void handleJIDRemovedFromRoster(const JID&); + void handleJIDUpdatedInRoster(const JID&); + void handleRosterCleared(); + void handleSettingChanged(const std::string& settingPath); + void markAllRecentsOffline(); + void handleTransformChatToMUC(ChatController* chatController, ChatWindow* chatWindow, const std::vector& jidsToInvite, const std::string& reason); + + void handleLocalServiceFound(const JID& service, boost::shared_ptr info); + void handleLocalServiceWalkFinished(); + + void updatePresenceReceivingStateOnChatController(const JID&); + ChatListWindow::Chat updateChatStatusAndAvatarHelper(const ChatListWindow::Chat& chat) const; + + + ChatController* getChatControllerOrFindAnother(const JID &contact); + ChatController* createNewChatController(const JID &contact); + ChatController* getChatControllerOrCreate(const JID &contact); + ChatController* getChatControllerIfExists(const JID &contact, bool rebindIfNeeded = true); + + private: + std::map mucControllers_; + std::map chatControllers_; + std::map chatWindowFactoryAdapters_; + EventController* eventController_; + JID jid_; + StanzaChannel* stanzaChannel_; + IQRouter* iqRouter_; + ChatWindowFactory* chatWindowFactory_; + JoinMUCWindowFactory* joinMUCWindowFactory_; + NickResolver* nickResolver_; + PresenceOracle* presenceOracle_; + AvatarManager* avatarManager_; + PresenceSender* presenceSender_; + UIEventStream* uiEventStream_; + MUCBookmarkManager* mucBookmarkManager_; + boost::shared_ptr serverDiscoInfo_; + ChatListWindow* chatListWindow_; + JoinMUCWindow* joinMUCWindow_; + boost::bsignals::scoped_connection uiEventConnection_; + bool useDelayForLatency_; + TimerFactory* timerFactory_; + MUCRegistry* mucRegistry_; + EntityCapsProvider* entityCapsProvider_; + MUCManager* mucManager; + MUCSearchController* mucSearchController_; + std::list recentChats_; + ProfileSettingsProvider* profileSettings_; + FileTransferOverview* ftOverview_; + XMPPRoster* roster_; + bool eagleMode_; + bool userWantsReceipts_; + SettingsProvider* settings_; + HistoryController* historyController_; + WhiteboardManager* whiteboardManager_; + HighlightManager* highlightManager_; + std::map emoticons_; + ClientBlockListManager* clientBlockListManager_; + JID localMUCServiceJID_; + boost::shared_ptr localMUCServiceFinderWalker_; + AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider_; + IDGenerator idGenerator_; + VCardManager* vcardManager_; + }; } diff --git a/Swift/Controllers/Chat/MUCController.cpp b/Swift/Controllers/Chat/MUCController.cpp index 0bb670d..1e2b7ad 100644 --- a/Swift/Controllers/Chat/MUCController.cpp +++ b/Swift/Controllers/Chat/MUCController.cpp @@ -58,1163 +58,1163 @@ namespace Swift { class MUCBookmarkPredicate { - public: - MUCBookmarkPredicate(const JID& mucJID) : roomJID_(mucJID) { } - bool operator()(const MUCBookmark& operand) { - return operand.getRoom() == roomJID_; - } - - private: - JID roomJID_; + public: + MUCBookmarkPredicate(const JID& mucJID) : roomJID_(mucJID) { } + bool operator()(const MUCBookmark& operand) { + return operand.getRoom() == roomJID_; + } + + private: + JID roomJID_; }; /** * The controller does not gain ownership of the stanzaChannel, nor the factory. */ MUCController::MUCController ( - const JID& self, - MUC::ref muc, - const boost::optional& password, - const std::string &nick, - StanzaChannel* stanzaChannel, - IQRouter* iqRouter, - ChatWindowFactory* chatWindowFactory, - PresenceOracle* presenceOracle, - AvatarManager* avatarManager, - UIEventStream* uiEventStream, - bool useDelayForLatency, - TimerFactory* timerFactory, - EventController* eventController, - EntityCapsProvider* entityCapsProvider, - XMPPRoster* roster, - HistoryController* historyController, - MUCRegistry* mucRegistry, - HighlightManager* highlightManager, - ClientBlockListManager* clientBlockListManager, - boost::shared_ptr chatMessageParser, - bool isImpromptu, - AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider, - VCardManager* vcardManager, - MUCBookmarkManager* mucBookmarkManager) : - ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, muc->getJID(), presenceOracle, avatarManager, useDelayForLatency, uiEventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), muc_(muc), nick_(nick), desiredNick_(nick), password_(password), renameCounter_(0), isImpromptu_(isImpromptu), isImpromptuAlreadyConfigured_(false), clientBlockListManager_(clientBlockListManager), mucBookmarkManager_(mucBookmarkManager) { - parting_ = true; - joined_ = false; - lastWasPresence_ = false; - shouldJoinOnReconnect_ = true; - doneGettingHistory_ = false; - events_ = uiEventStream; - xmppRoster_ = roster; - - roster_ = new Roster(false, true); - rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithResource); - completer_ = new TabComplete(); - chatWindow_->setRosterModel(roster_); - chatWindow_->setTabComplete(completer_); - chatWindow_->onClosed.connect(boost::bind(&MUCController::handleWindowClosed, this)); - chatWindow_->onOccupantSelectionChanged.connect(boost::bind(&MUCController::handleWindowOccupantSelectionChanged, this, _1)); - chatWindow_->onOccupantActionSelected.connect(boost::bind(&MUCController::handleActionRequestedOnOccupant, this, _1, _2)); - chatWindow_->onChangeSubjectRequest.connect(boost::bind(&MUCController::handleChangeSubjectRequest, this, _1)); - chatWindow_->onBookmarkRequest.connect(boost::bind(&MUCController::handleBookmarkRequest, this)); - chatWindow_->onConfigureRequest.connect(boost::bind(&MUCController::handleConfigureRequest, this, _1)); - chatWindow_->onConfigurationFormCancelled.connect(boost::bind(&MUCController::handleConfigurationCancelled, this)); - chatWindow_->onDestroyRequest.connect(boost::bind(&MUCController::handleDestroyRoomRequest, this)); - chatWindow_->onInviteToChat.connect(boost::bind(&MUCController::handleInvitePersonToThisMUCRequest, this, _1)); - chatWindow_->onGetAffiliationsRequest.connect(boost::bind(&MUCController::handleGetAffiliationsRequest, this)); - chatWindow_->onChangeAffiliationsRequest.connect(boost::bind(&MUCController::handleChangeAffiliationsRequest, this, _1)); - chatWindow_->onUnblockUserRequest.connect(boost::bind(&MUCController::handleUnblockUserRequest, this)); - muc_->onJoinComplete.connect(boost::bind(&MUCController::handleJoinComplete, this, _1)); - muc_->onJoinFailed.connect(boost::bind(&MUCController::handleJoinFailed, this, _1)); - muc_->onOccupantJoined.connect(boost::bind(&MUCController::handleOccupantJoined, this, _1)); - muc_->onOccupantNicknameChanged.connect(boost::bind(&MUCController::handleOccupantNicknameChanged, this, _1, _2)); - muc_->onOccupantPresenceChange.connect(boost::bind(&MUCController::handleOccupantPresenceChange, this, _1)); - muc_->onOccupantLeft.connect(boost::bind(&MUCController::handleOccupantLeft, this, _1, _2, _3)); - muc_->onRoleChangeFailed.connect(boost::bind(&MUCController::handleOccupantRoleChangeFailed, this, _1, _2, _3)); - muc_->onAffiliationListReceived.connect(boost::bind(&MUCController::handleAffiliationListReceived, this, _1, _2)); - muc_->onConfigurationFailed.connect(boost::bind(&MUCController::handleConfigurationFailed, this, _1)); - muc_->onConfigurationFormReceived.connect(boost::bind(&MUCController::handleConfigurationFormReceived, this, _1)); - highlighter_->setMode(isImpromptu_ ? Highlighter::ChatMode : Highlighter::MUCMode); - highlighter_->setNick(nick_); - if (timerFactory && stanzaChannel_->isAvailable()) { - loginCheckTimer_ = boost::shared_ptr(timerFactory->createTimer(MUC_JOIN_WARNING_TIMEOUT_MILLISECONDS)); - loginCheckTimer_->onTick.connect(boost::bind(&MUCController::handleJoinTimeoutTick, this)); - loginCheckTimer_->start(); - } - else { - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You are currently offline. You will enter this room when you are connected.")), ChatWindow::DefaultDirection); - } - if (isImpromptu) { - muc_->onUnlocked.connect(boost::bind(&MUCController::handleRoomUnlocked, this)); - chatWindow_->convertToMUC(ChatWindow::ImpromptuMUC); - } else { - muc_->onOccupantRoleChanged.connect(boost::bind(&MUCController::handleOccupantRoleChanged, this, _1, _2, _3)); - muc_->onOccupantAffiliationChanged.connect(boost::bind(&MUCController::handleOccupantAffiliationChanged, this, _1, _2, _3)); - chatWindow_->convertToMUC(ChatWindow::StandardMUC); - chatWindow_->setName(muc->getJID().getNode()); - } - if (stanzaChannel->isAvailable()) { - MUCController::setOnline(true); - } - if (avatarManager_ != NULL) { - avatarChangedConnection_ = (avatarManager_->onAvatarChanged.connect(boost::bind(&MUCController::handleAvatarChanged, this, _1))); - } - MUCController::handleBareJIDCapsChanged(muc->getJID()); - eventStream_->onUIEvent.connect(boost::bind(&MUCController::handleUIEvent, this, _1)); - - - // setup handling of MUC bookmark changes - mucBookmarkManagerBookmarkAddedConnection_ = (mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&MUCController::handleMUCBookmarkAdded, this, _1))); - mucBookmarkManagerBookmarkRemovedConnection_ = (mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&MUCController::handleMUCBookmarkRemoved, this, _1))); - - std::vector mucBookmarks = mucBookmarkManager_->getBookmarks(); - std::vector::iterator bookmarkIterator = std::find_if(mucBookmarks.begin(), mucBookmarks.end(), MUCBookmarkPredicate(muc->getJID())); - if (bookmarkIterator != mucBookmarks.end()) { - updateChatWindowBookmarkStatus(*bookmarkIterator); - } - else { - updateChatWindowBookmarkStatus(boost::optional()); - } + const JID& self, + MUC::ref muc, + const boost::optional& password, + const std::string &nick, + StanzaChannel* stanzaChannel, + IQRouter* iqRouter, + ChatWindowFactory* chatWindowFactory, + PresenceOracle* presenceOracle, + AvatarManager* avatarManager, + UIEventStream* uiEventStream, + bool useDelayForLatency, + TimerFactory* timerFactory, + EventController* eventController, + EntityCapsProvider* entityCapsProvider, + XMPPRoster* roster, + HistoryController* historyController, + MUCRegistry* mucRegistry, + HighlightManager* highlightManager, + ClientBlockListManager* clientBlockListManager, + boost::shared_ptr chatMessageParser, + bool isImpromptu, + AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider, + VCardManager* vcardManager, + MUCBookmarkManager* mucBookmarkManager) : + ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, muc->getJID(), presenceOracle, avatarManager, useDelayForLatency, uiEventStream, eventController, timerFactory, entityCapsProvider, historyController, mucRegistry, highlightManager, chatMessageParser, autoAcceptMUCInviteDecider), muc_(muc), nick_(nick), desiredNick_(nick), password_(password), renameCounter_(0), isImpromptu_(isImpromptu), isImpromptuAlreadyConfigured_(false), clientBlockListManager_(clientBlockListManager), mucBookmarkManager_(mucBookmarkManager) { + parting_ = true; + joined_ = false; + lastWasPresence_ = false; + shouldJoinOnReconnect_ = true; + doneGettingHistory_ = false; + events_ = uiEventStream; + xmppRoster_ = roster; + + roster_ = new Roster(false, true); + rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithResource); + completer_ = new TabComplete(); + chatWindow_->setRosterModel(roster_); + chatWindow_->setTabComplete(completer_); + chatWindow_->onClosed.connect(boost::bind(&MUCController::handleWindowClosed, this)); + chatWindow_->onOccupantSelectionChanged.connect(boost::bind(&MUCController::handleWindowOccupantSelectionChanged, this, _1)); + chatWindow_->onOccupantActionSelected.connect(boost::bind(&MUCController::handleActionRequestedOnOccupant, this, _1, _2)); + chatWindow_->onChangeSubjectRequest.connect(boost::bind(&MUCController::handleChangeSubjectRequest, this, _1)); + chatWindow_->onBookmarkRequest.connect(boost::bind(&MUCController::handleBookmarkRequest, this)); + chatWindow_->onConfigureRequest.connect(boost::bind(&MUCController::handleConfigureRequest, this, _1)); + chatWindow_->onConfigurationFormCancelled.connect(boost::bind(&MUCController::handleConfigurationCancelled, this)); + chatWindow_->onDestroyRequest.connect(boost::bind(&MUCController::handleDestroyRoomRequest, this)); + chatWindow_->onInviteToChat.connect(boost::bind(&MUCController::handleInvitePersonToThisMUCRequest, this, _1)); + chatWindow_->onGetAffiliationsRequest.connect(boost::bind(&MUCController::handleGetAffiliationsRequest, this)); + chatWindow_->onChangeAffiliationsRequest.connect(boost::bind(&MUCController::handleChangeAffiliationsRequest, this, _1)); + chatWindow_->onUnblockUserRequest.connect(boost::bind(&MUCController::handleUnblockUserRequest, this)); + muc_->onJoinComplete.connect(boost::bind(&MUCController::handleJoinComplete, this, _1)); + muc_->onJoinFailed.connect(boost::bind(&MUCController::handleJoinFailed, this, _1)); + muc_->onOccupantJoined.connect(boost::bind(&MUCController::handleOccupantJoined, this, _1)); + muc_->onOccupantNicknameChanged.connect(boost::bind(&MUCController::handleOccupantNicknameChanged, this, _1, _2)); + muc_->onOccupantPresenceChange.connect(boost::bind(&MUCController::handleOccupantPresenceChange, this, _1)); + muc_->onOccupantLeft.connect(boost::bind(&MUCController::handleOccupantLeft, this, _1, _2, _3)); + muc_->onRoleChangeFailed.connect(boost::bind(&MUCController::handleOccupantRoleChangeFailed, this, _1, _2, _3)); + muc_->onAffiliationListReceived.connect(boost::bind(&MUCController::handleAffiliationListReceived, this, _1, _2)); + muc_->onConfigurationFailed.connect(boost::bind(&MUCController::handleConfigurationFailed, this, _1)); + muc_->onConfigurationFormReceived.connect(boost::bind(&MUCController::handleConfigurationFormReceived, this, _1)); + highlighter_->setMode(isImpromptu_ ? Highlighter::ChatMode : Highlighter::MUCMode); + highlighter_->setNick(nick_); + if (timerFactory && stanzaChannel_->isAvailable()) { + loginCheckTimer_ = boost::shared_ptr(timerFactory->createTimer(MUC_JOIN_WARNING_TIMEOUT_MILLISECONDS)); + loginCheckTimer_->onTick.connect(boost::bind(&MUCController::handleJoinTimeoutTick, this)); + loginCheckTimer_->start(); + } + else { + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You are currently offline. You will enter this room when you are connected.")), ChatWindow::DefaultDirection); + } + if (isImpromptu) { + muc_->onUnlocked.connect(boost::bind(&MUCController::handleRoomUnlocked, this)); + chatWindow_->convertToMUC(ChatWindow::ImpromptuMUC); + } else { + muc_->onOccupantRoleChanged.connect(boost::bind(&MUCController::handleOccupantRoleChanged, this, _1, _2, _3)); + muc_->onOccupantAffiliationChanged.connect(boost::bind(&MUCController::handleOccupantAffiliationChanged, this, _1, _2, _3)); + chatWindow_->convertToMUC(ChatWindow::StandardMUC); + chatWindow_->setName(muc->getJID().getNode()); + } + if (stanzaChannel->isAvailable()) { + MUCController::setOnline(true); + } + if (avatarManager_ != NULL) { + avatarChangedConnection_ = (avatarManager_->onAvatarChanged.connect(boost::bind(&MUCController::handleAvatarChanged, this, _1))); + } + MUCController::handleBareJIDCapsChanged(muc->getJID()); + eventStream_->onUIEvent.connect(boost::bind(&MUCController::handleUIEvent, this, _1)); + + + // setup handling of MUC bookmark changes + mucBookmarkManagerBookmarkAddedConnection_ = (mucBookmarkManager_->onBookmarkAdded.connect(boost::bind(&MUCController::handleMUCBookmarkAdded, this, _1))); + mucBookmarkManagerBookmarkRemovedConnection_ = (mucBookmarkManager_->onBookmarkRemoved.connect(boost::bind(&MUCController::handleMUCBookmarkRemoved, this, _1))); + + std::vector mucBookmarks = mucBookmarkManager_->getBookmarks(); + std::vector::iterator bookmarkIterator = std::find_if(mucBookmarks.begin(), mucBookmarks.end(), MUCBookmarkPredicate(muc->getJID())); + if (bookmarkIterator != mucBookmarks.end()) { + updateChatWindowBookmarkStatus(*bookmarkIterator); + } + else { + updateChatWindowBookmarkStatus(boost::optional()); + } } MUCController::~MUCController() { - eventStream_->onUIEvent.disconnect(boost::bind(&MUCController::handleUIEvent, this, _1)); - chatWindow_->setRosterModel(NULL); - delete rosterVCardProvider_; - delete roster_; - if (loginCheckTimer_) { - loginCheckTimer_->stop(); - } - chatWindow_->setTabComplete(NULL); - delete completer_; + eventStream_->onUIEvent.disconnect(boost::bind(&MUCController::handleUIEvent, this, _1)); + chatWindow_->setRosterModel(NULL); + delete rosterVCardProvider_; + delete roster_; + if (loginCheckTimer_) { + loginCheckTimer_->stop(); + } + chatWindow_->setTabComplete(NULL); + delete completer_; } void MUCController::cancelReplaces() { - lastWasPresence_ = false; + lastWasPresence_ = false; } void MUCController::handleWindowOccupantSelectionChanged(ContactRosterItem* item) { - std::vector actions; - - if (item) { - MUCOccupant::Affiliation affiliation = muc_->getOccupant(getNick()).getAffiliation(); - MUCOccupant::Role role = muc_->getOccupant(getNick()).getRole(); - if (role == MUCOccupant::Moderator && !isImpromptu_) - { - if (affiliation == MUCOccupant::Admin || affiliation == MUCOccupant::Owner) { - actions.push_back(ChatWindow::Ban); - } - - actions.push_back(ChatWindow::Kick); - actions.push_back(ChatWindow::MakeModerator); - actions.push_back(ChatWindow::MakeParticipant); - actions.push_back(ChatWindow::MakeVisitor); - } - // Add contact is available only if the real JID is also available - if (muc_->getOccupant(item->getJID().getResource()).getRealJID()) { - actions.push_back(ChatWindow::AddContact); - } - actions.push_back(ChatWindow::ShowProfile); - } - chatWindow_->setAvailableOccupantActions(actions); + std::vector actions; + + if (item) { + MUCOccupant::Affiliation affiliation = muc_->getOccupant(getNick()).getAffiliation(); + MUCOccupant::Role role = muc_->getOccupant(getNick()).getRole(); + if (role == MUCOccupant::Moderator && !isImpromptu_) + { + if (affiliation == MUCOccupant::Admin || affiliation == MUCOccupant::Owner) { + actions.push_back(ChatWindow::Ban); + } + + actions.push_back(ChatWindow::Kick); + actions.push_back(ChatWindow::MakeModerator); + actions.push_back(ChatWindow::MakeParticipant); + actions.push_back(ChatWindow::MakeVisitor); + } + // Add contact is available only if the real JID is also available + if (muc_->getOccupant(item->getJID().getResource()).getRealJID()) { + actions.push_back(ChatWindow::AddContact); + } + actions.push_back(ChatWindow::ShowProfile); + } + chatWindow_->setAvailableOccupantActions(actions); } void MUCController::handleActionRequestedOnOccupant(ChatWindow::OccupantAction action, ContactRosterItem* item) { - JID mucJID = item->getJID(); - MUCOccupant occupant = muc_->getOccupant(mucJID.getResource()); - JID realJID; - if (occupant.getRealJID()) { - realJID = occupant.getRealJID().get(); - } - switch (action) { - case ChatWindow::Kick: muc_->kickOccupant(mucJID);break; - case ChatWindow::Ban: muc_->changeAffiliation(realJID, MUCOccupant::Outcast);break; - case ChatWindow::MakeModerator: muc_->changeOccupantRole(mucJID, MUCOccupant::Moderator);break; - case ChatWindow::MakeParticipant: muc_->changeOccupantRole(mucJID, MUCOccupant::Participant);break; - case ChatWindow::MakeVisitor: muc_->changeOccupantRole(mucJID, MUCOccupant::Visitor);break; - case ChatWindow::AddContact: if (occupant.getRealJID()) events_->send(boost::make_shared(realJID, occupant.getNick()));break; - case ChatWindow::ShowProfile: events_->send(boost::make_shared(mucJID));break; - } + JID mucJID = item->getJID(); + MUCOccupant occupant = muc_->getOccupant(mucJID.getResource()); + JID realJID; + if (occupant.getRealJID()) { + realJID = occupant.getRealJID().get(); + } + switch (action) { + case ChatWindow::Kick: muc_->kickOccupant(mucJID);break; + case ChatWindow::Ban: muc_->changeAffiliation(realJID, MUCOccupant::Outcast);break; + case ChatWindow::MakeModerator: muc_->changeOccupantRole(mucJID, MUCOccupant::Moderator);break; + case ChatWindow::MakeParticipant: muc_->changeOccupantRole(mucJID, MUCOccupant::Participant);break; + case ChatWindow::MakeVisitor: muc_->changeOccupantRole(mucJID, MUCOccupant::Visitor);break; + case ChatWindow::AddContact: if (occupant.getRealJID()) events_->send(boost::make_shared(realJID, occupant.getNick()));break; + case ChatWindow::ShowProfile: events_->send(boost::make_shared(mucJID));break; + } } void MUCController::handleBareJIDCapsChanged(const JID& /*jid*/) { - Tristate support = Yes; - bool any = false; - foreach (const std::string& nick, currentOccupants_) { - DiscoInfo::ref disco = entityCapsProvider_->getCaps(toJID_.toBare().toString() + "/" + nick); - if (disco && disco->hasFeature(DiscoInfo::MessageCorrectionFeature)) { - any = true; - } else { - support = Maybe; - } - } - if (!any) { - support = No; - } - chatWindow_->setCorrectionEnabled(support); + Tristate support = Yes; + bool any = false; + foreach (const std::string& nick, currentOccupants_) { + DiscoInfo::ref disco = entityCapsProvider_->getCaps(toJID_.toBare().toString() + "/" + nick); + if (disco && disco->hasFeature(DiscoInfo::MessageCorrectionFeature)) { + any = true; + } else { + support = Maybe; + } + } + if (!any) { + support = No; + } + chatWindow_->setCorrectionEnabled(support); } /** * Join the MUC if not already in it. */ void MUCController::rejoin() { - if (parting_) { - joined_ = false; - parting_ = false; - if (password_) { - muc_->setPassword(*password_); - } - //FIXME: check for received activity + if (parting_) { + joined_ = false; + parting_ = false; + if (password_) { + muc_->setPassword(*password_); + } + //FIXME: check for received activity #ifdef SWIFT_EXPERIMENTAL_HISTORY - if (lastActivity_ == boost::posix_time::not_a_date_time && historyController_) { - lastActivity_ = historyController_->getLastTimeStampFromMUC(selfJID_, toJID_); - } + if (lastActivity_ == boost::posix_time::not_a_date_time && historyController_) { + lastActivity_ = historyController_->getLastTimeStampFromMUC(selfJID_, toJID_); + } #endif - if (lastActivity_ == boost::posix_time::not_a_date_time) { - muc_->joinAs(nick_); - } - else { - muc_->joinWithContextSince(nick_, lastActivity_); - } - } + if (lastActivity_ == boost::posix_time::not_a_date_time) { + muc_->joinAs(nick_); + } + else { + muc_->joinWithContextSince(nick_, lastActivity_); + } + } } bool MUCController::isJoined() { - return joined_; + return joined_; } const std::string& MUCController::getNick() { - return nick_; + return nick_; } const boost::optional MUCController::getPassword() const { - return password_; + return password_; } bool MUCController::isImpromptu() const { - return isImpromptu_; + return isImpromptu_; } std::map MUCController::getParticipantJIDs() const { - std::map participants; - typedef std::pair MUCOccupantPair; - std::map occupants = muc_->getOccupants(); - foreach(const MUCOccupantPair& occupant, occupants) { - if (occupant.first != nick_) { - participants[occupant.first] = occupant.second.getRealJID().is_initialized() ? occupant.second.getRealJID().get().toBare() : JID(); - } - } - return participants; + std::map participants; + typedef std::pair MUCOccupantPair; + std::map occupants = muc_->getOccupants(); + foreach(const MUCOccupantPair& occupant, occupants) { + if (occupant.first != nick_) { + participants[occupant.first] = occupant.second.getRealJID().is_initialized() ? occupant.second.getRealJID().get().toBare() : JID(); + } + } + return participants; } void MUCController::sendInvites(const std::vector& jids, const std::string& reason) const { - foreach (const JID& jid, jids) { - muc_->invitePerson(jid, reason, isImpromptu_); - } + foreach (const JID& jid, jids) { + muc_->invitePerson(jid, reason, isImpromptu_); + } } void MUCController::handleJoinTimeoutTick() { - receivedActivity(); - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Room %1% is not responding. This operation may never complete.")) % toJID_.toString())), ChatWindow::DefaultDirection); + receivedActivity(); + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Room %1% is not responding. This operation may never complete.")) % toJID_.toString())), ChatWindow::DefaultDirection); } void MUCController::receivedActivity() { - if (loginCheckTimer_) { - loginCheckTimer_->stop(); - } + if (loginCheckTimer_) { + loginCheckTimer_->stop(); + } } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch-enum" void MUCController::handleJoinFailed(boost::shared_ptr error) { - receivedActivity(); - std::string errorMessage = QT_TRANSLATE_NOOP("", "Unable to enter this room"); - std::string rejoinNick; - if (error) { - switch (error->getCondition()) { - case ErrorPayload::Conflict: - rejoinNick = nick_ + "_"; - errorMessage = str(format(QT_TRANSLATE_NOOP("", "Unable to enter this room as %1%, retrying as %2%")) % nick_ % rejoinNick); - break; - case ErrorPayload::JIDMalformed: - errorMessage += ": "; - errorMessage += QT_TRANSLATE_NOOP("", "No nickname specified"); - break; - case ErrorPayload::NotAuthorized: - errorMessage += ": "; - errorMessage += QT_TRANSLATE_NOOP("", "The correct room password is needed"); - break; - case ErrorPayload::RegistrationRequired: - errorMessage += ": "; - errorMessage += QT_TRANSLATE_NOOP("", "Only members may enter"); - break; - case ErrorPayload::Forbidden: - errorMessage += ": "; - errorMessage += QT_TRANSLATE_NOOP("", "You are banned from the room"); - break; - case ErrorPayload::ServiceUnavailable: - errorMessage += ": "; - errorMessage += QT_TRANSLATE_NOOP("", "The room is full"); - break; - case ErrorPayload::ItemNotFound: - errorMessage += ": "; - errorMessage += QT_TRANSLATE_NOOP("", "The room does not exist"); - break; - - default: break; - } - } - errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't enter room: %1%.")) % errorMessage); - chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); - parting_ = true; - if (!rejoinNick.empty() && renameCounter_ < 10) { - renameCounter_++; - setNick(rejoinNick); - rejoin(); - } + receivedActivity(); + std::string errorMessage = QT_TRANSLATE_NOOP("", "Unable to enter this room"); + std::string rejoinNick; + if (error) { + switch (error->getCondition()) { + case ErrorPayload::Conflict: + rejoinNick = nick_ + "_"; + errorMessage = str(format(QT_TRANSLATE_NOOP("", "Unable to enter this room as %1%, retrying as %2%")) % nick_ % rejoinNick); + break; + case ErrorPayload::JIDMalformed: + errorMessage += ": "; + errorMessage += QT_TRANSLATE_NOOP("", "No nickname specified"); + break; + case ErrorPayload::NotAuthorized: + errorMessage += ": "; + errorMessage += QT_TRANSLATE_NOOP("", "The correct room password is needed"); + break; + case ErrorPayload::RegistrationRequired: + errorMessage += ": "; + errorMessage += QT_TRANSLATE_NOOP("", "Only members may enter"); + break; + case ErrorPayload::Forbidden: + errorMessage += ": "; + errorMessage += QT_TRANSLATE_NOOP("", "You are banned from the room"); + break; + case ErrorPayload::ServiceUnavailable: + errorMessage += ": "; + errorMessage += QT_TRANSLATE_NOOP("", "The room is full"); + break; + case ErrorPayload::ItemNotFound: + errorMessage += ": "; + errorMessage += QT_TRANSLATE_NOOP("", "The room does not exist"); + break; + + default: break; + } + } + errorMessage = str(format(QT_TRANSLATE_NOOP("", "Couldn't enter room: %1%.")) % errorMessage); + chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); + parting_ = true; + if (!rejoinNick.empty() && renameCounter_ < 10) { + renameCounter_++; + setNick(rejoinNick); + rejoin(); + } } #pragma clang diagnostic pop void MUCController::handleJoinComplete(const std::string& nick) { - receivedActivity(); - renameCounter_ = 0; - joined_ = true; - std::string joinMessage; - if (isImpromptu_) { - joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have joined the chat as %1%.")) % nick); - } else { - joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have entered room %1% as %2%.")) % toJID_.toString() % nick); - } - setNick(nick); - chatWindow_->replaceSystemMessage(chatMessageParser_->parseMessageBody(joinMessage), lastJoinMessageUID_, ChatWindow::UpdateTimestamp); - lastJoinMessageUID_ = ""; + receivedActivity(); + renameCounter_ = 0; + joined_ = true; + std::string joinMessage; + if (isImpromptu_) { + joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have joined the chat as %1%.")) % nick); + } else { + joinMessage = str(format(QT_TRANSLATE_NOOP("", "You have entered room %1% as %2%.")) % toJID_.toString() % nick); + } + setNick(nick); + chatWindow_->replaceSystemMessage(chatMessageParser_->parseMessageBody(joinMessage), lastJoinMessageUID_, ChatWindow::UpdateTimestamp); + lastJoinMessageUID_ = ""; #ifdef SWIFT_EXPERIMENTAL_HISTORY - addRecentLogs(); + addRecentLogs(); #endif - clearPresenceQueue(); - shouldJoinOnReconnect_ = true; - setEnabled(true); - if (isImpromptu_) { - setAvailableRoomActions(MUCOccupant::NoAffiliation, MUCOccupant::Participant); - } else { - MUCOccupant occupant = muc_->getOccupant(nick); - setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole()); - } - onUserJoined(); + clearPresenceQueue(); + shouldJoinOnReconnect_ = true; + setEnabled(true); + if (isImpromptu_) { + setAvailableRoomActions(MUCOccupant::NoAffiliation, MUCOccupant::Participant); + } else { + MUCOccupant occupant = muc_->getOccupant(nick); + setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole()); + } + onUserJoined(); - if (isImpromptu_) { - setImpromptuWindowTitle(); - } + if (isImpromptu_) { + setImpromptuWindowTitle(); + } } void MUCController::handleAvatarChanged(const JID& jid) { - if (parting_ || !jid.equals(toJID_, JID::WithoutResource)) { - return; - } - roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid), JID::WithResource)); + if (parting_ || !jid.equals(toJID_, JID::WithoutResource)) { + return; + } + roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid), JID::WithResource)); } void MUCController::handleWindowClosed() { - parting_ = true; - shouldJoinOnReconnect_ = false; - muc_->part(); - onUserLeft(); + parting_ = true; + shouldJoinOnReconnect_ = false; + muc_->part(); + onUserLeft(); } void MUCController::handleOccupantJoined(const MUCOccupant& occupant) { - if (nick_ != occupant.getNick()) { - completer_->addWord(occupant.getNick()); - } - receivedActivity(); - JID jid(nickToJID(occupant.getNick())); - JID realJID; - if (occupant.getRealJID()) { - realJID = occupant.getRealJID().get(); - } - currentOccupants_.insert(occupant.getNick()); - NickJoinPart event(occupant.getNick(), Join); - appendToJoinParts(joinParts_, event); - MUCOccupant::Role role = MUCOccupant::Participant; - MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation; - if (!isImpromptu_) { - role = occupant.getRole(); - affiliation = occupant.getAffiliation(); - } - std::string groupName(roleToGroupName(role)); - roster_->addContact(jid, realJID, occupant.getNick(), groupName, avatarManager_->getAvatarPath(jid)); - roster_->applyOnItems(SetMUC(jid, role, affiliation)); - roster_->getGroup(groupName)->setManualSort(roleToSortName(role)); - if (joined_) { - std::string joinString; - if (role != MUCOccupant::NoRole && role != MUCOccupant::Participant) { - joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %3% as a %2%.")) % occupant.getNick() % roleToFriendlyName(role) % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room"))); - } - else { - joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %2%.")) % occupant.getNick() % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room"))); - } - if (shouldUpdateJoinParts()) { - updateJoinParts(); - } else { - addPresenceMessage(joinString); - } - - if (isImpromptu_) { - setImpromptuWindowTitle(); - onActivity(""); - } - } - if (avatarManager_ != NULL) { - handleAvatarChanged(jid); - } + if (nick_ != occupant.getNick()) { + completer_->addWord(occupant.getNick()); + } + receivedActivity(); + JID jid(nickToJID(occupant.getNick())); + JID realJID; + if (occupant.getRealJID()) { + realJID = occupant.getRealJID().get(); + } + currentOccupants_.insert(occupant.getNick()); + NickJoinPart event(occupant.getNick(), Join); + appendToJoinParts(joinParts_, event); + MUCOccupant::Role role = MUCOccupant::Participant; + MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation; + if (!isImpromptu_) { + role = occupant.getRole(); + affiliation = occupant.getAffiliation(); + } + std::string groupName(roleToGroupName(role)); + roster_->addContact(jid, realJID, occupant.getNick(), groupName, avatarManager_->getAvatarPath(jid)); + roster_->applyOnItems(SetMUC(jid, role, affiliation)); + roster_->getGroup(groupName)->setManualSort(roleToSortName(role)); + if (joined_) { + std::string joinString; + if (role != MUCOccupant::NoRole && role != MUCOccupant::Participant) { + joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %3% as a %2%.")) % occupant.getNick() % roleToFriendlyName(role) % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room"))); + } + else { + joinString = str(format(QT_TRANSLATE_NOOP("", "%1% has entered the %2%.")) % occupant.getNick() % (isImpromptu_ ? QT_TRANSLATE_NOOP("", "chat") : QT_TRANSLATE_NOOP("", "room"))); + } + if (shouldUpdateJoinParts()) { + updateJoinParts(); + } else { + addPresenceMessage(joinString); + } + + if (isImpromptu_) { + setImpromptuWindowTitle(); + onActivity(""); + } + } + if (avatarManager_ != NULL) { + handleAvatarChanged(jid); + } } void MUCController::addPresenceMessage(const std::string& message) { - lastWasPresence_ = true; - chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(message), ChatWindow::DefaultDirection); + lastWasPresence_ = true; + chatWindow_->addPresenceMessage(chatMessageParser_->parseMessageBody(message), ChatWindow::DefaultDirection); } void MUCController::setAvailableRoomActions(const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Role& role) { - std::vector actions; - - if (role <= MUCOccupant::Participant) { - actions.push_back(ChatWindow::ChangeSubject); - } - if (affiliation == MUCOccupant::Owner) { - actions.push_back(ChatWindow::Configure); - } - if (affiliation <= MUCOccupant::Admin) { - actions.push_back(ChatWindow::Affiliations); - } - if (affiliation == MUCOccupant::Owner) { - actions.push_back(ChatWindow::Destroy); - } - if (role <= MUCOccupant::Visitor) { - actions.push_back(ChatWindow::Invite); - } - chatWindow_->setAvailableRoomActions(actions); + std::vector actions; + + if (role <= MUCOccupant::Participant) { + actions.push_back(ChatWindow::ChangeSubject); + } + if (affiliation == MUCOccupant::Owner) { + actions.push_back(ChatWindow::Configure); + } + if (affiliation <= MUCOccupant::Admin) { + actions.push_back(ChatWindow::Affiliations); + } + if (affiliation == MUCOccupant::Owner) { + actions.push_back(ChatWindow::Destroy); + } + if (role <= MUCOccupant::Visitor) { + actions.push_back(ChatWindow::Invite); + } + chatWindow_->setAvailableRoomActions(actions); } void MUCController::clearPresenceQueue() { - lastWasPresence_ = false; - joinParts_.clear(); + lastWasPresence_ = false; + joinParts_.clear(); } std::string MUCController::roleToFriendlyName(MUCOccupant::Role role) { - switch (role) { - case MUCOccupant::Moderator: return QT_TRANSLATE_NOOP("", "moderator"); - case MUCOccupant::Participant: return QT_TRANSLATE_NOOP("", "participant"); - case MUCOccupant::Visitor: return QT_TRANSLATE_NOOP("", "visitor"); - case MUCOccupant::NoRole: return ""; - } - assert(false); - return ""; + switch (role) { + case MUCOccupant::Moderator: return QT_TRANSLATE_NOOP("", "moderator"); + case MUCOccupant::Participant: return QT_TRANSLATE_NOOP("", "participant"); + case MUCOccupant::Visitor: return QT_TRANSLATE_NOOP("", "visitor"); + case MUCOccupant::NoRole: return ""; + } + assert(false); + return ""; } std::string MUCController::roleToSortName(MUCOccupant::Role role) { - switch (role) { - case MUCOccupant::Moderator: return "1"; - case MUCOccupant::Participant: return "2"; - case MUCOccupant::Visitor: return "3"; - case MUCOccupant::NoRole: return "4"; - } - assert(false); - return "5"; + switch (role) { + case MUCOccupant::Moderator: return "1"; + case MUCOccupant::Participant: return "2"; + case MUCOccupant::Visitor: return "3"; + case MUCOccupant::NoRole: return "4"; + } + assert(false); + return "5"; } JID MUCController::nickToJID(const std::string& nick) { - return muc_->getJID().withResource(nick); + return muc_->getJID().withResource(nick); } bool MUCController::messageTargetsMe(boost::shared_ptr message) { - std::string stringRegexp(".*\\b" + boost::to_lower_copy(nick_) + "\\b.*"); - boost::regex myRegexp(stringRegexp); - return boost::regex_match(boost::to_lower_copy(message->getBody().get_value_or("")), myRegexp); + std::string stringRegexp(".*\\b" + boost::to_lower_copy(nick_) + "\\b.*"); + boost::regex myRegexp(stringRegexp); + return boost::regex_match(boost::to_lower_copy(message->getBody().get_value_or("")), myRegexp); } void MUCController::preHandleIncomingMessage(boost::shared_ptr messageEvent) { - if (messageEvent->getStanza()->getType() == Message::Groupchat) { - lastActivity_ = boost::posix_time::microsec_clock::universal_time(); - } - clearPresenceQueue(); - boost::shared_ptr message = messageEvent->getStanza(); - if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && messageTargetsMe(message) && !message->getPayload() && messageEvent->isReadable()) { - chatWindow_->flash(); - } - else { - messageEvent->setTargetsMe(false); - } - if (messageEvent->isReadable() && isImpromptu_) { - chatWindow_->flash(); /* behave like a regular char*/ - } - if (joined_) { - std::string nick = message->getFrom().getResource(); - if (nick != nick_ && currentOccupants_.find(nick) != currentOccupants_.end()) { - completer_->addWord(nick); - } - } - /*Buggy implementations never send the status code, so use an incoming message as a hint that joining's done (e.g. the old ejabberd on psi-im.org).*/ - receivedActivity(); - joined_ = true; - - if (message->hasSubject() && !message->getPayload() && !message->getPayload()) { - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The room subject is now: %1%")) % message->getSubject())), ChatWindow::DefaultDirection); - chatWindow_->setSubject(message->getSubject()); - doneGettingHistory_ = true; - } - - if (!doneGettingHistory_ && !message->getPayload()) { - doneGettingHistory_ = true; - } - - if (!doneGettingHistory_) { - checkDuplicates(message); - messageEvent->conclude(); - } + if (messageEvent->getStanza()->getType() == Message::Groupchat) { + lastActivity_ = boost::posix_time::microsec_clock::universal_time(); + } + clearPresenceQueue(); + boost::shared_ptr message = messageEvent->getStanza(); + if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && messageTargetsMe(message) && !message->getPayload() && messageEvent->isReadable()) { + chatWindow_->flash(); + } + else { + messageEvent->setTargetsMe(false); + } + if (messageEvent->isReadable() && isImpromptu_) { + chatWindow_->flash(); /* behave like a regular char*/ + } + if (joined_) { + std::string nick = message->getFrom().getResource(); + if (nick != nick_ && currentOccupants_.find(nick) != currentOccupants_.end()) { + completer_->addWord(nick); + } + } + /*Buggy implementations never send the status code, so use an incoming message as a hint that joining's done (e.g. the old ejabberd on psi-im.org).*/ + receivedActivity(); + joined_ = true; + + if (message->hasSubject() && !message->getPayload() && !message->getPayload()) { + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "The room subject is now: %1%")) % message->getSubject())), ChatWindow::DefaultDirection); + chatWindow_->setSubject(message->getSubject()); + doneGettingHistory_ = true; + } + + if (!doneGettingHistory_ && !message->getPayload()) { + doneGettingHistory_ = true; + } + + if (!doneGettingHistory_) { + checkDuplicates(message); + messageEvent->conclude(); + } } void MUCController::addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr label, const boost::posix_time::ptime& time) { - if (from.isBare()) { - chatWindow_->addSystemMessage(message, ChatWindow::DefaultDirection); - } - else { - ChatControllerBase::addMessageHandleIncomingMessage(from, message, senderIsSelf, label, time); - } + if (from.isBare()) { + chatWindow_->addSystemMessage(message, ChatWindow::DefaultDirection); + } + else { + ChatControllerBase::addMessageHandleIncomingMessage(from, message, senderIsSelf, label, time); + } } void MUCController::postHandleIncomingMessage(boost::shared_ptr messageEvent, const ChatWindow::ChatMessage& chatMessage) { - boost::shared_ptr message = messageEvent->getStanza(); - if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && !message->getPayload()) { - if (messageTargetsMe(message) || isImpromptu_) { - eventController_->handleIncomingEvent(messageEvent); - } - if (!messageEvent->getConcluded()) { - handleHighlightActions(chatMessage); - } - } + boost::shared_ptr message = messageEvent->getStanza(); + if (joined_ && messageEvent->getStanza()->getFrom().getResource() != nick_ && !message->getPayload()) { + if (messageTargetsMe(message) || isImpromptu_) { + eventController_->handleIncomingEvent(messageEvent); + } + if (!messageEvent->getConcluded()) { + handleHighlightActions(chatMessage); + } + } } void MUCController::handleOccupantRoleChanged(const std::string& nick, const MUCOccupant& occupant, const MUCOccupant::Role& oldRole) { - clearPresenceQueue(); - receivedActivity(); - JID jid(nickToJID(nick)); - roster_->removeContactFromGroup(jid, roleToGroupName(oldRole)); - JID realJID; - if (occupant.getRealJID()) { - realJID = occupant.getRealJID().get(); - } - std::string group(roleToGroupName(occupant.getRole())); - roster_->addContact(jid, realJID, nick, group, avatarManager_->getAvatarPath(jid)); - roster_->getGroup(group)->setManualSort(roleToSortName(occupant.getRole())); - roster_->applyOnItems(SetMUC(jid, occupant.getRole(), occupant.getAffiliation())); - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "%1% is now a %2%")) % nick % roleToFriendlyName(occupant.getRole()))), ChatWindow::DefaultDirection); - if (nick == nick_) { - setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole()); - } + clearPresenceQueue(); + receivedActivity(); + JID jid(nickToJID(nick)); + roster_->removeContactFromGroup(jid, roleToGroupName(oldRole)); + JID realJID; + if (occupant.getRealJID()) { + realJID = occupant.getRealJID().get(); + } + std::string group(roleToGroupName(occupant.getRole())); + roster_->addContact(jid, realJID, nick, group, avatarManager_->getAvatarPath(jid)); + roster_->getGroup(group)->setManualSort(roleToSortName(occupant.getRole())); + roster_->applyOnItems(SetMUC(jid, occupant.getRole(), occupant.getAffiliation())); + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "%1% is now a %2%")) % nick % roleToFriendlyName(occupant.getRole()))), ChatWindow::DefaultDirection); + if (nick == nick_) { + setAvailableRoomActions(occupant.getAffiliation(), occupant.getRole()); + } } void MUCController::handleOccupantAffiliationChanged(const std::string& nick, const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Affiliation& /*oldAffiliation*/) { - if (nick == nick_) { - setAvailableRoomActions(affiliation, muc_->getOccupant(nick_).getRole()); - } - JID jid(nickToJID(nick)); - MUCOccupant occupant = muc_->getOccupant(nick); - roster_->applyOnItems(SetMUC(jid, occupant.getRole(), affiliation)); + if (nick == nick_) { + setAvailableRoomActions(affiliation, muc_->getOccupant(nick_).getRole()); + } + JID jid(nickToJID(nick)); + MUCOccupant occupant = muc_->getOccupant(nick); + roster_->applyOnItems(SetMUC(jid, occupant.getRole(), affiliation)); } std::string MUCController::roleToGroupName(MUCOccupant::Role role) { - std::string result; - switch (role) { - case MUCOccupant::Moderator: result = QT_TRANSLATE_NOOP("", "Moderators"); break; - case MUCOccupant::Participant: result = QT_TRANSLATE_NOOP("", "Participants"); break; - case MUCOccupant::Visitor: result = QT_TRANSLATE_NOOP("", "Visitors"); break; - case MUCOccupant::NoRole: result = QT_TRANSLATE_NOOP("", "Occupants"); break; - } - return result; + std::string result; + switch (role) { + case MUCOccupant::Moderator: result = QT_TRANSLATE_NOOP("", "Moderators"); break; + case MUCOccupant::Participant: result = QT_TRANSLATE_NOOP("", "Participants"); break; + case MUCOccupant::Visitor: result = QT_TRANSLATE_NOOP("", "Visitors"); break; + case MUCOccupant::NoRole: result = QT_TRANSLATE_NOOP("", "Occupants"); break; + } + return result; } void MUCController::setOnline(bool online) { - ChatControllerBase::setOnline(online); - if (!online) { - muc_->part(); - parting_ = true; - processUserPart(); - } else { - if (shouldJoinOnReconnect_) { - renameCounter_ = 0; - boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); - if (blockList && blockList->isBlocked(muc_->getJID())) { - handleBlockingStateChanged(); - lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again")), ChatWindow::DefaultDirection); - } - else { - if (isImpromptu_) { - lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "Trying to join chat")), ChatWindow::DefaultDirection); - } else { - lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Trying to enter room %1%")) % toJID_.toString())), ChatWindow::DefaultDirection); - } - if (loginCheckTimer_) { - loginCheckTimer_->start(); - } - setNick(desiredNick_); - rejoin(); - } - } - } + ChatControllerBase::setOnline(online); + if (!online) { + muc_->part(); + parting_ = true; + processUserPart(); + } else { + if (shouldJoinOnReconnect_) { + renameCounter_ = 0; + boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); + if (blockList && blockList->isBlocked(muc_->getJID())) { + handleBlockingStateChanged(); + lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again")), ChatWindow::DefaultDirection); + } + else { + if (isImpromptu_) { + lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "Trying to join chat")), ChatWindow::DefaultDirection); + } else { + lastJoinMessageUID_ = chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(str(format(QT_TRANSLATE_NOOP("", "Trying to enter room %1%")) % toJID_.toString())), ChatWindow::DefaultDirection); + } + if (loginCheckTimer_) { + loginCheckTimer_->start(); + } + setNick(desiredNick_); + rejoin(); + } + } + } } void MUCController::processUserPart() { - roster_->removeAll(); - /* handleUserLeft won't throw a part back up unless this is called - when it doesn't yet know we've left - which only happens on - disconnect, so call with disconnect here so if the signal does - bubble back up, it'll be with the right type.*/ - muc_->handleUserLeft(MUC::Disconnect); - setEnabled(false); + roster_->removeAll(); + /* handleUserLeft won't throw a part back up unless this is called + when it doesn't yet know we've left - which only happens on + disconnect, so call with disconnect here so if the signal does + bubble back up, it'll be with the right type.*/ + muc_->handleUserLeft(MUC::Disconnect); + setEnabled(false); } bool MUCController::shouldUpdateJoinParts() { - return lastWasPresence_; + return lastWasPresence_; } void MUCController::handleOccupantLeft(const MUCOccupant& occupant, MUC::LeavingType type, const std::string& reason) { - NickJoinPart event(occupant.getNick(), Part); - appendToJoinParts(joinParts_, event); - currentOccupants_.erase(occupant.getNick()); - completer_->removeWord(occupant.getNick()); - std::string partMessage; - bool clearAfter = false; - if (occupant.getNick() != nick_) { - std::string partType; - switch (type) { - case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partType = " (kicked)"; break; - case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partType = " (banned)"; break; - case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partType = " (no longer a member)"; break; - case MUC::LeaveDestroy: - case MUC::Disconnect: - case MUC::LeavePart: break; - } - if (isImpromptu_) { - partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the chat%2%")) % occupant.getNick() % partType); - } else { - partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the room%2%")) % occupant.getNick() % partType); - } - } - else if (isImpromptu_) { - switch (type) { - case MUC::LeaveKick: - case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break; - case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break; - case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "This chat has ended"); break; - case MUC::Disconnect: - case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the chat"); - } - } - else { - switch (type) { - case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been kicked out of the room"); break; - case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been banned from the room"); break; - case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You are no longer a member of the room and have been removed"); break; - case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "The room has been destroyed"); break; - case MUC::Disconnect: - case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the room"); - } - } - if (!reason.empty()) { - partMessage += " (" + reason + ")"; - } - partMessage += "."; - - if (occupant.getNick() != nick_) { - if (shouldUpdateJoinParts()) { - updateJoinParts(); - } else { - addPresenceMessage(partMessage); - } - roster_->removeContact(JID(toJID_.getNode(), toJID_.getDomain(), occupant.getNick())); - } else { - addPresenceMessage(partMessage); - parting_ = true; - processUserPart(); - } - if (clearAfter) { - clearPresenceQueue(); - } - - if (isImpromptu_) { - setImpromptuWindowTitle(); - } + NickJoinPart event(occupant.getNick(), Part); + appendToJoinParts(joinParts_, event); + currentOccupants_.erase(occupant.getNick()); + completer_->removeWord(occupant.getNick()); + std::string partMessage; + bool clearAfter = false; + if (occupant.getNick() != nick_) { + std::string partType; + switch (type) { + case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partType = " (kicked)"; break; + case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partType = " (banned)"; break; + case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partType = " (no longer a member)"; break; + case MUC::LeaveDestroy: + case MUC::Disconnect: + case MUC::LeavePart: break; + } + if (isImpromptu_) { + partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the chat%2%")) % occupant.getNick() % partType); + } else { + partMessage = str(format(QT_TRANSLATE_NOOP("", "%1% has left the room%2%")) % occupant.getNick() % partType); + } + } + else if (isImpromptu_) { + switch (type) { + case MUC::LeaveKick: + case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break; + case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been removed from this chat"); break; + case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "This chat has ended"); break; + case MUC::Disconnect: + case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the chat"); + } + } + else { + switch (type) { + case MUC::LeaveKick: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been kicked out of the room"); break; + case MUC::LeaveBan: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You have been banned from the room"); break; + case MUC::LeaveNotMember: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "You are no longer a member of the room and have been removed"); break; + case MUC::LeaveDestroy: clearPresenceQueue(); clearAfter = true; partMessage = QT_TRANSLATE_NOOP("", "The room has been destroyed"); break; + case MUC::Disconnect: + case MUC::LeavePart: partMessage = QT_TRANSLATE_NOOP("", "You have left the room"); + } + } + if (!reason.empty()) { + partMessage += " (" + reason + ")"; + } + partMessage += "."; + + if (occupant.getNick() != nick_) { + if (shouldUpdateJoinParts()) { + updateJoinParts(); + } else { + addPresenceMessage(partMessage); + } + roster_->removeContact(JID(toJID_.getNode(), toJID_.getDomain(), occupant.getNick())); + } else { + addPresenceMessage(partMessage); + parting_ = true; + processUserPart(); + } + if (clearAfter) { + clearPresenceQueue(); + } + + if (isImpromptu_) { + setImpromptuWindowTitle(); + } } void MUCController::handleOccupantNicknameChanged(const std::string& oldNickname, const std::string& newNickname) { - addPresenceMessage(generateNicknameChangeString(oldNickname, newNickname)); - JID oldJID = muc_->getJID().withResource(oldNickname); - JID newJID = muc_->getJID().withResource(newNickname); - - // adjust occupants - currentOccupants_.erase(oldNickname); - currentOccupants_.insert(newNickname); - - // adjust completer - completer_->removeWord(oldNickname); - completer_->addWord(newNickname); - - // update contact - roster_->removeContact(oldJID); - MUCOccupant occupant = muc_->getOccupant(newNickname); - - JID realJID; - if (occupant.getRealJID()) { - realJID = occupant.getRealJID().get(); - } - MUCOccupant::Role role = MUCOccupant::Participant; - MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation; - if (!isImpromptu_) { - role = occupant.getRole(); - affiliation = occupant.getAffiliation(); - } - std::string groupName(roleToGroupName(role)); - roster_->addContact(newJID, realJID, newNickname, groupName, avatarManager_->getAvatarPath(newJID)); - roster_->applyOnItems(SetMUC(newJID, role, affiliation)); - if (avatarManager_ != NULL) { - handleAvatarChanged(newJID); - } - - clearPresenceQueue(); - onUserNicknameChanged(oldNickname, newNickname); + addPresenceMessage(generateNicknameChangeString(oldNickname, newNickname)); + JID oldJID = muc_->getJID().withResource(oldNickname); + JID newJID = muc_->getJID().withResource(newNickname); + + // adjust occupants + currentOccupants_.erase(oldNickname); + currentOccupants_.insert(newNickname); + + // adjust completer + completer_->removeWord(oldNickname); + completer_->addWord(newNickname); + + // update contact + roster_->removeContact(oldJID); + MUCOccupant occupant = muc_->getOccupant(newNickname); + + JID realJID; + if (occupant.getRealJID()) { + realJID = occupant.getRealJID().get(); + } + MUCOccupant::Role role = MUCOccupant::Participant; + MUCOccupant::Affiliation affiliation = MUCOccupant::NoAffiliation; + if (!isImpromptu_) { + role = occupant.getRole(); + affiliation = occupant.getAffiliation(); + } + std::string groupName(roleToGroupName(role)); + roster_->addContact(newJID, realJID, newNickname, groupName, avatarManager_->getAvatarPath(newJID)); + roster_->applyOnItems(SetMUC(newJID, role, affiliation)); + if (avatarManager_ != NULL) { + handleAvatarChanged(newJID); + } + + clearPresenceQueue(); + onUserNicknameChanged(oldNickname, newNickname); } void MUCController::handleOccupantPresenceChange(boost::shared_ptr presence) { - receivedActivity(); - roster_->applyOnItems(SetPresence(presence, JID::WithResource)); + receivedActivity(); + roster_->applyOnItems(SetPresence(presence, JID::WithResource)); } bool MUCController::isIncomingMessageFromMe(boost::shared_ptr message) { - JID from = message->getFrom(); - return nick_ == from.getResource(); + JID from = message->getFrom(); + return nick_ == from.getResource(); } std::string MUCController::senderHighlightNameFromMessage(const JID& from) { - return from.getResource(); + return from.getResource(); } std::string MUCController::senderDisplayNameFromMessage(const JID& from) { - return from.getResource(); + return from.getResource(); } void MUCController::preSendMessageRequest(boost::shared_ptr message) { - message->setType(Swift::Message::Groupchat); + message->setType(Swift::Message::Groupchat); } boost::optional MUCController::getMessageTimestamp(boost::shared_ptr message) const { - return message->getTimestampFrom(toJID_); + return message->getTimestampFrom(toJID_); } void MUCController::updateJoinParts() { - chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(generateJoinPartString(joinParts_, isImpromptu())), ChatWindow::UpdateTimestamp); + chatWindow_->replaceLastMessage(chatMessageParser_->parseMessageBody(generateJoinPartString(joinParts_, isImpromptu())), ChatWindow::UpdateTimestamp); } void MUCController::appendToJoinParts(std::vector& joinParts, const NickJoinPart& newEvent) { - std::vector::iterator it = joinParts.begin(); - bool matched = false; - for (; it != joinParts.end(); ++it) { - if ((*it).nick == newEvent.nick) { - matched = true; - JoinPart type = (*it).type; - switch (newEvent.type) { - case Join: type = (type == Part) ? PartThenJoin : Join; break; - case Part: type = (type == Join) ? JoinThenPart : Part; break; - case PartThenJoin: break; - case JoinThenPart: break; - } - (*it).type = type; - break; - } - } - if (!matched) { - joinParts.push_back(newEvent); - } + std::vector::iterator it = joinParts.begin(); + bool matched = false; + for (; it != joinParts.end(); ++it) { + if ((*it).nick == newEvent.nick) { + matched = true; + JoinPart type = (*it).type; + switch (newEvent.type) { + case Join: type = (type == Part) ? PartThenJoin : Join; break; + case Part: type = (type == Join) ? JoinThenPart : Part; break; + case PartThenJoin: break; + case JoinThenPart: break; + } + (*it).type = type; + break; + } + } + if (!matched) { + joinParts.push_back(newEvent); + } } std::string MUCController::concatenateListOfNames(const std::vector& joinParts) { - std::string result; - for (size_t i = 0; i < joinParts.size(); i++) { - if (i > 0) { - if (i < joinParts.size() - 1) { - result += ", "; - } else { - result += QT_TRANSLATE_NOOP("", " and "); - } - } - NickJoinPart event = joinParts[i]; - result += event.nick; - } - return result; + std::string result; + for (size_t i = 0; i < joinParts.size(); i++) { + if (i > 0) { + if (i < joinParts.size() - 1) { + result += ", "; + } else { + result += QT_TRANSLATE_NOOP("", " and "); + } + } + NickJoinPart event = joinParts[i]; + result += event.nick; + } + return result; } std::string MUCController::generateJoinPartString(const std::vector& joinParts, bool isImpromptu) { - std::vector sorted[4]; - std::string eventStrings[4]; - foreach (NickJoinPart event, joinParts) { - sorted[event.type].push_back(event); - } - std::string result; - std::vector populatedEvents; - for (size_t i = 0; i < 4; i++) { - std::string names = concatenateListOfNames(sorted[i]); - if (!names.empty()) { - std::string eventString; - switch (i) { - case Join: - if (sorted[i].size() > 1) { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined the chat") : QT_TRANSLATE_NOOP("", "%1% have entered the room")); - } - else { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined the chat") : QT_TRANSLATE_NOOP("", "%1% has entered the room")); - } - break; - case Part: - if (sorted[i].size() > 1) { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% have left the room")); - } - else { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% has left the room")); - } - break; - case JoinThenPart: - if (sorted[i].size() > 1) { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% have entered then left the room")); - } - else { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% has entered then left the room")); - } - break; - case PartThenJoin: - if (sorted[i].size() > 1) { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% have left then returned to the room")); - } - else { - eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% has left then returned to the room")); - } - break; - } - populatedEvents.push_back(static_cast(i)); - eventStrings[i] = str(boost::format(eventString) % names); - } - } - for (size_t i = 0; i < populatedEvents.size(); i++) { - if (i > 0) { - if (i < populatedEvents.size() - 1) { - result += ", "; - } else { - result += QT_TRANSLATE_NOOP("", " and "); - } - } - result += eventStrings[populatedEvents[i]]; - } - return result; + std::vector sorted[4]; + std::string eventStrings[4]; + foreach (NickJoinPart event, joinParts) { + sorted[event.type].push_back(event); + } + std::string result; + std::vector populatedEvents; + for (size_t i = 0; i < 4; i++) { + std::string names = concatenateListOfNames(sorted[i]); + if (!names.empty()) { + std::string eventString; + switch (i) { + case Join: + if (sorted[i].size() > 1) { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined the chat") : QT_TRANSLATE_NOOP("", "%1% have entered the room")); + } + else { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined the chat") : QT_TRANSLATE_NOOP("", "%1% has entered the room")); + } + break; + case Part: + if (sorted[i].size() > 1) { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% have left the room")); + } + else { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left the chat") : QT_TRANSLATE_NOOP("", "%1% has left the room")); + } + break; + case JoinThenPart: + if (sorted[i].size() > 1) { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% have entered then left the room")); + } + else { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has joined then left the chat") : QT_TRANSLATE_NOOP("", "%1% has entered then left the room")); + } + break; + case PartThenJoin: + if (sorted[i].size() > 1) { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% have left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% have left then returned to the room")); + } + else { + eventString = (isImpromptu ? QT_TRANSLATE_NOOP("", "%1% has left then returned to the chat") : QT_TRANSLATE_NOOP("", "%1% has left then returned to the room")); + } + break; + } + populatedEvents.push_back(static_cast(i)); + eventStrings[i] = str(boost::format(eventString) % names); + } + } + for (size_t i = 0; i < populatedEvents.size(); i++) { + if (i > 0) { + if (i < populatedEvents.size() - 1) { + result += ", "; + } else { + result += QT_TRANSLATE_NOOP("", " and "); + } + } + result += eventStrings[populatedEvents[i]]; + } + return result; } std::string MUCController::generateNicknameChangeString(const std::string& oldNickname, const std::string& newNickname) { - return str(boost::format(QT_TRANSLATE_NOOP("", "%1% is now known as %2%.")) % oldNickname % newNickname); + return str(boost::format(QT_TRANSLATE_NOOP("", "%1% is now known as %2%.")) % oldNickname % newNickname); } void MUCController::handleChangeSubjectRequest(const std::string& subject) { - muc_->changeSubject(subject); + muc_->changeSubject(subject); } void MUCController::handleBookmarkRequest() { - const JID jid = muc_->getJID(); + const JID jid = muc_->getJID(); - // Prepare new bookmark for this room. - MUCBookmark roomBookmark(jid, jid.toBare().toString()); - roomBookmark.setPassword(password_); - roomBookmark.setNick(nick_); + // Prepare new bookmark for this room. + MUCBookmark roomBookmark(jid, jid.toBare().toString()); + roomBookmark.setPassword(password_); + roomBookmark.setNick(nick_); - // Check for existing bookmark for this room and, if it exists, use it instead. - std::vector bookmarks = mucBookmarkManager_->getBookmarks(); - foreach (const MUCBookmark& bookmark, bookmarks) { - if (bookmark.getRoom() == jid.toBare()) { - roomBookmark = bookmark; - break; - } - } + // Check for existing bookmark for this room and, if it exists, use it instead. + std::vector bookmarks = mucBookmarkManager_->getBookmarks(); + foreach (const MUCBookmark& bookmark, bookmarks) { + if (bookmark.getRoom() == jid.toBare()) { + roomBookmark = bookmark; + break; + } + } - chatWindow_->showBookmarkWindow(roomBookmark); + chatWindow_->showBookmarkWindow(roomBookmark); } void MUCController::handleConfigureRequest(Form::ref form) { - if (form) { - muc_->configureRoom(form); - } - else { - muc_->requestConfigurationForm(); - } + if (form) { + muc_->configureRoom(form); + } + else { + muc_->requestConfigurationForm(); + } } void MUCController::handleConfigurationFailed(ErrorPayload::ref error) { - std::string errorMessage = getErrorMessage(error); - errorMessage = str(format(QT_TRANSLATE_NOOP("", "Room configuration failed: %1%.")) % errorMessage); - chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); + std::string errorMessage = getErrorMessage(error); + errorMessage = str(format(QT_TRANSLATE_NOOP("", "Room configuration failed: %1%.")) % errorMessage); + chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); } void MUCController::handleOccupantRoleChangeFailed(ErrorPayload::ref error, const JID&, MUCOccupant::Role) { - std::string errorMessage = getErrorMessage(error); - errorMessage = str(format(QT_TRANSLATE_NOOP("", "Occupant role change failed: %1%.")) % errorMessage); - chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); + std::string errorMessage = getErrorMessage(error); + errorMessage = str(format(QT_TRANSLATE_NOOP("", "Occupant role change failed: %1%.")) % errorMessage); + chatWindow_->addErrorMessage(chatMessageParser_->parseMessageBody(errorMessage)); } void MUCController::configureAsImpromptuRoom(Form::ref form) { - muc_->configureRoom(buildImpromptuRoomConfiguration(form)); - isImpromptuAlreadyConfigured_ = true; - onImpromptuConfigCompleted(); + muc_->configureRoom(buildImpromptuRoomConfiguration(form)); + isImpromptuAlreadyConfigured_ = true; + onImpromptuConfigCompleted(); } void MUCController::handleConfigurationFormReceived(Form::ref form) { - if (isImpromptu_) { - if (!isImpromptuAlreadyConfigured_) { - configureAsImpromptuRoom(form); - } - } else { - chatWindow_->showRoomConfigurationForm(form); - } + if (isImpromptu_) { + if (!isImpromptuAlreadyConfigured_) { + configureAsImpromptuRoom(form); + } + } else { + chatWindow_->showRoomConfigurationForm(form); + } } void MUCController::handleConfigurationCancelled() { - muc_->cancelConfigureRoom(); + muc_->cancelConfigureRoom(); } void MUCController::handleDestroyRoomRequest() { - muc_->destroyRoom(); + muc_->destroyRoom(); } void MUCController::handleInvitePersonToThisMUCRequest(const std::vector& jidsToInvite) { - RequestInviteToMUCUIEvent::ImpromptuMode mode = isImpromptu_ ? RequestInviteToMUCUIEvent::Impromptu : RequestInviteToMUCUIEvent::NotImpromptu; - boost::shared_ptr event(new RequestInviteToMUCUIEvent(muc_->getJID(), jidsToInvite, mode)); - eventStream_->send(event); + RequestInviteToMUCUIEvent::ImpromptuMode mode = isImpromptu_ ? RequestInviteToMUCUIEvent::Impromptu : RequestInviteToMUCUIEvent::NotImpromptu; + boost::shared_ptr event(new RequestInviteToMUCUIEvent(muc_->getJID(), jidsToInvite, mode)); + eventStream_->send(event); } void MUCController::handleUIEvent(boost::shared_ptr event) { - boost::shared_ptr inviteEvent = boost::dynamic_pointer_cast(event); - if (inviteEvent && inviteEvent->getRoom() == muc_->getJID()) { - foreach (const JID& jid, inviteEvent->getInvites()) { - muc_->invitePerson(jid, inviteEvent->getReason(), isImpromptu_); - } - } + boost::shared_ptr inviteEvent = boost::dynamic_pointer_cast(event); + if (inviteEvent && inviteEvent->getRoom() == muc_->getJID()) { + foreach (const JID& jid, inviteEvent->getInvites()) { + muc_->invitePerson(jid, inviteEvent->getReason(), isImpromptu_); + } + } } void MUCController::handleGetAffiliationsRequest() { - muc_->requestAffiliationList(MUCOccupant::Owner); - muc_->requestAffiliationList(MUCOccupant::Admin); - muc_->requestAffiliationList(MUCOccupant::Member); - muc_->requestAffiliationList(MUCOccupant::Outcast); + muc_->requestAffiliationList(MUCOccupant::Owner); + muc_->requestAffiliationList(MUCOccupant::Admin); + muc_->requestAffiliationList(MUCOccupant::Member); + muc_->requestAffiliationList(MUCOccupant::Outcast); } typedef std::pair AffiliationChangePair; void MUCController::handleChangeAffiliationsRequest(const std::vector >& changes) { - std::set addedJIDs; - foreach (const AffiliationChangePair& change, changes) { - if (change.first != MUCOccupant::NoAffiliation) { - addedJIDs.insert(change.second); - } - } - foreach (const AffiliationChangePair& change, changes) { - if (change.first != MUCOccupant::NoAffiliation || addedJIDs.find(change.second) == addedJIDs.end()) { - muc_->changeAffiliation(change.second, change.first); - } - } + std::set addedJIDs; + foreach (const AffiliationChangePair& change, changes) { + if (change.first != MUCOccupant::NoAffiliation) { + addedJIDs.insert(change.second); + } + } + foreach (const AffiliationChangePair& change, changes) { + if (change.first != MUCOccupant::NoAffiliation || addedJIDs.find(change.second) == addedJIDs.end()) { + muc_->changeAffiliation(change.second, change.first); + } + } } void MUCController::handleUnblockUserRequest() { - eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Unblocked, muc_->getJID())); + eventStream_->send(boost::make_shared(RequestChangeBlockStateUIEvent::Unblocked, muc_->getJID())); } void MUCController::handleBlockingStateChanged() { - boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); - if (blockList->getState() == BlockList::Available) { - if (blockList->isBlocked(toJID_)) { - if (!blockedContactAlert_) { - blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again")); - } - chatWindow_->setBlockingState(ChatWindow::IsBlocked); - } else { - if (blockedContactAlert_) { - chatWindow_->removeAlert(*blockedContactAlert_); - blockedContactAlert_.reset(); - } - chatWindow_->setBlockingState(ChatWindow::IsUnblocked); - } - } + boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); + if (blockList->getState() == BlockList::Available) { + if (blockList->isBlocked(toJID_)) { + if (!blockedContactAlert_) { + blockedContactAlert_ = chatWindow_->addAlert(QT_TRANSLATE_NOOP("", "You've blocked this room. To enter the room, first unblock it using the cog menu and try again")); + } + chatWindow_->setBlockingState(ChatWindow::IsBlocked); + } else { + if (blockedContactAlert_) { + chatWindow_->removeAlert(*blockedContactAlert_); + blockedContactAlert_.reset(); + } + chatWindow_->setBlockingState(ChatWindow::IsUnblocked); + } + } } void MUCController::handleAffiliationListReceived(MUCOccupant::Affiliation affiliation, const std::vector& jids) { - chatWindow_->setAffiliations(affiliation, jids); + chatWindow_->setAffiliations(affiliation, jids); } void MUCController::logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) { - // log only incoming messages - if (isIncoming && historyController_) { - historyController_->addMessage(message, fromJID, toJID, HistoryMessage::Groupchat, timeStamp); - } + // log only incoming messages + if (isIncoming && historyController_) { + historyController_->addMessage(message, fromJID, toJID, HistoryMessage::Groupchat, timeStamp); + } } void MUCController::addRecentLogs() { - if (!historyController_) { - return; - } + if (!historyController_) { + return; + } - joinContext_ = historyController_->getMUCContext(selfJID_, toJID_, lastActivity_); + joinContext_ = historyController_->getMUCContext(selfJID_, toJID_, lastActivity_); - foreach (const HistoryMessage& message, joinContext_) { - bool senderIsSelf = nick_ == message.getFromJID().getResource(); + foreach (const HistoryMessage& message, joinContext_) { + bool senderIsSelf = nick_ == message.getFromJID().getResource(); - // the chatWindow uses utc timestamps - addMessage(chatMessageParser_->parseMessageBody(message.getMessage()), senderDisplayNameFromMessage(message.getFromJID()), senderIsSelf, boost::shared_ptr(new SecurityLabel()), avatarManager_->getAvatarPath(message.getFromJID()), message.getTime() - boost::posix_time::hours(message.getOffset())); - } + // the chatWindow uses utc timestamps + addMessage(chatMessageParser_->parseMessageBody(message.getMessage()), senderDisplayNameFromMessage(message.getFromJID()), senderIsSelf, boost::shared_ptr(new SecurityLabel()), avatarManager_->getAvatarPath(message.getFromJID()), message.getTime() - boost::posix_time::hours(message.getOffset())); + } } void MUCController::checkDuplicates(boost::shared_ptr newMessage) { - std::string body = newMessage->getBody().get_value_or(""); - JID jid = newMessage->getFrom(); - boost::optional time = newMessage->getTimestamp(); - - reverse_foreach (const HistoryMessage& message, joinContext_) { - boost::posix_time::ptime messageTime = message.getTime() - boost::posix_time::hours(message.getOffset()); - if (time && time < messageTime) { - break; - } - if (time && time != messageTime) { - continue; - } - if (message.getFromJID() != jid) { - continue; - } - if (message.getMessage() != body) { - continue; - } - - // Mark the message as unreadable - newMessage->setBody(""); - } + std::string body = newMessage->getBody().get_value_or(""); + JID jid = newMessage->getFrom(); + boost::optional time = newMessage->getTimestamp(); + + reverse_foreach (const HistoryMessage& message, joinContext_) { + boost::posix_time::ptime messageTime = message.getTime() - boost::posix_time::hours(message.getOffset()); + if (time && time < messageTime) { + break; + } + if (time && time != messageTime) { + continue; + } + if (message.getFromJID() != jid) { + continue; + } + if (message.getMessage() != body) { + continue; + } + + // Mark the message as unreadable + newMessage->setBody(""); + } } void MUCController::setNick(const std::string& nick) { - nick_ = nick; - highlighter_->setNick(nick_); + nick_ = nick; + highlighter_->setNick(nick_); } Form::ref MUCController::buildImpromptuRoomConfiguration(Form::ref roomConfigurationForm) { - Form::ref result = boost::make_shared(Form::SubmitType); - std::string impromptuConfigs[] = { "muc#roomconfig_enablelogging", "muc#roomconfig_persistentroom", "muc#roomconfig_publicroom", "muc#roomconfig_whois"}; - std::set impromptuConfigsMissing(impromptuConfigs, impromptuConfigs + 4); - foreach (boost::shared_ptr field, roomConfigurationForm->getFields()) { - boost::shared_ptr resultField; - if (field->getName() == "muc#roomconfig_enablelogging") { - resultField = boost::make_shared(FormField::BooleanType, "0"); - } - if (field->getName() == "muc#roomconfig_persistentroom") { - resultField = boost::make_shared(FormField::BooleanType, "0"); - } - if (field->getName() == "muc#roomconfig_publicroom") { - resultField = boost::make_shared(FormField::BooleanType, "0"); - } - if (field->getName() == "muc#roomconfig_whois") { - resultField = boost::make_shared(FormField::ListSingleType, "anyone"); - } - - if (field->getName() == "FORM_TYPE") { - resultField = boost::make_shared(FormField::HiddenType, "http://jabber.org/protocol/muc#roomconfig"); - } - - if (resultField) { - impromptuConfigsMissing.erase(field->getName()); - resultField->setName(field->getName()); - result->addField(resultField); - } - } - - foreach (const std::string& config, impromptuConfigsMissing) { - if (config == "muc#roomconfig_publicroom") { - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support hiding your chat from other users.")), ChatWindow::DefaultDirection); - } else if (config == "muc#roomconfig_whois") { - chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support sharing people's real identity in this chat.")), ChatWindow::DefaultDirection); - } - } - - return result; + Form::ref result = boost::make_shared(Form::SubmitType); + std::string impromptuConfigs[] = { "muc#roomconfig_enablelogging", "muc#roomconfig_persistentroom", "muc#roomconfig_publicroom", "muc#roomconfig_whois"}; + std::set impromptuConfigsMissing(impromptuConfigs, impromptuConfigs + 4); + foreach (boost::shared_ptr field, roomConfigurationForm->getFields()) { + boost::shared_ptr resultField; + if (field->getName() == "muc#roomconfig_enablelogging") { + resultField = boost::make_shared(FormField::BooleanType, "0"); + } + if (field->getName() == "muc#roomconfig_persistentroom") { + resultField = boost::make_shared(FormField::BooleanType, "0"); + } + if (field->getName() == "muc#roomconfig_publicroom") { + resultField = boost::make_shared(FormField::BooleanType, "0"); + } + if (field->getName() == "muc#roomconfig_whois") { + resultField = boost::make_shared(FormField::ListSingleType, "anyone"); + } + + if (field->getName() == "FORM_TYPE") { + resultField = boost::make_shared(FormField::HiddenType, "http://jabber.org/protocol/muc#roomconfig"); + } + + if (resultField) { + impromptuConfigsMissing.erase(field->getName()); + resultField->setName(field->getName()); + result->addField(resultField); + } + } + + foreach (const std::string& config, impromptuConfigsMissing) { + if (config == "muc#roomconfig_publicroom") { + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support hiding your chat from other users.")), ChatWindow::DefaultDirection); + } else if (config == "muc#roomconfig_whois") { + chatWindow_->addSystemMessage(chatMessageParser_->parseMessageBody(QT_TRANSLATE_NOOP("", "This server doesn't support sharing people's real identity in this chat.")), ChatWindow::DefaultDirection); + } + } + + return result; } void MUCController::setImpromptuWindowTitle() { - std::string title; - typedef std::pair StringMUCOccupantPair; - std::map occupants = muc_->getOccupants(); - if (occupants.size() <= 1) { - title = QT_TRANSLATE_NOOP("", "Empty Chat"); - } else { - foreach (StringMUCOccupantPair pair, occupants) { - if (pair.first != nick_) { - title += (title.empty() ? "" : ", ") + pair.first; - } - } - } - chatWindow_->setName(title); + std::string title; + typedef std::pair StringMUCOccupantPair; + std::map occupants = muc_->getOccupants(); + if (occupants.size() <= 1) { + title = QT_TRANSLATE_NOOP("", "Empty Chat"); + } else { + foreach (StringMUCOccupantPair pair, occupants) { + if (pair.first != nick_) { + title += (title.empty() ? "" : ", ") + pair.first; + } + } + } + chatWindow_->setName(title); } void MUCController::handleRoomUnlocked() { - // Handle buggy MUC implementations where the joined room already exists and is unlocked. - // Configure the room again in this case. - if (!isImpromptuAlreadyConfigured_) { - if (isImpromptu_ && (muc_->getOccupant(nick_).getAffiliation() == MUCOccupant::Owner)) { - muc_->requestConfigurationForm(); - } else if (isImpromptu_) { - onImpromptuConfigCompleted(); - } - } + // Handle buggy MUC implementations where the joined room already exists and is unlocked. + // Configure the room again in this case. + if (!isImpromptuAlreadyConfigured_) { + if (isImpromptu_ && (muc_->getOccupant(nick_).getAffiliation() == MUCOccupant::Owner)) { + muc_->requestConfigurationForm(); + } else if (isImpromptu_) { + onImpromptuConfigCompleted(); + } + } } void MUCController::setAvailableServerFeatures(boost::shared_ptr info) { - ChatControllerBase::setAvailableServerFeatures(info); - if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) { - boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); + ChatControllerBase::setAvailableServerFeatures(info); + if (iqRouter_->isAvailable() && info->hasFeature(DiscoInfo::BlockingCommandFeature)) { + boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); - blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&MUCController::handleBlockingStateChanged, this)); - blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&MUCController::handleBlockingStateChanged, this)); - blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&MUCController::handleBlockingStateChanged, this)); + blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&MUCController::handleBlockingStateChanged, this)); + blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&MUCController::handleBlockingStateChanged, this)); + blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&MUCController::handleBlockingStateChanged, this)); - handleBlockingStateChanged(); - } + handleBlockingStateChanged(); + } } void MUCController::handleMUCBookmarkAdded(const MUCBookmark& bookmark) { - if (bookmark.getRoom() == muc_->getJID()) { - updateChatWindowBookmarkStatus(bookmark); - } + if (bookmark.getRoom() == muc_->getJID()) { + updateChatWindowBookmarkStatus(bookmark); + } } void MUCController::handleMUCBookmarkRemoved(const MUCBookmark& bookmark) { - if (bookmark.getRoom() == muc_->getJID()) { - updateChatWindowBookmarkStatus(boost::optional()); - } + if (bookmark.getRoom() == muc_->getJID()) { + updateChatWindowBookmarkStatus(boost::optional()); + } } void MUCController::updateChatWindowBookmarkStatus(const boost::optional& bookmark) { - assert(chatWindow_); - if (bookmark) { - if (bookmark->getAutojoin()) { - chatWindow_->setBookmarkState(ChatWindow::RoomAutoJoined); - } - else { - chatWindow_->setBookmarkState(ChatWindow::RoomBookmarked); - } - } - else { - chatWindow_->setBookmarkState(ChatWindow::RoomNotBookmarked); - } + assert(chatWindow_); + if (bookmark) { + if (bookmark->getAutojoin()) { + chatWindow_->setBookmarkState(ChatWindow::RoomAutoJoined); + } + else { + chatWindow_->setBookmarkState(ChatWindow::RoomBookmarked); + } + } + else { + chatWindow_->setBookmarkState(ChatWindow::RoomNotBookmarked); + } } } diff --git a/Swift/Controllers/Chat/MUCController.h b/Swift/Controllers/Chat/MUCController.h index 0fb739a..3a61952 100644 --- a/Swift/Controllers/Chat/MUCController.h +++ b/Swift/Controllers/Chat/MUCController.h @@ -27,159 +27,159 @@ #include namespace Swift { - class StanzaChannel; - class IQRouter; - class ChatWindowFactory; - class Roster; - class AvatarManager; - class UIEventStream; - class TimerFactory; - class TabComplete; - class XMPPRoster; - class HighlightManager; - class UIEvent; - class VCardManager; - class RosterVCardProvider; - class ClientBlockListManager; - class MUCBookmarkManager; - class MUCBookmark; - - enum JoinPart {Join, Part, JoinThenPart, PartThenJoin}; - - struct NickJoinPart { - NickJoinPart(const std::string& nick, JoinPart type) : nick(nick), type(type) {} - std::string nick; - JoinPart type; - }; - - class MUCController : public ChatControllerBase { - public: - MUCController(const JID& self, MUC::ref muc, const boost::optional& password, const std::string &nick, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, PresenceOracle* presenceOracle, AvatarManager* avatarManager, UIEventStream* events, bool useDelayForLatency, TimerFactory* timerFactory, EventController* eventController, EntityCapsProvider* entityCapsProvider, XMPPRoster* roster, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr chatMessageParser, bool isImpromptu, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider, VCardManager* vcardManager, MUCBookmarkManager* mucBookmarkManager); - virtual ~MUCController(); - boost::signal onUserLeft; - boost::signal onUserJoined; - boost::signal onImpromptuConfigCompleted; - boost::signal onUserNicknameChanged; - virtual void setOnline(bool online) SWIFTEN_OVERRIDE; - virtual void setAvailableServerFeatures(boost::shared_ptr info) SWIFTEN_OVERRIDE; - void rejoin(); - static void appendToJoinParts(std::vector& joinParts, const NickJoinPart& newEvent); - static std::string generateJoinPartString(const std::vector& joinParts, bool isImpromptu); - static std::string concatenateListOfNames(const std::vector& joinParts); - static std::string generateNicknameChangeString(const std::string& oldNickname, const std::string& newNickname); - bool isJoined(); - const std::string& getNick(); - const boost::optional getPassword() const; - bool isImpromptu() const; - std::map getParticipantJIDs() const; - void sendInvites(const std::vector& jids, const std::string& reason) const; - - protected: - virtual void preSendMessageRequest(boost::shared_ptr message) SWIFTEN_OVERRIDE; - virtual bool isIncomingMessageFromMe(boost::shared_ptr message) SWIFTEN_OVERRIDE; - virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; - virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; - virtual boost::optional getMessageTimestamp(boost::shared_ptr message) const SWIFTEN_OVERRIDE; - virtual void preHandleIncomingMessage(boost::shared_ptr) SWIFTEN_OVERRIDE; - virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr label, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE; - virtual void postHandleIncomingMessage(boost::shared_ptr, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE; - virtual void cancelReplaces() SWIFTEN_OVERRIDE; - virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE; - - private: - void setAvailableRoomActions(const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Role& role); - void clearPresenceQueue(); - void addPresenceMessage(const std::string& message); - void handleWindowOccupantSelectionChanged(ContactRosterItem* item); - void handleActionRequestedOnOccupant(ChatWindow::OccupantAction, ContactRosterItem* item); - void handleWindowClosed(); - void handleAvatarChanged(const JID& jid); - void handleOccupantJoined(const MUCOccupant& occupant); - void handleOccupantNicknameChanged(const std::string& oldNickname, const std::string& newNickname); - void handleOccupantLeft(const MUCOccupant& occupant, MUC::LeavingType type, const std::string& reason); - void handleOccupantPresenceChange(boost::shared_ptr presence); - void handleOccupantRoleChanged(const std::string& nick, const MUCOccupant& occupant,const MUCOccupant::Role& oldRole); - void handleOccupantAffiliationChanged(const std::string& nick, const MUCOccupant::Affiliation& affiliation,const MUCOccupant::Affiliation& oldAffiliation); - void handleJoinComplete(const std::string& nick); - void handleJoinFailed(boost::shared_ptr error); - void handleJoinTimeoutTick(); - void handleChangeSubjectRequest(const std::string&); - void handleBookmarkRequest(); - std::string roleToGroupName(MUCOccupant::Role role); - std::string roleToSortName(MUCOccupant::Role role); - JID nickToJID(const std::string& nick); - std::string roleToFriendlyName(MUCOccupant::Role role); - void receivedActivity(); - bool messageTargetsMe(boost::shared_ptr message); - void updateJoinParts(); - bool shouldUpdateJoinParts(); - virtual void dayTicked() SWIFTEN_OVERRIDE { clearPresenceQueue(); } - void processUserPart(); - virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE; - void handleConfigureRequest(Form::ref); - void handleConfigurationFailed(ErrorPayload::ref); - void handleConfigurationFormReceived(Form::ref); - void handleDestroyRoomRequest(); - void handleInvitePersonToThisMUCRequest(const std::vector& jidsToInvite); - void handleConfigurationCancelled(); - void handleOccupantRoleChangeFailed(ErrorPayload::ref, const JID&, MUCOccupant::Role); - void handleGetAffiliationsRequest(); - void handleAffiliationListReceived(MUCOccupant::Affiliation affiliation, const std::vector& jids); - void handleChangeAffiliationsRequest(const std::vector >& changes); - void handleInviteToMUCWindowDismissed(); - void handleInviteToMUCWindowCompleted(); - void handleUIEvent(boost::shared_ptr event); - void addRecentLogs(); - void checkDuplicates(boost::shared_ptr newMessage); - void setNick(const std::string& nick); - void setImpromptuWindowTitle(); - void handleRoomUnlocked(); - void configureAsImpromptuRoom(Form::ref form); - Form::ref buildImpromptuRoomConfiguration(Form::ref roomConfigurationForm); - - void handleUnblockUserRequest(); - void handleBlockingStateChanged(); - - void handleMUCBookmarkAdded(const MUCBookmark& bookmark); - void handleMUCBookmarkRemoved(const MUCBookmark& bookmark); - void updateChatWindowBookmarkStatus(const boost::optional& bookmark); - - private: - MUC::ref muc_; - UIEventStream* events_; - std::string nick_; - std::string desiredNick_; - Roster* roster_; - TabComplete* completer_; - bool parting_; - bool joined_; - bool lastWasPresence_; - bool shouldJoinOnReconnect_; - bool doneGettingHistory_; - boost::bsignals::scoped_connection avatarChangedConnection_; - boost::shared_ptr loginCheckTimer_; - std::set currentOccupants_; - std::vector joinParts_; - boost::posix_time::ptime lastActivity_; - boost::optional password_; - XMPPRoster* xmppRoster_; - std::vector joinContext_; - size_t renameCounter_; - bool isImpromptu_; - bool isImpromptuAlreadyConfigured_; - RosterVCardProvider* rosterVCardProvider_; - std::string lastJoinMessageUID_; - - ClientBlockListManager* clientBlockListManager_; - boost::bsignals::scoped_connection blockingOnStateChangedConnection_; - boost::bsignals::scoped_connection blockingOnItemAddedConnection_; - boost::bsignals::scoped_connection blockingOnItemRemovedConnection_; - - boost::optional blockedContactAlert_; - - MUCBookmarkManager* mucBookmarkManager_; - boost::bsignals::scoped_connection mucBookmarkManagerBookmarkAddedConnection_; - boost::bsignals::scoped_connection mucBookmarkManagerBookmarkRemovedConnection_; - }; + class StanzaChannel; + class IQRouter; + class ChatWindowFactory; + class Roster; + class AvatarManager; + class UIEventStream; + class TimerFactory; + class TabComplete; + class XMPPRoster; + class HighlightManager; + class UIEvent; + class VCardManager; + class RosterVCardProvider; + class ClientBlockListManager; + class MUCBookmarkManager; + class MUCBookmark; + + enum JoinPart {Join, Part, JoinThenPart, PartThenJoin}; + + struct NickJoinPart { + NickJoinPart(const std::string& nick, JoinPart type) : nick(nick), type(type) {} + std::string nick; + JoinPart type; + }; + + class MUCController : public ChatControllerBase { + public: + MUCController(const JID& self, MUC::ref muc, const boost::optional& password, const std::string &nick, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, PresenceOracle* presenceOracle, AvatarManager* avatarManager, UIEventStream* events, bool useDelayForLatency, TimerFactory* timerFactory, EventController* eventController, EntityCapsProvider* entityCapsProvider, XMPPRoster* roster, HistoryController* historyController, MUCRegistry* mucRegistry, HighlightManager* highlightManager, ClientBlockListManager* clientBlockListManager, boost::shared_ptr chatMessageParser, bool isImpromptu, AutoAcceptMUCInviteDecider* autoAcceptMUCInviteDecider, VCardManager* vcardManager, MUCBookmarkManager* mucBookmarkManager); + virtual ~MUCController(); + boost::signal onUserLeft; + boost::signal onUserJoined; + boost::signal onImpromptuConfigCompleted; + boost::signal onUserNicknameChanged; + virtual void setOnline(bool online) SWIFTEN_OVERRIDE; + virtual void setAvailableServerFeatures(boost::shared_ptr info) SWIFTEN_OVERRIDE; + void rejoin(); + static void appendToJoinParts(std::vector& joinParts, const NickJoinPart& newEvent); + static std::string generateJoinPartString(const std::vector& joinParts, bool isImpromptu); + static std::string concatenateListOfNames(const std::vector& joinParts); + static std::string generateNicknameChangeString(const std::string& oldNickname, const std::string& newNickname); + bool isJoined(); + const std::string& getNick(); + const boost::optional getPassword() const; + bool isImpromptu() const; + std::map getParticipantJIDs() const; + void sendInvites(const std::vector& jids, const std::string& reason) const; + + protected: + virtual void preSendMessageRequest(boost::shared_ptr message) SWIFTEN_OVERRIDE; + virtual bool isIncomingMessageFromMe(boost::shared_ptr message) SWIFTEN_OVERRIDE; + virtual std::string senderHighlightNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; + virtual std::string senderDisplayNameFromMessage(const JID& from) SWIFTEN_OVERRIDE; + virtual boost::optional getMessageTimestamp(boost::shared_ptr message) const SWIFTEN_OVERRIDE; + virtual void preHandleIncomingMessage(boost::shared_ptr) SWIFTEN_OVERRIDE; + virtual void addMessageHandleIncomingMessage(const JID& from, const ChatWindow::ChatMessage& message, bool senderIsSelf, boost::shared_ptr label, const boost::posix_time::ptime& time) SWIFTEN_OVERRIDE; + virtual void postHandleIncomingMessage(boost::shared_ptr, const ChatWindow::ChatMessage& chatMessage) SWIFTEN_OVERRIDE; + virtual void cancelReplaces() SWIFTEN_OVERRIDE; + virtual void logMessage(const std::string& message, const JID& fromJID, const JID& toJID, const boost::posix_time::ptime& timeStamp, bool isIncoming) SWIFTEN_OVERRIDE; + + private: + void setAvailableRoomActions(const MUCOccupant::Affiliation& affiliation, const MUCOccupant::Role& role); + void clearPresenceQueue(); + void addPresenceMessage(const std::string& message); + void handleWindowOccupantSelectionChanged(ContactRosterItem* item); + void handleActionRequestedOnOccupant(ChatWindow::OccupantAction, ContactRosterItem* item); + void handleWindowClosed(); + void handleAvatarChanged(const JID& jid); + void handleOccupantJoined(const MUCOccupant& occupant); + void handleOccupantNicknameChanged(const std::string& oldNickname, const std::string& newNickname); + void handleOccupantLeft(const MUCOccupant& occupant, MUC::LeavingType type, const std::string& reason); + void handleOccupantPresenceChange(boost::shared_ptr presence); + void handleOccupantRoleChanged(const std::string& nick, const MUCOccupant& occupant,const MUCOccupant::Role& oldRole); + void handleOccupantAffiliationChanged(const std::string& nick, const MUCOccupant::Affiliation& affiliation,const MUCOccupant::Affiliation& oldAffiliation); + void handleJoinComplete(const std::string& nick); + void handleJoinFailed(boost::shared_ptr error); + void handleJoinTimeoutTick(); + void handleChangeSubjectRequest(const std::string&); + void handleBookmarkRequest(); + std::string roleToGroupName(MUCOccupant::Role role); + std::string roleToSortName(MUCOccupant::Role role); + JID nickToJID(const std::string& nick); + std::string roleToFriendlyName(MUCOccupant::Role role); + void receivedActivity(); + bool messageTargetsMe(boost::shared_ptr message); + void updateJoinParts(); + bool shouldUpdateJoinParts(); + virtual void dayTicked() SWIFTEN_OVERRIDE { clearPresenceQueue(); } + void processUserPart(); + virtual void handleBareJIDCapsChanged(const JID& jid) SWIFTEN_OVERRIDE; + void handleConfigureRequest(Form::ref); + void handleConfigurationFailed(ErrorPayload::ref); + void handleConfigurationFormReceived(Form::ref); + void handleDestroyRoomRequest(); + void handleInvitePersonToThisMUCRequest(const std::vector& jidsToInvite); + void handleConfigurationCancelled(); + void handleOccupantRoleChangeFailed(ErrorPayload::ref, const JID&, MUCOccupant::Role); + void handleGetAffiliationsRequest(); + void handleAffiliationListReceived(MUCOccupant::Affiliation affiliation, const std::vector& jids); + void handleChangeAffiliationsRequest(const std::vector >& changes); + void handleInviteToMUCWindowDismissed(); + void handleInviteToMUCWindowCompleted(); + void handleUIEvent(boost::shared_ptr event); + void addRecentLogs(); + void checkDuplicates(boost::shared_ptr newMessage); + void setNick(const std::string& nick); + void setImpromptuWindowTitle(); + void handleRoomUnlocked(); + void configureAsImpromptuRoom(Form::ref form); + Form::ref buildImpromptuRoomConfiguration(Form::ref roomConfigurationForm); + + void handleUnblockUserRequest(); + void handleBlockingStateChanged(); + + void handleMUCBookmarkAdded(const MUCBookmark& bookmark); + void handleMUCBookmarkRemoved(const MUCBookmark& bookmark); + void updateChatWindowBookmarkStatus(const boost::optional& bookmark); + + private: + MUC::ref muc_; + UIEventStream* events_; + std::string nick_; + std::string desiredNick_; + Roster* roster_; + TabComplete* completer_; + bool parting_; + bool joined_; + bool lastWasPresence_; + bool shouldJoinOnReconnect_; + bool doneGettingHistory_; + boost::bsignals::scoped_connection avatarChangedConnection_; + boost::shared_ptr loginCheckTimer_; + std::set currentOccupants_; + std::vector joinParts_; + boost::posix_time::ptime lastActivity_; + boost::optional password_; + XMPPRoster* xmppRoster_; + std::vector joinContext_; + size_t renameCounter_; + bool isImpromptu_; + bool isImpromptuAlreadyConfigured_; + RosterVCardProvider* rosterVCardProvider_; + std::string lastJoinMessageUID_; + + ClientBlockListManager* clientBlockListManager_; + boost::bsignals::scoped_connection blockingOnStateChangedConnection_; + boost::bsignals::scoped_connection blockingOnItemAddedConnection_; + boost::bsignals::scoped_connection blockingOnItemRemovedConnection_; + + boost::optional blockedContactAlert_; + + MUCBookmarkManager* mucBookmarkManager_; + boost::bsignals::scoped_connection mucBookmarkManagerBookmarkAddedConnection_; + boost::bsignals::scoped_connection mucBookmarkManagerBookmarkRemovedConnection_; + }; } diff --git a/Swift/Controllers/Chat/MUCSearchController.cpp b/Swift/Controllers/Chat/MUCSearchController.cpp index 702a366..884978c 100644 --- a/Swift/Controllers/Chat/MUCSearchController.cpp +++ b/Swift/Controllers/Chat/MUCSearchController.cpp @@ -26,159 +26,159 @@ namespace Swift { static const std::string SEARCHED_SERVICES = "searchedServices"; MUCSearchController::MUCSearchController(const JID& jid, MUCSearchWindowFactory* factory, IQRouter* iqRouter, ProfileSettingsProvider* settings) : jid_(jid), factory_(factory), iqRouter_(iqRouter), settings_(settings), window_(NULL), walker_(NULL) { - itemsInProgress_ = 0; - loadSavedServices(); + itemsInProgress_ = 0; + loadSavedServices(); } MUCSearchController::~MUCSearchController() { - delete walker_; - delete window_; + delete walker_; + delete window_; } void MUCSearchController::openSearchWindow() { - if (!window_) { - window_ = factory_->createMUCSearchWindow(); - window_->onSearchService.connect(boost::bind(&MUCSearchController::handleSearchService, this, _1)); - window_->onFinished.connect(boost::bind(&MUCSearchController::handleMUCSearchFinished, this, _1)); - window_->addSavedServices(savedServices_); - } - handleSearchService(JID(jid_.getDomain())); - window_->show(); + if (!window_) { + window_ = factory_->createMUCSearchWindow(); + window_->onSearchService.connect(boost::bind(&MUCSearchController::handleSearchService, this, _1)); + window_->onFinished.connect(boost::bind(&MUCSearchController::handleMUCSearchFinished, this, _1)); + window_->addSavedServices(savedServices_); + } + handleSearchService(JID(jid_.getDomain())); + window_->show(); } void MUCSearchController::loadSavedServices() { - savedServices_.clear(); - foreach (std::string stringItem, String::split(settings_->getStringSetting(SEARCHED_SERVICES), '\n')) { - savedServices_.push_back(JID(stringItem)); - } + savedServices_.clear(); + foreach (std::string stringItem, String::split(settings_->getStringSetting(SEARCHED_SERVICES), '\n')) { + savedServices_.push_back(JID(stringItem)); + } } void MUCSearchController::addToSavedServices(const JID& jid) { - savedServices_.erase(std::remove(savedServices_.begin(), savedServices_.end(), jid), savedServices_.end()); - savedServices_.push_front(jid); - - std::string collapsed; - int i = 0; - foreach (JID jidItem, savedServices_) { - if (i >= 15) { - break; - } - if (!collapsed.empty()) { - collapsed += "\n"; - } - collapsed += jidItem.toString(); - ++i; - } - settings_->storeString(SEARCHED_SERVICES, collapsed); - window_->addSavedServices(savedServices_); + savedServices_.erase(std::remove(savedServices_.begin(), savedServices_.end(), jid), savedServices_.end()); + savedServices_.push_front(jid); + + std::string collapsed; + int i = 0; + foreach (JID jidItem, savedServices_) { + if (i >= 15) { + break; + } + if (!collapsed.empty()) { + collapsed += "\n"; + } + collapsed += jidItem.toString(); + ++i; + } + settings_->storeString(SEARCHED_SERVICES, collapsed); + window_->addSavedServices(savedServices_); } void MUCSearchController::handleSearchService(const JID& jid) { - if (!jid.isValid()) { - //Set Window to say error this isn't valid - return; - } - addToSavedServices(jid); - - services_.clear(); - serviceDetails_.clear(); - - window_->setSearchInProgress(true); - refreshView(); - - if (walker_) { - walker_->endWalk(); - walker_->onServiceFound.disconnect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2)); - walker_->onWalkComplete.disconnect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this)); - delete walker_; - } - - SWIFT_LOG(debug) << "Starting walking MUC services" << std::endl; - itemsInProgress_ = 0; - walker_ = new DiscoServiceWalker(jid, iqRouter_); - walker_->onServiceFound.connect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2)); - walker_->onWalkComplete.connect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this)); - walker_->beginWalk(); + if (!jid.isValid()) { + //Set Window to say error this isn't valid + return; + } + addToSavedServices(jid); + + services_.clear(); + serviceDetails_.clear(); + + window_->setSearchInProgress(true); + refreshView(); + + if (walker_) { + walker_->endWalk(); + walker_->onServiceFound.disconnect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2)); + walker_->onWalkComplete.disconnect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this)); + delete walker_; + } + + SWIFT_LOG(debug) << "Starting walking MUC services" << std::endl; + itemsInProgress_ = 0; + walker_ = new DiscoServiceWalker(jid, iqRouter_); + walker_->onServiceFound.connect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2)); + walker_->onWalkComplete.connect(boost::bind(&MUCSearchController::handleDiscoWalkFinished, this)); + walker_->beginWalk(); } void MUCSearchController::handleDiscoServiceFound(const JID& jid, boost::shared_ptr info) { - bool isMUC = false; - std::string name; - foreach (DiscoInfo::Identity identity, info->getIdentities()) { - if ((identity.getCategory() == "directory" - && identity.getType() == "chatroom") - || (identity.getCategory() == "conference" - && identity.getType() == "text")) { - isMUC = true; - name = identity.getName(); - } - } - if (isMUC) { - SWIFT_LOG(debug) << "MUC Service found: " << jid << std::endl; - services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end()); - services_.push_back(jid); - serviceDetails_[jid].setName(name); - serviceDetails_[jid].setJID(jid); - serviceDetails_[jid].setComplete(false); - itemsInProgress_++; - SWIFT_LOG(debug) << "Requesting items of " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl; - GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(jid, iqRouter_); - discoItemsRequest->onResponse.connect(boost::bind(&MUCSearchController::handleRoomsItemsResponse, this, _1, _2, jid)); - discoItemsRequest->send(); - } - else { - removeService(jid); - } - refreshView(); + bool isMUC = false; + std::string name; + foreach (DiscoInfo::Identity identity, info->getIdentities()) { + if ((identity.getCategory() == "directory" + && identity.getType() == "chatroom") + || (identity.getCategory() == "conference" + && identity.getType() == "text")) { + isMUC = true; + name = identity.getName(); + } + } + if (isMUC) { + SWIFT_LOG(debug) << "MUC Service found: " << jid << std::endl; + services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end()); + services_.push_back(jid); + serviceDetails_[jid].setName(name); + serviceDetails_[jid].setJID(jid); + serviceDetails_[jid].setComplete(false); + itemsInProgress_++; + SWIFT_LOG(debug) << "Requesting items of " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl; + GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(jid, iqRouter_); + discoItemsRequest->onResponse.connect(boost::bind(&MUCSearchController::handleRoomsItemsResponse, this, _1, _2, jid)); + discoItemsRequest->send(); + } + else { + removeService(jid); + } + refreshView(); } void MUCSearchController::handleDiscoWalkFinished() { - SWIFT_LOG(debug) << "MUC Walk finished" << std::endl; - updateInProgressness(); + SWIFT_LOG(debug) << "MUC Walk finished" << std::endl; + updateInProgressness(); } void MUCSearchController::removeService(const JID& jid) { - serviceDetails_.erase(jid); - services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end()); - refreshView(); + serviceDetails_.erase(jid); + services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end()); + refreshView(); } void MUCSearchController::handleRoomsItemsResponse(boost::shared_ptr items, ErrorPayload::ref error, const JID& jid) { - itemsInProgress_--; - SWIFT_LOG(debug) << "Items received for " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl; - updateInProgressness(); - if (error) { - handleDiscoError(jid, error); - return; - } - serviceDetails_[jid].clearRooms(); - foreach (DiscoItems::Item item, items->getItems()) { - serviceDetails_[jid].addRoom(MUCService::MUCRoom(item.getJID().getNode(), item.getName(), -1)); - } - serviceDetails_[jid].setComplete(true); - refreshView(); + itemsInProgress_--; + SWIFT_LOG(debug) << "Items received for " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl; + updateInProgressness(); + if (error) { + handleDiscoError(jid, error); + return; + } + serviceDetails_[jid].clearRooms(); + foreach (DiscoItems::Item item, items->getItems()) { + serviceDetails_[jid].addRoom(MUCService::MUCRoom(item.getJID().getNode(), item.getName(), -1)); + } + serviceDetails_[jid].setComplete(true); + refreshView(); } void MUCSearchController::handleDiscoError(const JID& jid, ErrorPayload::ref error) { - serviceDetails_[jid].setComplete(true); - serviceDetails_[jid].setError(error->getText()); + serviceDetails_[jid].setComplete(true); + serviceDetails_[jid].setError(error->getText()); } void MUCSearchController::refreshView() { - window_->clearList(); - foreach (JID jid, services_) { - window_->addService(serviceDetails_[jid]); - } + window_->clearList(); + foreach (JID jid, services_) { + window_->addService(serviceDetails_[jid]); + } } void MUCSearchController::updateInProgressness() { - window_->setSearchInProgress((walker_ && walker_->isActive()) || itemsInProgress_ > 0); + window_->setSearchInProgress((walker_ && walker_->isActive()) || itemsInProgress_ > 0); } void MUCSearchController::handleMUCSearchFinished(const boost::optional& result) { - if (result) { - onMUCSelected(*result); - } + if (result) { + onMUCSelected(*result); + } } } diff --git a/Swift/Controllers/Chat/MUCSearchController.h b/Swift/Controllers/Chat/MUCSearchController.h index 01bcf74..3d2a2ca 100644 --- a/Swift/Controllers/Chat/MUCSearchController.h +++ b/Swift/Controllers/Chat/MUCSearchController.h @@ -22,103 +22,103 @@ #include namespace Swift { - class UIEventStream; - class MUCSearchWindow; - class MUCSearchWindowFactory; - class IQRouter; - class DiscoServiceWalker; - class NickResolver; - - class MUCService { - public: - class MUCRoom { - public: - MUCRoom(const std::string& node, const std::string& name, int occupants) : node_(node), name_(name), occupants_(occupants) {} - std::string getNode() {return node_;} - std::string getName() {return name_;} - int getOccupantCount() {return occupants_;} - private: - std::string node_; - std::string name_; - int occupants_; - }; - - MUCService() {error_ = false; complete_ = false;} - - void setComplete(bool complete) { - complete_ = complete; - } - - void setName(const std::string& name) { - name_ = name; - } - - void setJID(const JID& jid) { - jid_ = jid; - } - - bool getComplete() const { - return complete_; - } - - JID getJID() const { - return jid_; - } - - std::string getName() const { - return name_; - } - - void setError(const std::string& errorText) {error_ = true; errorText_ = errorText;} - - void clearRooms() {rooms_.clear();} - - void addRoom(const MUCRoom& room) {rooms_.push_back(room);} - - std::vector getRooms() const {return rooms_;} - private: - std::string name_; - JID jid_; - std::vector rooms_; - bool complete_; - bool error_; - std::string errorText_; - }; - - class MUCSearchController { - public: - MUCSearchController(const JID& jid, MUCSearchWindowFactory* mucSearchWindowFactory, IQRouter* iqRouter, ProfileSettingsProvider* settings); - ~MUCSearchController(); - - void openSearchWindow(); - - public: - boost::signal onMUCSelected; - - private: - void handleSearchService(const JID& jid); - void handleRoomsItemsResponse(boost::shared_ptr items, ErrorPayload::ref error, const JID& jid); - void handleDiscoError(const JID& jid, ErrorPayload::ref error); - void handleDiscoServiceFound(const JID&, boost::shared_ptr); - void handleDiscoWalkFinished(); - void handleMUCSearchFinished(const boost::optional& result); - void removeService(const JID& jid); - void refreshView(); - void loadSavedServices(); - void addToSavedServices(const JID& jid); - void updateInProgressness(); - - private: - JID jid_; - MUCSearchWindowFactory* factory_; - IQRouter* iqRouter_; - ProfileSettingsProvider* settings_; - MUCSearchWindow* window_; - DiscoServiceWalker* walker_; - std::list services_; - std::list savedServices_; - std::map serviceDetails_; - std::vector walksInProgress_; - int itemsInProgress_; - }; + class UIEventStream; + class MUCSearchWindow; + class MUCSearchWindowFactory; + class IQRouter; + class DiscoServiceWalker; + class NickResolver; + + class MUCService { + public: + class MUCRoom { + public: + MUCRoom(const std::string& node, const std::string& name, int occupants) : node_(node), name_(name), occupants_(occupants) {} + std::string getNode() {return node_;} + std::string getName() {return name_;} + int getOccupantCount() {return occupants_;} + private: + std::string node_; + std::string name_; + int occupants_; + }; + + MUCService() {error_ = false; complete_ = false;} + + void setComplete(bool complete) { + complete_ = complete; + } + + void setName(const std::string& name) { + name_ = name; + } + + void setJID(const JID& jid) { + jid_ = jid; + } + + bool getComplete() const { + return complete_; + } + + JID getJID() const { + return jid_; + } + + std::string getName() const { + return name_; + } + + void setError(const std::string& errorText) {error_ = true; errorText_ = errorText;} + + void clearRooms() {rooms_.clear();} + + void addRoom(const MUCRoom& room) {rooms_.push_back(room);} + + std::vector getRooms() const {return rooms_;} + private: + std::string name_; + JID jid_; + std::vector rooms_; + bool complete_; + bool error_; + std::string errorText_; + }; + + class MUCSearchController { + public: + MUCSearchController(const JID& jid, MUCSearchWindowFactory* mucSearchWindowFactory, IQRouter* iqRouter, ProfileSettingsProvider* settings); + ~MUCSearchController(); + + void openSearchWindow(); + + public: + boost::signal onMUCSelected; + + private: + void handleSearchService(const JID& jid); + void handleRoomsItemsResponse(boost::shared_ptr items, ErrorPayload::ref error, const JID& jid); + void handleDiscoError(const JID& jid, ErrorPayload::ref error); + void handleDiscoServiceFound(const JID&, boost::shared_ptr); + void handleDiscoWalkFinished(); + void handleMUCSearchFinished(const boost::optional& result); + void removeService(const JID& jid); + void refreshView(); + void loadSavedServices(); + void addToSavedServices(const JID& jid); + void updateInProgressness(); + + private: + JID jid_; + MUCSearchWindowFactory* factory_; + IQRouter* iqRouter_; + ProfileSettingsProvider* settings_; + MUCSearchWindow* window_; + DiscoServiceWalker* walker_; + std::list services_; + std::list savedServices_; + std::map serviceDetails_; + std::vector walksInProgress_; + int itemsInProgress_; + }; } diff --git a/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp b/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp index 6748b9e..9ed8bf4 100644 --- a/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp +++ b/Swift/Controllers/Chat/UnitTest/ChatMessageParserTest.cpp @@ -13,269 +13,269 @@ using namespace Swift; class ChatMessageParserTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ChatMessageParserTest); - CPPUNIT_TEST(testFullBody); - CPPUNIT_TEST(testOneEmoticon); - CPPUNIT_TEST(testBareEmoticon); - CPPUNIT_TEST(testHiddenEmoticon); - CPPUNIT_TEST(testEndlineEmoticon); - CPPUNIT_TEST(testBoundedEmoticons); - CPPUNIT_TEST(testNoColourNoHighlight); - CPPUNIT_TEST_SUITE_END(); - + CPPUNIT_TEST_SUITE(ChatMessageParserTest); + CPPUNIT_TEST(testFullBody); + CPPUNIT_TEST(testOneEmoticon); + CPPUNIT_TEST(testBareEmoticon); + CPPUNIT_TEST(testHiddenEmoticon); + CPPUNIT_TEST(testEndlineEmoticon); + CPPUNIT_TEST(testBoundedEmoticons); + CPPUNIT_TEST(testNoColourNoHighlight); + CPPUNIT_TEST_SUITE_END(); + public: - void setUp() { - smile1_ = ":)"; - smile1Path_ = "/blah/smile1.png"; - smile2_ = ":("; - smile2Path_ = "/blah/smile2.jpg"; - emoticons_[smile1_] = smile1Path_; - emoticons_[smile2_] = smile2Path_; - } - - void tearDown() { - emoticons_.clear(); - } - - void assertText(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) { - boost::shared_ptr part = boost::dynamic_pointer_cast(result.getParts()[index]); - CPPUNIT_ASSERT_EQUAL(text, part->text); - } - - void assertEmoticon(const ChatWindow::ChatMessage& result, size_t index, const std::string& text, const std::string& path) { - boost::shared_ptr part = boost::dynamic_pointer_cast(result.getParts()[index]); - CPPUNIT_ASSERT(!!part); - CPPUNIT_ASSERT_EQUAL(text, part->alternativeText); - CPPUNIT_ASSERT_EQUAL(path, part->imagePath); - } + void setUp() { + smile1_ = ":)"; + smile1Path_ = "/blah/smile1.png"; + smile2_ = ":("; + smile2Path_ = "/blah/smile2.jpg"; + emoticons_[smile1_] = smile1Path_; + emoticons_[smile2_] = smile2Path_; + } + + void tearDown() { + emoticons_.clear(); + } + + void assertText(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) { + boost::shared_ptr part = boost::dynamic_pointer_cast(result.getParts()[index]); + CPPUNIT_ASSERT_EQUAL(text, part->text); + } + + void assertEmoticon(const ChatWindow::ChatMessage& result, size_t index, const std::string& text, const std::string& path) { + boost::shared_ptr part = boost::dynamic_pointer_cast(result.getParts()[index]); + CPPUNIT_ASSERT(!!part); + CPPUNIT_ASSERT_EQUAL(text, part->alternativeText); + CPPUNIT_ASSERT_EQUAL(path, part->imagePath); + } #define assertHighlight(RESULT, INDEX, TEXT, EXPECTED_HIGHLIGHT) \ - { \ - boost::shared_ptr part = boost::dynamic_pointer_cast(RESULT.getParts()[INDEX]); \ - CPPUNIT_ASSERT_EQUAL(std::string(TEXT), part->text); \ - CPPUNIT_ASSERT(EXPECTED_HIGHLIGHT == part->action); \ - } - - void assertURL(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) { - boost::shared_ptr part = boost::dynamic_pointer_cast(result.getParts()[index]); - CPPUNIT_ASSERT_EQUAL(text, part->target); - } - - static HighlightRule ruleFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord) - { - HighlightRule rule; - std::vector keywords; - keywords.push_back(keyword); - rule.setKeywords(keywords); - rule.setMatchCase(matchCase); - rule.setMatchWholeWords(matchWholeWord); - rule.setMatchChat(true); - rule.getAction().setTextBackground("white"); - return rule; - } - - static const HighlightRulesListPtr ruleListFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord) - { - boost::shared_ptr list = boost::make_shared(); - list->addRule(ruleFromKeyword(keyword, matchCase, matchWholeWord)); - return list; - } - - static const HighlightRulesListPtr ruleListFromKeywords(const HighlightRule &rule1, const HighlightRule &rule2) - { - boost::shared_ptr list = boost::make_shared(); - list->addRule(rule1); - list->addRule(rule2); - return list; - } - - static HighlightRulesListPtr ruleListWithNickHighlight(bool withHighlightColour = true) - { - HighlightRule rule; - rule.setMatchChat(true); - rule.setNickIsKeyword(true); - rule.setMatchCase(true); - rule.setMatchWholeWords(true); - if (withHighlightColour) { - rule.getAction().setTextBackground("white"); - } - boost::shared_ptr list = boost::make_shared(); - list->addRule(rule); - return list; - } - - void testFullBody() { - const std::string no_special_message = "a message with no special content"; - ChatMessageParser testling(emoticons_, boost::make_shared()); - ChatWindow::ChatMessage result = testling.parseMessageBody(no_special_message); - assertText(result, 0, no_special_message); - - HighlightRulesListPtr highlightRuleList = ruleListFromKeyword("trigger", false, false); - testling = ChatMessageParser(emoticons_, highlightRuleList); - result = testling.parseMessageBody(":) shiny :( trigger :) http://wonderland.lit/blah http://denmark.lit boom boom"); - assertEmoticon(result, 0, smile1_, smile1Path_); - assertText(result, 1, " shiny "); - assertEmoticon(result, 2, smile2_, smile2Path_); - assertText(result, 3, " "); - assertHighlight(result, 4, "trigger", highlightRuleList->getRule(0).getAction()); - assertText(result, 5, " "); - assertEmoticon(result, 6, smile1_, smile1Path_); - assertText(result, 7, " "); - assertURL(result, 8, "http://wonderland.lit/blah"); - assertText(result, 9, " "); - assertURL(result, 10, "http://denmark.lit"); - assertText(result, 11, " boom boom"); - - testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false)); - result = testling.parseMessageBody("testtriggermessage"); - assertText(result, 0, "test"); - assertHighlight(result, 1, "trigger", highlightRuleList->getRule(0).getAction()); - assertText(result, 2, "message"); - - testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, true)); - result = testling.parseMessageBody("testtriggermessage"); - assertText(result, 0, "testtriggermessage"); - - testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", true, false)); - result = testling.parseMessageBody("TrIgGeR"); - assertText(result, 0, "TrIgGeR"); - - testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false)); - result = testling.parseMessageBody("TrIgGeR"); - assertHighlight(result, 0, "TrIgGeR", highlightRuleList->getRule(0).getAction()); - - testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false)); - result = testling.parseMessageBody("partialTrIgGeRmatch"); - assertText(result, 0, "partial"); - assertHighlight(result, 1, "TrIgGeR", highlightRuleList->getRule(0).getAction()); - assertText(result, 2, "match"); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false))); - result = testling.parseMessageBody("zero one two three"); - assertText(result, 0, "zero "); - assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction()); - assertText(result, 2, " two "); - assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction()); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false))); - result = testling.parseMessageBody("zero oNe two tHrEe"); - assertText(result, 0, "zero "); - assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction()); - assertText(result, 2, " two "); - assertHighlight(result, 3, "tHrEe", highlightRuleList->getRule(0).getAction()); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", true, false))); - result = testling.parseMessageBody("zero oNe two tHrEe"); - assertText(result, 0, "zero "); - assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction()); - assertText(result, 2, " two tHrEe"); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", true, false))); - result = testling.parseMessageBody("zero oNe two tHrEe"); - assertText(result, 0, "zero oNe two tHrEe"); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false))); - result = testling.parseMessageBody("zeroonetwothree"); - assertText(result, 0, "zero"); - assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction()); - assertText(result, 2, "two"); - assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction()); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", false, false))); - result = testling.parseMessageBody("zeroOnEtwoThReE"); - assertText(result, 0, "zeroOnEtwo"); - assertHighlight(result, 1, "ThReE", highlightRuleList->getRule(0).getAction()); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, false))); - result = testling.parseMessageBody("zeroonetwothree"); - assertText(result, 0, "zeroonetwo"); - assertHighlight(result, 1, "three", highlightRuleList->getRule(0).getAction()); - - testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, true))); - result = testling.parseMessageBody("zeroonetwothree"); - assertText(result, 0, "zeroonetwothree"); - - testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); - result = testling.parseMessageBody("Alice", "Alice"); - assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction()); - - testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); - result = testling.parseMessageBody("TextAliceText", "Alice"); - assertText(result, 0, "TextAliceText"); - - testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); - result = testling.parseMessageBody("Text Alice Text", "Alice"); - assertText(result, 0, "Text "); - assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction()); - assertText(result, 2, " Text"); - - testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); - result = testling.parseMessageBody("Alice Text", "Alice"); - assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction()); - assertText(result, 1, " Text"); - - testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); - result = testling.parseMessageBody("Text Alice", "Alice"); - assertText(result, 0, "Text "); - assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction()); - } - - void testOneEmoticon() { - ChatMessageParser testling(emoticons_, boost::make_shared()); - ChatWindow::ChatMessage result = testling.parseMessageBody(" :) "); - assertText(result, 0, " "); - assertEmoticon(result, 1, smile1_, smile1Path_); - assertText(result, 2, " "); - } - - - void testBareEmoticon() { - ChatMessageParser testling(emoticons_, boost::make_shared()); - ChatWindow::ChatMessage result = testling.parseMessageBody(":)"); - assertEmoticon(result, 0, smile1_, smile1Path_); - } - - void testHiddenEmoticon() { - ChatMessageParser testling(emoticons_, boost::make_shared()); - ChatWindow::ChatMessage result = testling.parseMessageBody("b:)a"); - assertText(result, 0, "b:)a"); - } - - void testEndlineEmoticon() { - ChatMessageParser testling(emoticons_, boost::make_shared()); - ChatWindow::ChatMessage result = testling.parseMessageBody("Lazy:)"); - assertText(result, 0, "Lazy"); - assertEmoticon(result, 1, smile1_, smile1Path_); - } - - void testBoundedEmoticons() { - ChatMessageParser testling(emoticons_, boost::make_shared()); - ChatWindow::ChatMessage result = testling.parseMessageBody(":)Lazy:("); - assertEmoticon(result, 0, smile1_, smile1Path_); - assertText(result, 1, "Lazy"); - assertEmoticon(result, 2, smile2_, smile2Path_); - } - - void testEmoticonParenthesis() { - ChatMessageParser testling(emoticons_, boost::make_shared()); - ChatWindow::ChatMessage result = testling.parseMessageBody("(Like this :))"); - assertText(result, 0, "(Like this "); - assertEmoticon(result, 1, smile1_, smile1Path_); - assertText(result, 2, ")"); - } - - void testNoColourNoHighlight() { - ChatMessageParser testling(emoticons_, ruleListWithNickHighlight(false)); - ChatWindow::ChatMessage result = testling.parseMessageBody("Alice", "Alice"); - assertText(result, 0, "Alice"); - } + { \ + boost::shared_ptr part = boost::dynamic_pointer_cast(RESULT.getParts()[INDEX]); \ + CPPUNIT_ASSERT_EQUAL(std::string(TEXT), part->text); \ + CPPUNIT_ASSERT(EXPECTED_HIGHLIGHT == part->action); \ + } + + void assertURL(const ChatWindow::ChatMessage& result, size_t index, const std::string& text) { + boost::shared_ptr part = boost::dynamic_pointer_cast(result.getParts()[index]); + CPPUNIT_ASSERT_EQUAL(text, part->target); + } + + static HighlightRule ruleFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord) + { + HighlightRule rule; + std::vector keywords; + keywords.push_back(keyword); + rule.setKeywords(keywords); + rule.setMatchCase(matchCase); + rule.setMatchWholeWords(matchWholeWord); + rule.setMatchChat(true); + rule.getAction().setTextBackground("white"); + return rule; + } + + static const HighlightRulesListPtr ruleListFromKeyword(const std::string& keyword, bool matchCase, bool matchWholeWord) + { + boost::shared_ptr list = boost::make_shared(); + list->addRule(ruleFromKeyword(keyword, matchCase, matchWholeWord)); + return list; + } + + static const HighlightRulesListPtr ruleListFromKeywords(const HighlightRule &rule1, const HighlightRule &rule2) + { + boost::shared_ptr list = boost::make_shared(); + list->addRule(rule1); + list->addRule(rule2); + return list; + } + + static HighlightRulesListPtr ruleListWithNickHighlight(bool withHighlightColour = true) + { + HighlightRule rule; + rule.setMatchChat(true); + rule.setNickIsKeyword(true); + rule.setMatchCase(true); + rule.setMatchWholeWords(true); + if (withHighlightColour) { + rule.getAction().setTextBackground("white"); + } + boost::shared_ptr list = boost::make_shared(); + list->addRule(rule); + return list; + } + + void testFullBody() { + const std::string no_special_message = "a message with no special content"; + ChatMessageParser testling(emoticons_, boost::make_shared()); + ChatWindow::ChatMessage result = testling.parseMessageBody(no_special_message); + assertText(result, 0, no_special_message); + + HighlightRulesListPtr highlightRuleList = ruleListFromKeyword("trigger", false, false); + testling = ChatMessageParser(emoticons_, highlightRuleList); + result = testling.parseMessageBody(":) shiny :( trigger :) http://wonderland.lit/blah http://denmark.lit boom boom"); + assertEmoticon(result, 0, smile1_, smile1Path_); + assertText(result, 1, " shiny "); + assertEmoticon(result, 2, smile2_, smile2Path_); + assertText(result, 3, " "); + assertHighlight(result, 4, "trigger", highlightRuleList->getRule(0).getAction()); + assertText(result, 5, " "); + assertEmoticon(result, 6, smile1_, smile1Path_); + assertText(result, 7, " "); + assertURL(result, 8, "http://wonderland.lit/blah"); + assertText(result, 9, " "); + assertURL(result, 10, "http://denmark.lit"); + assertText(result, 11, " boom boom"); + + testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false)); + result = testling.parseMessageBody("testtriggermessage"); + assertText(result, 0, "test"); + assertHighlight(result, 1, "trigger", highlightRuleList->getRule(0).getAction()); + assertText(result, 2, "message"); + + testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, true)); + result = testling.parseMessageBody("testtriggermessage"); + assertText(result, 0, "testtriggermessage"); + + testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", true, false)); + result = testling.parseMessageBody("TrIgGeR"); + assertText(result, 0, "TrIgGeR"); + + testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false)); + result = testling.parseMessageBody("TrIgGeR"); + assertHighlight(result, 0, "TrIgGeR", highlightRuleList->getRule(0).getAction()); + + testling = ChatMessageParser(emoticons_, ruleListFromKeyword("trigger", false, false)); + result = testling.parseMessageBody("partialTrIgGeRmatch"); + assertText(result, 0, "partial"); + assertHighlight(result, 1, "TrIgGeR", highlightRuleList->getRule(0).getAction()); + assertText(result, 2, "match"); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false))); + result = testling.parseMessageBody("zero one two three"); + assertText(result, 0, "zero "); + assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction()); + assertText(result, 2, " two "); + assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction()); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false))); + result = testling.parseMessageBody("zero oNe two tHrEe"); + assertText(result, 0, "zero "); + assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction()); + assertText(result, 2, " two "); + assertHighlight(result, 3, "tHrEe", highlightRuleList->getRule(0).getAction()); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", true, false))); + result = testling.parseMessageBody("zero oNe two tHrEe"); + assertText(result, 0, "zero "); + assertHighlight(result, 1, "oNe", highlightRuleList->getRule(0).getAction()); + assertText(result, 2, " two tHrEe"); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", true, false))); + result = testling.parseMessageBody("zero oNe two tHrEe"); + assertText(result, 0, "zero oNe two tHrEe"); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, false), ruleFromKeyword("three", false, false))); + result = testling.parseMessageBody("zeroonetwothree"); + assertText(result, 0, "zero"); + assertHighlight(result, 1, "one", highlightRuleList->getRule(0).getAction()); + assertText(result, 2, "two"); + assertHighlight(result, 3, "three", highlightRuleList->getRule(0).getAction()); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", true, false), ruleFromKeyword("three", false, false))); + result = testling.parseMessageBody("zeroOnEtwoThReE"); + assertText(result, 0, "zeroOnEtwo"); + assertHighlight(result, 1, "ThReE", highlightRuleList->getRule(0).getAction()); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, false))); + result = testling.parseMessageBody("zeroonetwothree"); + assertText(result, 0, "zeroonetwo"); + assertHighlight(result, 1, "three", highlightRuleList->getRule(0).getAction()); + + testling = ChatMessageParser(emoticons_, ruleListFromKeywords(ruleFromKeyword("one", false, true), ruleFromKeyword("three", false, true))); + result = testling.parseMessageBody("zeroonetwothree"); + assertText(result, 0, "zeroonetwothree"); + + testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); + result = testling.parseMessageBody("Alice", "Alice"); + assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction()); + + testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); + result = testling.parseMessageBody("TextAliceText", "Alice"); + assertText(result, 0, "TextAliceText"); + + testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); + result = testling.parseMessageBody("Text Alice Text", "Alice"); + assertText(result, 0, "Text "); + assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction()); + assertText(result, 2, " Text"); + + testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); + result = testling.parseMessageBody("Alice Text", "Alice"); + assertHighlight(result, 0, "Alice", highlightRuleList->getRule(0).getAction()); + assertText(result, 1, " Text"); + + testling = ChatMessageParser(emoticons_, ruleListWithNickHighlight()); + result = testling.parseMessageBody("Text Alice", "Alice"); + assertText(result, 0, "Text "); + assertHighlight(result, 1, "Alice", highlightRuleList->getRule(0).getAction()); + } + + void testOneEmoticon() { + ChatMessageParser testling(emoticons_, boost::make_shared()); + ChatWindow::ChatMessage result = testling.parseMessageBody(" :) "); + assertText(result, 0, " "); + assertEmoticon(result, 1, smile1_, smile1Path_); + assertText(result, 2, " "); + } + + + void testBareEmoticon() { + ChatMessageParser testling(emoticons_, boost::make_shared()); + ChatWindow::ChatMessage result = testling.parseMessageBody(":)"); + assertEmoticon(result, 0, smile1_, smile1Path_); + } + + void testHiddenEmoticon() { + ChatMessageParser testling(emoticons_, boost::make_shared()); + ChatWindow::ChatMessage result = testling.parseMessageBody("b:)a"); + assertText(result, 0, "b:)a"); + } + + void testEndlineEmoticon() { + ChatMessageParser testling(emoticons_, boost::make_shared()); + ChatWindow::ChatMessage result = testling.parseMessageBody("Lazy:)"); + assertText(result, 0, "Lazy"); + assertEmoticon(result, 1, smile1_, smile1Path_); + } + + void testBoundedEmoticons() { + ChatMessageParser testling(emoticons_, boost::make_shared()); + ChatWindow::ChatMessage result = testling.parseMessageBody(":)Lazy:("); + assertEmoticon(result, 0, smile1_, smile1Path_); + assertText(result, 1, "Lazy"); + assertEmoticon(result, 2, smile2_, smile2Path_); + } + + void testEmoticonParenthesis() { + ChatMessageParser testling(emoticons_, boost::make_shared()); + ChatWindow::ChatMessage result = testling.parseMessageBody("(Like this :))"); + assertText(result, 0, "(Like this "); + assertEmoticon(result, 1, smile1_, smile1Path_); + assertText(result, 2, ")"); + } + + void testNoColourNoHighlight() { + ChatMessageParser testling(emoticons_, ruleListWithNickHighlight(false)); + ChatWindow::ChatMessage result = testling.parseMessageBody("Alice", "Alice"); + assertText(result, 0, "Alice"); + } private: - std::map emoticons_; - std::string smile1_; - std::string smile1Path_; - std::string smile2_; - std::string smile2Path_; + std::map emoticons_; + std::string smile1_; + std::string smile1Path_; + std::string smile2_; + std::string smile2Path_; }; CPPUNIT_TEST_SUITE_REGISTRATION(ChatMessageParserTest); diff --git a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp index d29337d..7445c4b 100644 --- a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp +++ b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp @@ -61,808 +61,808 @@ using namespace Swift; class ChatsManagerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ChatsManagerTest); - CPPUNIT_TEST(testFirstOpenWindowIncoming); - CPPUNIT_TEST(testSecondOpenWindowIncoming); - CPPUNIT_TEST(testFirstOpenWindowOutgoing); - CPPUNIT_TEST(testFirstOpenWindowBareToFull); - CPPUNIT_TEST(testSecondWindow); - CPPUNIT_TEST(testUnbindRebind); - CPPUNIT_TEST(testNoDuplicateUnbind); - CPPUNIT_TEST(testThreeMUCWindows); - CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnRemoveFromRoster); - CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnAddToRoster); - CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth); - CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom); - CPPUNIT_TEST(testChatControllerFullJIDBindingOnMessageAndNotReceipt); - CPPUNIT_TEST(testChatControllerFullJIDBindingOnTypingAndNotActive); - CPPUNIT_TEST(testChatControllerPMPresenceHandling); - CPPUNIT_TEST(testLocalMUCServiceDiscoveryResetOnDisconnect); - CPPUNIT_TEST(testChatControllerHighlightingNotificationTesting); - CPPUNIT_TEST(testChatControllerHighlightingNotificationDeduplicateSounds); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(ChatsManagerTest); + CPPUNIT_TEST(testFirstOpenWindowIncoming); + CPPUNIT_TEST(testSecondOpenWindowIncoming); + CPPUNIT_TEST(testFirstOpenWindowOutgoing); + CPPUNIT_TEST(testFirstOpenWindowBareToFull); + CPPUNIT_TEST(testSecondWindow); + CPPUNIT_TEST(testUnbindRebind); + CPPUNIT_TEST(testNoDuplicateUnbind); + CPPUNIT_TEST(testThreeMUCWindows); + CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnRemoveFromRoster); + CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnAddToRoster); + CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth); + CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom); + CPPUNIT_TEST(testChatControllerFullJIDBindingOnMessageAndNotReceipt); + CPPUNIT_TEST(testChatControllerFullJIDBindingOnTypingAndNotActive); + CPPUNIT_TEST(testChatControllerPMPresenceHandling); + CPPUNIT_TEST(testLocalMUCServiceDiscoveryResetOnDisconnect); + CPPUNIT_TEST(testChatControllerHighlightingNotificationTesting); + CPPUNIT_TEST(testChatControllerHighlightingNotificationDeduplicateSounds); + CPPUNIT_TEST_SUITE_END(); public: - void setUp() { - mocks_ = new MockRepository(); - jid_ = JID("test@test.com/resource"); - stanzaChannel_ = new DummyStanzaChannel(); - iqChannel_ = new DummyIQChannel(); - iqRouter_ = new IQRouter(iqChannel_); -// capsProvider_ = new DummyCapsProvider(); - eventController_ = new EventController(); - chatWindowFactory_ = mocks_->InterfaceMock(); - joinMUCWindowFactory_ = mocks_->InterfaceMock(); - xmppRoster_ = new XMPPRosterImpl(); - mucRegistry_ = new MUCRegistry(); - nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_); - presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_); - serverDiscoInfo_ = boost::make_shared(); - presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_); - directedPresenceSender_ = new DirectedPresenceSender(presenceSender_); - mucManager_ = new MUCManager(stanzaChannel_, iqRouter_, directedPresenceSender_, mucRegistry_); - uiEventStream_ = new UIEventStream(); -// entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_); - entityCapsProvider_ = new DummyEntityCapsProvider(); - chatListWindowFactory_ = mocks_->InterfaceMock(); - mucSearchWindowFactory_ = mocks_->InterfaceMock(); - settings_ = new DummySettingsProvider(); - profileSettings_ = new ProfileSettingsProvider("a", settings_); - chatListWindow_ = new MockChatListWindow(); - ftManager_ = new DummyFileTransferManager(); - ftOverview_ = new FileTransferOverview(ftManager_); - avatarManager_ = new NullAvatarManager(); - wbSessionManager_ = new WhiteboardSessionManager(iqRouter_, stanzaChannel_, presenceOracle_, entityCapsProvider_); - wbManager_ = new WhiteboardManager(whiteboardWindowFactory_, uiEventStream_, nickResolver_, wbSessionManager_); - highlightManager_ = new HighlightManager(settings_); - handledHighlightActions_ = 0; - soundsPlayed_.clear(); - highlightManager_->onHighlight.connect(boost::bind(&ChatsManagerTest::handleHighlightAction, this, _1)); - - crypto_ = PlatformCryptoProvider::create(); - vcardStorage_ = new VCardMemoryStorage(crypto_); - vcardManager_ = new VCardManager(jid_, iqRouter_, vcardStorage_); - mocks_->ExpectCall(chatListWindowFactory_, ChatListWindowFactory::createChatListWindow).With(uiEventStream_).Return(chatListWindow_); - clientBlockListManager_ = new ClientBlockListManager(iqRouter_); - manager_ = new ChatsManager(jid_, stanzaChannel_, iqRouter_, eventController_, chatWindowFactory_, joinMUCWindowFactory_, nickResolver_, presenceOracle_, directedPresenceSender_, uiEventStream_, chatListWindowFactory_, true, NULL, mucRegistry_, entityCapsProvider_, mucManager_, mucSearchWindowFactory_, profileSettings_, ftOverview_, xmppRoster_, false, settings_, NULL, wbManager_, highlightManager_, clientBlockListManager_, emoticons_, vcardManager_); - - manager_->setAvatarManager(avatarManager_); - } - - void tearDown() { - delete highlightManager_; - //delete chatListWindowFactory - delete profileSettings_; - delete avatarManager_; - delete manager_; - delete clientBlockListManager_; - delete vcardManager_; - delete vcardStorage_; - delete crypto_; - delete ftOverview_; - delete ftManager_; - delete wbSessionManager_; - delete wbManager_; - delete directedPresenceSender_; - delete presenceSender_; - delete presenceOracle_; - delete nickResolver_; - delete mucRegistry_; - delete stanzaChannel_; - delete eventController_; - delete iqRouter_; - delete iqChannel_; - delete uiEventStream_; - delete mucManager_; - delete xmppRoster_; - delete entityCapsProvider_; - delete chatListWindow_; - delete mocks_; - delete settings_; - } - - void testFirstOpenWindowIncoming() { - JID messageJID("testling@test.com/resource1"); - - MockChatWindow* window = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); - - boost::shared_ptr message(new Message()); - message->setFrom(messageJID); - std::string body("This is a legible message. >HEH@)oeueu"); - message->setBody(body); - manager_->handleIncomingMessage(message); - CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_); - } - - void testSecondOpenWindowIncoming() { - JID messageJID1("testling@test.com/resource1"); - - MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1); - - boost::shared_ptr message1(new Message()); - message1->setFrom(messageJID1); - std::string body1("This is a legible message. >HEH@)oeueu"); - message1->setBody(body1); - manager_->handleIncomingMessage(message1); - CPPUNIT_ASSERT_EQUAL(body1, window1->lastMessageBody_); - - JID messageJID2("testling@test.com/resource2"); - - //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); - //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2); - - boost::shared_ptr message2(new Message()); - message2->setFrom(messageJID2); - std::string body2("This is a legible message. .cmaulm.chul"); - message2->setBody(body2); - manager_->handleIncomingMessage(message2); - CPPUNIT_ASSERT_EQUAL(body2, window1->lastMessageBody_); - } - - void testFirstOpenWindowOutgoing() { - std::string messageJIDString("testling@test.com"); - - ChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString), uiEventStream_).Return(window); - - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString)))); - } - - - void testFirstOpenWindowBareToFull() { - std::string bareJIDString("testling@test.com"); - std::string fullJIDString("testling@test.com/resource1"); - - MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window); - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(bareJIDString)))); - - boost::shared_ptr message(new Message()); - message->setFrom(JID(fullJIDString)); - std::string body("This is a legible message. mjuga3089gm8G(*>M)@*("); - message->setBody(body); - manager_->handleIncomingMessage(message); - CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_); - } - - void testSecondWindow() { - std::string messageJIDString1("testling1@test.com"); - ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1); - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString1)))); - - std::string messageJIDString2("testling2@test.com"); - ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2); - - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString2)))); - } - - /** Complete cycle. - Create unbound window. - Bind it. - Unbind it. - Rebind it. - */ - void testUnbindRebind() { - std::string bareJIDString("testling@test.com"); - std::string fullJIDString1("testling@test.com/resource1"); - std::string fullJIDString2("testling@test.com/resource2"); - - MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window); - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(bareJIDString)))); - - boost::shared_ptr message1(new Message()); - message1->setFrom(JID(fullJIDString1)); - std::string messageBody1("This is a legible message."); - message1->setBody(messageBody1); - manager_->handleIncomingMessage(message1); - CPPUNIT_ASSERT_EQUAL(messageBody1, window->lastMessageBody_); - - boost::shared_ptr jid1Online(new Presence()); - jid1Online->setFrom(JID(fullJIDString1)); - boost::shared_ptr jid1Offline(new Presence()); - jid1Offline->setFrom(JID(fullJIDString1)); - jid1Offline->setType(Presence::Unavailable); - presenceOracle_->onPresenceChange(jid1Offline); - - boost::shared_ptr message2(new Message()); - message2->setFrom(JID(fullJIDString2)); - std::string messageBody2("This is another legible message."); - message2->setBody(messageBody2); - manager_->handleIncomingMessage(message2); - CPPUNIT_ASSERT_EQUAL(messageBody2, window->lastMessageBody_); - } - - /** - * Test that MUC PMs get opened in the right windows - */ - void testThreeMUCWindows() { - JID muc("testling@test.com"); - ChatWindow* mucWindow = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc, uiEventStream_).Return(mucWindow); - uiEventStream_->send(boost::make_shared(muc, std::string("nick"))); - - - std::string messageJIDString1("testling@test.com/1"); - ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1); - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString1)))); - - std::string messageJIDString2("testling@test.com/2"); - ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2); - - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString2)))); - - std::string messageJIDString3("testling@test.com/3"); - ChatWindow* window3 = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString3), uiEventStream_).Return(window3); - - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString3)))); - - /* Refetch an earlier window */ - /* We do not expect a new window to be created */ - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString1)))); - - } - - /** - Test that a second window isn't unbound where there's already an unbound one. - Bind 1 - Bind 2 - Unbind 1 - Unbind 2 (but it doesn't) - Sent to bound 2 - Rebind 1 - */ - void testNoDuplicateUnbind() { - JID messageJID1("testling@test.com/resource1"); - - MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1); - - boost::shared_ptr message1(new Message()); - message1->setFrom(messageJID1); - message1->setBody("This is a legible message1."); - manager_->handleIncomingMessage(message1); - - JID messageJID2("testling@test.com/resource2"); - - //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); - //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2); - - boost::shared_ptr message2(new Message()); - message2->setFrom(messageJID2); - message2->setBody("This is a legible message2."); - manager_->handleIncomingMessage(message2); - - boost::shared_ptr jid1Online(new Presence()); - jid1Online->setFrom(JID(messageJID1)); - boost::shared_ptr jid1Offline(new Presence()); - jid1Offline->setFrom(JID(messageJID1)); - jid1Offline->setType(Presence::Unavailable); - presenceOracle_->onPresenceChange(jid1Offline); - - boost::shared_ptr jid2Online(new Presence()); - jid2Online->setFrom(JID(messageJID2)); - boost::shared_ptr jid2Offline(new Presence()); - jid2Offline->setFrom(JID(messageJID2)); - jid2Offline->setType(Presence::Unavailable); - presenceOracle_->onPresenceChange(jid2Offline); - - JID messageJID3("testling@test.com/resource3"); - - boost::shared_ptr message3(new Message()); - message3->setFrom(messageJID3); - std::string body3("This is a legible message3."); - message3->setBody(body3); - manager_->handleIncomingMessage(message3); - CPPUNIT_ASSERT_EQUAL(body3, window1->lastMessageBody_); - - boost::shared_ptr message2b(new Message()); - message2b->setFrom(messageJID2); - std::string body2b("This is a legible message2b."); - message2b->setBody(body2b); - manager_->handleIncomingMessage(message2b); - CPPUNIT_ASSERT_EQUAL(body2b, window1->lastMessageBody_); - } - - /** - * Test that ChatController doesn't send receipts anymore after removal of the contact from the roster. - */ - void testChatControllerPresenceAccessUpdatedOnRemoveFromRoster() { - JID messageJID("testling@test.com/resource1"); - xmppRoster_->addContact(messageJID, "foo", std::vector(), RosterItemPayload::Both); - - MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); - settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); - - boost::shared_ptr message = makeDeliveryReceiptTestMessage(messageJID, "1"); - manager_->handleIncomingMessage(message); - Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex(0); - CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); - CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload() != 0); - - xmppRoster_->removeContact(messageJID); - - message->setID("2"); - manager_->handleIncomingMessage(message); - CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); - } - - /** - * Test that ChatController sends receipts after the contact has been added to the roster. - */ - void testChatControllerPresenceAccessUpdatedOnAddToRoster() { - JID messageJID("testling@test.com/resource1"); - - MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); - settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); - - boost::shared_ptr message = makeDeliveryReceiptTestMessage(messageJID, "1"); - manager_->handleIncomingMessage(message); - - CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size()); - - xmppRoster_->addContact(messageJID, "foo", std::vector(), RosterItemPayload::Both); - message->setID("2"); - manager_->handleIncomingMessage(message); - - CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); - Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex(0); - CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload() != 0); - } - - /** - * Test that ChatController sends receipts if requested after change from subscription state To to subscription state Both. - */ - void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth() { - testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::Both); - } - - /** - * Test that ChatController sends receipts if requested after change from subscription state To to subscription state From. - */ - void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom() { - testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::From); - } - - void testChatControllerFullJIDBindingOnMessageAndNotReceipt() { - JID ownJID("test@test.com/resource"); - JID sender("foo@test.com"); - std::vector senderResource; - senderResource.push_back(sender.withResource("resourceA")); - senderResource.push_back(sender.withResource("resourceB")); - - // We support delivery receipts. - settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); - - // Open chat window to a sender. - MockChatWindow* window = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window); - - uiEventStream_->send(boost::make_shared(sender)); - - foreach(const JID& senderJID, senderResource) { - // The sender supports delivery receipts. - DiscoInfo::ref disco = boost::make_shared(); - disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature); - entityCapsProvider_->caps[senderJID] = disco; - - // The sender is online. - Presence::ref senderPresence = boost::make_shared(); - senderPresence->setFrom(senderJID); - senderPresence->setTo(ownJID); - stanzaChannel_->onPresenceReceived(senderPresence); - - entityCapsProvider_->onCapsChanged(senderJID); - } - - // Send first message. - window->onSendMessageRequest("hello there", false); - - // A bare message is send because no resources is bound. - CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(0)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(0)->getPayload()); - - // Two resources respond with message receipts. - foreach(const JID& senderJID, senderResource) { - Message::ref receiptReply = boost::make_shared(); - receiptReply->setFrom(senderJID); - receiptReply->setTo(ownJID); - - boost::shared_ptr receipt = boost::make_shared(); - receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(0)->getID()); - receiptReply->addPayload(receipt); - manager_->handleIncomingMessage(receiptReply); - } - - // Send second message. - window->onSendMessageRequest("how are you?", false); - - // A bare message is send because no resources is bound. - CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(1)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(1)->getPayload()); - - // Two resources respond with message receipts. - foreach(const JID& senderJID, senderResource) { - Message::ref receiptReply = boost::make_shared(); - receiptReply->setFrom(senderJID); - receiptReply->setTo(ownJID); - - boost::shared_ptr receipt = boost::make_shared(); - receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(1)->getID()); - receiptReply->addPayload(receipt); - manager_->handleIncomingMessage(receiptReply); - } - - // Reply with a message including a body text. - Message::ref reply = boost::make_shared(); - reply->setFrom(senderResource[0]); - reply->setTo(ownJID); - reply->setBody("fine."); - manager_->handleIncomingMessage(reply); - - // Send third message. - window->onSendMessageRequest("great to hear.", false); - - // The chat session is bound to the full JID of the first resource. - CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex(2)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(2)->getPayload()); - - // Receive random receipt from second sender resource. - reply = boost::make_shared(); - reply->setFrom(senderResource[1]); - reply->setTo(ownJID); - - boost::shared_ptr receipt = boost::make_shared(); - receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(2)->getID()); - reply->addPayload(receipt); - manager_->handleIncomingMessage(reply); - - // Send forth message. - window->onSendMessageRequest("what else is new?", false); - - // The chat session is bound to the full JID of the first resource. - CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex(3)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(3)->getPayload()); - - // Reply with a message including a body text from second resource. - reply = boost::make_shared(); - reply->setFrom(senderResource[1]); - reply->setTo(ownJID); - reply->setBody("nothing."); - manager_->handleIncomingMessage(reply); - - // Send fifth message. - window->onSendMessageRequest("okay", false); - - // The chat session is now bound to the full JID of the second resource. - CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex(4)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(4)->getPayload()); - } - - void testChatControllerFullJIDBindingOnTypingAndNotActive() { - JID ownJID("test@test.com/resource"); - JID sender("foo@test.com"); - std::vector senderResource; - senderResource.push_back(sender.withResource("resourceA")); - senderResource.push_back(sender.withResource("resourceB")); - - // We support delivery receipts. - settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); - - // Open chat window to a sender. - MockChatWindow* window = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window); - - uiEventStream_->send(boost::make_shared(sender)); - - foreach(const JID& senderJID, senderResource) { - // The sender supports delivery receipts. - DiscoInfo::ref disco = boost::make_shared(); - disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature); - entityCapsProvider_->caps[senderJID] = disco; - - // The sender is online. - Presence::ref senderPresence = boost::make_shared(); - senderPresence->setFrom(senderJID); - senderPresence->setTo(ownJID); - stanzaChannel_->onPresenceReceived(senderPresence); - - entityCapsProvider_->onCapsChanged(senderJID); - } - - // Send first message. - window->onSendMessageRequest("hello there", false); - - // A bare message is send because no resources is bound. - CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(0)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(0)->getPayload()); - - // Two resources respond with message receipts. - foreach(const JID& senderJID, senderResource) { - Message::ref reply = boost::make_shared(); - reply->setFrom(senderJID); - reply->setTo(ownJID); - - boost::shared_ptr csn = boost::make_shared(); - csn->setChatState(ChatState::Active); - reply->addPayload(csn); - manager_->handleIncomingMessage(reply); - } - - // Send second message. - window->onSendMessageRequest("how are you?", false); - - // A bare message is send because no resources is bound. - CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(1)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(1)->getPayload()); - - // Two resources respond with message receipts. - foreach(const JID& senderJID, senderResource) { - Message::ref receiptReply = boost::make_shared(); - receiptReply->setFrom(senderJID); - receiptReply->setTo(ownJID); - - boost::shared_ptr receipt = boost::make_shared(); - receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(1)->getID()); - receiptReply->addPayload(receipt); - manager_->handleIncomingMessage(receiptReply); - } - - // Reply with a message including a CSN. - Message::ref reply = boost::make_shared(); - reply->setFrom(senderResource[0]); - reply->setTo(ownJID); - - boost::shared_ptr csn = boost::make_shared(); - csn->setChatState(ChatState::Composing); - reply->addPayload(csn); - manager_->handleIncomingMessage(reply); - - // Send third message. - window->onSendMessageRequest("great to hear.", false); - - // The chat session is now bound to the full JID of the first resource due to its recent composing message. - CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex(2)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(2)->getPayload()); - - // Reply with a message including a CSN from the other resource. - reply = boost::make_shared(); - reply->setFrom(senderResource[1]); - reply->setTo(ownJID); - - csn = boost::make_shared(); - csn->setChatState(ChatState::Composing); - reply->addPayload(csn); - manager_->handleIncomingMessage(reply); - - // Send third message. - window->onSendMessageRequest("ping.", false); - - // The chat session is now bound to the full JID of the second resource due to its recent composing message. - CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex(3)->getTo()); - CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(3)->getPayload()); - } - - void testChatControllerPMPresenceHandling() { - JID participantA = JID("test@rooms.test.com/participantA"); - JID participantB = JID("test@rooms.test.com/participantB"); - - mucRegistry_->addMUC("test@rooms.test.com"); - - MockChatWindow* window = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(participantA, uiEventStream_).Return(window); - - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(participantA)))); - - Presence::ref presence = Presence::create(); - presence->setFrom(participantA); - presence->setShow(StatusShow::Online); - stanzaChannel_->onPresenceReceived(presence); - CPPUNIT_ASSERT_EQUAL(std::string("participantA has become available."), MockChatWindow::bodyFromMessage(window->lastAddedPresence_)); - - presence = Presence::create(); - presence->setFrom(participantB); - presence->setShow(StatusShow::Away); - stanzaChannel_->onPresenceReceived(presence); - - presence = Presence::create(); - presence->setFrom(participantA); - presence->setShow(StatusShow::None); - presence->setType(Presence::Unavailable); - stanzaChannel_->onPresenceReceived(presence); - CPPUNIT_ASSERT_EQUAL(std::string("participantA has gone offline."), MockChatWindow::bodyFromMessage(window->lastReplacedMessage_)); - } - - void testLocalMUCServiceDiscoveryResetOnDisconnect() { - JID ownJID("test@test.com/resource"); - JID sender("foo@test.com"); - - manager_->setOnline(true); - - // Open chat window to a sender. - MockChatWindow* window = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window); - - uiEventStream_->send(boost::make_shared(sender)); - - CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_); - - boost::shared_ptr infoRequest= iqChannel_->iqs_[1]; - boost::shared_ptr infoResponse = IQ::createResult(infoRequest->getFrom(), infoRequest->getTo(), infoRequest->getID()); - - DiscoInfo info; - info.addIdentity(DiscoInfo::Identity("Shakespearean Chat Service", "conference", "text")); - info.addFeature("http://jabber.org/protocol/muc"); - infoResponse->addPayload(boost::make_shared(info)); - iqChannel_->onIQReceived(infoResponse); - - CPPUNIT_ASSERT_EQUAL(true, window->impromptuMUCSupported_); - manager_->setOnline(false); - CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_); - } - - void testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::Subscription from, RosterItemPayload::Subscription to) { - JID messageJID("testling@test.com/resource1"); - xmppRoster_->addContact(messageJID, "foo", std::vector(), from); - - MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); - settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); - - boost::shared_ptr message = makeDeliveryReceiptTestMessage(messageJID, "1"); - manager_->handleIncomingMessage(message); - - CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size()); - - xmppRoster_->addContact(messageJID, "foo", std::vector(), to); - message->setID("2"); - manager_->handleIncomingMessage(message); - - CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); - Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex(0); - CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload() != 0); - } - - void testChatControllerHighlightingNotificationTesting() { - HighlightRule keywordRuleA; - keywordRuleA.setMatchChat(true); - std::vector keywordsA; - keywordsA.push_back("Romeo"); - keywordRuleA.setKeywords(keywordsA); - keywordRuleA.getAction().setTextColor("yellow"); - keywordRuleA.getAction().setPlaySound(true); - highlightManager_->insertRule(0, keywordRuleA); - - HighlightRule keywordRuleB; - keywordRuleB.setMatchChat(true); - std::vector keywordsB; - keywordsB.push_back("Juliet"); - keywordRuleB.setKeywords(keywordsB); - keywordRuleB.getAction().setTextColor("green"); - keywordRuleB.getAction().setPlaySound(true); - keywordRuleB.getAction().setSoundFile("/tmp/someotherfile.wav"); - highlightManager_->insertRule(0, keywordRuleB); - - JID messageJID = JID("testling@test.com"); - - MockChatWindow* window = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); - - boost::shared_ptr message(new Message()); - message->setFrom(messageJID); - std::string body("This message should cause two sounds: Juliet and Romeo."); - message->setBody(body); - manager_->handleIncomingMessage(message); - - CPPUNIT_ASSERT_EQUAL(2, handledHighlightActions_); - CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end()); - CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end()); - } - - void testChatControllerHighlightingNotificationDeduplicateSounds() { - HighlightRule keywordRuleA; - keywordRuleA.setMatchChat(true); - std::vector keywordsA; - keywordsA.push_back("Romeo"); - keywordRuleA.setKeywords(keywordsA); - keywordRuleA.getAction().setTextColor("yellow"); - keywordRuleA.getAction().setPlaySound(true); - highlightManager_->insertRule(0, keywordRuleA); - - HighlightRule keywordRuleB; - keywordRuleB.setMatchChat(true); - std::vector keywordsB; - keywordsB.push_back("Juliet"); - keywordRuleB.setKeywords(keywordsB); - keywordRuleB.getAction().setTextColor("green"); - keywordRuleB.getAction().setPlaySound(true); - highlightManager_->insertRule(0, keywordRuleB); - - JID messageJID = JID("testling@test.com"); - - MockChatWindow* window = new MockChatWindow(); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); - - boost::shared_ptr message(new Message()); - message->setFrom(messageJID); - std::string body("This message should cause one sound, because both actions have the same sound: Juliet and Romeo."); - message->setBody(body); - manager_->handleIncomingMessage(message); - - CPPUNIT_ASSERT_EQUAL(1, handledHighlightActions_); - CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end()); - CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end()); - } + void setUp() { + mocks_ = new MockRepository(); + jid_ = JID("test@test.com/resource"); + stanzaChannel_ = new DummyStanzaChannel(); + iqChannel_ = new DummyIQChannel(); + iqRouter_ = new IQRouter(iqChannel_); +// capsProvider_ = new DummyCapsProvider(); + eventController_ = new EventController(); + chatWindowFactory_ = mocks_->InterfaceMock(); + joinMUCWindowFactory_ = mocks_->InterfaceMock(); + xmppRoster_ = new XMPPRosterImpl(); + mucRegistry_ = new MUCRegistry(); + nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_); + presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_); + serverDiscoInfo_ = boost::make_shared(); + presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_); + directedPresenceSender_ = new DirectedPresenceSender(presenceSender_); + mucManager_ = new MUCManager(stanzaChannel_, iqRouter_, directedPresenceSender_, mucRegistry_); + uiEventStream_ = new UIEventStream(); +// entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_); + entityCapsProvider_ = new DummyEntityCapsProvider(); + chatListWindowFactory_ = mocks_->InterfaceMock(); + mucSearchWindowFactory_ = mocks_->InterfaceMock(); + settings_ = new DummySettingsProvider(); + profileSettings_ = new ProfileSettingsProvider("a", settings_); + chatListWindow_ = new MockChatListWindow(); + ftManager_ = new DummyFileTransferManager(); + ftOverview_ = new FileTransferOverview(ftManager_); + avatarManager_ = new NullAvatarManager(); + wbSessionManager_ = new WhiteboardSessionManager(iqRouter_, stanzaChannel_, presenceOracle_, entityCapsProvider_); + wbManager_ = new WhiteboardManager(whiteboardWindowFactory_, uiEventStream_, nickResolver_, wbSessionManager_); + highlightManager_ = new HighlightManager(settings_); + handledHighlightActions_ = 0; + soundsPlayed_.clear(); + highlightManager_->onHighlight.connect(boost::bind(&ChatsManagerTest::handleHighlightAction, this, _1)); + + crypto_ = PlatformCryptoProvider::create(); + vcardStorage_ = new VCardMemoryStorage(crypto_); + vcardManager_ = new VCardManager(jid_, iqRouter_, vcardStorage_); + mocks_->ExpectCall(chatListWindowFactory_, ChatListWindowFactory::createChatListWindow).With(uiEventStream_).Return(chatListWindow_); + clientBlockListManager_ = new ClientBlockListManager(iqRouter_); + manager_ = new ChatsManager(jid_, stanzaChannel_, iqRouter_, eventController_, chatWindowFactory_, joinMUCWindowFactory_, nickResolver_, presenceOracle_, directedPresenceSender_, uiEventStream_, chatListWindowFactory_, true, NULL, mucRegistry_, entityCapsProvider_, mucManager_, mucSearchWindowFactory_, profileSettings_, ftOverview_, xmppRoster_, false, settings_, NULL, wbManager_, highlightManager_, clientBlockListManager_, emoticons_, vcardManager_); + + manager_->setAvatarManager(avatarManager_); + } + + void tearDown() { + delete highlightManager_; + //delete chatListWindowFactory + delete profileSettings_; + delete avatarManager_; + delete manager_; + delete clientBlockListManager_; + delete vcardManager_; + delete vcardStorage_; + delete crypto_; + delete ftOverview_; + delete ftManager_; + delete wbSessionManager_; + delete wbManager_; + delete directedPresenceSender_; + delete presenceSender_; + delete presenceOracle_; + delete nickResolver_; + delete mucRegistry_; + delete stanzaChannel_; + delete eventController_; + delete iqRouter_; + delete iqChannel_; + delete uiEventStream_; + delete mucManager_; + delete xmppRoster_; + delete entityCapsProvider_; + delete chatListWindow_; + delete mocks_; + delete settings_; + } + + void testFirstOpenWindowIncoming() { + JID messageJID("testling@test.com/resource1"); + + MockChatWindow* window = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); + + boost::shared_ptr message(new Message()); + message->setFrom(messageJID); + std::string body("This is a legible message. >HEH@)oeueu"); + message->setBody(body); + manager_->handleIncomingMessage(message); + CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_); + } + + void testSecondOpenWindowIncoming() { + JID messageJID1("testling@test.com/resource1"); + + MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1); + + boost::shared_ptr message1(new Message()); + message1->setFrom(messageJID1); + std::string body1("This is a legible message. >HEH@)oeueu"); + message1->setBody(body1); + manager_->handleIncomingMessage(message1); + CPPUNIT_ASSERT_EQUAL(body1, window1->lastMessageBody_); + + JID messageJID2("testling@test.com/resource2"); + + //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); + //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2); + + boost::shared_ptr message2(new Message()); + message2->setFrom(messageJID2); + std::string body2("This is a legible message. .cmaulm.chul"); + message2->setBody(body2); + manager_->handleIncomingMessage(message2); + CPPUNIT_ASSERT_EQUAL(body2, window1->lastMessageBody_); + } + + void testFirstOpenWindowOutgoing() { + std::string messageJIDString("testling@test.com"); + + ChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString), uiEventStream_).Return(window); + + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString)))); + } + + + void testFirstOpenWindowBareToFull() { + std::string bareJIDString("testling@test.com"); + std::string fullJIDString("testling@test.com/resource1"); + + MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window); + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(bareJIDString)))); + + boost::shared_ptr message(new Message()); + message->setFrom(JID(fullJIDString)); + std::string body("This is a legible message. mjuga3089gm8G(*>M)@*("); + message->setBody(body); + manager_->handleIncomingMessage(message); + CPPUNIT_ASSERT_EQUAL(body, window->lastMessageBody_); + } + + void testSecondWindow() { + std::string messageJIDString1("testling1@test.com"); + ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1); + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString1)))); + + std::string messageJIDString2("testling2@test.com"); + ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2); + + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString2)))); + } + + /** Complete cycle. + Create unbound window. + Bind it. + Unbind it. + Rebind it. + */ + void testUnbindRebind() { + std::string bareJIDString("testling@test.com"); + std::string fullJIDString1("testling@test.com/resource1"); + std::string fullJIDString2("testling@test.com/resource2"); + + MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window); + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(bareJIDString)))); + + boost::shared_ptr message1(new Message()); + message1->setFrom(JID(fullJIDString1)); + std::string messageBody1("This is a legible message."); + message1->setBody(messageBody1); + manager_->handleIncomingMessage(message1); + CPPUNIT_ASSERT_EQUAL(messageBody1, window->lastMessageBody_); + + boost::shared_ptr jid1Online(new Presence()); + jid1Online->setFrom(JID(fullJIDString1)); + boost::shared_ptr jid1Offline(new Presence()); + jid1Offline->setFrom(JID(fullJIDString1)); + jid1Offline->setType(Presence::Unavailable); + presenceOracle_->onPresenceChange(jid1Offline); + + boost::shared_ptr message2(new Message()); + message2->setFrom(JID(fullJIDString2)); + std::string messageBody2("This is another legible message."); + message2->setBody(messageBody2); + manager_->handleIncomingMessage(message2); + CPPUNIT_ASSERT_EQUAL(messageBody2, window->lastMessageBody_); + } + + /** + * Test that MUC PMs get opened in the right windows + */ + void testThreeMUCWindows() { + JID muc("testling@test.com"); + ChatWindow* mucWindow = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc, uiEventStream_).Return(mucWindow); + uiEventStream_->send(boost::make_shared(muc, std::string("nick"))); + + + std::string messageJIDString1("testling@test.com/1"); + ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1); + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString1)))); + + std::string messageJIDString2("testling@test.com/2"); + ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2); + + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString2)))); + + std::string messageJIDString3("testling@test.com/3"); + ChatWindow* window3 = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString3), uiEventStream_).Return(window3); + + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString3)))); + + /* Refetch an earlier window */ + /* We do not expect a new window to be created */ + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(messageJIDString1)))); + + } + + /** + Test that a second window isn't unbound where there's already an unbound one. + Bind 1 + Bind 2 + Unbind 1 + Unbind 2 (but it doesn't) + Sent to bound 2 + Rebind 1 + */ + void testNoDuplicateUnbind() { + JID messageJID1("testling@test.com/resource1"); + + MockChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID1, uiEventStream_).Return(window1); + + boost::shared_ptr message1(new Message()); + message1->setFrom(messageJID1); + message1->setBody("This is a legible message1."); + manager_->handleIncomingMessage(message1); + + JID messageJID2("testling@test.com/resource2"); + + //MockChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock(); + //mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID2, uiEventStream_).Return(window2); + + boost::shared_ptr message2(new Message()); + message2->setFrom(messageJID2); + message2->setBody("This is a legible message2."); + manager_->handleIncomingMessage(message2); + + boost::shared_ptr jid1Online(new Presence()); + jid1Online->setFrom(JID(messageJID1)); + boost::shared_ptr jid1Offline(new Presence()); + jid1Offline->setFrom(JID(messageJID1)); + jid1Offline->setType(Presence::Unavailable); + presenceOracle_->onPresenceChange(jid1Offline); + + boost::shared_ptr jid2Online(new Presence()); + jid2Online->setFrom(JID(messageJID2)); + boost::shared_ptr jid2Offline(new Presence()); + jid2Offline->setFrom(JID(messageJID2)); + jid2Offline->setType(Presence::Unavailable); + presenceOracle_->onPresenceChange(jid2Offline); + + JID messageJID3("testling@test.com/resource3"); + + boost::shared_ptr message3(new Message()); + message3->setFrom(messageJID3); + std::string body3("This is a legible message3."); + message3->setBody(body3); + manager_->handleIncomingMessage(message3); + CPPUNIT_ASSERT_EQUAL(body3, window1->lastMessageBody_); + + boost::shared_ptr message2b(new Message()); + message2b->setFrom(messageJID2); + std::string body2b("This is a legible message2b."); + message2b->setBody(body2b); + manager_->handleIncomingMessage(message2b); + CPPUNIT_ASSERT_EQUAL(body2b, window1->lastMessageBody_); + } + + /** + * Test that ChatController doesn't send receipts anymore after removal of the contact from the roster. + */ + void testChatControllerPresenceAccessUpdatedOnRemoveFromRoster() { + JID messageJID("testling@test.com/resource1"); + xmppRoster_->addContact(messageJID, "foo", std::vector(), RosterItemPayload::Both); + + MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); + settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); + + boost::shared_ptr message = makeDeliveryReceiptTestMessage(messageJID, "1"); + manager_->handleIncomingMessage(message); + Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex(0); + CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); + CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload() != 0); + + xmppRoster_->removeContact(messageJID); + + message->setID("2"); + manager_->handleIncomingMessage(message); + CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); + } + + /** + * Test that ChatController sends receipts after the contact has been added to the roster. + */ + void testChatControllerPresenceAccessUpdatedOnAddToRoster() { + JID messageJID("testling@test.com/resource1"); + + MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); + settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); + + boost::shared_ptr message = makeDeliveryReceiptTestMessage(messageJID, "1"); + manager_->handleIncomingMessage(message); + + CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size()); + + xmppRoster_->addContact(messageJID, "foo", std::vector(), RosterItemPayload::Both); + message->setID("2"); + manager_->handleIncomingMessage(message); + + CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); + Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex(0); + CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload() != 0); + } + + /** + * Test that ChatController sends receipts if requested after change from subscription state To to subscription state Both. + */ + void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth() { + testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::Both); + } + + /** + * Test that ChatController sends receipts if requested after change from subscription state To to subscription state From. + */ + void testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom() { + testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::To, RosterItemPayload::From); + } + + void testChatControllerFullJIDBindingOnMessageAndNotReceipt() { + JID ownJID("test@test.com/resource"); + JID sender("foo@test.com"); + std::vector senderResource; + senderResource.push_back(sender.withResource("resourceA")); + senderResource.push_back(sender.withResource("resourceB")); + + // We support delivery receipts. + settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); + + // Open chat window to a sender. + MockChatWindow* window = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window); + + uiEventStream_->send(boost::make_shared(sender)); + + foreach(const JID& senderJID, senderResource) { + // The sender supports delivery receipts. + DiscoInfo::ref disco = boost::make_shared(); + disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature); + entityCapsProvider_->caps[senderJID] = disco; + + // The sender is online. + Presence::ref senderPresence = boost::make_shared(); + senderPresence->setFrom(senderJID); + senderPresence->setTo(ownJID); + stanzaChannel_->onPresenceReceived(senderPresence); + + entityCapsProvider_->onCapsChanged(senderJID); + } + + // Send first message. + window->onSendMessageRequest("hello there", false); + + // A bare message is send because no resources is bound. + CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(0)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(0)->getPayload()); + + // Two resources respond with message receipts. + foreach(const JID& senderJID, senderResource) { + Message::ref receiptReply = boost::make_shared(); + receiptReply->setFrom(senderJID); + receiptReply->setTo(ownJID); + + boost::shared_ptr receipt = boost::make_shared(); + receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(0)->getID()); + receiptReply->addPayload(receipt); + manager_->handleIncomingMessage(receiptReply); + } + + // Send second message. + window->onSendMessageRequest("how are you?", false); + + // A bare message is send because no resources is bound. + CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(1)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(1)->getPayload()); + + // Two resources respond with message receipts. + foreach(const JID& senderJID, senderResource) { + Message::ref receiptReply = boost::make_shared(); + receiptReply->setFrom(senderJID); + receiptReply->setTo(ownJID); + + boost::shared_ptr receipt = boost::make_shared(); + receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(1)->getID()); + receiptReply->addPayload(receipt); + manager_->handleIncomingMessage(receiptReply); + } + + // Reply with a message including a body text. + Message::ref reply = boost::make_shared(); + reply->setFrom(senderResource[0]); + reply->setTo(ownJID); + reply->setBody("fine."); + manager_->handleIncomingMessage(reply); + + // Send third message. + window->onSendMessageRequest("great to hear.", false); + + // The chat session is bound to the full JID of the first resource. + CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex(2)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(2)->getPayload()); + + // Receive random receipt from second sender resource. + reply = boost::make_shared(); + reply->setFrom(senderResource[1]); + reply->setTo(ownJID); + + boost::shared_ptr receipt = boost::make_shared(); + receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(2)->getID()); + reply->addPayload(receipt); + manager_->handleIncomingMessage(reply); + + // Send forth message. + window->onSendMessageRequest("what else is new?", false); + + // The chat session is bound to the full JID of the first resource. + CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex(3)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(3)->getPayload()); + + // Reply with a message including a body text from second resource. + reply = boost::make_shared(); + reply->setFrom(senderResource[1]); + reply->setTo(ownJID); + reply->setBody("nothing."); + manager_->handleIncomingMessage(reply); + + // Send fifth message. + window->onSendMessageRequest("okay", false); + + // The chat session is now bound to the full JID of the second resource. + CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex(4)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(4)->getPayload()); + } + + void testChatControllerFullJIDBindingOnTypingAndNotActive() { + JID ownJID("test@test.com/resource"); + JID sender("foo@test.com"); + std::vector senderResource; + senderResource.push_back(sender.withResource("resourceA")); + senderResource.push_back(sender.withResource("resourceB")); + + // We support delivery receipts. + settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); + + // Open chat window to a sender. + MockChatWindow* window = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window); + + uiEventStream_->send(boost::make_shared(sender)); + + foreach(const JID& senderJID, senderResource) { + // The sender supports delivery receipts. + DiscoInfo::ref disco = boost::make_shared(); + disco->addFeature(DiscoInfo::MessageDeliveryReceiptsFeature); + entityCapsProvider_->caps[senderJID] = disco; + + // The sender is online. + Presence::ref senderPresence = boost::make_shared(); + senderPresence->setFrom(senderJID); + senderPresence->setTo(ownJID); + stanzaChannel_->onPresenceReceived(senderPresence); + + entityCapsProvider_->onCapsChanged(senderJID); + } + + // Send first message. + window->onSendMessageRequest("hello there", false); + + // A bare message is send because no resources is bound. + CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(0)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(0)->getPayload()); + + // Two resources respond with message receipts. + foreach(const JID& senderJID, senderResource) { + Message::ref reply = boost::make_shared(); + reply->setFrom(senderJID); + reply->setTo(ownJID); + + boost::shared_ptr csn = boost::make_shared(); + csn->setChatState(ChatState::Active); + reply->addPayload(csn); + manager_->handleIncomingMessage(reply); + } + + // Send second message. + window->onSendMessageRequest("how are you?", false); + + // A bare message is send because no resources is bound. + CPPUNIT_ASSERT_EQUAL(sender, stanzaChannel_->getStanzaAtIndex(1)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(1)->getPayload()); + + // Two resources respond with message receipts. + foreach(const JID& senderJID, senderResource) { + Message::ref receiptReply = boost::make_shared(); + receiptReply->setFrom(senderJID); + receiptReply->setTo(ownJID); + + boost::shared_ptr receipt = boost::make_shared(); + receipt->setReceivedID(stanzaChannel_->getStanzaAtIndex(1)->getID()); + receiptReply->addPayload(receipt); + manager_->handleIncomingMessage(receiptReply); + } + + // Reply with a message including a CSN. + Message::ref reply = boost::make_shared(); + reply->setFrom(senderResource[0]); + reply->setTo(ownJID); + + boost::shared_ptr csn = boost::make_shared(); + csn->setChatState(ChatState::Composing); + reply->addPayload(csn); + manager_->handleIncomingMessage(reply); + + // Send third message. + window->onSendMessageRequest("great to hear.", false); + + // The chat session is now bound to the full JID of the first resource due to its recent composing message. + CPPUNIT_ASSERT_EQUAL(senderResource[0], stanzaChannel_->getStanzaAtIndex(2)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(2)->getPayload()); + + // Reply with a message including a CSN from the other resource. + reply = boost::make_shared(); + reply->setFrom(senderResource[1]); + reply->setTo(ownJID); + + csn = boost::make_shared(); + csn->setChatState(ChatState::Composing); + reply->addPayload(csn); + manager_->handleIncomingMessage(reply); + + // Send third message. + window->onSendMessageRequest("ping.", false); + + // The chat session is now bound to the full JID of the second resource due to its recent composing message. + CPPUNIT_ASSERT_EQUAL(senderResource[1], stanzaChannel_->getStanzaAtIndex(3)->getTo()); + CPPUNIT_ASSERT(stanzaChannel_->getStanzaAtIndex(3)->getPayload()); + } + + void testChatControllerPMPresenceHandling() { + JID participantA = JID("test@rooms.test.com/participantA"); + JID participantB = JID("test@rooms.test.com/participantB"); + + mucRegistry_->addMUC("test@rooms.test.com"); + + MockChatWindow* window = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(participantA, uiEventStream_).Return(window); + + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(JID(participantA)))); + + Presence::ref presence = Presence::create(); + presence->setFrom(participantA); + presence->setShow(StatusShow::Online); + stanzaChannel_->onPresenceReceived(presence); + CPPUNIT_ASSERT_EQUAL(std::string("participantA has become available."), MockChatWindow::bodyFromMessage(window->lastAddedPresence_)); + + presence = Presence::create(); + presence->setFrom(participantB); + presence->setShow(StatusShow::Away); + stanzaChannel_->onPresenceReceived(presence); + + presence = Presence::create(); + presence->setFrom(participantA); + presence->setShow(StatusShow::None); + presence->setType(Presence::Unavailable); + stanzaChannel_->onPresenceReceived(presence); + CPPUNIT_ASSERT_EQUAL(std::string("participantA has gone offline."), MockChatWindow::bodyFromMessage(window->lastReplacedMessage_)); + } + + void testLocalMUCServiceDiscoveryResetOnDisconnect() { + JID ownJID("test@test.com/resource"); + JID sender("foo@test.com"); + + manager_->setOnline(true); + + // Open chat window to a sender. + MockChatWindow* window = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(sender, uiEventStream_).Return(window); + + uiEventStream_->send(boost::make_shared(sender)); + + CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_); + + boost::shared_ptr infoRequest= iqChannel_->iqs_[1]; + boost::shared_ptr infoResponse = IQ::createResult(infoRequest->getFrom(), infoRequest->getTo(), infoRequest->getID()); + + DiscoInfo info; + info.addIdentity(DiscoInfo::Identity("Shakespearean Chat Service", "conference", "text")); + info.addFeature("http://jabber.org/protocol/muc"); + infoResponse->addPayload(boost::make_shared(info)); + iqChannel_->onIQReceived(infoResponse); + + CPPUNIT_ASSERT_EQUAL(true, window->impromptuMUCSupported_); + manager_->setOnline(false); + CPPUNIT_ASSERT_EQUAL(false, window->impromptuMUCSupported_); + } + + void testhelperChatControllerPresenceAccessUpdatedOnSubscriptionChangeReceiptsAllowed(RosterItemPayload::Subscription from, RosterItemPayload::Subscription to) { + JID messageJID("testling@test.com/resource1"); + xmppRoster_->addContact(messageJID, "foo", std::vector(), from); + + MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); + settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, true); + + boost::shared_ptr message = makeDeliveryReceiptTestMessage(messageJID, "1"); + manager_->handleIncomingMessage(message); + + CPPUNIT_ASSERT_EQUAL(st(0), stanzaChannel_->sentStanzas.size()); + + xmppRoster_->addContact(messageJID, "foo", std::vector(), to); + message->setID("2"); + manager_->handleIncomingMessage(message); + + CPPUNIT_ASSERT_EQUAL(st(1), stanzaChannel_->sentStanzas.size()); + Stanza::ref stanzaContactOnRoster = stanzaChannel_->getStanzaAtIndex(0); + CPPUNIT_ASSERT(stanzaContactOnRoster->getPayload() != 0); + } + + void testChatControllerHighlightingNotificationTesting() { + HighlightRule keywordRuleA; + keywordRuleA.setMatchChat(true); + std::vector keywordsA; + keywordsA.push_back("Romeo"); + keywordRuleA.setKeywords(keywordsA); + keywordRuleA.getAction().setTextColor("yellow"); + keywordRuleA.getAction().setPlaySound(true); + highlightManager_->insertRule(0, keywordRuleA); + + HighlightRule keywordRuleB; + keywordRuleB.setMatchChat(true); + std::vector keywordsB; + keywordsB.push_back("Juliet"); + keywordRuleB.setKeywords(keywordsB); + keywordRuleB.getAction().setTextColor("green"); + keywordRuleB.getAction().setPlaySound(true); + keywordRuleB.getAction().setSoundFile("/tmp/someotherfile.wav"); + highlightManager_->insertRule(0, keywordRuleB); + + JID messageJID = JID("testling@test.com"); + + MockChatWindow* window = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); + + boost::shared_ptr message(new Message()); + message->setFrom(messageJID); + std::string body("This message should cause two sounds: Juliet and Romeo."); + message->setBody(body); + manager_->handleIncomingMessage(message); + + CPPUNIT_ASSERT_EQUAL(2, handledHighlightActions_); + CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end()); + CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end()); + } + + void testChatControllerHighlightingNotificationDeduplicateSounds() { + HighlightRule keywordRuleA; + keywordRuleA.setMatchChat(true); + std::vector keywordsA; + keywordsA.push_back("Romeo"); + keywordRuleA.setKeywords(keywordsA); + keywordRuleA.getAction().setTextColor("yellow"); + keywordRuleA.getAction().setPlaySound(true); + highlightManager_->insertRule(0, keywordRuleA); + + HighlightRule keywordRuleB; + keywordRuleB.setMatchChat(true); + std::vector keywordsB; + keywordsB.push_back("Juliet"); + keywordRuleB.setKeywords(keywordsB); + keywordRuleB.getAction().setTextColor("green"); + keywordRuleB.getAction().setPlaySound(true); + highlightManager_->insertRule(0, keywordRuleB); + + JID messageJID = JID("testling@test.com"); + + MockChatWindow* window = new MockChatWindow(); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(messageJID, uiEventStream_).Return(window); + + boost::shared_ptr message(new Message()); + message->setFrom(messageJID); + std::string body("This message should cause one sound, because both actions have the same sound: Juliet and Romeo."); + message->setBody(body); + manager_->handleIncomingMessage(message); + + CPPUNIT_ASSERT_EQUAL(1, handledHighlightActions_); + CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleA.getAction().getSoundFile()) != soundsPlayed_.end()); + CPPUNIT_ASSERT(soundsPlayed_.find(keywordRuleB.getAction().getSoundFile()) != soundsPlayed_.end()); + } private: - boost::shared_ptr makeDeliveryReceiptTestMessage(const JID& from, const std::string& id) { - boost::shared_ptr message = boost::make_shared(); - message->setFrom(from); - message->setID(id); - message->setBody("This will cause the window to open"); - message->addPayload(boost::make_shared()); - return message; - } - - size_t st(int i) { - return static_cast(i); - } - - void handleHighlightAction(const HighlightAction& action) { - handledHighlightActions_++; - if (action.playSound()) { - soundsPlayed_.insert(action.getSoundFile()); - } - } + boost::shared_ptr makeDeliveryReceiptTestMessage(const JID& from, const std::string& id) { + boost::shared_ptr message = boost::make_shared(); + message->setFrom(from); + message->setID(id); + message->setBody("This will cause the window to open"); + message->addPayload(boost::make_shared()); + return message; + } + + size_t st(int i) { + return static_cast(i); + } + + void handleHighlightAction(const HighlightAction& action) { + handledHighlightActions_++; + if (action.playSound()) { + soundsPlayed_.insert(action.getSoundFile()); + } + } private: - JID jid_; - ChatsManager* manager_; - DummyStanzaChannel* stanzaChannel_; - DummyIQChannel* iqChannel_; - IQRouter* iqRouter_; - EventController* eventController_; - ChatWindowFactory* chatWindowFactory_; - JoinMUCWindowFactory* joinMUCWindowFactory_; - NickResolver* nickResolver_; - PresenceOracle* presenceOracle_; - AvatarManager* avatarManager_; - boost::shared_ptr serverDiscoInfo_; - XMPPRosterImpl* xmppRoster_; - PresenceSender* presenceSender_; - MockRepository* mocks_; - UIEventStream* uiEventStream_; - ChatListWindowFactory* chatListWindowFactory_; - WhiteboardWindowFactory* whiteboardWindowFactory_; - MUCSearchWindowFactory* mucSearchWindowFactory_; - MUCRegistry* mucRegistry_; - DirectedPresenceSender* directedPresenceSender_; - DummyEntityCapsProvider* entityCapsProvider_; - MUCManager* mucManager_; - DummySettingsProvider* settings_; - ProfileSettingsProvider* profileSettings_; - ChatListWindow* chatListWindow_; - FileTransferOverview* ftOverview_; - FileTransferManager* ftManager_; - WhiteboardSessionManager* wbSessionManager_; - WhiteboardManager* wbManager_; - HighlightManager* highlightManager_; - ClientBlockListManager* clientBlockListManager_; - VCardManager* vcardManager_; - CryptoProvider* crypto_; - VCardStorage* vcardStorage_; - std::map emoticons_; - int handledHighlightActions_; - std::set soundsPlayed_; + JID jid_; + ChatsManager* manager_; + DummyStanzaChannel* stanzaChannel_; + DummyIQChannel* iqChannel_; + IQRouter* iqRouter_; + EventController* eventController_; + ChatWindowFactory* chatWindowFactory_; + JoinMUCWindowFactory* joinMUCWindowFactory_; + NickResolver* nickResolver_; + PresenceOracle* presenceOracle_; + AvatarManager* avatarManager_; + boost::shared_ptr serverDiscoInfo_; + XMPPRosterImpl* xmppRoster_; + PresenceSender* presenceSender_; + MockRepository* mocks_; + UIEventStream* uiEventStream_; + ChatListWindowFactory* chatListWindowFactory_; + WhiteboardWindowFactory* whiteboardWindowFactory_; + MUCSearchWindowFactory* mucSearchWindowFactory_; + MUCRegistry* mucRegistry_; + DirectedPresenceSender* directedPresenceSender_; + DummyEntityCapsProvider* entityCapsProvider_; + MUCManager* mucManager_; + DummySettingsProvider* settings_; + ProfileSettingsProvider* profileSettings_; + ChatListWindow* chatListWindow_; + FileTransferOverview* ftOverview_; + FileTransferManager* ftManager_; + WhiteboardSessionManager* wbSessionManager_; + WhiteboardManager* wbManager_; + HighlightManager* highlightManager_; + ClientBlockListManager* clientBlockListManager_; + VCardManager* vcardManager_; + CryptoProvider* crypto_; + VCardStorage* vcardStorage_; + std::map emoticons_; + int handledHighlightActions_; + std::set soundsPlayed_; }; CPPUNIT_TEST_SUITE_REGISTRATION(ChatsManagerTest); diff --git a/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp b/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp index e8fc41d..db9bcdc 100644 --- a/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp +++ b/Swift/Controllers/Chat/UnitTest/MUCControllerTest.cpp @@ -48,509 +48,509 @@ using namespace Swift; class MUCControllerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(MUCControllerTest); - CPPUNIT_TEST(testJoinPartStringContructionSimple); - CPPUNIT_TEST(testJoinPartStringContructionMixed); - CPPUNIT_TEST(testAppendToJoinParts); - CPPUNIT_TEST(testAddressedToSelf); - CPPUNIT_TEST(testNotAddressedToSelf); - CPPUNIT_TEST(testAddressedToSelfBySelf); - CPPUNIT_TEST(testMessageWithEmptyLabelItem); - CPPUNIT_TEST(testMessageWithLabelItem); - CPPUNIT_TEST(testCorrectMessageWithLabelItem); - CPPUNIT_TEST(testRoleAffiliationStates); - CPPUNIT_TEST(testSubjectChangeCorrect); - CPPUNIT_TEST(testSubjectChangeIncorrectA); - CPPUNIT_TEST(testSubjectChangeIncorrectB); - CPPUNIT_TEST(testSubjectChangeIncorrectC); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(MUCControllerTest); + CPPUNIT_TEST(testJoinPartStringContructionSimple); + CPPUNIT_TEST(testJoinPartStringContructionMixed); + CPPUNIT_TEST(testAppendToJoinParts); + CPPUNIT_TEST(testAddressedToSelf); + CPPUNIT_TEST(testNotAddressedToSelf); + CPPUNIT_TEST(testAddressedToSelfBySelf); + CPPUNIT_TEST(testMessageWithEmptyLabelItem); + CPPUNIT_TEST(testMessageWithLabelItem); + CPPUNIT_TEST(testCorrectMessageWithLabelItem); + CPPUNIT_TEST(testRoleAffiliationStates); + CPPUNIT_TEST(testSubjectChangeCorrect); + CPPUNIT_TEST(testSubjectChangeIncorrectA); + CPPUNIT_TEST(testSubjectChangeIncorrectB); + CPPUNIT_TEST(testSubjectChangeIncorrectC); + CPPUNIT_TEST_SUITE_END(); public: - void setUp() { - crypto_ = boost::shared_ptr(PlatformCryptoProvider::create()); - self_ = JID("girl@wonderland.lit/rabbithole"); - nick_ = "aLiCe"; - mucJID_ = JID("teaparty@rooms.wonderland.lit"); - mocks_ = new MockRepository(); - stanzaChannel_ = new DummyStanzaChannel(); - iqChannel_ = new DummyIQChannel(); - iqRouter_ = new IQRouter(iqChannel_); - eventController_ = new EventController(); - chatWindowFactory_ = mocks_->InterfaceMock(); - userSearchWindowFactory_ = mocks_->InterfaceMock(); - xmppRoster_ = new XMPPRosterImpl(); - presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_); - presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_); - directedPresenceSender_ = new DirectedPresenceSender(presenceSender_); - uiEventStream_ = new UIEventStream(); - avatarManager_ = new NullAvatarManager(); - TimerFactory* timerFactory = NULL; - window_ = new MockChatWindow(); - mucRegistry_ = new MUCRegistry(); - entityCapsProvider_ = new DummyEntityCapsProvider(); - settings_ = new DummySettingsProvider(); - highlightManager_ = new HighlightManager(settings_); - muc_ = boost::make_shared(mucJID_); - mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc_->getJID(), uiEventStream_).Return(window_); - chatMessageParser_ = boost::make_shared(std::map(), highlightManager_->getRules(), true); - vcardStorage_ = new VCardMemoryStorage(crypto_.get()); - vcardManager_ = new VCardManager(self_, iqRouter_, vcardStorage_); - clientBlockListManager_ = new ClientBlockListManager(iqRouter_); - mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_); - controller_ = new MUCController (self_, muc_, boost::optional(), nick_, stanzaChannel_, iqRouter_, chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory, eventController_, entityCapsProvider_, NULL, NULL, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser_, false, NULL, vcardManager_, mucBookmarkManager_); - } - - void tearDown() { - delete controller_; - delete mucBookmarkManager_; - delete clientBlockListManager_; - delete vcardManager_; - delete vcardStorage_; - delete highlightManager_; - delete settings_; - delete entityCapsProvider_; - delete eventController_; - delete presenceOracle_; - delete xmppRoster_; - delete mocks_; - delete uiEventStream_; - delete stanzaChannel_; - delete presenceSender_; - delete directedPresenceSender_; - delete iqRouter_; - delete iqChannel_; - delete mucRegistry_; - delete avatarManager_; - } - - void finishJoin() { - Presence::ref presence(new Presence()); - presence->setFrom(JID(muc_->getJID().toString() + "/" + nick_)); - MUCUserPayload::ref status(new MUCUserPayload()); - MUCUserPayload::StatusCode code; - code.code = 110; - status->addStatusCode(code); - presence->addPayload(status); - stanzaChannel_->onPresenceReceived(presence); - } - - void testAddressedToSelf() { - finishJoin(); - Message::ref message(new Message()); - - message = Message::ref(new Message()); - message->setFrom(JID(muc_->getJID().toString() + "/otherperson")); - message->setBody("basic " + nick_ + " test."); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)1, eventController_->getEvents().size()); - - message = Message::ref(new Message()); - message->setFrom(JID(muc_->getJID().toString() + "/otherperson")); - message->setBody(nick_ + ": hi there"); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)2, eventController_->getEvents().size()); - - message->setFrom(JID(muc_->getJID().toString() + "/other")); - message->setBody("Hi there " + nick_); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)3, eventController_->getEvents().size()); - - message = Message::ref(new Message()); - message->setFrom(JID(muc_->getJID().toString() + "/other2")); - message->setBody("Hi " + boost::to_lower_copy(nick_) + "."); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size()); - - message = Message::ref(new Message()); - message->setFrom(JID(muc_->getJID().toString() + "/other3")); - message->setBody("Hi bert."); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size()); - - message = Message::ref(new Message()); - message->setFrom(JID(muc_->getJID().toString() + "/other2")); - message->setBody("Hi " + boost::to_lower_copy(nick_) + "ie."); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size()); - } - - void testNotAddressedToSelf() { - finishJoin(); - Message::ref message(new Message()); - message->setFrom(JID(muc_->getJID().toString() + "/other3")); - message->setBody("Hi there Hatter"); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size()); - } - - void testAddressedToSelfBySelf() { - finishJoin(); - Message::ref message(new Message()); - message->setFrom(JID(muc_->getJID().toString() + "/" + nick_)); - message->setBody("Hi there " + nick_); - message->setType(Message::Groupchat); - controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); - CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size()); - } - - void testMessageWithEmptyLabelItem() { - SecurityLabelsCatalog::Item label; - label.setSelector("Bob"); - window_->label_ = label; - boost::shared_ptr features = boost::make_shared(); - features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature); - controller_->setAvailableServerFeatures(features); - IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1]; - SecurityLabelsCatalog::ref labelPayload = boost::make_shared(); - labelPayload->addItem(label); - IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload); - iqChannel_->onIQReceived(result); - std::string messageBody("agamemnon"); - window_->onSendMessageRequest(messageBody, false); - boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - Message::ref message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom()); - CPPUNIT_ASSERT(window_->labelsEnabled_); - CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ - CPPUNIT_ASSERT(message); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); - CPPUNIT_ASSERT(!message->getPayload()); - } - - void testMessageWithLabelItem() { - boost::shared_ptr label = boost::make_shared(); - label->setLabel("a"); - SecurityLabelsCatalog::Item labelItem; - labelItem.setSelector("Bob"); - labelItem.setLabel(label); - window_->label_ = labelItem; - boost::shared_ptr features = boost::make_shared(); - features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature); - controller_->setAvailableServerFeatures(features); - IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1]; - SecurityLabelsCatalog::ref labelPayload = boost::make_shared(); - labelPayload->addItem(labelItem); - IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload); - iqChannel_->onIQReceived(result); - std::string messageBody("agamemnon"); - window_->onSendMessageRequest(messageBody, false); - boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - Message::ref message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom()); - CPPUNIT_ASSERT(window_->labelsEnabled_); - CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ - CPPUNIT_ASSERT(message); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); - CPPUNIT_ASSERT_EQUAL(label, message->getPayload()); - } - - void testCorrectMessageWithLabelItem() { - boost::shared_ptr label = boost::make_shared(); - label->setLabel("a"); - SecurityLabelsCatalog::Item labelItem; - labelItem.setSelector("Bob"); - labelItem.setLabel(label); - boost::shared_ptr label2 = boost::make_shared(); - label->setLabel("b"); - SecurityLabelsCatalog::Item labelItem2; - labelItem2.setSelector("Charlie"); - labelItem2.setLabel(label2); - window_->label_ = labelItem; - boost::shared_ptr features = boost::make_shared(); - features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature); - controller_->setAvailableServerFeatures(features); - IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1]; - SecurityLabelsCatalog::ref labelPayload = boost::make_shared(); - labelPayload->addItem(labelItem); - IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload); - iqChannel_->onIQReceived(result); - std::string messageBody("agamemnon"); - window_->onSendMessageRequest(messageBody, false); - boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - Message::ref message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom()); - CPPUNIT_ASSERT(window_->labelsEnabled_); - CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ - CPPUNIT_ASSERT(message); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); - CPPUNIT_ASSERT_EQUAL(label, message->getPayload()); - window_->label_ = labelItem2; - window_->onSendMessageRequest(messageBody, true); - rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); - CPPUNIT_ASSERT_EQUAL(label, message->getPayload()); - } - - void checkEqual(const std::vector& expected, const std::vector& actual) { - CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size()); - for (size_t i = 0; i < expected.size(); i++) { - CPPUNIT_ASSERT_EQUAL(expected[i].nick, actual[i].nick); - CPPUNIT_ASSERT_EQUAL(expected[i].type, actual[i].type); - } - } - - void testAppendToJoinParts() { - std::vector list; - std::vector gold; - MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join)); - gold.push_back(NickJoinPart("Kev", Join)); - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Remko", Join)); - gold.push_back(NickJoinPart("Remko", Join)); - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Bert", Join)); - gold.push_back(NickJoinPart("Bert", Join)); - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Bert", Part)); - gold[2].type = JoinThenPart; - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Kev", Part)); - gold[0].type = JoinThenPart; - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Remko", Part)); - gold[1].type = JoinThenPart; - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part)); - gold.push_back(NickJoinPart("Ernie", Part)); - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Join)); - gold[3].type = PartThenJoin; - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join)); - gold[0].type = Join; - checkEqual(gold, list); - MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part)); - gold[3].type = Part; - checkEqual(gold, list); - - } - - void testJoinPartStringContructionSimple() { - std::vector list; - list.push_back(NickJoinPart("Kev", Join)); - CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room"), MUCController::generateJoinPartString(list, false)); - list.push_back(NickJoinPart("Remko", Part)); - CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false)); - list.push_back(NickJoinPart("Bert", Join)); - CPPUNIT_ASSERT_EQUAL(std::string("Kev and Bert have entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false)); - list.push_back(NickJoinPart("Ernie", Join)); - CPPUNIT_ASSERT_EQUAL(std::string("Kev, Bert and Ernie have entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false)); - } - - void testJoinPartStringContructionMixed() { - std::vector list; - list.push_back(NickJoinPart("Kev", JoinThenPart)); - CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered then left the room"), MUCController::generateJoinPartString(list, false)); - list.push_back(NickJoinPart("Remko", Part)); - CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room and Kev has entered then left the room"), MUCController::generateJoinPartString(list, false)); - list.push_back(NickJoinPart("Bert", PartThenJoin)); - CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room, Kev has entered then left the room and Bert has left then returned to the room"), MUCController::generateJoinPartString(list, false)); - list.push_back(NickJoinPart("Ernie", JoinThenPart)); - CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room, Kev and Ernie have entered then left the room and Bert has left then returned to the room"), MUCController::generateJoinPartString(list, false)); - } - - JID jidFromOccupant(const MUCOccupant& occupant) { - return JID(mucJID_.toString()+"/"+occupant.getNick()); - } - - void testRoleAffiliationStates() { - - typedef std::map occupant_map; - occupant_map occupants; - occupants.insert(occupant_map::value_type("Kev", MUCOccupant("Kev", MUCOccupant::Participant, MUCOccupant::Owner))); - occupants.insert(occupant_map::value_type("Remko", MUCOccupant("Remko", MUCOccupant::Participant, MUCOccupant::Owner))); - occupants.insert(occupant_map::value_type("Bert", MUCOccupant("Bert", MUCOccupant::Participant, MUCOccupant::Owner))); - occupants.insert(occupant_map::value_type("Ernie", MUCOccupant("Ernie", MUCOccupant::Participant, MUCOccupant::Owner))); - - /* populate the MUC with fake users */ - typedef const std::pair occupantIterator; - foreach(occupantIterator &occupant, occupants) { - muc_->insertOccupant(occupant.second); - } - - std::vector alterations; - alterations.push_back(MUCOccupant("Kev", MUCOccupant::Visitor, MUCOccupant::Admin)); - alterations.push_back(MUCOccupant("Remko", MUCOccupant::Moderator, MUCOccupant::Member)); - alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::Outcast)); - alterations.push_back(MUCOccupant("Ernie", MUCOccupant::NoRole, MUCOccupant::Member)); - alterations.push_back(MUCOccupant("Bert", MUCOccupant::Moderator, MUCOccupant::Owner)); - alterations.push_back(MUCOccupant("Kev", MUCOccupant::Participant, MUCOccupant::Outcast)); - alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::NoAffiliation)); - alterations.push_back(MUCOccupant("Remko", MUCOccupant::NoRole, MUCOccupant::NoAffiliation)); - alterations.push_back(MUCOccupant("Ernie", MUCOccupant::Visitor, MUCOccupant::Outcast)); - - foreach(const MUCOccupant& alteration, alterations) { - /* perform an alteration to a user's role and affiliation */ - occupant_map::iterator occupant = occupants.find(alteration.getNick()); - CPPUNIT_ASSERT(occupant != occupants.end()); - const JID jid = jidFromOccupant(occupant->second); - /* change the affiliation, leave the role in place */ - muc_->changeAffiliation(jid, alteration.getAffiliation()); - occupant->second = MUCOccupant(occupant->first, occupant->second.getRole(), alteration.getAffiliation()); - testRoleAffiliationStatesVerify(occupants); - /* change the role, leave the affiliation in place */ - muc_->changeOccupantRole(jid, alteration.getRole()); - occupant->second = MUCOccupant(occupant->first, alteration.getRole(), occupant->second.getAffiliation()); - testRoleAffiliationStatesVerify(occupants); - } - } - - void testSubjectChangeCorrect() { - std::string messageBody("test message"); - window_->onSendMessageRequest(messageBody, false); - boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - Message::ref message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ - CPPUNIT_ASSERT(message); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); - - { - Message::ref message = boost::make_shared(); - message->setType(Message::Groupchat); - message->setTo(self_); - message->setFrom(mucJID_.withResource("SomeNickname")); - message->setID(iqChannel_->getNewIQID()); - message->setSubject("New Room Subject"); - - controller_->handleIncomingMessage(boost::make_shared(message)); - CPPUNIT_ASSERT_EQUAL(std::string("The room subject is now: New Room Subject"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); - } - } - - /* - * Test that message stanzas with subject element and non-empty body element do not cause a subject change. - */ - void testSubjectChangeIncorrectA() { - std::string messageBody("test message"); - window_->onSendMessageRequest(messageBody, false); - boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - Message::ref message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ - CPPUNIT_ASSERT(message); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); - - { - Message::ref message = boost::make_shared(); - message->setType(Message::Groupchat); - message->setTo(self_); - message->setFrom(mucJID_.withResource("SomeNickname")); - message->setID(iqChannel_->getNewIQID()); - message->setSubject("New Room Subject"); - message->setBody("Some body text that prevents this stanza from being a subject change."); - - controller_->handleIncomingMessage(boost::make_shared(message)); - CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); - } - } - - /* - * Test that message stanzas with subject element and thread element do not cause a subject change. - */ - void testSubjectChangeIncorrectB() { - std::string messageBody("test message"); - window_->onSendMessageRequest(messageBody, false); - boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - Message::ref message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ - CPPUNIT_ASSERT(message); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); - - { - Message::ref message = boost::make_shared(); - message->setType(Message::Groupchat); - message->setTo(self_); - message->setFrom(mucJID_.withResource("SomeNickname")); - message->setID(iqChannel_->getNewIQID()); - message->setSubject("New Room Subject"); - message->addPayload(boost::make_shared("Thread that prevents the subject change.")); - - controller_->handleIncomingMessage(boost::make_shared(message)); - CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); - } - } - - /* - * Test that message stanzas with subject element and empty body element do not cause a subject change. - */ - void testSubjectChangeIncorrectC() { - std::string messageBody("test message"); - window_->onSendMessageRequest(messageBody, false); - boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; - Message::ref message = boost::dynamic_pointer_cast(rawStanza); - CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ - CPPUNIT_ASSERT(message); - CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); - - { - Message::ref message = boost::make_shared(); - message->setType(Message::Groupchat); - message->setTo(self_); - message->setFrom(mucJID_.withResource("SomeNickname")); - message->setID(iqChannel_->getNewIQID()); - message->setSubject("New Room Subject"); - message->setBody(""); - - controller_->handleIncomingMessage(boost::make_shared(message)); - CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); - } - } - - void testRoleAffiliationStatesVerify(const std::map &occupants) { - /* verify that the roster is in sync */ - GroupRosterItem* group = window_->getRosterModel()->getRoot(); - foreach(RosterItem* rosterItem, group->getChildren()) { - GroupRosterItem* child = dynamic_cast(rosterItem); - CPPUNIT_ASSERT(child); - foreach(RosterItem* childItem, child->getChildren()) { - ContactRosterItem* item = dynamic_cast(childItem); - CPPUNIT_ASSERT(item); - std::map::const_iterator occupant = occupants.find(item->getJID().getResource()); - CPPUNIT_ASSERT(occupant != occupants.end()); - CPPUNIT_ASSERT(item->getMUCRole() == occupant->second.getRole()); - CPPUNIT_ASSERT(item->getMUCAffiliation() == occupant->second.getAffiliation()); - } - } - } + void setUp() { + crypto_ = boost::shared_ptr(PlatformCryptoProvider::create()); + self_ = JID("girl@wonderland.lit/rabbithole"); + nick_ = "aLiCe"; + mucJID_ = JID("teaparty@rooms.wonderland.lit"); + mocks_ = new MockRepository(); + stanzaChannel_ = new DummyStanzaChannel(); + iqChannel_ = new DummyIQChannel(); + iqRouter_ = new IQRouter(iqChannel_); + eventController_ = new EventController(); + chatWindowFactory_ = mocks_->InterfaceMock(); + userSearchWindowFactory_ = mocks_->InterfaceMock(); + xmppRoster_ = new XMPPRosterImpl(); + presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_); + presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_); + directedPresenceSender_ = new DirectedPresenceSender(presenceSender_); + uiEventStream_ = new UIEventStream(); + avatarManager_ = new NullAvatarManager(); + TimerFactory* timerFactory = NULL; + window_ = new MockChatWindow(); + mucRegistry_ = new MUCRegistry(); + entityCapsProvider_ = new DummyEntityCapsProvider(); + settings_ = new DummySettingsProvider(); + highlightManager_ = new HighlightManager(settings_); + muc_ = boost::make_shared(mucJID_); + mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc_->getJID(), uiEventStream_).Return(window_); + chatMessageParser_ = boost::make_shared(std::map(), highlightManager_->getRules(), true); + vcardStorage_ = new VCardMemoryStorage(crypto_.get()); + vcardManager_ = new VCardManager(self_, iqRouter_, vcardStorage_); + clientBlockListManager_ = new ClientBlockListManager(iqRouter_); + mucBookmarkManager_ = new MUCBookmarkManager(iqRouter_); + controller_ = new MUCController (self_, muc_, boost::optional(), nick_, stanzaChannel_, iqRouter_, chatWindowFactory_, presenceOracle_, avatarManager_, uiEventStream_, false, timerFactory, eventController_, entityCapsProvider_, NULL, NULL, mucRegistry_, highlightManager_, clientBlockListManager_, chatMessageParser_, false, NULL, vcardManager_, mucBookmarkManager_); + } + + void tearDown() { + delete controller_; + delete mucBookmarkManager_; + delete clientBlockListManager_; + delete vcardManager_; + delete vcardStorage_; + delete highlightManager_; + delete settings_; + delete entityCapsProvider_; + delete eventController_; + delete presenceOracle_; + delete xmppRoster_; + delete mocks_; + delete uiEventStream_; + delete stanzaChannel_; + delete presenceSender_; + delete directedPresenceSender_; + delete iqRouter_; + delete iqChannel_; + delete mucRegistry_; + delete avatarManager_; + } + + void finishJoin() { + Presence::ref presence(new Presence()); + presence->setFrom(JID(muc_->getJID().toString() + "/" + nick_)); + MUCUserPayload::ref status(new MUCUserPayload()); + MUCUserPayload::StatusCode code; + code.code = 110; + status->addStatusCode(code); + presence->addPayload(status); + stanzaChannel_->onPresenceReceived(presence); + } + + void testAddressedToSelf() { + finishJoin(); + Message::ref message(new Message()); + + message = Message::ref(new Message()); + message->setFrom(JID(muc_->getJID().toString() + "/otherperson")); + message->setBody("basic " + nick_ + " test."); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)1, eventController_->getEvents().size()); + + message = Message::ref(new Message()); + message->setFrom(JID(muc_->getJID().toString() + "/otherperson")); + message->setBody(nick_ + ": hi there"); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)2, eventController_->getEvents().size()); + + message->setFrom(JID(muc_->getJID().toString() + "/other")); + message->setBody("Hi there " + nick_); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)3, eventController_->getEvents().size()); + + message = Message::ref(new Message()); + message->setFrom(JID(muc_->getJID().toString() + "/other2")); + message->setBody("Hi " + boost::to_lower_copy(nick_) + "."); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size()); + + message = Message::ref(new Message()); + message->setFrom(JID(muc_->getJID().toString() + "/other3")); + message->setBody("Hi bert."); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size()); + + message = Message::ref(new Message()); + message->setFrom(JID(muc_->getJID().toString() + "/other2")); + message->setBody("Hi " + boost::to_lower_copy(nick_) + "ie."); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)4, eventController_->getEvents().size()); + } + + void testNotAddressedToSelf() { + finishJoin(); + Message::ref message(new Message()); + message->setFrom(JID(muc_->getJID().toString() + "/other3")); + message->setBody("Hi there Hatter"); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size()); + } + + void testAddressedToSelfBySelf() { + finishJoin(); + Message::ref message(new Message()); + message->setFrom(JID(muc_->getJID().toString() + "/" + nick_)); + message->setBody("Hi there " + nick_); + message->setType(Message::Groupchat); + controller_->handleIncomingMessage(MessageEvent::ref(new MessageEvent(message))); + CPPUNIT_ASSERT_EQUAL((size_t)0, eventController_->getEvents().size()); + } + + void testMessageWithEmptyLabelItem() { + SecurityLabelsCatalog::Item label; + label.setSelector("Bob"); + window_->label_ = label; + boost::shared_ptr features = boost::make_shared(); + features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature); + controller_->setAvailableServerFeatures(features); + IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1]; + SecurityLabelsCatalog::ref labelPayload = boost::make_shared(); + labelPayload->addItem(label); + IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload); + iqChannel_->onIQReceived(result); + std::string messageBody("agamemnon"); + window_->onSendMessageRequest(messageBody, false); + boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + Message::ref message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom()); + CPPUNIT_ASSERT(window_->labelsEnabled_); + CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ + CPPUNIT_ASSERT(message); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); + CPPUNIT_ASSERT(!message->getPayload()); + } + + void testMessageWithLabelItem() { + boost::shared_ptr label = boost::make_shared(); + label->setLabel("a"); + SecurityLabelsCatalog::Item labelItem; + labelItem.setSelector("Bob"); + labelItem.setLabel(label); + window_->label_ = labelItem; + boost::shared_ptr features = boost::make_shared(); + features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature); + controller_->setAvailableServerFeatures(features); + IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1]; + SecurityLabelsCatalog::ref labelPayload = boost::make_shared(); + labelPayload->addItem(labelItem); + IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload); + iqChannel_->onIQReceived(result); + std::string messageBody("agamemnon"); + window_->onSendMessageRequest(messageBody, false); + boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + Message::ref message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom()); + CPPUNIT_ASSERT(window_->labelsEnabled_); + CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ + CPPUNIT_ASSERT(message); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); + CPPUNIT_ASSERT_EQUAL(label, message->getPayload()); + } + + void testCorrectMessageWithLabelItem() { + boost::shared_ptr label = boost::make_shared(); + label->setLabel("a"); + SecurityLabelsCatalog::Item labelItem; + labelItem.setSelector("Bob"); + labelItem.setLabel(label); + boost::shared_ptr label2 = boost::make_shared(); + label->setLabel("b"); + SecurityLabelsCatalog::Item labelItem2; + labelItem2.setSelector("Charlie"); + labelItem2.setLabel(label2); + window_->label_ = labelItem; + boost::shared_ptr features = boost::make_shared(); + features->addFeature(DiscoInfo::SecurityLabelsCatalogFeature); + controller_->setAvailableServerFeatures(features); + IQ::ref iq = iqChannel_->iqs_[iqChannel_->iqs_.size() - 1]; + SecurityLabelsCatalog::ref labelPayload = boost::make_shared(); + labelPayload->addItem(labelItem); + IQ::ref result = IQ::createResult(self_, iq->getID(), labelPayload); + iqChannel_->onIQReceived(result); + std::string messageBody("agamemnon"); + window_->onSendMessageRequest(messageBody, false); + boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + Message::ref message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT_EQUAL(iq->getTo(), result->getFrom()); + CPPUNIT_ASSERT(window_->labelsEnabled_); + CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ + CPPUNIT_ASSERT(message); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); + CPPUNIT_ASSERT_EQUAL(label, message->getPayload()); + window_->label_ = labelItem2; + window_->onSendMessageRequest(messageBody, true); + rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get()); + CPPUNIT_ASSERT_EQUAL(label, message->getPayload()); + } + + void checkEqual(const std::vector& expected, const std::vector& actual) { + CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size()); + for (size_t i = 0; i < expected.size(); i++) { + CPPUNIT_ASSERT_EQUAL(expected[i].nick, actual[i].nick); + CPPUNIT_ASSERT_EQUAL(expected[i].type, actual[i].type); + } + } + + void testAppendToJoinParts() { + std::vector list; + std::vector gold; + MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join)); + gold.push_back(NickJoinPart("Kev", Join)); + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Remko", Join)); + gold.push_back(NickJoinPart("Remko", Join)); + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Bert", Join)); + gold.push_back(NickJoinPart("Bert", Join)); + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Bert", Part)); + gold[2].type = JoinThenPart; + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Kev", Part)); + gold[0].type = JoinThenPart; + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Remko", Part)); + gold[1].type = JoinThenPart; + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part)); + gold.push_back(NickJoinPart("Ernie", Part)); + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Join)); + gold[3].type = PartThenJoin; + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Kev", Join)); + gold[0].type = Join; + checkEqual(gold, list); + MUCController::appendToJoinParts(list, NickJoinPart("Ernie", Part)); + gold[3].type = Part; + checkEqual(gold, list); + + } + + void testJoinPartStringContructionSimple() { + std::vector list; + list.push_back(NickJoinPart("Kev", Join)); + CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room"), MUCController::generateJoinPartString(list, false)); + list.push_back(NickJoinPart("Remko", Part)); + CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false)); + list.push_back(NickJoinPart("Bert", Join)); + CPPUNIT_ASSERT_EQUAL(std::string("Kev and Bert have entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false)); + list.push_back(NickJoinPart("Ernie", Join)); + CPPUNIT_ASSERT_EQUAL(std::string("Kev, Bert and Ernie have entered the room and Remko has left the room"), MUCController::generateJoinPartString(list, false)); + } + + void testJoinPartStringContructionMixed() { + std::vector list; + list.push_back(NickJoinPart("Kev", JoinThenPart)); + CPPUNIT_ASSERT_EQUAL(std::string("Kev has entered then left the room"), MUCController::generateJoinPartString(list, false)); + list.push_back(NickJoinPart("Remko", Part)); + CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room and Kev has entered then left the room"), MUCController::generateJoinPartString(list, false)); + list.push_back(NickJoinPart("Bert", PartThenJoin)); + CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room, Kev has entered then left the room and Bert has left then returned to the room"), MUCController::generateJoinPartString(list, false)); + list.push_back(NickJoinPart("Ernie", JoinThenPart)); + CPPUNIT_ASSERT_EQUAL(std::string("Remko has left the room, Kev and Ernie have entered then left the room and Bert has left then returned to the room"), MUCController::generateJoinPartString(list, false)); + } + + JID jidFromOccupant(const MUCOccupant& occupant) { + return JID(mucJID_.toString()+"/"+occupant.getNick()); + } + + void testRoleAffiliationStates() { + + typedef std::map occupant_map; + occupant_map occupants; + occupants.insert(occupant_map::value_type("Kev", MUCOccupant("Kev", MUCOccupant::Participant, MUCOccupant::Owner))); + occupants.insert(occupant_map::value_type("Remko", MUCOccupant("Remko", MUCOccupant::Participant, MUCOccupant::Owner))); + occupants.insert(occupant_map::value_type("Bert", MUCOccupant("Bert", MUCOccupant::Participant, MUCOccupant::Owner))); + occupants.insert(occupant_map::value_type("Ernie", MUCOccupant("Ernie", MUCOccupant::Participant, MUCOccupant::Owner))); + + /* populate the MUC with fake users */ + typedef const std::pair occupantIterator; + foreach(occupantIterator &occupant, occupants) { + muc_->insertOccupant(occupant.second); + } + + std::vector alterations; + alterations.push_back(MUCOccupant("Kev", MUCOccupant::Visitor, MUCOccupant::Admin)); + alterations.push_back(MUCOccupant("Remko", MUCOccupant::Moderator, MUCOccupant::Member)); + alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::Outcast)); + alterations.push_back(MUCOccupant("Ernie", MUCOccupant::NoRole, MUCOccupant::Member)); + alterations.push_back(MUCOccupant("Bert", MUCOccupant::Moderator, MUCOccupant::Owner)); + alterations.push_back(MUCOccupant("Kev", MUCOccupant::Participant, MUCOccupant::Outcast)); + alterations.push_back(MUCOccupant("Bert", MUCOccupant::Visitor, MUCOccupant::NoAffiliation)); + alterations.push_back(MUCOccupant("Remko", MUCOccupant::NoRole, MUCOccupant::NoAffiliation)); + alterations.push_back(MUCOccupant("Ernie", MUCOccupant::Visitor, MUCOccupant::Outcast)); + + foreach(const MUCOccupant& alteration, alterations) { + /* perform an alteration to a user's role and affiliation */ + occupant_map::iterator occupant = occupants.find(alteration.getNick()); + CPPUNIT_ASSERT(occupant != occupants.end()); + const JID jid = jidFromOccupant(occupant->second); + /* change the affiliation, leave the role in place */ + muc_->changeAffiliation(jid, alteration.getAffiliation()); + occupant->second = MUCOccupant(occupant->first, occupant->second.getRole(), alteration.getAffiliation()); + testRoleAffiliationStatesVerify(occupants); + /* change the role, leave the affiliation in place */ + muc_->changeOccupantRole(jid, alteration.getRole()); + occupant->second = MUCOccupant(occupant->first, alteration.getRole(), occupant->second.getAffiliation()); + testRoleAffiliationStatesVerify(occupants); + } + } + + void testSubjectChangeCorrect() { + std::string messageBody("test message"); + window_->onSendMessageRequest(messageBody, false); + boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + Message::ref message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ + CPPUNIT_ASSERT(message); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); + + { + Message::ref message = boost::make_shared(); + message->setType(Message::Groupchat); + message->setTo(self_); + message->setFrom(mucJID_.withResource("SomeNickname")); + message->setID(iqChannel_->getNewIQID()); + message->setSubject("New Room Subject"); + + controller_->handleIncomingMessage(boost::make_shared(message)); + CPPUNIT_ASSERT_EQUAL(std::string("The room subject is now: New Room Subject"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); + } + } + + /* + * Test that message stanzas with subject element and non-empty body element do not cause a subject change. + */ + void testSubjectChangeIncorrectA() { + std::string messageBody("test message"); + window_->onSendMessageRequest(messageBody, false); + boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + Message::ref message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ + CPPUNIT_ASSERT(message); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); + + { + Message::ref message = boost::make_shared(); + message->setType(Message::Groupchat); + message->setTo(self_); + message->setFrom(mucJID_.withResource("SomeNickname")); + message->setID(iqChannel_->getNewIQID()); + message->setSubject("New Room Subject"); + message->setBody("Some body text that prevents this stanza from being a subject change."); + + controller_->handleIncomingMessage(boost::make_shared(message)); + CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); + } + } + + /* + * Test that message stanzas with subject element and thread element do not cause a subject change. + */ + void testSubjectChangeIncorrectB() { + std::string messageBody("test message"); + window_->onSendMessageRequest(messageBody, false); + boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + Message::ref message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ + CPPUNIT_ASSERT(message); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); + + { + Message::ref message = boost::make_shared(); + message->setType(Message::Groupchat); + message->setTo(self_); + message->setFrom(mucJID_.withResource("SomeNickname")); + message->setID(iqChannel_->getNewIQID()); + message->setSubject("New Room Subject"); + message->addPayload(boost::make_shared("Thread that prevents the subject change.")); + + controller_->handleIncomingMessage(boost::make_shared(message)); + CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); + } + } + + /* + * Test that message stanzas with subject element and empty body element do not cause a subject change. + */ + void testSubjectChangeIncorrectC() { + std::string messageBody("test message"); + window_->onSendMessageRequest(messageBody, false); + boost::shared_ptr rawStanza = stanzaChannel_->sentStanzas[stanzaChannel_->sentStanzas.size() - 1]; + Message::ref message = boost::dynamic_pointer_cast(rawStanza); + CPPUNIT_ASSERT(stanzaChannel_->isAvailable()); /* Otherwise will prevent sends. */ + CPPUNIT_ASSERT(message); + CPPUNIT_ASSERT_EQUAL(messageBody, message->getBody().get_value_or("")); + + { + Message::ref message = boost::make_shared(); + message->setType(Message::Groupchat); + message->setTo(self_); + message->setFrom(mucJID_.withResource("SomeNickname")); + message->setID(iqChannel_->getNewIQID()); + message->setSubject("New Room Subject"); + message->setBody(""); + + controller_->handleIncomingMessage(boost::make_shared(message)); + CPPUNIT_ASSERT_EQUAL(std::string("Trying to enter room teaparty@rooms.wonderland.lit"), boost::dynamic_pointer_cast(window_->lastAddedSystemMessage_.getParts()[0])->text); + } + } + + void testRoleAffiliationStatesVerify(const std::map &occupants) { + /* verify that the roster is in sync */ + GroupRosterItem* group = window_->getRosterModel()->getRoot(); + foreach(RosterItem* rosterItem, group->getChildren()) { + GroupRosterItem* child = dynamic_cast(rosterItem); + CPPUNIT_ASSERT(child); + foreach(RosterItem* childItem, child->getChildren()) { + ContactRosterItem* item = dynamic_cast(childItem); + CPPUNIT_ASSERT(item); + std::map::const_iterator occupant = occupants.find(item->getJID().getResource()); + CPPUNIT_ASSERT(occupant != occupants.end()); + CPPUNIT_ASSERT(item->getMUCRole() == occupant->second.getRole()); + CPPUNIT_ASSERT(item->getMUCAffiliation() == occupant->second.getAffiliation()); + } + } + } private: - JID self_; - JID mucJID_; - MockMUC::ref muc_; - std::string nick_; - DummyStanzaChannel* stanzaChannel_; - DummyIQChannel* iqChannel_; - IQRouter* iqRouter_; - EventController* eventController_; - ChatWindowFactory* chatWindowFactory_; - UserSearchWindowFactory* userSearchWindowFactory_; - MUCController* controller_; -// NickResolver* nickResolver_; - PresenceOracle* presenceOracle_; - AvatarManager* avatarManager_; - StanzaChannelPresenceSender* presenceSender_; - DirectedPresenceSender* directedPresenceSender_; - MockRepository* mocks_; - UIEventStream* uiEventStream_; - MockChatWindow* window_; - MUCRegistry* mucRegistry_; - DummyEntityCapsProvider* entityCapsProvider_; - DummySettingsProvider* settings_; - HighlightManager* highlightManager_; - boost::shared_ptr chatMessageParser_; - boost::shared_ptr crypto_; - VCardManager* vcardManager_; - VCardMemoryStorage* vcardStorage_; - ClientBlockListManager* clientBlockListManager_; - MUCBookmarkManager* mucBookmarkManager_; - XMPPRoster* xmppRoster_; + JID self_; + JID mucJID_; + MockMUC::ref muc_; + std::string nick_; + DummyStanzaChannel* stanzaChannel_; + DummyIQChannel* iqChannel_; + IQRouter* iqRouter_; + EventController* eventController_; + ChatWindowFactory* chatWindowFactory_; + UserSearchWindowFactory* userSearchWindowFactory_; + MUCController* controller_; +// NickResolver* nickResolver_; + PresenceOracle* presenceOracle_; + AvatarManager* avatarManager_; + StanzaChannelPresenceSender* presenceSender_; + DirectedPresenceSender* directedPresenceSender_; + MockRepository* mocks_; + UIEventStream* uiEventStream_; + MockChatWindow* window_; + MUCRegistry* mucRegistry_; + DummyEntityCapsProvider* entityCapsProvider_; + DummySettingsProvider* settings_; + HighlightManager* highlightManager_; + boost::shared_ptr chatMessageParser_; + boost::shared_ptr crypto_; + VCardManager* vcardManager_; + VCardMemoryStorage* vcardStorage_; + ClientBlockListManager* clientBlockListManager_; + MUCBookmarkManager* mucBookmarkManager_; + XMPPRoster* xmppRoster_; }; CPPUNIT_TEST_SUITE_REGISTRATION(MUCControllerTest); diff --git a/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h b/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h index 0754749..395b050 100644 --- a/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h +++ b/Swift/Controllers/Chat/UnitTest/MockChatListWindow.h @@ -10,19 +10,19 @@ namespace Swift { - class MockChatListWindow : public ChatListWindow { - public: - MockChatListWindow() {} - virtual ~MockChatListWindow() {} - void addMUCBookmark(const MUCBookmark& /*bookmark*/) {} - void removeMUCBookmark(const MUCBookmark& /*bookmark*/) {} - void addWhiteboardSession(const ChatListWindow::Chat& /*chat*/) {} - void removeWhiteboardSession(const JID& /*jid*/) {} - void setBookmarksEnabled(bool /*enabled*/) {} - void setRecents(const std::list& /*recents*/) {} - void setUnreadCount(int /*unread*/) {} - void clearBookmarks() {} - void setOnline(bool /*isOnline*/) {} - }; + class MockChatListWindow : public ChatListWindow { + public: + MockChatListWindow() {} + virtual ~MockChatListWindow() {} + void addMUCBookmark(const MUCBookmark& /*bookmark*/) {} + void removeMUCBookmark(const MUCBookmark& /*bookmark*/) {} + void addWhiteboardSession(const ChatListWindow::Chat& /*chat*/) {} + void removeWhiteboardSession(const JID& /*jid*/) {} + void setBookmarksEnabled(bool /*enabled*/) {} + void setRecents(const std::list& /*recents*/) {} + void setUnreadCount(int /*unread*/) {} + void clearBookmarks() {} + void setOnline(bool /*isOnline*/) {} + }; } diff --git a/Swift/Controllers/Chat/UserSearchController.cpp b/Swift/Controllers/Chat/UserSearchController.cpp index e08912a..216488a 100644 --- a/Swift/Controllers/Chat/UserSearchController.cpp +++ b/Swift/Controllers/Chat/UserSearchController.cpp @@ -36,357 +36,357 @@ namespace Swift { static const std::string SEARCHED_DIRECTORIES = "searchedDirectories"; UserSearchController::UserSearchController(Type type, const JID& jid, UIEventStream* uiEventStream, VCardManager* vcardManager, UserSearchWindowFactory* factory, IQRouter* iqRouter, RosterController* rosterController, ContactSuggester* contactSuggester, AvatarManager* avatarManager, PresenceOracle* presenceOracle, ProfileSettingsProvider* settings) : type_(type), jid_(jid), uiEventStream_(uiEventStream), vcardManager_(vcardManager), factory_(factory), iqRouter_(iqRouter), rosterController_(rosterController), contactSuggester_(contactSuggester), avatarManager_(avatarManager), presenceOracle_(presenceOracle), settings_(settings) { - uiEventStream_->onUIEvent.connect(boost::bind(&UserSearchController::handleUIEvent, this, _1)); - vcardManager_->onVCardChanged.connect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2)); - avatarManager_->onAvatarChanged.connect(boost::bind(&UserSearchController::handleAvatarChanged, this, _1)); - presenceOracle_->onPresenceChange.connect(boost::bind(&UserSearchController::handlePresenceChanged, this, _1)); - window_ = NULL; - discoWalker_ = NULL; - loadSavedDirectories(); + uiEventStream_->onUIEvent.connect(boost::bind(&UserSearchController::handleUIEvent, this, _1)); + vcardManager_->onVCardChanged.connect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2)); + avatarManager_->onAvatarChanged.connect(boost::bind(&UserSearchController::handleAvatarChanged, this, _1)); + presenceOracle_->onPresenceChange.connect(boost::bind(&UserSearchController::handlePresenceChanged, this, _1)); + window_ = NULL; + discoWalker_ = NULL; + loadSavedDirectories(); } UserSearchController::~UserSearchController() { - endDiscoWalker(); - delete discoWalker_; - if (window_) { - window_->onNameSuggestionRequested.disconnect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1)); - window_->onFormRequested.disconnect(boost::bind(&UserSearchController::handleFormRequested, this, _1)); - window_->onSearchRequested.disconnect(boost::bind(&UserSearchController::handleSearch, this, _1, _2)); - window_->onContactSuggestionsRequested.disconnect(boost::bind(&UserSearchController::handleContactSuggestionsRequested, this, _1)); - window_->onJIDUpdateRequested.disconnect(boost::bind(&UserSearchController::handleJIDUpdateRequested, this, _1)); - window_->onJIDAddRequested.disconnect(boost::bind(&UserSearchController::handleJIDAddRequested, this, _1)); - window_->onJIDEditFieldChanged.disconnect(boost::bind(&UserSearchController::handleJIDEditingFinished, this, _1)); - delete window_; - } - presenceOracle_->onPresenceChange.disconnect(boost::bind(&UserSearchController::handlePresenceChanged, this, _1)); - avatarManager_->onAvatarChanged.disconnect(boost::bind(&UserSearchController::handleAvatarChanged, this, _1)); - vcardManager_->onVCardChanged.disconnect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2)); - uiEventStream_->onUIEvent.disconnect(boost::bind(&UserSearchController::handleUIEvent, this, _1)); + endDiscoWalker(); + delete discoWalker_; + if (window_) { + window_->onNameSuggestionRequested.disconnect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1)); + window_->onFormRequested.disconnect(boost::bind(&UserSearchController::handleFormRequested, this, _1)); + window_->onSearchRequested.disconnect(boost::bind(&UserSearchController::handleSearch, this, _1, _2)); + window_->onContactSuggestionsRequested.disconnect(boost::bind(&UserSearchController::handleContactSuggestionsRequested, this, _1)); + window_->onJIDUpdateRequested.disconnect(boost::bind(&UserSearchController::handleJIDUpdateRequested, this, _1)); + window_->onJIDAddRequested.disconnect(boost::bind(&UserSearchController::handleJIDAddRequested, this, _1)); + window_->onJIDEditFieldChanged.disconnect(boost::bind(&UserSearchController::handleJIDEditingFinished, this, _1)); + delete window_; + } + presenceOracle_->onPresenceChange.disconnect(boost::bind(&UserSearchController::handlePresenceChanged, this, _1)); + avatarManager_->onAvatarChanged.disconnect(boost::bind(&UserSearchController::handleAvatarChanged, this, _1)); + vcardManager_->onVCardChanged.disconnect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2)); + uiEventStream_->onUIEvent.disconnect(boost::bind(&UserSearchController::handleUIEvent, this, _1)); } UserSearchWindow* UserSearchController::getUserSearchWindow() { - initializeUserWindow(); - assert(window_); - return window_; + initializeUserWindow(); + assert(window_); + return window_; } void UserSearchController::setCanInitiateImpromptuMUC(bool supportsImpromptu) { - if (!window_) { - initializeUserWindow(); - } - if (window_) { - window_->setCanStartImpromptuChats(supportsImpromptu); - } // Else doesn't support search + if (!window_) { + initializeUserWindow(); + } + if (window_) { + window_->setCanStartImpromptuChats(supportsImpromptu); + } // Else doesn't support search } void UserSearchController::handleUIEvent(boost::shared_ptr event) { - bool handle = false; - boost::shared_ptr addUserRequest = boost::shared_ptr(); - RequestInviteToMUCUIEvent::ref inviteToMUCRequest = RequestInviteToMUCUIEvent::ref(); - switch (type_) { - case AddContact: - if ((addUserRequest = boost::dynamic_pointer_cast(event))) { - handle = true; - } - break; - case StartChat: - if (boost::dynamic_pointer_cast(event)) { - handle = true; - } - break; - case InviteToChat: - if ((inviteToMUCRequest = boost::dynamic_pointer_cast(event))) { - handle = true; - } - break; - } - if (handle) { - initializeUserWindow(); - window_->show(); - window_->addSavedServices(savedDirectories_); - if (addUserRequest) { - const std::string& name = addUserRequest->getPredefinedName(); - const JID& jid = addUserRequest->getPredefinedJID(); - if (!name.empty() && jid.isValid()) { - window_->prepopulateJIDAndName(jid, name); - } - } else if (inviteToMUCRequest) { - window_->setCanSupplyDescription(!inviteToMUCRequest->isImpromptu()); - window_->setJIDs(inviteToMUCRequest->getInvites()); - window_->setRoomJID(inviteToMUCRequest->getRoom()); - } - return; - } + bool handle = false; + boost::shared_ptr addUserRequest = boost::shared_ptr(); + RequestInviteToMUCUIEvent::ref inviteToMUCRequest = RequestInviteToMUCUIEvent::ref(); + switch (type_) { + case AddContact: + if ((addUserRequest = boost::dynamic_pointer_cast(event))) { + handle = true; + } + break; + case StartChat: + if (boost::dynamic_pointer_cast(event)) { + handle = true; + } + break; + case InviteToChat: + if ((inviteToMUCRequest = boost::dynamic_pointer_cast(event))) { + handle = true; + } + break; + } + if (handle) { + initializeUserWindow(); + window_->show(); + window_->addSavedServices(savedDirectories_); + if (addUserRequest) { + const std::string& name = addUserRequest->getPredefinedName(); + const JID& jid = addUserRequest->getPredefinedJID(); + if (!name.empty() && jid.isValid()) { + window_->prepopulateJIDAndName(jid, name); + } + } else if (inviteToMUCRequest) { + window_->setCanSupplyDescription(!inviteToMUCRequest->isImpromptu()); + window_->setJIDs(inviteToMUCRequest->getInvites()); + window_->setRoomJID(inviteToMUCRequest->getRoom()); + } + return; + } } void UserSearchController::handleFormRequested(const JID& service) { - window_->setSearchError(false); - window_->setServerSupportsSearch(true); - - //Abort a previous search if is active - endDiscoWalker(); - delete discoWalker_; - discoWalker_ = new DiscoServiceWalker(service, iqRouter_); - discoWalker_->onServiceFound.connect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2)); - discoWalker_->onWalkComplete.connect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this)); - discoWalker_->beginWalk(); + window_->setSearchError(false); + window_->setServerSupportsSearch(true); + + //Abort a previous search if is active + endDiscoWalker(); + delete discoWalker_; + discoWalker_ = new DiscoServiceWalker(service, iqRouter_); + discoWalker_->onServiceFound.connect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2)); + discoWalker_->onWalkComplete.connect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this)); + discoWalker_->beginWalk(); } void UserSearchController::endDiscoWalker() { - if (discoWalker_) { - discoWalker_->endWalk(); - discoWalker_->onServiceFound.disconnect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2)); - discoWalker_->onWalkComplete.disconnect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this)); - } + if (discoWalker_) { + discoWalker_->endWalk(); + discoWalker_->onServiceFound.disconnect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2)); + discoWalker_->onWalkComplete.disconnect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this)); + } } void UserSearchController::handleDiscoServiceFound(const JID& jid, boost::shared_ptr info) { - //bool isUserDirectory = false; - bool supports55 = false; - foreach (DiscoInfo::Identity identity, info->getIdentities()) { - if ((identity.getCategory() == "directory" - && identity.getType() == "user")) { - //isUserDirectory = true; - } - } - std::vector features = info->getFeatures(); - supports55 = std::find(features.begin(), features.end(), DiscoInfo::JabberSearchFeature) != features.end(); - if (/*isUserDirectory && */supports55) { //FIXME: once M-Link correctly advertises directoryness. - /* Abort further searches.*/ - endDiscoWalker(); - boost::shared_ptr > searchRequest(new GenericRequest(IQ::Get, jid, boost::make_shared(), iqRouter_)); - searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleFormResponse, this, _1, _2)); - searchRequest->send(); - } + //bool isUserDirectory = false; + bool supports55 = false; + foreach (DiscoInfo::Identity identity, info->getIdentities()) { + if ((identity.getCategory() == "directory" + && identity.getType() == "user")) { + //isUserDirectory = true; + } + } + std::vector features = info->getFeatures(); + supports55 = std::find(features.begin(), features.end(), DiscoInfo::JabberSearchFeature) != features.end(); + if (/*isUserDirectory && */supports55) { //FIXME: once M-Link correctly advertises directoryness. + /* Abort further searches.*/ + endDiscoWalker(); + boost::shared_ptr > searchRequest(new GenericRequest(IQ::Get, jid, boost::make_shared(), iqRouter_)); + searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleFormResponse, this, _1, _2)); + searchRequest->send(); + } } void UserSearchController::handleFormResponse(boost::shared_ptr fields, ErrorPayload::ref error) { - if (error || !fields) { - window_->setServerSupportsSearch(false); - return; - } - window_->setSearchFields(fields); + if (error || !fields) { + window_->setServerSupportsSearch(false); + return; + } + window_->setSearchFields(fields); } void UserSearchController::handleSearch(boost::shared_ptr fields, const JID& jid) { - addToSavedDirectories(jid); - boost::shared_ptr > searchRequest(new GenericRequest(IQ::Set, jid, fields, iqRouter_)); - searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleSearchResponse, this, _1, _2)); - searchRequest->send(); + addToSavedDirectories(jid); + boost::shared_ptr > searchRequest(new GenericRequest(IQ::Set, jid, fields, iqRouter_)); + searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleSearchResponse, this, _1, _2)); + searchRequest->send(); } void UserSearchController::handleSearchResponse(boost::shared_ptr resultsPayload, ErrorPayload::ref error) { - if (error || !resultsPayload) { - window_->setSearchError(true); - return; - } - - std::vector results; - - if (resultsPayload->getForm()) { - window_->setResultsForm(resultsPayload->getForm()); - } else { - foreach (SearchPayload::Item item, resultsPayload->getItems()) { - JID jid(item.jid); - std::map fields; - fields["first"] = item.first; - fields["last"] = item.last; - fields["nick"] = item.nick; - fields["email"] = item.email; - UserSearchResult result(jid, fields); - results.push_back(result); - } - window_->setResults(results); - } + if (error || !resultsPayload) { + window_->setSearchError(true); + return; + } + + std::vector results; + + if (resultsPayload->getForm()) { + window_->setResultsForm(resultsPayload->getForm()); + } else { + foreach (SearchPayload::Item item, resultsPayload->getItems()) { + JID jid(item.jid); + std::map fields; + fields["first"] = item.first; + fields["last"] = item.last; + fields["nick"] = item.nick; + fields["email"] = item.email; + UserSearchResult result(jid, fields); + results.push_back(result); + } + window_->setResults(results); + } } void UserSearchController::handleNameSuggestionRequest(const JID &jid) { - suggestionsJID_= jid; - VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid); - if (vcard) { - handleVCardChanged(jid, vcard); - } + suggestionsJID_= jid; + VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid); + if (vcard) { + handleVCardChanged(jid, vcard); + } } void UserSearchController::handleJIDEditingFinished(const JID& jid) { - if (jid.isValid()) { - if (rosterController_->getItem(jid)) { - window_->setWarning(QT_TRANSLATE_NOOP("", "This contact is already on your contact list.")); - } - else if (jid.getNode().empty()) { - window_->setWarning(QT_TRANSLATE_NOOP("", "Part of the address you have entered is missing. An address has a structure of 'user@example.com'.")); - } - else { - window_->setWarning(boost::optional()); - } - } - else { - window_->setWarning(QT_TRANSLATE_NOOP("", "The address you have entered is invalid.")); - } + if (jid.isValid()) { + if (rosterController_->getItem(jid)) { + window_->setWarning(QT_TRANSLATE_NOOP("", "This contact is already on your contact list.")); + } + else if (jid.getNode().empty()) { + window_->setWarning(QT_TRANSLATE_NOOP("", "Part of the address you have entered is missing. An address has a structure of 'user@example.com'.")); + } + else { + window_->setWarning(boost::optional()); + } + } + else { + window_->setWarning(QT_TRANSLATE_NOOP("", "The address you have entered is invalid.")); + } } void UserSearchController::handleContactSuggestionsRequested(std::string text) { - const std::vector existingJIDs = window_->getJIDs(); - std::vector suggestions = contactSuggester_->getSuggestions(text, false); - /* do not suggest contacts that have already been added to the chat list */ - std::vector::iterator i = suggestions.begin(); - while (i != suggestions.end()) { - bool found = false; - foreach (const JID& jid, existingJIDs) { - if ((*i)->jid == jid) { - found = true; - break; - } - } - - // remove contact suggestions which are already on the contact list in add-contact-mode - if (type_ == AddContact) { - if (!found && !!rosterController_->getItem((*i)->jid)) { - found = true; - } - } - - if (found) { - i = suggestions.erase(i); - } else { - i++; - } - } - window_->setContactSuggestions(suggestions); + const std::vector existingJIDs = window_->getJIDs(); + std::vector suggestions = contactSuggester_->getSuggestions(text, false); + /* do not suggest contacts that have already been added to the chat list */ + std::vector::iterator i = suggestions.begin(); + while (i != suggestions.end()) { + bool found = false; + foreach (const JID& jid, existingJIDs) { + if ((*i)->jid == jid) { + found = true; + break; + } + } + + // remove contact suggestions which are already on the contact list in add-contact-mode + if (type_ == AddContact) { + if (!found && !!rosterController_->getItem((*i)->jid)) { + found = true; + } + } + + if (found) { + i = suggestions.erase(i); + } else { + i++; + } + } + window_->setContactSuggestions(suggestions); } void UserSearchController::handleVCardChanged(const JID& jid, VCard::ref vcard) { - if (jid == suggestionsJID_) { - window_->setNameSuggestions(ContactEditController::nameSuggestionsFromVCard(vcard)); - suggestionsJID_ = JID(); - } - handleJIDUpdateRequested(std::vector(1, jid)); + if (jid == suggestionsJID_) { + window_->setNameSuggestions(ContactEditController::nameSuggestionsFromVCard(vcard)); + suggestionsJID_ = JID(); + } + handleJIDUpdateRequested(std::vector(1, jid)); } void UserSearchController::handleAvatarChanged(const JID& jid) { - handleJIDUpdateRequested(std::vector(1, jid)); + handleJIDUpdateRequested(std::vector(1, jid)); } void UserSearchController::handlePresenceChanged(Presence::ref presence) { - handleJIDUpdateRequested(std::vector(1, presence->getFrom().toBare())); + handleJIDUpdateRequested(std::vector(1, presence->getFrom().toBare())); } void UserSearchController::handleJIDUpdateRequested(const std::vector& jids) { - if (window_) { - std::vector updates; - foreach(const JID& jid, jids) { - updates.push_back(convertJIDtoContact(jid)); - } - window_->updateContacts(updates); - } + if (window_) { + std::vector updates; + foreach(const JID& jid, jids) { + updates.push_back(convertJIDtoContact(jid)); + } + window_->updateContacts(updates); + } } void UserSearchController::handleJIDAddRequested(const std::vector& jids) { - std::vector contacts; - foreach(const JID& jid, jids) { - contacts.push_back(convertJIDtoContact(jid)); - } - window_->addContacts(contacts); + std::vector contacts; + foreach(const JID& jid, jids) { + contacts.push_back(convertJIDtoContact(jid)); + } + window_->addContacts(contacts); } Contact::ref UserSearchController::convertJIDtoContact(const JID& jid) { - Contact::ref contact = boost::make_shared(); - contact->jid = jid; - - // name lookup - boost::optional rosterItem = rosterController_->getItem(jid); - if (rosterItem && !rosterItem->getName().empty()) { - contact->name = rosterItem->getName(); - } else { - VCard::ref vcard = vcardManager_->getVCard(jid); - if (vcard && !vcard->getFullName().empty()) { - contact->name = vcard->getFullName(); - } else { - contact->name = jid.toString(); - } - } - - // presence lookup - Presence::ref presence = presenceOracle_->getAccountPresence(jid); - if (presence) { - contact->statusType = presence->getShow(); - } else { - contact->statusType = StatusShow::None; - } - - // avatar lookup - contact->avatarPath = avatarManager_->getAvatarPath(jid); - return contact; + Contact::ref contact = boost::make_shared(); + contact->jid = jid; + + // name lookup + boost::optional rosterItem = rosterController_->getItem(jid); + if (rosterItem && !rosterItem->getName().empty()) { + contact->name = rosterItem->getName(); + } else { + VCard::ref vcard = vcardManager_->getVCard(jid); + if (vcard && !vcard->getFullName().empty()) { + contact->name = vcard->getFullName(); + } else { + contact->name = jid.toString(); + } + } + + // presence lookup + Presence::ref presence = presenceOracle_->getAccountPresence(jid); + if (presence) { + contact->statusType = presence->getShow(); + } else { + contact->statusType = StatusShow::None; + } + + // avatar lookup + contact->avatarPath = avatarManager_->getAvatarPath(jid); + return contact; } void UserSearchController::handleDiscoWalkFinished() { - window_->setServerSupportsSearch(false); - endDiscoWalker(); + window_->setServerSupportsSearch(false); + endDiscoWalker(); } void UserSearchController::initializeUserWindow() { - if (!window_) { - UserSearchWindow::Type windowType = UserSearchWindow::AddContact; - switch(type_) { - case AddContact: - windowType = UserSearchWindow::AddContact; - break; - case StartChat: - windowType = UserSearchWindow::ChatToContact; - break; - case InviteToChat: - windowType = UserSearchWindow::InviteToChat; - break; - } - - window_ = factory_->createUserSearchWindow(windowType, uiEventStream_, rosterController_->getGroups()); - if (!window_) { - // UI Doesn't support user search - return; - } - window_->onNameSuggestionRequested.connect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1)); - window_->onFormRequested.connect(boost::bind(&UserSearchController::handleFormRequested, this, _1)); - window_->onSearchRequested.connect(boost::bind(&UserSearchController::handleSearch, this, _1, _2)); - window_->onContactSuggestionsRequested.connect(boost::bind(&UserSearchController::handleContactSuggestionsRequested, this, _1)); - window_->onJIDUpdateRequested.connect(boost::bind(&UserSearchController::handleJIDUpdateRequested, this, _1)); - window_->onJIDAddRequested.connect(boost::bind(&UserSearchController::handleJIDAddRequested, this, _1)); - window_->onJIDEditFieldChanged.connect(boost::bind(&UserSearchController::handleJIDEditingFinished, this, _1)); - window_->setSelectedService(JID(jid_.getDomain())); - window_->clear(); - } + if (!window_) { + UserSearchWindow::Type windowType = UserSearchWindow::AddContact; + switch(type_) { + case AddContact: + windowType = UserSearchWindow::AddContact; + break; + case StartChat: + windowType = UserSearchWindow::ChatToContact; + break; + case InviteToChat: + windowType = UserSearchWindow::InviteToChat; + break; + } + + window_ = factory_->createUserSearchWindow(windowType, uiEventStream_, rosterController_->getGroups()); + if (!window_) { + // UI Doesn't support user search + return; + } + window_->onNameSuggestionRequested.connect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1)); + window_->onFormRequested.connect(boost::bind(&UserSearchController::handleFormRequested, this, _1)); + window_->onSearchRequested.connect(boost::bind(&UserSearchController::handleSearch, this, _1, _2)); + window_->onContactSuggestionsRequested.connect(boost::bind(&UserSearchController::handleContactSuggestionsRequested, this, _1)); + window_->onJIDUpdateRequested.connect(boost::bind(&UserSearchController::handleJIDUpdateRequested, this, _1)); + window_->onJIDAddRequested.connect(boost::bind(&UserSearchController::handleJIDAddRequested, this, _1)); + window_->onJIDEditFieldChanged.connect(boost::bind(&UserSearchController::handleJIDEditingFinished, this, _1)); + window_->setSelectedService(JID(jid_.getDomain())); + window_->clear(); + } } void UserSearchController::loadSavedDirectories() { - savedDirectories_.clear(); - foreach (std::string stringItem, String::split(settings_->getStringSetting(SEARCHED_DIRECTORIES), '\n')) { - if(!stringItem.empty()) { - savedDirectories_.push_back(JID(stringItem)); - } - } + savedDirectories_.clear(); + foreach (std::string stringItem, String::split(settings_->getStringSetting(SEARCHED_DIRECTORIES), '\n')) { + if(!stringItem.empty()) { + savedDirectories_.push_back(JID(stringItem)); + } + } } void UserSearchController::addToSavedDirectories(const JID& jid) { - if (!jid.isValid()) { - return; - } - - savedDirectories_.erase(std::remove(savedDirectories_.begin(), savedDirectories_.end(), jid), savedDirectories_.end()); - savedDirectories_.insert(savedDirectories_.begin(), jid); - - std::string collapsed; - int i = 0; - foreach (JID jidItem, savedDirectories_) { - if (i >= 15) { - break; - } - if (!collapsed.empty()) { - collapsed += "\n"; - } - collapsed += jidItem.toString(); - ++i; - } - settings_->storeString(SEARCHED_DIRECTORIES, collapsed); - window_->addSavedServices(savedDirectories_); + if (!jid.isValid()) { + return; + } + + savedDirectories_.erase(std::remove(savedDirectories_.begin(), savedDirectories_.end(), jid), savedDirectories_.end()); + savedDirectories_.insert(savedDirectories_.begin(), jid); + + std::string collapsed; + int i = 0; + foreach (JID jidItem, savedDirectories_) { + if (i >= 15) { + break; + } + if (!collapsed.empty()) { + collapsed += "\n"; + } + collapsed += jidItem.toString(); + ++i; + } + settings_->storeString(SEARCHED_DIRECTORIES, collapsed); + window_->addSavedServices(savedDirectories_); } } diff --git a/Swift/Controllers/Chat/UserSearchController.h b/Swift/Controllers/Chat/UserSearchController.h index 0423a65..71b8331 100644 --- a/Swift/Controllers/Chat/UserSearchController.h +++ b/Swift/Controllers/Chat/UserSearchController.h @@ -24,76 +24,76 @@ #include namespace Swift { - class UIEventStream; - class UIEvent; - class UserSearchWindow; - class UserSearchWindowFactory; - class IQRouter; - class DiscoServiceWalker; - class RosterController; - class VCardManager; - class ContactSuggester; - class AvatarManager; - class PresenceOracle; - class ProfileSettingsProvider; + class UIEventStream; + class UIEvent; + class UserSearchWindow; + class UserSearchWindowFactory; + class IQRouter; + class DiscoServiceWalker; + class RosterController; + class VCardManager; + class ContactSuggester; + class AvatarManager; + class PresenceOracle; + class ProfileSettingsProvider; - class UserSearchResult { - public: - UserSearchResult(const JID& jid, const std::map& fields) : jid_(jid), fields_(fields) {} - const JID& getJID() const {return jid_;} - const std::map& getFields() const {return fields_;} - private: - JID jid_; - std::map fields_; - }; + class UserSearchResult { + public: + UserSearchResult(const JID& jid, const std::map& fields) : jid_(jid), fields_(fields) {} + const JID& getJID() const {return jid_;} + const std::map& getFields() const {return fields_;} + private: + JID jid_; + std::map fields_; + }; - class UserSearchController { - public: - enum Type {AddContact, StartChat, InviteToChat}; - UserSearchController(Type type, const JID& jid, UIEventStream* uiEventStream, VCardManager* vcardManager, UserSearchWindowFactory* userSearchWindowFactory, IQRouter* iqRouter, RosterController* rosterController, ContactSuggester* contactSuggester, AvatarManager* avatarManager, PresenceOracle* presenceOracle, ProfileSettingsProvider* settings); - ~UserSearchController(); + class UserSearchController { + public: + enum Type {AddContact, StartChat, InviteToChat}; + UserSearchController(Type type, const JID& jid, UIEventStream* uiEventStream, VCardManager* vcardManager, UserSearchWindowFactory* userSearchWindowFactory, IQRouter* iqRouter, RosterController* rosterController, ContactSuggester* contactSuggester, AvatarManager* avatarManager, PresenceOracle* presenceOracle, ProfileSettingsProvider* settings); + ~UserSearchController(); - UserSearchWindow* getUserSearchWindow(); - void setCanInitiateImpromptuMUC(bool supportsImpromptu); + UserSearchWindow* getUserSearchWindow(); + void setCanInitiateImpromptuMUC(bool supportsImpromptu); - private: - void handleUIEvent(boost::shared_ptr event); - void handleFormRequested(const JID& service); - void handleDiscoServiceFound(const JID& jid, boost::shared_ptr info); - void handleDiscoWalkFinished(); - void handleFormResponse(boost::shared_ptr items, ErrorPayload::ref error); - void handleSearch(boost::shared_ptr fields, const JID& jid); - void handleSearchResponse(boost::shared_ptr results, ErrorPayload::ref error); - void handleNameSuggestionRequest(const JID& jid); - void handleContactSuggestionsRequested(std::string text); - void handleVCardChanged(const JID& jid, VCard::ref vcard); - void handleAvatarChanged(const JID& jid); - void handlePresenceChanged(Presence::ref presence); - void handleJIDUpdateRequested(const std::vector& jids); - void handleJIDAddRequested(const std::vector& jids); - void handleJIDEditingFinished(const JID& jid); - Contact::ref convertJIDtoContact(const JID& jid); - void endDiscoWalker(); - void initializeUserWindow(); + private: + void handleUIEvent(boost::shared_ptr event); + void handleFormRequested(const JID& service); + void handleDiscoServiceFound(const JID& jid, boost::shared_ptr info); + void handleDiscoWalkFinished(); + void handleFormResponse(boost::shared_ptr items, ErrorPayload::ref error); + void handleSearch(boost::shared_ptr fields, const JID& jid); + void handleSearchResponse(boost::shared_ptr results, ErrorPayload::ref error); + void handleNameSuggestionRequest(const JID& jid); + void handleContactSuggestionsRequested(std::string text); + void handleVCardChanged(const JID& jid, VCard::ref vcard); + void handleAvatarChanged(const JID& jid); + void handlePresenceChanged(Presence::ref presence); + void handleJIDUpdateRequested(const std::vector& jids); + void handleJIDAddRequested(const std::vector& jids); + void handleJIDEditingFinished(const JID& jid); + Contact::ref convertJIDtoContact(const JID& jid); + void endDiscoWalker(); + void initializeUserWindow(); - void loadSavedDirectories(); - void addToSavedDirectories(const JID& jid); + void loadSavedDirectories(); + void addToSavedDirectories(const JID& jid); - private: - Type type_; - JID jid_; - JID suggestionsJID_; - UIEventStream* uiEventStream_; - VCardManager* vcardManager_; - UserSearchWindowFactory* factory_; - IQRouter* iqRouter_; - RosterController* rosterController_; - UserSearchWindow* window_; - DiscoServiceWalker* discoWalker_; - ContactSuggester* contactSuggester_; - AvatarManager* avatarManager_; - PresenceOracle* presenceOracle_; - std::vector savedDirectories_; - ProfileSettingsProvider* settings_; - }; + private: + Type type_; + JID jid_; + JID suggestionsJID_; + UIEventStream* uiEventStream_; + VCardManager* vcardManager_; + UserSearchWindowFactory* factory_; + IQRouter* iqRouter_; + RosterController* rosterController_; + UserSearchWindow* window_; + DiscoServiceWalker* discoWalker_; + ContactSuggester* contactSuggester_; + AvatarManager* avatarManager_; + PresenceOracle* presenceOracle_; + std::vector savedDirectories_; + ProfileSettingsProvider* settings_; + }; } diff --git a/Swift/Controllers/ChatMessageSummarizer.cpp b/Swift/Controllers/ChatMessageSummarizer.cpp index a0ae6d1..6b630e7 100644 --- a/Swift/Controllers/ChatMessageSummarizer.cpp +++ b/Swift/Controllers/ChatMessageSummarizer.cpp @@ -15,32 +15,32 @@ using namespace Swift; using namespace std; string ChatMessageSummarizer::getSummary(const string& current, const vector& unreads) { - vector others; - int currentUnread = 0; - int otherCount = 0; - foreach (UnreadPair unread, unreads) { - if (unread.first == current) { - currentUnread += unread.second; - } else { - if (unread.second > 0) { - otherCount += unread.second; - others.push_back(unread); - } - } - } - string myString(current); + vector others; + int currentUnread = 0; + int otherCount = 0; + foreach (UnreadPair unread, unreads) { + if (unread.first == current) { + currentUnread += unread.second; + } else { + if (unread.second > 0) { + otherCount += unread.second; + others.push_back(unread); + } + } + } + string myString(current); - if (currentUnread > 0) { - string result(QT_TRANSLATE_NOOP("", "%1% (%2%)")); - myString = str(format(result) % current % currentUnread); - } + if (currentUnread > 0) { + string result(QT_TRANSLATE_NOOP("", "%1% (%2%)")); + myString = str(format(result) % current % currentUnread); + } - if (others.size() > 1) { - string result(QT_TRANSLATE_NOOP("", "%1% and %2% others (%3%)")); - myString = str(format(result) % myString % others.size() % otherCount); - } else if (!others.empty()) { - string result(QT_TRANSLATE_NOOP("", "%1%; %2% (%3%)")); - myString = str(format(result) % myString % others[0].first % otherCount); - } - return myString; + if (others.size() > 1) { + string result(QT_TRANSLATE_NOOP("", "%1% and %2% others (%3%)")); + myString = str(format(result) % myString % others.size() % otherCount); + } else if (!others.empty()) { + string result(QT_TRANSLATE_NOOP("", "%1%; %2% (%3%)")); + myString = str(format(result) % myString % others[0].first % otherCount); + } + return myString; } diff --git a/Swift/Controllers/ChatMessageSummarizer.h b/Swift/Controllers/ChatMessageSummarizer.h index 9ed867d..0b4df21 100644 --- a/Swift/Controllers/ChatMessageSummarizer.h +++ b/Swift/Controllers/ChatMessageSummarizer.h @@ -13,8 +13,8 @@ namespace Swift { typedef std::pair UnreadPair; - class ChatMessageSummarizer { - public: - std::string getSummary(const std::string& current, const std::vector& unreads); - }; + class ChatMessageSummarizer { + public: + std::string getSummary(const std::string& current, const std::vector& unreads); + }; } diff --git a/Swift/Controllers/ConnectionSettings.h b/Swift/Controllers/ConnectionSettings.h index 6a2fded..7ce45cd 100644 --- a/Swift/Controllers/ConnectionSettings.h +++ b/Swift/Controllers/ConnectionSettings.h @@ -9,32 +9,32 @@ #include struct ConnectionSettings { - enum Method { - Automatic, - Manual, - BOSH - }; - enum ProxyType { - None, - System, - SOCKS5, - HTTPConnect - }; + enum Method { + Automatic, + Manual, + BOSH + }; + enum ProxyType { + None, + System, + SOCKS5, + HTTPConnect + }; - Method method; - struct { - bool useManualServer; - std::string manualServerHostname; - int manualServerPort; - ProxyType proxyType; - bool useManualProxy; - std::string manualProxyHostname; - int manualProxyPort; - } manualSettings; - struct { - std::string boshURI; - bool useManualProxy; - std::string manualProxyHostname; - int manualProxyPort; - } boshSettings; + Method method; + struct { + bool useManualServer; + std::string manualServerHostname; + int manualServerPort; + ProxyType proxyType; + bool useManualProxy; + std::string manualProxyHostname; + int manualProxyPort; + } manualSettings; + struct { + std::string boshURI; + bool useManualProxy; + std::string manualProxyHostname; + int manualProxyPort; + } boshSettings; }; diff --git a/Swift/Controllers/Contact.cpp b/Swift/Controllers/Contact.cpp index bda1239..b9b98c3 100644 --- a/Swift/Controllers/Contact.cpp +++ b/Swift/Controllers/Contact.cpp @@ -24,54 +24,54 @@ Contact::Contact(const std::string& name, const JID& jid, StatusShow::Type statu } bool Contact::lexicographicalSortPredicate(const Contact::ref& a, const Contact::ref& b) { - if (a->jid.isValid() && b->jid.isValid()) { - return a->jid < b->jid; - } else { - return a->name < b->name; - } + if (a->jid.isValid() && b->jid.isValid()) { + return a->jid < b->jid; + } else { + return a->name < b->name; + } } bool Contact::equalityPredicate(const Contact::ref& a, const Contact::ref& b) { - if (a->jid.isValid() && b->jid.isValid()) { - return a->jid == b->jid; - } else { - return a->name == b->name; - } + if (a->jid.isValid() && b->jid.isValid()) { + return a->jid == b->jid; + } else { + return a->name == b->name; + } } bool Contact::sortPredicate(const Contact::ref& a, const Contact::ref& b, const std::string& search) { - /* perform case insensitive comparisons */ - std::string aLower = a->name; - boost::to_lower(aLower); - std::string bLower = b->name; - boost::to_lower(bLower); - std::string searchLower = search; - boost::to_lower(searchLower); + /* perform case insensitive comparisons */ + std::string aLower = a->name; + boost::to_lower(aLower); + std::string bLower = b->name; + boost::to_lower(bLower); + std::string searchLower = search; + boost::to_lower(searchLower); - /* name starts with the search term */ - if (aLower.find(searchLower) == 0 && bLower.find(searchLower) != 0) { - return true; - } else if (bLower.find(searchLower) == 0 && aLower.find(searchLower) != 0) { - return false; - } + /* name starts with the search term */ + if (aLower.find(searchLower) == 0 && bLower.find(searchLower) != 0) { + return true; + } else if (bLower.find(searchLower) == 0 && aLower.find(searchLower) != 0) { + return false; + } - /* name contains search term */ - if (aLower.find(searchLower) != std::string::npos && bLower.find(searchLower) == std::string::npos) { - return true; - } else if (bLower.find(searchLower) != std::string::npos && aLower.find(searchLower) == std::string::npos) { - return false; - } + /* name contains search term */ + if (aLower.find(searchLower) != std::string::npos && bLower.find(searchLower) == std::string::npos) { + return true; + } else if (bLower.find(searchLower) != std::string::npos && aLower.find(searchLower) == std::string::npos) { + return false; + } - /* Levenshtein should be done here */ - /* if edit distances are equal, fall through to the tests below */ + /* Levenshtein should be done here */ + /* if edit distances are equal, fall through to the tests below */ - /* lexicographical sort */ - if (a->statusType == b->statusType) { - return aLower.compare(bLower) < 0; - } + /* lexicographical sort */ + if (a->statusType == b->statusType) { + return aLower.compare(bLower) < 0; + } - /* online status */ - return a->statusType < b->statusType; + /* online status */ + return a->statusType < b->statusType; } } diff --git a/Swift/Controllers/Contact.h b/Swift/Controllers/Contact.h index b03a118..4aa6999 100644 --- a/Swift/Controllers/Contact.h +++ b/Swift/Controllers/Contact.h @@ -21,21 +21,21 @@ namespace Swift { class Contact : public boost::enable_shared_from_this { - public: - typedef boost::shared_ptr ref; + public: + typedef boost::shared_ptr ref; - Contact(); - Contact(const std::string& name, const JID& jid, StatusShow::Type statusType, const boost::filesystem::path& path); + Contact(); + Contact(const std::string& name, const JID& jid, StatusShow::Type statusType, const boost::filesystem::path& path); - static bool lexicographicalSortPredicate(const Contact::ref& a, const Contact::ref& b); - static bool equalityPredicate(const Contact::ref& a, const Contact::ref& b); - static bool sortPredicate(const Contact::ref& a, const Contact::ref& b, const std::string& search); + static bool lexicographicalSortPredicate(const Contact::ref& a, const Contact::ref& b); + static bool equalityPredicate(const Contact::ref& a, const Contact::ref& b); + static bool sortPredicate(const Contact::ref& a, const Contact::ref& b, const std::string& search); - public: - std::string name; - JID jid; - StatusShow::Type statusType; - boost::filesystem::path avatarPath; + public: + std::string name; + JID jid; + StatusShow::Type statusType; + boost::filesystem::path avatarPath; }; } diff --git a/Swift/Controllers/ContactEditController.cpp b/Swift/Controllers/ContactEditController.cpp index 704e3bc..734ef79 100644 --- a/Swift/Controllers/ContactEditController.cpp +++ b/Swift/Controllers/ContactEditController.cpp @@ -21,89 +21,89 @@ namespace Swift { ContactEditController::ContactEditController(RosterController* rosterController, VCardManager* vcardManager, ContactEditWindowFactory* contactEditWindowFactory, UIEventStream* uiEventStream) : rosterController(rosterController), vcardManager(vcardManager), contactEditWindowFactory(contactEditWindowFactory), uiEventStream(uiEventStream), contactEditWindow(NULL) { - uiEventStream->onUIEvent.connect(boost::bind(&ContactEditController::handleUIEvent, this, _1)); - vcardManager->onVCardChanged.connect(boost::bind(&ContactEditController::handleVCardChanged, this, _1, _2)); + uiEventStream->onUIEvent.connect(boost::bind(&ContactEditController::handleUIEvent, this, _1)); + vcardManager->onVCardChanged.connect(boost::bind(&ContactEditController::handleVCardChanged, this, _1, _2)); } ContactEditController::~ContactEditController() { - if (contactEditWindow) { - contactEditWindow->onChangeContactRequest.disconnect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2)); - contactEditWindow->onRemoveContactRequest.disconnect(boost::bind(&ContactEditController::handleRemoveContactRequest, this)); - delete contactEditWindow; - } - uiEventStream->onUIEvent.disconnect(boost::bind(&ContactEditController::handleUIEvent, this, _1)); + if (contactEditWindow) { + contactEditWindow->onChangeContactRequest.disconnect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2)); + contactEditWindow->onRemoveContactRequest.disconnect(boost::bind(&ContactEditController::handleRemoveContactRequest, this)); + delete contactEditWindow; + } + uiEventStream->onUIEvent.disconnect(boost::bind(&ContactEditController::handleUIEvent, this, _1)); } void ContactEditController::handleUIEvent(UIEvent::ref event) { - RequestContactEditorUIEvent::ref editEvent = boost::dynamic_pointer_cast(event); - if (!editEvent) { - return; - } - - if (!contactEditWindow) { - contactEditWindow = contactEditWindowFactory->createContactEditWindow(); - contactEditWindow->onRemoveContactRequest.connect(boost::bind(&ContactEditController::handleRemoveContactRequest, this)); - contactEditWindow->onChangeContactRequest.connect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2)); - } - currentContact = rosterController->getItem(editEvent->getJID()); - assert(currentContact); - jid = rosterController->getItem(editEvent->getJID())->getJID(); - contactEditWindow->setContact(jid, currentContact->getName(), currentContact->getGroups(), rosterController->getGroups()); - contactEditWindow->show(); - - if (vcardManager) { - VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(jid); - if (vcard) { - handleVCardChanged(jid, vcard); - } - } + RequestContactEditorUIEvent::ref editEvent = boost::dynamic_pointer_cast(event); + if (!editEvent) { + return; + } + + if (!contactEditWindow) { + contactEditWindow = contactEditWindowFactory->createContactEditWindow(); + contactEditWindow->onRemoveContactRequest.connect(boost::bind(&ContactEditController::handleRemoveContactRequest, this)); + contactEditWindow->onChangeContactRequest.connect(boost::bind(&ContactEditController::handleChangeContactRequest, this, _1, _2)); + } + currentContact = rosterController->getItem(editEvent->getJID()); + assert(currentContact); + jid = rosterController->getItem(editEvent->getJID())->getJID(); + contactEditWindow->setContact(jid, currentContact->getName(), currentContact->getGroups(), rosterController->getGroups()); + contactEditWindow->show(); + + if (vcardManager) { + VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(jid); + if (vcard) { + handleVCardChanged(jid, vcard); + } + } } void ContactEditController::handleVCardChanged(const JID &jid, VCard::ref vcard) { - if (jid == this->jid) { - contactEditWindow->setNameSuggestions(nameSuggestionsFromVCard(vcard)); - } + if (jid == this->jid) { + contactEditWindow->setNameSuggestions(nameSuggestionsFromVCard(vcard)); + } } void ContactEditController::setAvailable(bool b) { - if (contactEditWindow) { - contactEditWindow->setEnabled(b); - } + if (contactEditWindow) { + contactEditWindow->setEnabled(b); + } } std::vector ContactEditController::nameSuggestionsFromVCard(VCard::ref vcard) { - std::vector suggestions; - if (!vcard->getNickname().empty()) { - suggestions.push_back(vcard->getNickname()); - } - if (!vcard->getFullName().empty()) { - suggestions.push_back(vcard->getFullName()); - } - if (!vcard->getGivenName().empty()) { - std::string suggestedName; - suggestedName = vcard->getGivenName(); - boost::algorithm::trim(suggestedName); - suggestions.push_back(suggestedName); - } - return suggestions; + std::vector suggestions; + if (!vcard->getNickname().empty()) { + suggestions.push_back(vcard->getNickname()); + } + if (!vcard->getFullName().empty()) { + suggestions.push_back(vcard->getFullName()); + } + if (!vcard->getGivenName().empty()) { + std::string suggestedName; + suggestedName = vcard->getGivenName(); + boost::algorithm::trim(suggestedName); + suggestions.push_back(suggestedName); + } + return suggestions; } void ContactEditController::handleRemoveContactRequest() { - assert(currentContact); - uiEventStream->send(boost::make_shared(currentContact->getJID())); - contactEditWindow->hide(); + assert(currentContact); + uiEventStream->send(boost::make_shared(currentContact->getJID())); + contactEditWindow->hide(); } void ContactEditController::handleChangeContactRequest(const std::string& name, const std::set& newGroups) { - std::vector oldGroupsVector = currentContact->getGroups(); - std::set oldGroups(oldGroupsVector.begin(), oldGroupsVector.end()); - if (oldGroups != newGroups || currentContact->getName() != name) { - XMPPRosterItem newContact(*currentContact); - newContact.setName(name); - newContact.setGroups(std::vector(newGroups.begin(), newGroups.end())); - rosterController->updateItem(newContact); - } - contactEditWindow->hide(); + std::vector oldGroupsVector = currentContact->getGroups(); + std::set oldGroups(oldGroupsVector.begin(), oldGroupsVector.end()); + if (oldGroups != newGroups || currentContact->getName() != name) { + XMPPRosterItem newContact(*currentContact); + newContact.setName(name); + newContact.setGroups(std::vector(newGroups.begin(), newGroups.end())); + rosterController->updateItem(newContact); + } + contactEditWindow->hide(); } } diff --git a/Swift/Controllers/ContactEditController.h b/Swift/Controllers/ContactEditController.h index 671fe38..ab2b52e 100644 --- a/Swift/Controllers/ContactEditController.h +++ b/Swift/Controllers/ContactEditController.h @@ -19,38 +19,38 @@ #include namespace Swift { - class UIEventStream; - class ContactEditWindowFactory; - class ContactEditWindow; - class RosterController; - class VCardManager; - - class ContactEditController { - public: - ContactEditController(RosterController* rosterController, VCardManager* vcardManager, ContactEditWindowFactory* contactEditWindowFactory, UIEventStream* uiEventStream); - ~ContactEditController(); - - void setAvailable(bool b); - - public: - static std::vector nameSuggestionsFromVCard(VCard::ref vcard); - - private: - void handleRemoveContactRequest(); - void handleChangeContactRequest(const std::string& name, const std::set& groups); - - private: - void handleUIEvent(UIEvent::ref event); - void handleVCardChanged(const JID& jid, VCard::ref vcard); - - private: - boost::optional currentContact; - RosterController* rosterController; - VCardManager* vcardManager; - ContactEditWindowFactory* contactEditWindowFactory; - UIEventStream* uiEventStream; - JID jid; - ContactEditWindow* contactEditWindow; - }; + class UIEventStream; + class ContactEditWindowFactory; + class ContactEditWindow; + class RosterController; + class VCardManager; + + class ContactEditController { + public: + ContactEditController(RosterController* rosterController, VCardManager* vcardManager, ContactEditWindowFactory* contactEditWindowFactory, UIEventStream* uiEventStream); + ~ContactEditController(); + + void setAvailable(bool b); + + public: + static std::vector nameSuggestionsFromVCard(VCard::ref vcard); + + private: + void handleRemoveContactRequest(); + void handleChangeContactRequest(const std::string& name, const std::set& groups); + + private: + void handleUIEvent(UIEvent::ref event); + void handleVCardChanged(const JID& jid, VCard::ref vcard); + + private: + boost::optional currentContact; + RosterController* rosterController; + VCardManager* vcardManager; + ContactEditWindowFactory* contactEditWindowFactory; + UIEventStream* uiEventStream; + JID jid; + ContactEditWindow* contactEditWindow; + }; } diff --git a/Swift/Controllers/ContactProvider.h b/Swift/Controllers/ContactProvider.h index 08812d5..423f8a3 100644 --- a/Swift/Controllers/ContactProvider.h +++ b/Swift/Controllers/ContactProvider.h @@ -19,9 +19,9 @@ namespace Swift { class ContactProvider { - public: - virtual ~ContactProvider(); - virtual std::vector getContacts(bool withMUCNicks) = 0; + public: + virtual ~ContactProvider(); + virtual std::vector getContacts(bool withMUCNicks) = 0; }; } diff --git a/Swift/Controllers/ContactSuggester.cpp b/Swift/Controllers/ContactSuggester.cpp index a2b605a..04e9dc4 100644 --- a/Swift/Controllers/ContactSuggester.cpp +++ b/Swift/Controllers/ContactSuggester.cpp @@ -39,49 +39,49 @@ ContactSuggester::~ContactSuggester() { } void ContactSuggester::addContactProvider(ContactProvider* provider) { - contactProviders_.push_back(provider); + contactProviders_.push_back(provider); } bool ContactSuggester::matchContact(const std::string& search, const Contact::ref& c) { - if (fuzzyMatch(c->name, search)) { - return true; - } - else if (c->jid.isValid()) { - return fuzzyMatch(c->jid.toString(), search); - } - return false; + if (fuzzyMatch(c->name, search)) { + return true; + } + else if (c->jid.isValid()) { + return fuzzyMatch(c->jid.toString(), search); + } + return false; } std::vector ContactSuggester::getSuggestions(const std::string& search, bool withMUCNicks) const { - std::vector results; + std::vector results; - foreach(ContactProvider* provider, contactProviders_) { - append(results, provider->getContacts(withMUCNicks)); - } + foreach(ContactProvider* provider, contactProviders_) { + append(results, provider->getContacts(withMUCNicks)); + } - std::sort(results.begin(), results.end(), Contact::lexicographicalSortPredicate); - results.erase(std::unique(results.begin(), results.end(), Contact::equalityPredicate), results.end()); - results.erase(std::remove_if(results.begin(), results.end(), !lambda::bind(&matchContact, search, lambda::_1)), - results.end()); - std::sort(results.begin(), results.end(), boost::bind(&Contact::sortPredicate, _1, _2, search)); + std::sort(results.begin(), results.end(), Contact::lexicographicalSortPredicate); + results.erase(std::unique(results.begin(), results.end(), Contact::equalityPredicate), results.end()); + results.erase(std::remove_if(results.begin(), results.end(), !lambda::bind(&matchContact, search, lambda::_1)), + results.end()); + std::sort(results.begin(), results.end(), boost::bind(&Contact::sortPredicate, _1, _2, search)); - return results; + return results; } bool ContactSuggester::fuzzyMatch(std::string text, std::string match) { - std::string lowerText = text; - boost::algorithm::to_lower(lowerText); - std::string lowerMatch = match; - boost::algorithm::to_lower(lowerMatch); - size_t lastMatch = 0; - for (size_t i = 0; i < lowerMatch.length(); ++i) { - size_t where = lowerText.find_first_of(lowerMatch[i], lastMatch); - if (where == std::string::npos) { - return false; - } - lastMatch = where + 1; - } - return true; + std::string lowerText = text; + boost::algorithm::to_lower(lowerText); + std::string lowerMatch = match; + boost::algorithm::to_lower(lowerMatch); + size_t lastMatch = 0; + for (size_t i = 0; i < lowerMatch.length(); ++i) { + size_t where = lowerText.find_first_of(lowerMatch[i], lastMatch); + if (where == std::string::npos) { + return false; + } + lastMatch = where + 1; + } + return true; } } diff --git a/Swift/Controllers/ContactSuggester.h b/Swift/Controllers/ContactSuggester.h index a57f638..f91879d 100644 --- a/Swift/Controllers/ContactSuggester.h +++ b/Swift/Controllers/ContactSuggester.h @@ -20,24 +20,24 @@ class ContactSuggesterTest; namespace Swift { - class ContactProvider; - - class ContactSuggester { - public: - ContactSuggester(); - ~ContactSuggester(); - - void addContactProvider(ContactProvider* provider); - - std::vector getSuggestions(const std::string& search, bool withMUCNicks) const; - public: - static bool matchContact(const std::string& search, const Contact::ref& c); - /** - * Performs fuzzy matching on the string text. Matches when each character of match string is present in sequence in text string. - */ - static bool fuzzyMatch(std::string text, std::string match); - - private: - std::vector contactProviders_; - }; + class ContactProvider; + + class ContactSuggester { + public: + ContactSuggester(); + ~ContactSuggester(); + + void addContactProvider(ContactProvider* provider); + + std::vector getSuggestions(const std::string& search, bool withMUCNicks) const; + public: + static bool matchContact(const std::string& search, const Contact::ref& c); + /** + * Performs fuzzy matching on the string text. Matches when each character of match string is present in sequence in text string. + */ + static bool fuzzyMatch(std::string text, std::string match); + + private: + std::vector contactProviders_; + }; } diff --git a/Swift/Controllers/ContactsFromXMPPRoster.cpp b/Swift/Controllers/ContactsFromXMPPRoster.cpp index 1cab9b1..1aa4424 100644 --- a/Swift/Controllers/ContactsFromXMPPRoster.cpp +++ b/Swift/Controllers/ContactsFromXMPPRoster.cpp @@ -27,15 +27,15 @@ ContactsFromXMPPRoster::~ContactsFromXMPPRoster() { } std::vector ContactsFromXMPPRoster::getContacts(bool /*withMUCNicks*/) { - std::vector results; - std::vector rosterItems = roster_->getItems(); - foreach(const XMPPRosterItem& rosterItem, rosterItems) { - Contact::ref contact = boost::make_shared(rosterItem.getName().empty() ? rosterItem.getJID().toString() : rosterItem.getName(), rosterItem.getJID(), StatusShow::None,""); - contact->statusType = presenceOracle_->getAccountPresence(contact->jid) ? presenceOracle_->getAccountPresence(contact->jid)->getShow() : StatusShow::None; - contact->avatarPath = avatarManager_->getAvatarPath(contact->jid); - results.push_back(contact); - } - return results; + std::vector results; + std::vector rosterItems = roster_->getItems(); + foreach(const XMPPRosterItem& rosterItem, rosterItems) { + Contact::ref contact = boost::make_shared(rosterItem.getName().empty() ? rosterItem.getJID().toString() : rosterItem.getName(), rosterItem.getJID(), StatusShow::None,""); + contact->statusType = presenceOracle_->getAccountPresence(contact->jid) ? presenceOracle_->getAccountPresence(contact->jid)->getShow() : StatusShow::None; + contact->avatarPath = avatarManager_->getAvatarPath(contact->jid); + results.push_back(contact); + } + return results; } } diff --git a/Swift/Controllers/ContactsFromXMPPRoster.h b/Swift/Controllers/ContactsFromXMPPRoster.h index 43d4985..2782dcc 100644 --- a/Swift/Controllers/ContactsFromXMPPRoster.h +++ b/Swift/Controllers/ContactsFromXMPPRoster.h @@ -21,15 +21,15 @@ class AvatarManager; class XMPPRoster; class ContactsFromXMPPRoster : public ContactProvider { - public: - ContactsFromXMPPRoster(XMPPRoster* roster, AvatarManager* avatarManager, PresenceOracle* presenceOracle); - virtual ~ContactsFromXMPPRoster(); - - virtual std::vector getContacts(bool withMUCNicks); - private: - XMPPRoster* roster_; - AvatarManager* avatarManager_; - PresenceOracle* presenceOracle_; + public: + ContactsFromXMPPRoster(XMPPRoster* roster, AvatarManager* avatarManager, PresenceOracle* presenceOracle); + virtual ~ContactsFromXMPPRoster(); + + virtual std::vector getContacts(bool withMUCNicks); + private: + XMPPRoster* roster_; + AvatarManager* avatarManager_; + PresenceOracle* presenceOracle_; }; } diff --git a/Swift/Controllers/DummySoundPlayer.h b/Swift/Controllers/DummySoundPlayer.h index 2d99fb9..e297cae 100644 --- a/Swift/Controllers/DummySoundPlayer.h +++ b/Swift/Controllers/DummySoundPlayer.h @@ -9,8 +9,8 @@ #include namespace Swift { - class DummySoundPlayer : public SoundPlayer { - public: - void playSound(SoundEffect /*sound*/, const std::string& /*soundResource*/) {} - }; + class DummySoundPlayer : public SoundPlayer { + public: + void playSound(SoundEffect /*sound*/, const std::string& /*soundResource*/) {} + }; } diff --git a/Swift/Controllers/DummySystemTray.h b/Swift/Controllers/DummySystemTray.h index b413737..b36ed28 100644 --- a/Swift/Controllers/DummySystemTray.h +++ b/Swift/Controllers/DummySystemTray.h @@ -9,10 +9,10 @@ #include namespace Swift { - class DummySystemTray : public SystemTray { - public: - void setUnreadMessages(bool /*some*/) {} - void setStatusType(StatusShow::Type /*type*/) {} - void setConnecting() {} - }; + class DummySystemTray : public SystemTray { + public: + void setUnreadMessages(bool /*some*/) {} + void setStatusType(StatusShow::Type /*type*/) {} + void setConnecting() {} + }; } diff --git a/Swift/Controllers/EventNotifier.cpp b/Swift/Controllers/EventNotifier.cpp index 6615448..f4a9c2f 100644 --- a/Swift/Controllers/EventNotifier.cpp +++ b/Swift/Controllers/EventNotifier.cpp @@ -28,53 +28,53 @@ namespace Swift { EventNotifier::EventNotifier(EventController* eventController, Notifier* notifier, AvatarManager* avatarManager, NickResolver* nickResolver) : eventController(eventController), notifier(notifier), avatarManager(avatarManager), nickResolver(nickResolver) { - eventController->onEventQueueEventAdded.connect(boost::bind(&EventNotifier::handleEventAdded, this, _1)); + eventController->onEventQueueEventAdded.connect(boost::bind(&EventNotifier::handleEventAdded, this, _1)); } EventNotifier::~EventNotifier() { - notifier->purgeCallbacks(); - eventController->onEventQueueEventAdded.disconnect(boost::bind(&EventNotifier::handleEventAdded, this, _1)); + notifier->purgeCallbacks(); + eventController->onEventQueueEventAdded.disconnect(boost::bind(&EventNotifier::handleEventAdded, this, _1)); } void EventNotifier::handleEventAdded(boost::shared_ptr event) { - if (event->getConcluded()) { - return; - } - if (boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event)) { - JID jid = messageEvent->getStanza()->getFrom(); - std::string title = nickResolver->jidToNick(jid); - if (!messageEvent->getStanza()->isError() && !messageEvent->getStanza()->getBody().get_value_or("").empty()) { - JID activationJID = jid; - if (messageEvent->getStanza()->getType() == Message::Groupchat) { - activationJID = jid.toBare(); - } - std::string messageText = messageEvent->getStanza()->getBody().get_value_or(""); - if (boost::starts_with(messageText, "/me ")) { - messageText = "*" + String::getSplittedAtFirst(messageText, ' ').second + "*"; - } - notifier->showMessage(Notifier::IncomingMessage, title, messageText, avatarManager->getAvatarPath(jid), boost::bind(&EventNotifier::handleNotificationActivated, this, activationJID)); - } - } - else if(boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(event)) { - JID jid = subscriptionEvent->getJID(); - std::string title = jid; - std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% wants to add you to his/her contact list")) % nickResolver->jidToNick(jid)); - notifier->showMessage(Notifier::SystemMessage, title, message, boost::filesystem::path(), boost::function()); - } - else if(boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event)) { - notifier->showMessage(Notifier::SystemMessage, QT_TRANSLATE_NOOP("", "Error"), errorEvent->getText(), boost::filesystem::path(), boost::function()); - } - else if (boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event)) { - std::string title = mucInviteEvent->getInviter(); - std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% has invited you to enter the %2% room")) % nickResolver->jidToNick(mucInviteEvent->getInviter()) % mucInviteEvent->getRoomJID()); - // FIXME: not show avatar or greyed out avatar for mediated invites - notifier->showMessage(Notifier::SystemMessage, title, message, avatarManager->getAvatarPath(mucInviteEvent->getInviter()), boost::bind(&EventNotifier::handleNotificationActivated, this, mucInviteEvent->getInviter())); - } + if (event->getConcluded()) { + return; + } + if (boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event)) { + JID jid = messageEvent->getStanza()->getFrom(); + std::string title = nickResolver->jidToNick(jid); + if (!messageEvent->getStanza()->isError() && !messageEvent->getStanza()->getBody().get_value_or("").empty()) { + JID activationJID = jid; + if (messageEvent->getStanza()->getType() == Message::Groupchat) { + activationJID = jid.toBare(); + } + std::string messageText = messageEvent->getStanza()->getBody().get_value_or(""); + if (boost::starts_with(messageText, "/me ")) { + messageText = "*" + String::getSplittedAtFirst(messageText, ' ').second + "*"; + } + notifier->showMessage(Notifier::IncomingMessage, title, messageText, avatarManager->getAvatarPath(jid), boost::bind(&EventNotifier::handleNotificationActivated, this, activationJID)); + } + } + else if(boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(event)) { + JID jid = subscriptionEvent->getJID(); + std::string title = jid; + std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% wants to add you to his/her contact list")) % nickResolver->jidToNick(jid)); + notifier->showMessage(Notifier::SystemMessage, title, message, boost::filesystem::path(), boost::function()); + } + else if(boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event)) { + notifier->showMessage(Notifier::SystemMessage, QT_TRANSLATE_NOOP("", "Error"), errorEvent->getText(), boost::filesystem::path(), boost::function()); + } + else if (boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event)) { + std::string title = mucInviteEvent->getInviter(); + std::string message = str(format(QT_TRANSLATE_NOOP("", "%1% has invited you to enter the %2% room")) % nickResolver->jidToNick(mucInviteEvent->getInviter()) % mucInviteEvent->getRoomJID()); + // FIXME: not show avatar or greyed out avatar for mediated invites + notifier->showMessage(Notifier::SystemMessage, title, message, avatarManager->getAvatarPath(mucInviteEvent->getInviter()), boost::bind(&EventNotifier::handleNotificationActivated, this, mucInviteEvent->getInviter())); + } } void EventNotifier::handleNotificationActivated(JID jid) { - onNotificationActivated(jid); + onNotificationActivated(jid); } } diff --git a/Swift/Controllers/EventNotifier.h b/Swift/Controllers/EventNotifier.h index 2ecff6a..4661c46 100644 --- a/Swift/Controllers/EventNotifier.h +++ b/Swift/Controllers/EventNotifier.h @@ -16,29 +16,29 @@ #include namespace Swift { - class EventController; - class Notifier; - class AvatarManager; - class NickResolver; - class JID; - class UIEventStream; - class SettingsProvider; - - class EventNotifier { - public: - EventNotifier(EventController* eventController, Notifier* notifier, AvatarManager* avatarManager, NickResolver* nickResolver); - ~EventNotifier(); - - boost::signal onNotificationActivated; - - private: - void handleEventAdded(boost::shared_ptr); - void handleNotificationActivated(JID jid); - - private: - EventController* eventController; - Notifier* notifier; - AvatarManager* avatarManager; - NickResolver* nickResolver; - }; + class EventController; + class Notifier; + class AvatarManager; + class NickResolver; + class JID; + class UIEventStream; + class SettingsProvider; + + class EventNotifier { + public: + EventNotifier(EventController* eventController, Notifier* notifier, AvatarManager* avatarManager, NickResolver* nickResolver); + ~EventNotifier(); + + boost::signal onNotificationActivated; + + private: + void handleEventAdded(boost::shared_ptr); + void handleNotificationActivated(JID jid); + + private: + EventController* eventController; + Notifier* notifier; + AvatarManager* avatarManager; + NickResolver* nickResolver; + }; } diff --git a/Swift/Controllers/EventWindowController.cpp b/Swift/Controllers/EventWindowController.cpp index 91fedd2..2739a87 100644 --- a/Swift/Controllers/EventWindowController.cpp +++ b/Swift/Controllers/EventWindowController.cpp @@ -14,41 +14,41 @@ namespace Swift { EventWindowController::EventWindowController(EventController* eventController, EventWindowFactory* windowFactory) { - eventController_ = eventController; - windowFactory_ = windowFactory; - window_ = windowFactory_->createEventWindow(); - eventAddedConnection_ = eventController_->onEventQueueEventAdded.connect(boost::bind(&EventWindowController::handleEventQueueEventAdded, this, _1)); + eventController_ = eventController; + windowFactory_ = windowFactory; + window_ = windowFactory_->createEventWindow(); + eventAddedConnection_ = eventController_->onEventQueueEventAdded.connect(boost::bind(&EventWindowController::handleEventQueueEventAdded, this, _1)); } EventWindowController::~EventWindowController() { - if (window_->canDelete()) { - delete window_; - } + if (window_->canDelete()) { + delete window_; + } } void EventWindowController::handleEventQueueEventAdded(boost::shared_ptr event) { - if (event->getConcluded()) { - handleEventConcluded(event); - } else { - boost::shared_ptr message = boost::dynamic_pointer_cast(event); - if (!(message && message->isReadable())) { - event->onConclusion.connect(boost::bind(&EventWindowController::handleEventConcluded, this, event)); - window_->addEvent(event, true); - } - } + if (event->getConcluded()) { + handleEventConcluded(event); + } else { + boost::shared_ptr message = boost::dynamic_pointer_cast(event); + if (!(message && message->isReadable())) { + event->onConclusion.connect(boost::bind(&EventWindowController::handleEventConcluded, this, event)); + window_->addEvent(event, true); + } + } } void EventWindowController::handleEventConcluded(boost::shared_ptr event) { - window_->removeEvent(event); - bool includeAsCompleted = true; - /* Because subscription requests get duplicated, don't add them back */ - if (boost::dynamic_pointer_cast(event) || boost::dynamic_pointer_cast(event)) { - includeAsCompleted = false; - } - if (includeAsCompleted) { - window_->addEvent(event, false); - } - event->onConclusion.disconnect(boost::bind(&EventWindowController::handleEventConcluded, this, event)); + window_->removeEvent(event); + bool includeAsCompleted = true; + /* Because subscription requests get duplicated, don't add them back */ + if (boost::dynamic_pointer_cast(event) || boost::dynamic_pointer_cast(event)) { + includeAsCompleted = false; + } + if (includeAsCompleted) { + window_->addEvent(event, false); + } + event->onConclusion.disconnect(boost::bind(&EventWindowController::handleEventConcluded, this, event)); } } diff --git a/Swift/Controllers/EventWindowController.h b/Swift/Controllers/EventWindowController.h index 1c50830..eba07ca 100644 --- a/Swift/Controllers/EventWindowController.h +++ b/Swift/Controllers/EventWindowController.h @@ -12,18 +12,18 @@ namespace Swift { - class EventWindowController { - public: - EventWindowController(EventController* eventController, EventWindowFactory* windowFactory); - ~EventWindowController(); - private: - void handleEventQueueEventAdded(boost::shared_ptr event); - void handleEventConcluded(boost::shared_ptr event); + class EventWindowController { + public: + EventWindowController(EventController* eventController, EventWindowFactory* windowFactory); + ~EventWindowController(); + private: + void handleEventQueueEventAdded(boost::shared_ptr event); + void handleEventConcluded(boost::shared_ptr event); - EventController* eventController_; - EventWindowFactory* windowFactory_; - EventWindow* window_; - boost::bsignals::scoped_connection eventAddedConnection_; - }; + EventController* eventController_; + EventWindowFactory* windowFactory_; + EventWindow* window_; + boost::bsignals::scoped_connection eventAddedConnection_; + }; } diff --git a/Swift/Controllers/FileTransfer/FileTransferController.cpp b/Swift/Controllers/FileTransfer/FileTransferController.cpp index 89e9a91..fd13d99 100644 --- a/Swift/Controllers/FileTransfer/FileTransferController.cpp +++ b/Swift/Controllers/FileTransfer/FileTransferController.cpp @@ -28,135 +28,135 @@ namespace Swift { FileTransferController::FileTransferController(const JID& receipient, const std::string& filename, FileTransferManager* fileTransferManager) : - sending(true), otherParty(receipient), filename(filename), ftManager(fileTransferManager), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) { - + sending(true), otherParty(receipient), filename(filename), ftManager(fileTransferManager), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) { + } FileTransferController::FileTransferController(IncomingFileTransfer::ref transfer) : - sending(false), otherParty(transfer->getSender()), filename(transfer->getFileName()), transfer(transfer), ftManager(0), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) { - transfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1)); + sending(false), otherParty(transfer->getSender()), filename(transfer->getFileName()), transfer(transfer), ftManager(0), ftProgressInfo(0), chatWindow(0), currentState(FileTransfer::State::WaitingForStart) { + transfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1)); } FileTransferController::~FileTransferController() { - delete ftProgressInfo; - transfer->onStateChanged.disconnect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1)); + delete ftProgressInfo; + transfer->onStateChanged.disconnect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1)); } const JID &FileTransferController::getOtherParty() const { - return otherParty; + return otherParty; } std::string FileTransferController::setChatWindow(ChatWindow* wnd, std::string nickname) { - chatWindow = wnd; - if (sending) { - uiID = wnd->addFileTransfer(QT_TRANSLATE_NOOP("", "me"), true, filename, boost::filesystem::file_size(boost::filesystem::path(filename)), ""); - } else { - uiID = wnd->addFileTransfer(nickname, false, filename, transfer->getFileSizeInBytes(), transfer->getDescription()); - } - return uiID; + chatWindow = wnd; + if (sending) { + uiID = wnd->addFileTransfer(QT_TRANSLATE_NOOP("", "me"), true, filename, boost::filesystem::file_size(boost::filesystem::path(filename)), ""); + } else { + uiID = wnd->addFileTransfer(nickname, false, filename, transfer->getFileSizeInBytes(), transfer->getDescription()); + } + return uiID; } void FileTransferController::setReceipient(const JID& receipient) { - this->otherParty = receipient; + this->otherParty = receipient; } bool FileTransferController::isIncoming() const { - return !sending; + return !sending; } FileTransfer::State FileTransferController::getState() const { - return currentState; + return currentState; } int FileTransferController::getProgress() const { - return ftProgressInfo ? ftProgressInfo->getPercentage() : 0; + return ftProgressInfo ? ftProgressInfo->getPercentage() : 0; } boost::uintmax_t FileTransferController::getSize() const { - if (transfer) { - return transfer->getFileSizeInBytes(); - } else { - return 0; - } + if (transfer) { + return transfer->getFileSizeInBytes(); + } else { + return 0; + } } void FileTransferController::start(std::string& description) { - SWIFT_LOG(debug) << "FileTransferController::start" << std::endl; - fileReadStream = boost::make_shared(boost::filesystem::path(filename)); - OutgoingFileTransfer::ref outgoingTransfer = ftManager->createOutgoingFileTransfer(otherParty, boost::filesystem::path(filename), description, fileReadStream); - if (outgoingTransfer) { - ftProgressInfo = new FileTransferProgressInfo(outgoingTransfer->getFileSizeInBytes()); - ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1)); - outgoingTransfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1)); - outgoingTransfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1)); - outgoingTransfer->start(); - transfer = outgoingTransfer; - } else { - std::cerr << "File transfer not supported!" << std::endl; - } + SWIFT_LOG(debug) << "FileTransferController::start" << std::endl; + fileReadStream = boost::make_shared(boost::filesystem::path(filename)); + OutgoingFileTransfer::ref outgoingTransfer = ftManager->createOutgoingFileTransfer(otherParty, boost::filesystem::path(filename), description, fileReadStream); + if (outgoingTransfer) { + ftProgressInfo = new FileTransferProgressInfo(outgoingTransfer->getFileSizeInBytes()); + ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1)); + outgoingTransfer->onStateChanged.connect(boost::bind(&FileTransferController::handleFileTransferStateChange, this, _1)); + outgoingTransfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1)); + outgoingTransfer->start(); + transfer = outgoingTransfer; + } else { + std::cerr << "File transfer not supported!" << std::endl; + } } void FileTransferController::accept(std::string& file) { - SWIFT_LOG(debug) << "FileTransferController::accept" << std::endl; - IncomingFileTransfer::ref incomingTransfer = boost::dynamic_pointer_cast(transfer); - if (incomingTransfer) { - fileWriteStream = boost::make_shared(boost::filesystem::path(file)); + SWIFT_LOG(debug) << "FileTransferController::accept" << std::endl; + IncomingFileTransfer::ref incomingTransfer = boost::dynamic_pointer_cast(transfer); + if (incomingTransfer) { + fileWriteStream = boost::make_shared(boost::filesystem::path(file)); - ftProgressInfo = new FileTransferProgressInfo(transfer->getFileSizeInBytes()); - ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1)); - transfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1)); - incomingTransfer->accept(fileWriteStream); - } else { - std::cerr << "Expected an incoming transfer in this situation!" << std::endl; - } + ftProgressInfo = new FileTransferProgressInfo(transfer->getFileSizeInBytes()); + ftProgressInfo->onProgressPercentage.connect(boost::bind(&FileTransferController::handleProgressPercentageChange, this, _1)); + transfer->onProcessedBytes.connect(boost::bind(&FileTransferProgressInfo::setBytesProcessed, ftProgressInfo, _1)); + incomingTransfer->accept(fileWriteStream); + } else { + std::cerr << "Expected an incoming transfer in this situation!" << std::endl; + } } void FileTransferController::cancel() { - if (transfer) { - transfer->cancel(); - } else { - chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled); - } + if (transfer) { + transfer->cancel(); + } else { + chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled); + } } void FileTransferController::handleFileTransferStateChange(FileTransfer::State state) { - currentState = state; - onStateChanged(); - switch(state.type) { - case FileTransfer::State::Initial: - assert(false); - return; - case FileTransfer::State::Negotiating: - chatWindow->setFileTransferStatus(uiID, ChatWindow::Negotiating); - return; - case FileTransfer::State::Transferring: - chatWindow->setFileTransferStatus(uiID, ChatWindow::Transferring); - return; - case FileTransfer::State::Canceled: - chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled); - return; - case FileTransfer::State::Finished: - chatWindow->setFileTransferStatus(uiID, ChatWindow::Finished); - if (fileWriteStream) { - fileWriteStream->close(); - } - return; - case FileTransfer::State::Failed: - chatWindow->setFileTransferStatus(uiID, ChatWindow::FTFailed); - return; - case FileTransfer::State::WaitingForAccept: - chatWindow->setFileTransferStatus(uiID, ChatWindow::WaitingForAccept); - return; - case FileTransfer::State::WaitingForStart: - chatWindow->setFileTransferStatus(uiID, ChatWindow::Initialisation); - return; - } - assert(false); + currentState = state; + onStateChanged(); + switch(state.type) { + case FileTransfer::State::Initial: + assert(false); + return; + case FileTransfer::State::Negotiating: + chatWindow->setFileTransferStatus(uiID, ChatWindow::Negotiating); + return; + case FileTransfer::State::Transferring: + chatWindow->setFileTransferStatus(uiID, ChatWindow::Transferring); + return; + case FileTransfer::State::Canceled: + chatWindow->setFileTransferStatus(uiID, ChatWindow::Canceled); + return; + case FileTransfer::State::Finished: + chatWindow->setFileTransferStatus(uiID, ChatWindow::Finished); + if (fileWriteStream) { + fileWriteStream->close(); + } + return; + case FileTransfer::State::Failed: + chatWindow->setFileTransferStatus(uiID, ChatWindow::FTFailed); + return; + case FileTransfer::State::WaitingForAccept: + chatWindow->setFileTransferStatus(uiID, ChatWindow::WaitingForAccept); + return; + case FileTransfer::State::WaitingForStart: + chatWindow->setFileTransferStatus(uiID, ChatWindow::Initialisation); + return; + } + assert(false); } void FileTransferController::handleProgressPercentageChange(int percentage) { - onProgressChange(); - chatWindow->setFileTransferProgress(uiID, percentage); + onProgressChange(); + chatWindow->setFileTransferProgress(uiID, percentage); } } diff --git a/Swift/Controllers/FileTransfer/FileTransferController.h b/Swift/Controllers/FileTransfer/FileTransferController.h index 490773d..a25abee 100644 --- a/Swift/Controllers/FileTransfer/FileTransferController.h +++ b/Swift/Controllers/FileTransfer/FileTransferController.h @@ -32,49 +32,49 @@ class ChatWindow; class FileTransferController { public: - /** - * For outgoing file transfers. It'll create a file transfer via FileTransferManager as soon as the descriptive information is available. - */ - FileTransferController(const JID&, const std::string&, FileTransferManager*); + /** + * For outgoing file transfers. It'll create a file transfer via FileTransferManager as soon as the descriptive information is available. + */ + FileTransferController(const JID&, const std::string&, FileTransferManager*); - /** - * For incoming file transfers. - */ - FileTransferController(IncomingFileTransfer::ref transfer); - ~FileTransferController(); + /** + * For incoming file transfers. + */ + FileTransferController(IncomingFileTransfer::ref transfer); + ~FileTransferController(); - std::string setChatWindow(ChatWindow*, std::string nickname); - void setReceipient(const JID& otherParty); + std::string setChatWindow(ChatWindow*, std::string nickname); + void setReceipient(const JID& otherParty); - void start(std::string& description); - void accept(std::string& file); - void cancel(); + void start(std::string& description); + void accept(std::string& file); + void cancel(); - const JID &getOtherParty() const; - bool isIncoming() const; - FileTransfer::State getState() const; - int getProgress() const; - boost::uintmax_t getSize() const; + const JID &getOtherParty() const; + bool isIncoming() const; + FileTransfer::State getState() const; + int getProgress() const; + boost::uintmax_t getSize() const; - boost::signal onStateChanged; - boost::signal onProgressChange; + boost::signal onStateChanged; + boost::signal onProgressChange; private: - void handleFileTransferStateChange(FileTransfer::State); - void handleProgressPercentageChange(int percentage); + void handleFileTransferStateChange(FileTransfer::State); + void handleProgressPercentageChange(int percentage); private: - bool sending; - JID otherParty; - std::string filename; - FileTransfer::ref transfer; - boost::shared_ptr fileReadStream; - boost::shared_ptr fileWriteStream; - FileTransferManager* ftManager; - FileTransferProgressInfo* ftProgressInfo; - ChatWindow* chatWindow; - std::string uiID; - FileTransfer::State currentState; + bool sending; + JID otherParty; + std::string filename; + FileTransfer::ref transfer; + boost::shared_ptr fileReadStream; + boost::shared_ptr fileWriteStream; + FileTransferManager* ftManager; + FileTransferProgressInfo* ftProgressInfo; + ChatWindow* chatWindow; + std::string uiID; + FileTransfer::State currentState; }; } diff --git a/Swift/Controllers/FileTransfer/FileTransferOverview.cpp b/Swift/Controllers/FileTransfer/FileTransferOverview.cpp index 8616c1e..a53b000 100644 --- a/Swift/Controllers/FileTransfer/FileTransferOverview.cpp +++ b/Swift/Controllers/FileTransfer/FileTransferOverview.cpp @@ -23,70 +23,70 @@ namespace Swift { FileTransferOverview::FileTransferOverview(FileTransferManager* ftm) : fileTransferManager(ftm) { - fileTransferManager->onIncomingFileTransfer.connect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1)); - onNewFileTransferController.connect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1)); + fileTransferManager->onIncomingFileTransfer.connect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1)); + onNewFileTransferController.connect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1)); } FileTransferOverview::~FileTransferOverview() { - onNewFileTransferController.disconnect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1)); - fileTransferManager->onIncomingFileTransfer.disconnect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1)); - foreach(FileTransferController* controller, fileTransfers) { - controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this)); - } + onNewFileTransferController.disconnect(boost::bind(&FileTransferOverview::handleNewFileTransferController, this, _1)); + fileTransferManager->onIncomingFileTransfer.disconnect(boost::bind(&FileTransferOverview::handleIncomingFileTransfer, this, _1)); + foreach(FileTransferController* controller, fileTransfers) { + controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this)); + } } - + void FileTransferOverview::sendFile(const JID& jid, const std::string& filename) { - if (boost::filesystem::exists(filename) && boost::filesystem::file_size(filename) > 0) { - FileTransferController* controller = new FileTransferController(jid, filename, fileTransferManager); - onNewFileTransferController(controller); - } + if (boost::filesystem::exists(filename) && boost::filesystem::file_size(filename) > 0) { + FileTransferController* controller = new FileTransferController(jid, filename, fileTransferManager); + onNewFileTransferController(controller); + } } void FileTransferOverview::handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) { - FileTransferController* controller = new FileTransferController(transfer); - onNewFileTransferController(controller); + FileTransferController* controller = new FileTransferController(transfer); + onNewFileTransferController(controller); } void FileTransferOverview::handleNewFileTransferController(FileTransferController* controller) { - fileTransfers.push_back(controller); - controller->onStateChanged.connect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this)); + fileTransfers.push_back(controller); + controller->onStateChanged.connect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this)); } void FileTransferOverview::handleFileTransferStateChanged() { - onFileTransferListChanged(); + onFileTransferListChanged(); } const std::vector& FileTransferOverview::getFileTransfers() const { - return fileTransfers; + return fileTransfers; } void FileTransferOverview::clearFinished() { - for (std::vector::iterator it = fileTransfers.begin(); it != fileTransfers.end(); ) { - if((*it)->getState().type == FileTransfer::State::Finished - || (*it)->getState().type == FileTransfer::State::Failed - || (*it)->getState().type == FileTransfer::State::Canceled) { - FileTransferController* controller = *it; - it = fileTransfers.erase(it); - controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this)); - delete controller; - } else { - ++it; - } - } - onFileTransferListChanged(); + for (std::vector::iterator it = fileTransfers.begin(); it != fileTransfers.end(); ) { + if((*it)->getState().type == FileTransfer::State::Finished + || (*it)->getState().type == FileTransfer::State::Failed + || (*it)->getState().type == FileTransfer::State::Canceled) { + FileTransferController* controller = *it; + it = fileTransfers.erase(it); + controller->onStateChanged.disconnect(boost::bind(&FileTransferOverview::handleFileTransferStateChanged, this)); + delete controller; + } else { + ++it; + } + } + onFileTransferListChanged(); } bool FileTransferOverview::isClearable() const { - bool isClearable = false; - foreach (FileTransferController* controller, fileTransfers) { - if(controller->getState().type == FileTransfer::State::Finished - || controller->getState().type == FileTransfer::State::Failed - || controller->getState().type == FileTransfer::State::Canceled) { - isClearable = true; - break; - } - } - return isClearable; + bool isClearable = false; + foreach (FileTransferController* controller, fileTransfers) { + if(controller->getState().type == FileTransfer::State::Finished + || controller->getState().type == FileTransfer::State::Failed + || controller->getState().type == FileTransfer::State::Canceled) { + isClearable = true; + break; + } + } + return isClearable; } } diff --git a/Swift/Controllers/FileTransfer/FileTransferOverview.h b/Swift/Controllers/FileTransfer/FileTransferOverview.h index e3cbf81..a55727c 100644 --- a/Swift/Controllers/FileTransfer/FileTransferOverview.h +++ b/Swift/Controllers/FileTransfer/FileTransferOverview.h @@ -25,25 +25,25 @@ class FileTransferManager; class FileTransferOverview { public: - FileTransferOverview(FileTransferManager*); - ~FileTransferOverview(); - - void sendFile(const JID&, const std::string&); - const std::vector& getFileTransfers() const; - void clearFinished(); - bool isClearable() const; + FileTransferOverview(FileTransferManager*); + ~FileTransferOverview(); - boost::signal onNewFileTransferController; - boost::signal onFileTransferListChanged; + void sendFile(const JID&, const std::string&); + const std::vector& getFileTransfers() const; + void clearFinished(); + bool isClearable() const; + + boost::signal onNewFileTransferController; + boost::signal onFileTransferListChanged; private: - void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer); - void handleNewFileTransferController(FileTransferController* controller); - void handleFileTransferStateChanged(); + void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer); + void handleNewFileTransferController(FileTransferController* controller); + void handleFileTransferStateChanged(); private: - std::vector fileTransfers; - FileTransferManager *fileTransferManager; + std::vector fileTransfers; + FileTransferManager *fileTransferManager; }; } diff --git a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp index a2fff03..b073017 100644 --- a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp +++ b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.cpp @@ -19,21 +19,21 @@ namespace Swift { FileTransferProgressInfo::FileTransferProgressInfo(boost::uintmax_t completeBytes) : completeBytes(completeBytes), completedBytes(0), percentage(0) { - onProgressPercentage(0); + onProgressPercentage(0); } void FileTransferProgressInfo::setBytesProcessed(int processedBytes) { - int oldPercentage = int(double(completedBytes) / double(completeBytes) * 100.0); - completedBytes += boost::numeric_cast(processedBytes); - int newPercentage = int(double(completedBytes) / double(completeBytes) * 100.0); - if (oldPercentage != newPercentage) { - onProgressPercentage(newPercentage); - } - percentage = newPercentage; + int oldPercentage = int(double(completedBytes) / double(completeBytes) * 100.0); + completedBytes += boost::numeric_cast(processedBytes); + int newPercentage = int(double(completedBytes) / double(completeBytes) * 100.0); + if (oldPercentage != newPercentage) { + onProgressPercentage(newPercentage); + } + percentage = newPercentage; } int FileTransferProgressInfo::getPercentage() const { - return percentage; + return percentage; } } diff --git a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h index ea88657..783874a 100644 --- a/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h +++ b/Swift/Controllers/FileTransfer/FileTransferProgressInfo.h @@ -20,18 +20,18 @@ namespace Swift { class FileTransferProgressInfo { public: - FileTransferProgressInfo(boost::uintmax_t completeBytes); + FileTransferProgressInfo(boost::uintmax_t completeBytes); public: - void setBytesProcessed(int processedBytes); + void setBytesProcessed(int processedBytes); - int getPercentage() const; - boost::signal onProgressPercentage; + int getPercentage() const; + boost::signal onProgressPercentage; private: - boost::uintmax_t completeBytes; - boost::uintmax_t completedBytes; - int percentage; + boost::uintmax_t completeBytes; + boost::uintmax_t completedBytes; + int percentage; }; } diff --git a/Swift/Controllers/FileTransferListController.cpp b/Swift/Controllers/FileTransferListController.cpp index 6e84435..a383ae5 100644 --- a/Swift/Controllers/FileTransferListController.cpp +++ b/Swift/Controllers/FileTransferListController.cpp @@ -20,32 +20,32 @@ namespace Swift { FileTransferListController::FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory) : fileTransferListWidgetFactory(fileTransferListWidgetFactory), fileTransferListWidget(NULL), fileTransferOverview(0) { - uiEventStream->onUIEvent.connect(boost::bind(&FileTransferListController::handleUIEvent, this, _1)); + uiEventStream->onUIEvent.connect(boost::bind(&FileTransferListController::handleUIEvent, this, _1)); } FileTransferListController::~FileTransferListController() { - delete fileTransferListWidget; + delete fileTransferListWidget; } void FileTransferListController::setFileTransferOverview(FileTransferOverview *overview) { - fileTransferOverview = overview; - if (fileTransferListWidget) { - fileTransferListWidget->setFileTransferOverview(fileTransferOverview); - } + fileTransferOverview = overview; + if (fileTransferListWidget) { + fileTransferListWidget->setFileTransferOverview(fileTransferOverview); + } } void FileTransferListController::handleUIEvent(boost::shared_ptr rawEvent) { - boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); - if (event != NULL) { - if (fileTransferListWidget == NULL) { - fileTransferListWidget = fileTransferListWidgetFactory->createFileTransferListWidget(); - if (fileTransferOverview) { - fileTransferListWidget->setFileTransferOverview(fileTransferOverview); - } - } - fileTransferListWidget->show(); - fileTransferListWidget->activate(); - } + boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); + if (event != NULL) { + if (fileTransferListWidget == NULL) { + fileTransferListWidget = fileTransferListWidgetFactory->createFileTransferListWidget(); + if (fileTransferOverview) { + fileTransferListWidget->setFileTransferOverview(fileTransferOverview); + } + } + fileTransferListWidget->show(); + fileTransferListWidget->activate(); + } } } diff --git a/Swift/Controllers/FileTransferListController.h b/Swift/Controllers/FileTransferListController.h index 079cd35..df79d1f 100644 --- a/Swift/Controllers/FileTransferListController.h +++ b/Swift/Controllers/FileTransferListController.h @@ -24,18 +24,18 @@ class FileTransferOverview; class FileTransferListController { public: - FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory); - ~FileTransferListController(); + FileTransferListController(UIEventStream* uiEventStream, FileTransferListWidgetFactory* fileTransferListWidgetFactory); + ~FileTransferListController(); - void setFileTransferOverview(FileTransferOverview* overview); + void setFileTransferOverview(FileTransferOverview* overview); private: - void handleUIEvent(boost::shared_ptr event); + void handleUIEvent(boost::shared_ptr event); private: - FileTransferListWidgetFactory* fileTransferListWidgetFactory; - FileTransferListWidget* fileTransferListWidget; - FileTransferOverview* fileTransferOverview; + FileTransferListWidgetFactory* fileTransferListWidgetFactory; + FileTransferListWidget* fileTransferListWidget; + FileTransferOverview* fileTransferOverview; }; } diff --git a/Swift/Controllers/HighlightAction.cpp b/Swift/Controllers/HighlightAction.cpp index 4603408..3ea2c86 100644 --- a/Swift/Controllers/HighlightAction.cpp +++ b/Swift/Controllers/HighlightAction.cpp @@ -16,47 +16,47 @@ namespace Swift { void HighlightAction::setHighlightWholeMessage(bool highlightText) { - highlightWholeMessage_ = highlightText; - if (!highlightWholeMessage_) { - textColor_.clear(); - textBackground_.clear(); - } + highlightWholeMessage_ = highlightText; + if (!highlightWholeMessage_) { + textColor_.clear(); + textBackground_.clear(); + } } void HighlightAction::setPlaySound(bool playSound) { - playSound_ = playSound; - if (!playSound_) { - soundFile_.clear(); - } + playSound_ = playSound; + if (!playSound_) { + soundFile_.clear(); + } } bool operator ==(HighlightAction const& a, HighlightAction const& b) { - if (a.highlightWholeMessage() != b.highlightWholeMessage()) { - return false; - } + if (a.highlightWholeMessage() != b.highlightWholeMessage()) { + return false; + } - if (a.getTextColor() != b.getTextColor()) { - return false; - } + if (a.getTextColor() != b.getTextColor()) { + return false; + } - if (a.getTextBackground() != b.getTextBackground()) { - return false; - } + if (a.getTextBackground() != b.getTextBackground()) { + return false; + } - if (a.playSound() != b.playSound()) { - return false; - } + if (a.playSound() != b.playSound()) { + return false; + } - if (a.getSoundFile() != b.getSoundFile()) { - return false; - } + if (a.getSoundFile() != b.getSoundFile()) { + return false; + } - return true; + return true; } bool operator !=(HighlightAction const& a, HighlightAction const& b) { - return !(a == b); + return !(a == b); } } diff --git a/Swift/Controllers/HighlightAction.h b/Swift/Controllers/HighlightAction.h index 3930eee..b9d4539 100644 --- a/Swift/Controllers/HighlightAction.h +++ b/Swift/Controllers/HighlightAction.h @@ -19,64 +19,64 @@ namespace Swift { - class HighlightRule; - - class HighlightAction { - public: - HighlightAction() : highlightWholeMessage_(false), playSound_(false) {} - - /** - * Gets the flag that indicates the entire message should be highlighted. - */ - bool highlightWholeMessage() const { return highlightWholeMessage_; } - void setHighlightWholeMessage(bool highlightText); - - /** - * Gets the foreground highlight color. - */ - const std::string& getTextColor() const { return textColor_; } - void setTextColor(const std::string& textColor) { textColor_ = textColor; } - - /** - * Gets the background highlight color. - */ - const std::string& getTextBackground() const { return textBackground_; } - void setTextBackground(const std::string& textBackground) { textBackground_ = textBackground; } - - bool playSound() const { return playSound_; } - void setPlaySound(bool playSound); - - /** - * Gets the sound filename. If the string is empty, assume a default sound file. - */ - const std::string& getSoundFile() const { return soundFile_; } - void setSoundFile(const std::string& soundFile) { soundFile_ = soundFile; } - - bool isEmpty() const { return !highlightWholeMessage_ && !playSound_; } - - private: - friend class boost::serialization::access; - template void serialize(Archive & ar, const unsigned int version); - - bool highlightWholeMessage_; - std::string textColor_; - std::string textBackground_; - - bool playSound_; - std::string soundFile_; - }; - - bool operator ==(HighlightAction const& a, HighlightAction const& b); - bool operator !=(HighlightAction const& a, HighlightAction const& b); - - template - void HighlightAction::serialize(Archive& ar, const unsigned int /*version*/) - { - ar & highlightWholeMessage_; - ar & textColor_; - ar & textBackground_; - ar & playSound_; - ar & soundFile_; - } + class HighlightRule; + + class HighlightAction { + public: + HighlightAction() : highlightWholeMessage_(false), playSound_(false) {} + + /** + * Gets the flag that indicates the entire message should be highlighted. + */ + bool highlightWholeMessage() const { return highlightWholeMessage_; } + void setHighlightWholeMessage(bool highlightText); + + /** + * Gets the foreground highlight color. + */ + const std::string& getTextColor() const { return textColor_; } + void setTextColor(const std::string& textColor) { textColor_ = textColor; } + + /** + * Gets the background highlight color. + */ + const std::string& getTextBackground() const { return textBackground_; } + void setTextBackground(const std::string& textBackground) { textBackground_ = textBackground; } + + bool playSound() const { return playSound_; } + void setPlaySound(bool playSound); + + /** + * Gets the sound filename. If the string is empty, assume a default sound file. + */ + const std::string& getSoundFile() const { return soundFile_; } + void setSoundFile(const std::string& soundFile) { soundFile_ = soundFile; } + + bool isEmpty() const { return !highlightWholeMessage_ && !playSound_; } + + private: + friend class boost::serialization::access; + template void serialize(Archive & ar, const unsigned int version); + + bool highlightWholeMessage_; + std::string textColor_; + std::string textBackground_; + + bool playSound_; + std::string soundFile_; + }; + + bool operator ==(HighlightAction const& a, HighlightAction const& b); + bool operator !=(HighlightAction const& a, HighlightAction const& b); + + template + void HighlightAction::serialize(Archive& ar, const unsigned int /*version*/) + { + ar & highlightWholeMessage_; + ar & textColor_; + ar & textBackground_; + ar & playSound_; + ar & soundFile_; + } } diff --git a/Swift/Controllers/HighlightEditorController.cpp b/Swift/Controllers/HighlightEditorController.cpp index ebda81c..bf5dbc4 100644 --- a/Swift/Controllers/HighlightEditorController.cpp +++ b/Swift/Controllers/HighlightEditorController.cpp @@ -25,33 +25,33 @@ namespace Swift { HighlightEditorController::HighlightEditorController(UIEventStream* uiEventStream, HighlightEditorWindowFactory* highlightEditorWindowFactory, HighlightManager* highlightManager) : highlightEditorWindowFactory_(highlightEditorWindowFactory), highlightEditorWindow_(NULL), highlightManager_(highlightManager), contactSuggester_(0) { - uiEventStream->onUIEvent.connect(boost::bind(&HighlightEditorController::handleUIEvent, this, _1)); + uiEventStream->onUIEvent.connect(boost::bind(&HighlightEditorController::handleUIEvent, this, _1)); } HighlightEditorController::~HighlightEditorController() { - delete highlightEditorWindow_; - highlightEditorWindow_ = NULL; + delete highlightEditorWindow_; + highlightEditorWindow_ = NULL; } void HighlightEditorController::handleUIEvent(boost::shared_ptr rawEvent) { - boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); - if (event) { - if (!highlightEditorWindow_) { - highlightEditorWindow_ = highlightEditorWindowFactory_->createHighlightEditorWindow(); - highlightEditorWindow_->setHighlightManager(highlightManager_); - highlightEditorWindow_->onContactSuggestionsRequested.connect(boost::bind(&HighlightEditorController::handleContactSuggestionsRequested, this, _1)); - } - highlightEditorWindow_->show(); - } + boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); + if (event) { + if (!highlightEditorWindow_) { + highlightEditorWindow_ = highlightEditorWindowFactory_->createHighlightEditorWindow(); + highlightEditorWindow_->setHighlightManager(highlightManager_); + highlightEditorWindow_->onContactSuggestionsRequested.connect(boost::bind(&HighlightEditorController::handleContactSuggestionsRequested, this, _1)); + } + highlightEditorWindow_->show(); + } } void HighlightEditorController::handleContactSuggestionsRequested(const std::string& text) { - if (contactSuggester_) { - highlightEditorWindow_->setContactSuggestions(contactSuggester_->getSuggestions(text, true)); - } + if (contactSuggester_) { + highlightEditorWindow_->setContactSuggestions(contactSuggester_->getSuggestions(text, true)); + } } } diff --git a/Swift/Controllers/HighlightEditorController.h b/Swift/Controllers/HighlightEditorController.h index 52587c2..24ad9c2 100644 --- a/Swift/Controllers/HighlightEditorController.h +++ b/Swift/Controllers/HighlightEditorController.h @@ -18,31 +18,31 @@ namespace Swift { - class UIEventStream; + class UIEventStream; - class HighlightEditorWindowFactory; - class HighlightEditorWindow; + class HighlightEditorWindowFactory; + class HighlightEditorWindow; - class HighlightManager; - class ContactSuggester; + class HighlightManager; + class ContactSuggester; - class HighlightEditorController { - public: - HighlightEditorController(UIEventStream* uiEventStream, HighlightEditorWindowFactory* highlightEditorWindowFactory, HighlightManager* highlightManager); - ~HighlightEditorController(); + class HighlightEditorController { + public: + HighlightEditorController(UIEventStream* uiEventStream, HighlightEditorWindowFactory* highlightEditorWindowFactory, HighlightManager* highlightManager); + ~HighlightEditorController(); - HighlightManager* getHighlightManager() const { return highlightManager_; } - void setContactSuggester(ContactSuggester *suggester) { contactSuggester_ = suggester; } + HighlightManager* getHighlightManager() const { return highlightManager_; } + void setContactSuggester(ContactSuggester *suggester) { contactSuggester_ = suggester; } - private: - void handleUIEvent(boost::shared_ptr event); - void handleContactSuggestionsRequested(const std::string& text); + private: + void handleUIEvent(boost::shared_ptr event); + void handleContactSuggestionsRequested(const std::string& text); - private: - HighlightEditorWindowFactory* highlightEditorWindowFactory_; - HighlightEditorWindow* highlightEditorWindow_; - HighlightManager* highlightManager_; - ContactSuggester* contactSuggester_; - }; + private: + HighlightEditorWindowFactory* highlightEditorWindowFactory_; + HighlightEditorWindow* highlightEditorWindow_; + HighlightManager* highlightManager_; + ContactSuggester* contactSuggester_; + }; } diff --git a/Swift/Controllers/HighlightManager.cpp b/Swift/Controllers/HighlightManager.cpp index 07f8e54..45b800a 100644 --- a/Swift/Controllers/HighlightManager.cpp +++ b/Swift/Controllers/HighlightManager.cpp @@ -48,102 +48,102 @@ namespace Swift { HighlightManager::HighlightManager(SettingsProvider* settings) - : settings_(settings) - , storingSettings_(false) { - rules_ = boost::make_shared(); - loadSettings(); - handleSettingChangedConnection_ = settings_->onSettingChanged.connect(boost::bind(&HighlightManager::handleSettingChanged, this, _1)); + : settings_(settings) + , storingSettings_(false) { + rules_ = boost::make_shared(); + loadSettings(); + handleSettingChangedConnection_ = settings_->onSettingChanged.connect(boost::bind(&HighlightManager::handleSettingChanged, this, _1)); } void HighlightManager::handleSettingChanged(const std::string& settingPath) { - if (!storingSettings_ && SettingConstants::HIGHLIGHT_RULES.getKey() == settingPath) { - loadSettings(); - } + if (!storingSettings_ && SettingConstants::HIGHLIGHT_RULES.getKey() == settingPath) { + loadSettings(); + } } std::string HighlightManager::rulesToString() const { - std::stringstream stream; - boost::archive::text_oarchive archive(stream); - archive << rules_->list_; - return stream.str(); + std::stringstream stream; + boost::archive::text_oarchive archive(stream); + archive << rules_->list_; + return stream.str(); } std::vector HighlightManager::getDefaultRules() { - std::vector rules; - - HighlightRule chatNotificationRule; - chatNotificationRule.setMatchChat(true); - chatNotificationRule.getAction().setPlaySound(true); - chatNotificationRule.setMatchWholeWords(true); - rules.push_back(chatNotificationRule); - - HighlightRule selfMentionMUCRule; - selfMentionMUCRule.setMatchMUC(true); - selfMentionMUCRule.getAction().setPlaySound(true); - selfMentionMUCRule.setNickIsKeyword(true); - selfMentionMUCRule.setMatchCase(true); - selfMentionMUCRule.setMatchWholeWords(true); - rules.push_back(selfMentionMUCRule); - - return rules; + std::vector rules; + + HighlightRule chatNotificationRule; + chatNotificationRule.setMatchChat(true); + chatNotificationRule.getAction().setPlaySound(true); + chatNotificationRule.setMatchWholeWords(true); + rules.push_back(chatNotificationRule); + + HighlightRule selfMentionMUCRule; + selfMentionMUCRule.setMatchMUC(true); + selfMentionMUCRule.getAction().setPlaySound(true); + selfMentionMUCRule.setNickIsKeyword(true); + selfMentionMUCRule.setMatchCase(true); + selfMentionMUCRule.setMatchWholeWords(true); + rules.push_back(selfMentionMUCRule); + + return rules; } HighlightRule HighlightManager::getRule(int index) const { - assert(index >= 0 && static_cast(index) < rules_->getSize()); - return rules_->getRule(static_cast(index)); + assert(index >= 0 && static_cast(index) < rules_->getSize()); + return rules_->getRule(static_cast(index)); } void HighlightManager::setRule(int index, const HighlightRule& rule) { - assert(index >= 0 && static_cast(index) < rules_->getSize()); - rules_->list_[static_cast(index)] = rule; + assert(index >= 0 && static_cast(index) < rules_->getSize()); + rules_->list_[static_cast(index)] = rule; } void HighlightManager::insertRule(int index, const HighlightRule& rule) { - assert(index >= 0 && boost::numeric_cast::size_type>(index) <= rules_->getSize()); - rules_->list_.insert(rules_->list_.begin() + index, rule); + assert(index >= 0 && boost::numeric_cast::size_type>(index) <= rules_->getSize()); + rules_->list_.insert(rules_->list_.begin() + index, rule); } void HighlightManager::removeRule(int index) { - assert(index >= 0 && boost::numeric_cast::size_type>(index) < rules_->getSize()); - rules_->list_.erase(rules_->list_.begin() + index); + assert(index >= 0 && boost::numeric_cast::size_type>(index) < rules_->getSize()); + rules_->list_.erase(rules_->list_.begin() + index); } void HighlightManager::swapRules(const size_t first, const size_t second) { - assert(first < rules_->getSize()); - assert(second < rules_->getSize()); - const HighlightRule swap = rules_->getRule(first); - rules_->setRule(first, rules_->getRule(second)); - rules_->setRule(second, swap); + assert(first < rules_->getSize()); + assert(second < rules_->getSize()); + const HighlightRule swap = rules_->getRule(first); + rules_->setRule(first, rules_->getRule(second)); + rules_->setRule(second, swap); } void HighlightManager::storeSettings() { - storingSettings_ = true; // don't reload settings while saving - settings_->storeSetting(SettingConstants::HIGHLIGHT_RULES, rulesToString()); - storingSettings_ = false; + storingSettings_ = true; // don't reload settings while saving + settings_->storeSetting(SettingConstants::HIGHLIGHT_RULES, rulesToString()); + storingSettings_ = false; } void HighlightManager::loadSettings() { - std::string rulesString = settings_->getSetting(SettingConstants::HIGHLIGHT_RULES); - std::stringstream stream; - stream << rulesString; - try { - boost::archive::text_iarchive archive(stream); - archive >> rules_->list_; - } catch (boost::archive::archive_exception&) { - rules_->list_ = getDefaultRules(); - } + std::string rulesString = settings_->getSetting(SettingConstants::HIGHLIGHT_RULES); + std::stringstream stream; + stream << rulesString; + try { + boost::archive::text_iarchive archive(stream); + archive >> rules_->list_; + } catch (boost::archive::archive_exception&) { + rules_->list_ = getDefaultRules(); + } } Highlighter* HighlightManager::createHighlighter() { - return new Highlighter(this); + return new Highlighter(this); } bool HighlightManager::isDefaultRulesList() const { - return getDefaultRules() == rules_->list_; + return getDefaultRules() == rules_->list_; } void HighlightManager::resetToDefaultRulesList() { - rules_->list_ = getDefaultRules(); + rules_->list_ = getDefaultRules(); } } diff --git a/Swift/Controllers/HighlightManager.h b/Swift/Controllers/HighlightManager.h index 180f7a3..1d2eb8a 100644 --- a/Swift/Controllers/HighlightManager.h +++ b/Swift/Controllers/HighlightManager.h @@ -21,61 +21,61 @@ namespace Swift { - class SettingsProvider; - class Highlighter; - - class HighlightManager { - public: - - class HighlightRulesList { - public: - friend class HighlightManager; - size_t getSize() const { return list_.size(); } - const HighlightRule& getRule(const size_t index) const { return list_[index]; } - void addRule(const HighlightRule& rule) { list_.push_back(rule); } - void combineRules(const HighlightRulesList& rhs) { - list_.insert(list_.end(), rhs.list_.begin(), rhs.list_.end()); - } - void setRule(const size_t index, const HighlightRule& rule) { - list_[index] = rule; - } - private: - std::vector list_; - }; - - HighlightManager(SettingsProvider* settings); - - Highlighter* createHighlighter(); - - boost::shared_ptr getRules() const { return rules_; } - - bool isDefaultRulesList() const; - void resetToDefaultRulesList(); - - HighlightRule getRule(int index) const; - void setRule(int index, const HighlightRule& rule); - void insertRule(int index, const HighlightRule& rule); - void removeRule(int index); - void swapRules(const size_t first, const size_t second); - void storeSettings(); - void loadSettings(); - - boost::signal onHighlight; - - private: - void handleSettingChanged(const std::string& settingPath); - - std::string rulesToString() const; - static std::vector getDefaultRules(); - - private: - SettingsProvider* settings_; - bool storingSettings_; - - boost::shared_ptr rules_; - boost::bsignals::scoped_connection handleSettingChangedConnection_; - }; - - typedef boost::shared_ptr HighlightRulesListPtr; + class SettingsProvider; + class Highlighter; + + class HighlightManager { + public: + + class HighlightRulesList { + public: + friend class HighlightManager; + size_t getSize() const { return list_.size(); } + const HighlightRule& getRule(const size_t index) const { return list_[index]; } + void addRule(const HighlightRule& rule) { list_.push_back(rule); } + void combineRules(const HighlightRulesList& rhs) { + list_.insert(list_.end(), rhs.list_.begin(), rhs.list_.end()); + } + void setRule(const size_t index, const HighlightRule& rule) { + list_[index] = rule; + } + private: + std::vector list_; + }; + + HighlightManager(SettingsProvider* settings); + + Highlighter* createHighlighter(); + + boost::shared_ptr getRules() const { return rules_; } + + bool isDefaultRulesList() const; + void resetToDefaultRulesList(); + + HighlightRule getRule(int index) const; + void setRule(int index, const HighlightRule& rule); + void insertRule(int index, const HighlightRule& rule); + void removeRule(int index); + void swapRules(const size_t first, const size_t second); + void storeSettings(); + void loadSettings(); + + boost::signal onHighlight; + + private: + void handleSettingChanged(const std::string& settingPath); + + std::string rulesToString() const; + static std::vector getDefaultRules(); + + private: + SettingsProvider* settings_; + bool storingSettings_; + + boost::shared_ptr rules_; + boost::bsignals::scoped_connection handleSettingChangedConnection_; + }; + + typedef boost::shared_ptr HighlightRulesListPtr; } diff --git a/Swift/Controllers/HighlightRule.cpp b/Swift/Controllers/HighlightRule.cpp index 021e15d..86ac5f7 100644 --- a/Swift/Controllers/HighlightRule.cpp +++ b/Swift/Controllers/HighlightRule.cpp @@ -23,179 +23,179 @@ namespace Swift { HighlightRule::HighlightRule() - : nickIsKeyword_(false) - , matchCase_(false) - , matchWholeWords_(false) - , matchChat_(false) - , matchMUC_(false) + : nickIsKeyword_(false) + , matchCase_(false) + , matchWholeWords_(false) + , matchChat_(false) + , matchMUC_(false) { } boost::regex HighlightRule::regexFromString(const std::string & s) const { - std::string escaped = Regex::escape(s); - std::string word = matchWholeWords_ ? "\\b" : ""; - boost::regex::flag_type flags = boost::regex::normal; - if (!matchCase_) { - flags |= boost::regex::icase; - } - return boost::regex(word + escaped + word, flags); + std::string escaped = Regex::escape(s); + std::string word = matchWholeWords_ ? "\\b" : ""; + boost::regex::flag_type flags = boost::regex::normal; + if (!matchCase_) { + flags |= boost::regex::icase; + } + return boost::regex(word + escaped + word, flags); } void HighlightRule::updateRegex() const { - keywordRegex_.clear(); - foreach (const std::string & k, keywords_) { - keywordRegex_.push_back(regexFromString(k)); - } - senderRegex_.clear(); - foreach (const std::string & s, senders_) { - senderRegex_.push_back(regexFromString(s)); - } + keywordRegex_.clear(); + foreach (const std::string & k, keywords_) { + keywordRegex_.push_back(regexFromString(k)); + } + senderRegex_.clear(); + foreach (const std::string & s, senders_) { + senderRegex_.push_back(regexFromString(s)); + } } std::string HighlightRule::boolToString(bool b) { - return b ? "1" : "0"; + return b ? "1" : "0"; } bool HighlightRule::boolFromString(const std::string& s) { - return s == "1"; + return s == "1"; } bool HighlightRule::isMatch(const std::string& body, const std::string& sender, const std::string& nick, MessageType messageType) const { - if ((messageType == HighlightRule::ChatMessage && matchChat_) || (messageType == HighlightRule::MUCMessage && matchMUC_)) { - - bool matchesKeyword = keywords_.empty() && (nick.empty() || !nickIsKeyword_); - bool matchesSender = senders_.empty(); - - if (!matchesKeyword) { - // check if the nickname matches - if (nickIsKeyword_ && !nick.empty() && boost::regex_search(body, regexFromString(nick))) { - matchesKeyword = true; - } - - // check if a keyword matches - if (!matchesKeyword && !keywords_.empty()) { - foreach (const boost::regex &keyword, keywordRegex_) { - if (boost::regex_search(body, keyword)) { - matchesKeyword = true; - break; - } - } - } - } - - foreach (const boost::regex & rx, senderRegex_) { - if (boost::regex_search(sender, rx)) { - matchesSender = true; - break; - } - } - - if (matchesKeyword && matchesSender) { - return true; - } - } - - return false; + if ((messageType == HighlightRule::ChatMessage && matchChat_) || (messageType == HighlightRule::MUCMessage && matchMUC_)) { + + bool matchesKeyword = keywords_.empty() && (nick.empty() || !nickIsKeyword_); + bool matchesSender = senders_.empty(); + + if (!matchesKeyword) { + // check if the nickname matches + if (nickIsKeyword_ && !nick.empty() && boost::regex_search(body, regexFromString(nick))) { + matchesKeyword = true; + } + + // check if a keyword matches + if (!matchesKeyword && !keywords_.empty()) { + foreach (const boost::regex &keyword, keywordRegex_) { + if (boost::regex_search(body, keyword)) { + matchesKeyword = true; + break; + } + } + } + } + + foreach (const boost::regex & rx, senderRegex_) { + if (boost::regex_search(sender, rx)) { + matchesSender = true; + break; + } + } + + if (matchesKeyword && matchesSender) { + return true; + } + } + + return false; } void HighlightRule::setSenders(const std::vector& senders) { - senders_ = senders; - updateRegex(); + senders_ = senders; + updateRegex(); } void HighlightRule::setKeywords(const std::vector& keywords) { - keywords_ = keywords; - updateRegex(); + keywords_ = keywords; + updateRegex(); } std::vector HighlightRule::getKeywordRegex(const std::string& nick) const { - if (nickIsKeyword_) { - std::vector regex; - if (!nick.empty()) { - regex.push_back(regexFromString(nick)); - } - return regex; - } else { - return keywordRegex_; - } + if (nickIsKeyword_) { + std::vector regex; + if (!nick.empty()) { + regex.push_back(regexFromString(nick)); + } + return regex; + } else { + return keywordRegex_; + } } void HighlightRule::setNickIsKeyword(bool nickIsKeyword) { - nickIsKeyword_ = nickIsKeyword; - updateRegex(); + nickIsKeyword_ = nickIsKeyword; + updateRegex(); } void HighlightRule::setMatchCase(bool matchCase) { - matchCase_ = matchCase; - updateRegex(); + matchCase_ = matchCase; + updateRegex(); } void HighlightRule::setMatchWholeWords(bool matchWholeWords) { - matchWholeWords_ = matchWholeWords; - updateRegex(); + matchWholeWords_ = matchWholeWords; + updateRegex(); } void HighlightRule::setMatchChat(bool matchChat) { - matchChat_ = matchChat; - updateRegex(); + matchChat_ = matchChat; + updateRegex(); } void HighlightRule::setMatchMUC(bool matchMUC) { - matchMUC_ = matchMUC; - updateRegex(); + matchMUC_ = matchMUC; + updateRegex(); } bool HighlightRule::isEmpty() const { - return senders_.empty() && keywords_.empty() && !nickIsKeyword_ && !matchChat_ && !matchMUC_ && action_.isEmpty(); + return senders_.empty() && keywords_.empty() && !nickIsKeyword_ && !matchChat_ && !matchMUC_ && action_.isEmpty(); } bool operator ==(HighlightRule const& a, HighlightRule const& b) { - if (a.getSenders() != b.getSenders()) { - return false; - } + if (a.getSenders() != b.getSenders()) { + return false; + } - if (a.getKeywords() != b.getKeywords()) { - return false; - } + if (a.getKeywords() != b.getKeywords()) { + return false; + } - if (a.getNickIsKeyword() != b.getNickIsKeyword()) { - return false; - } + if (a.getNickIsKeyword() != b.getNickIsKeyword()) { + return false; + } - if (a.getMatchChat() != b.getMatchChat()) { - return false; - } + if (a.getMatchChat() != b.getMatchChat()) { + return false; + } - if (a.getMatchMUC() != b.getMatchMUC()) { - return false; - } + if (a.getMatchMUC() != b.getMatchMUC()) { + return false; + } - if (a.getMatchCase() != b.getMatchCase()) { - return false; - } + if (a.getMatchCase() != b.getMatchCase()) { + return false; + } - if (a.getMatchWholeWords() != b.getMatchWholeWords()) { - return false; - } + if (a.getMatchWholeWords() != b.getMatchWholeWords()) { + return false; + } - if (a.getAction() != b.getAction()) { - return false; - } + if (a.getAction() != b.getAction()) { + return false; + } - return true; + return true; } } diff --git a/Swift/Controllers/HighlightRule.h b/Swift/Controllers/HighlightRule.h index caacaee..bffdc41 100644 --- a/Swift/Controllers/HighlightRule.h +++ b/Swift/Controllers/HighlightRule.h @@ -23,81 +23,81 @@ namespace Swift { - class HighlightRule { - public: - HighlightRule(); + class HighlightRule { + public: + HighlightRule(); - enum MessageType { ChatMessage, MUCMessage }; + enum MessageType { ChatMessage, MUCMessage }; - bool isMatch(const std::string& body, const std::string& sender, const std::string& nick, MessageType) const; + bool isMatch(const std::string& body, const std::string& sender, const std::string& nick, MessageType) const; - const HighlightAction& getAction() const { return action_; } - HighlightAction& getAction() { return action_; } + const HighlightAction& getAction() const { return action_; } + HighlightAction& getAction() { return action_; } - const std::vector& getSenders() const { return senders_; } - void setSenders(const std::vector&); - const std::vector& getSenderRegex() const { return senderRegex_; } + const std::vector& getSenders() const { return senders_; } + void setSenders(const std::vector&); + const std::vector& getSenderRegex() const { return senderRegex_; } - const std::vector& getKeywords() const { return keywords_; } - void setKeywords(const std::vector&); - std::vector getKeywordRegex(const std::string& nick) const; + const std::vector& getKeywords() const { return keywords_; } + void setKeywords(const std::vector&); + std::vector getKeywordRegex(const std::string& nick) const; - bool getNickIsKeyword() const { return nickIsKeyword_; } - void setNickIsKeyword(bool); + bool getNickIsKeyword() const { return nickIsKeyword_; } + void setNickIsKeyword(bool); - bool getMatchCase() const { return matchCase_; } - void setMatchCase(bool); + bool getMatchCase() const { return matchCase_; } + void setMatchCase(bool); - bool getMatchWholeWords() const { return matchWholeWords_; } - void setMatchWholeWords(bool); + bool getMatchWholeWords() const { return matchWholeWords_; } + void setMatchWholeWords(bool); - bool getMatchChat() const { return matchChat_; } - void setMatchChat(bool); + bool getMatchChat() const { return matchChat_; } + void setMatchChat(bool); - bool getMatchMUC() const { return matchMUC_; } - void setMatchMUC(bool); + bool getMatchMUC() const { return matchMUC_; } + void setMatchMUC(bool); - bool isEmpty() const; + bool isEmpty() const; - private: - friend class boost::serialization::access; - template void serialize(Archive & ar, const unsigned int version); + private: + friend class boost::serialization::access; + template void serialize(Archive & ar, const unsigned int version); - static std::string boolToString(bool); - static bool boolFromString(const std::string&); + static std::string boolToString(bool); + static bool boolFromString(const std::string&); - std::vector senders_; - std::vector keywords_; - bool nickIsKeyword_; + std::vector senders_; + std::vector keywords_; + bool nickIsKeyword_; - mutable std::vector senderRegex_; - mutable std::vector keywordRegex_; - void updateRegex() const; - boost::regex regexFromString(const std::string&) const; + mutable std::vector senderRegex_; + mutable std::vector keywordRegex_; + void updateRegex() const; + boost::regex regexFromString(const std::string&) const; - bool matchCase_; - bool matchWholeWords_; + bool matchCase_; + bool matchWholeWords_; - bool matchChat_; - bool matchMUC_; + bool matchChat_; + bool matchMUC_; - HighlightAction action_; - }; + HighlightAction action_; + }; - bool operator ==(HighlightRule const& a, HighlightRule const& b); + bool operator ==(HighlightRule const& a, HighlightRule const& b); - template - void HighlightRule::serialize(Archive& ar, const unsigned int /*version*/) - { - ar & senders_; - ar & keywords_; - ar & nickIsKeyword_; - ar & matchChat_; - ar & matchMUC_; - ar & matchCase_; - ar & matchWholeWords_; - ar & action_; - updateRegex(); - } + template + void HighlightRule::serialize(Archive& ar, const unsigned int /*version*/) + { + ar & senders_; + ar & keywords_; + ar & nickIsKeyword_; + ar & matchChat_; + ar & matchMUC_; + ar & matchCase_; + ar & matchWholeWords_; + ar & action_; + updateRegex(); + } } diff --git a/Swift/Controllers/Highlighter.cpp b/Swift/Controllers/Highlighter.cpp index 40f92ba..3499217 100644 --- a/Swift/Controllers/Highlighter.cpp +++ b/Swift/Controllers/Highlighter.cpp @@ -19,35 +19,35 @@ namespace Swift { Highlighter::Highlighter(HighlightManager* manager) - : manager_(manager) + : manager_(manager) { - setMode(ChatMode); + setMode(ChatMode); } void Highlighter::setMode(Mode mode) { - mode_ = mode; - messageType_ = mode_ == ChatMode ? HighlightRule::ChatMessage : HighlightRule::MUCMessage; + mode_ = mode; + messageType_ = mode_ == ChatMode ? HighlightRule::ChatMessage : HighlightRule::MUCMessage; } HighlightAction Highlighter::findFirstFullMessageMatchAction(const std::string& body, const std::string& sender) const { - HighlightAction match; - HighlightRulesListPtr rules = manager_->getRules(); - for (size_t i = 0; i < rules->getSize(); ++i) { - const HighlightRule& rule = rules->getRule(i); - if (rule.isMatch(body, sender, nick_, messageType_) && rule.getAction().highlightWholeMessage()) { - match = rule.getAction(); - break; - } - } - - return match; + HighlightAction match; + HighlightRulesListPtr rules = manager_->getRules(); + for (size_t i = 0; i < rules->getSize(); ++i) { + const HighlightRule& rule = rules->getRule(i); + if (rule.isMatch(body, sender, nick_, messageType_) && rule.getAction().highlightWholeMessage()) { + match = rule.getAction(); + break; + } + } + + return match; } void Highlighter::handleHighlightAction(const HighlightAction& action) { - manager_->onHighlight(action); + manager_->onHighlight(action); } } diff --git a/Swift/Controllers/Highlighter.h b/Swift/Controllers/Highlighter.h index 5d5f531..9ad3339 100644 --- a/Swift/Controllers/Highlighter.h +++ b/Swift/Controllers/Highlighter.h @@ -19,27 +19,27 @@ namespace Swift { - class HighlightManager; + class HighlightManager; - class Highlighter { - public: - Highlighter(HighlightManager* manager); + class Highlighter { + public: + Highlighter(HighlightManager* manager); - enum Mode { ChatMode, MUCMode }; - void setMode(Mode mode); + enum Mode { ChatMode, MUCMode }; + void setMode(Mode mode); - void setNick(const std::string& nick) { nick_ = nick; } - std::string getNick() const { return nick_; } + void setNick(const std::string& nick) { nick_ = nick; } + std::string getNick() const { return nick_; } - HighlightAction findFirstFullMessageMatchAction(const std::string& body, const std::string& sender) const; + HighlightAction findFirstFullMessageMatchAction(const std::string& body, const std::string& sender) const; - void handleHighlightAction(const HighlightAction& action); + void handleHighlightAction(const HighlightAction& action); - private: - HighlightManager* manager_; - Mode mode_; - HighlightRule::MessageType messageType_; - std::string nick_; - }; + private: + HighlightManager* manager_; + Mode mode_; + HighlightRule::MessageType messageType_; + std::string nick_; + }; } diff --git a/Swift/Controllers/HistoryController.cpp b/Swift/Controllers/HistoryController.cpp index f439429..1e5830c 100644 --- a/Swift/Controllers/HistoryController.cpp +++ b/Swift/Controllers/HistoryController.cpp @@ -28,39 +28,39 @@ HistoryController::~HistoryController() { } void HistoryController::addMessage(const std::string& message, const JID& fromJID, const JID& toJID, HistoryMessage::Type type, const boost::posix_time::ptime& timeStamp) { - // note: using localtime timestamps - boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor::utc_to_local(timeStamp); - int offset = (localTime - timeStamp).hours(); + // note: using localtime timestamps + boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor::utc_to_local(timeStamp); + int offset = (localTime - timeStamp).hours(); - HistoryMessage historyMessage(message, fromJID, toJID, type, localTime, offset); + HistoryMessage historyMessage(message, fromJID, toJID, type, localTime, offset); - localHistory_->addMessage(historyMessage); - onNewMessage(historyMessage); + localHistory_->addMessage(historyMessage); + onNewMessage(historyMessage); } std::vector HistoryController::getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const { - return localHistory_->getMessagesFromDate(selfJID, contactJID, type, date); + return localHistory_->getMessagesFromDate(selfJID, contactJID, type, date); } std::vector HistoryController::getMUCContext(const JID& selfJID, const JID& mucJID, const boost::posix_time::ptime& timeStamp) const { - boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor::utc_to_local(timeStamp); - return getMessagesFromDate(selfJID, mucJID, HistoryMessage::Groupchat, localTime.date()); + boost::posix_time::ptime localTime = boost::date_time::c_local_adjustor::utc_to_local(timeStamp); + return getMessagesFromDate(selfJID, mucJID, HistoryMessage::Groupchat, localTime.date()); } std::vector HistoryController::getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const { - return localHistory_->getMessagesFromPreviousDate(selfJID, contactJID, type, date); + return localHistory_->getMessagesFromPreviousDate(selfJID, contactJID, type, date); } std::vector HistoryController::getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const { - return localHistory_->getMessagesFromNextDate(selfJID, contactJID, type, date); + return localHistory_->getMessagesFromNextDate(selfJID, contactJID, type, date); } ContactsMap HistoryController::getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword) const { - return localHistory_->getContacts(selfJID, type, keyword); + return localHistory_->getContacts(selfJID, type, keyword); } boost::posix_time::ptime HistoryController::getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID) { - return localHistory_->getLastTimeStampFromMUC(selfJID, mucJID); + return localHistory_->getLastTimeStampFromMUC(selfJID, mucJID); } } diff --git a/Swift/Controllers/HistoryController.h b/Swift/Controllers/HistoryController.h index 0bdbb35..f1f613f 100644 --- a/Swift/Controllers/HistoryController.h +++ b/Swift/Controllers/HistoryController.h @@ -21,25 +21,25 @@ #include namespace Swift { - class JID; + class JID; - class HistoryController { - public: - HistoryController(HistoryStorage* localHistoryStorage); - ~HistoryController(); + class HistoryController { + public: + HistoryController(HistoryStorage* localHistoryStorage); + ~HistoryController(); - void addMessage(const std::string& message, const JID& fromJID, const JID& toJID, HistoryMessage::Type type, const boost::posix_time::ptime& timeStamp); - std::vector getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; - std::vector getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; - std::vector getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; - ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword = std::string()) const; - std::vector getMUCContext(const JID& selfJID, const JID& mucJID, const boost::posix_time::ptime& timeStamp) const; + void addMessage(const std::string& message, const JID& fromJID, const JID& toJID, HistoryMessage::Type type, const boost::posix_time::ptime& timeStamp); + std::vector getMessagesFromDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; + std::vector getMessagesFromPreviousDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; + std::vector getMessagesFromNextDate(const JID& selfJID, const JID& contactJID, HistoryMessage::Type type, const boost::gregorian::date& date) const; + ContactsMap getContacts(const JID& selfJID, HistoryMessage::Type type, const std::string& keyword = std::string()) const; + std::vector getMUCContext(const JID& selfJID, const JID& mucJID, const boost::posix_time::ptime& timeStamp) const; - boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID); + boost::posix_time::ptime getLastTimeStampFromMUC(const JID& selfJID, const JID& mucJID); - boost::signal onNewMessage; + boost::signal onNewMessage; - private: - HistoryStorage* localHistory_; - }; + private: + HistoryStorage* localHistory_; + }; } diff --git a/Swift/Controllers/HistoryViewController.cpp b/Swift/Controllers/HistoryViewController.cpp index 2d56b9e..d0ccc66 100644 --- a/Swift/Controllers/HistoryViewController.cpp +++ b/Swift/Controllers/HistoryViewController.cpp @@ -25,335 +25,335 @@ #include namespace Swift { - static const std::string category[] = { "Contacts", "MUC", "Contacts" }; + static const std::string category[] = { "Contacts", "MUC", "Contacts" }; HistoryViewController::HistoryViewController( - const JID& selfJID, - UIEventStream* uiEventStream, - HistoryController* historyController, - NickResolver* nickResolver, - AvatarManager* avatarManager, - PresenceOracle* presenceOracle, - HistoryWindowFactory* historyWindowFactory) : - selfJID_(selfJID), - uiEventStream_(uiEventStream), - historyController_(historyController), - nickResolver_(nickResolver), - avatarManager_(avatarManager), - presenceOracle_(presenceOracle), - historyWindowFactory_(historyWindowFactory), - historyWindow_(NULL), - selectedItem_(NULL), - currentResultDate_(boost::gregorian::not_a_date_time) { - uiEventStream_->onUIEvent.connect(boost::bind(&HistoryViewController::handleUIEvent, this, _1)); - - roster_ = new Roster(false, true); + const JID& selfJID, + UIEventStream* uiEventStream, + HistoryController* historyController, + NickResolver* nickResolver, + AvatarManager* avatarManager, + PresenceOracle* presenceOracle, + HistoryWindowFactory* historyWindowFactory) : + selfJID_(selfJID), + uiEventStream_(uiEventStream), + historyController_(historyController), + nickResolver_(nickResolver), + avatarManager_(avatarManager), + presenceOracle_(presenceOracle), + historyWindowFactory_(historyWindowFactory), + historyWindow_(NULL), + selectedItem_(NULL), + currentResultDate_(boost::gregorian::not_a_date_time) { + uiEventStream_->onUIEvent.connect(boost::bind(&HistoryViewController::handleUIEvent, this, _1)); + + roster_ = new Roster(false, true); } HistoryViewController::~HistoryViewController() { - uiEventStream_->onUIEvent.disconnect(boost::bind(&HistoryViewController::handleUIEvent, this, _1)); - if (historyWindow_) { - historyWindow_->onSelectedContactChanged.disconnect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1)); - historyWindow_->onReturnPressed.disconnect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1)); - historyWindow_->onScrollReachedTop.disconnect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1)); - historyWindow_->onScrollReachedBottom.disconnect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1)); - historyWindow_->onPreviousButtonClicked.disconnect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this)); - historyWindow_->onNextButtonClicked.disconnect(boost::bind(&HistoryViewController::handleNextButtonClicked, this)); - historyWindow_->onCalendarClicked.disconnect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1)); - historyController_->onNewMessage.disconnect(boost::bind(&HistoryViewController::handleNewMessage, this, _1)); - - presenceOracle_->onPresenceChange.disconnect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1)); - avatarManager_->onAvatarChanged.disconnect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1)); - - delete historyWindow_; - } - delete roster_; + uiEventStream_->onUIEvent.disconnect(boost::bind(&HistoryViewController::handleUIEvent, this, _1)); + if (historyWindow_) { + historyWindow_->onSelectedContactChanged.disconnect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1)); + historyWindow_->onReturnPressed.disconnect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1)); + historyWindow_->onScrollReachedTop.disconnect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1)); + historyWindow_->onScrollReachedBottom.disconnect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1)); + historyWindow_->onPreviousButtonClicked.disconnect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this)); + historyWindow_->onNextButtonClicked.disconnect(boost::bind(&HistoryViewController::handleNextButtonClicked, this)); + historyWindow_->onCalendarClicked.disconnect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1)); + historyController_->onNewMessage.disconnect(boost::bind(&HistoryViewController::handleNewMessage, this, _1)); + + presenceOracle_->onPresenceChange.disconnect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1)); + avatarManager_->onAvatarChanged.disconnect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1)); + + delete historyWindow_; + } + delete roster_; } void HistoryViewController::handleUIEvent(boost::shared_ptr rawEvent) { - boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); - if (event != NULL) { - if (historyWindow_ == NULL) { - historyWindow_ = historyWindowFactory_->createHistoryWindow(uiEventStream_); - historyWindow_->onSelectedContactChanged.connect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1)); - historyWindow_->onReturnPressed.connect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1)); - historyWindow_->onScrollReachedTop.connect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1)); - historyWindow_->onScrollReachedBottom.connect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1)); - historyWindow_->onPreviousButtonClicked.connect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this)); - historyWindow_->onNextButtonClicked.connect(boost::bind(&HistoryViewController::handleNextButtonClicked, this)); - historyWindow_->onCalendarClicked.connect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1)); - historyController_->onNewMessage.connect(boost::bind(&HistoryViewController::handleNewMessage, this, _1)); - - presenceOracle_->onPresenceChange.connect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1)); - avatarManager_->onAvatarChanged.connect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1)); - - historyWindow_->setRosterModel(roster_); - } - - // populate roster by doing an empty search - handleReturnPressed(std::string()); - - historyWindow_->activate(); - } + boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); + if (event != NULL) { + if (historyWindow_ == NULL) { + historyWindow_ = historyWindowFactory_->createHistoryWindow(uiEventStream_); + historyWindow_->onSelectedContactChanged.connect(boost::bind(&HistoryViewController::handleSelectedContactChanged, this, _1)); + historyWindow_->onReturnPressed.connect(boost::bind(&HistoryViewController::handleReturnPressed, this, _1)); + historyWindow_->onScrollReachedTop.connect(boost::bind(&HistoryViewController::handleScrollReachedTop, this, _1)); + historyWindow_->onScrollReachedBottom.connect(boost::bind(&HistoryViewController::handleScrollReachedBottom, this, _1)); + historyWindow_->onPreviousButtonClicked.connect(boost::bind(&HistoryViewController::handlePreviousButtonClicked, this)); + historyWindow_->onNextButtonClicked.connect(boost::bind(&HistoryViewController::handleNextButtonClicked, this)); + historyWindow_->onCalendarClicked.connect(boost::bind(&HistoryViewController::handleCalendarClicked, this, _1)); + historyController_->onNewMessage.connect(boost::bind(&HistoryViewController::handleNewMessage, this, _1)); + + presenceOracle_->onPresenceChange.connect(boost::bind(&HistoryViewController::handlePresenceChanged, this, _1)); + avatarManager_->onAvatarChanged.connect(boost::bind(&HistoryViewController::handleAvatarChanged, this, _1)); + + historyWindow_->setRosterModel(roster_); + } + + // populate roster by doing an empty search + handleReturnPressed(std::string()); + + historyWindow_->activate(); + } } void HistoryViewController::handleSelectedContactChanged(RosterItem* newContact) { - // FIXME: signal is triggerd twice. - ContactRosterItem* contact = dynamic_cast(newContact); - - if (contact && selectedItem_ != contact) { - selectedItem_ = contact; - historyWindow_->resetConversationView(); - } - else { - return; - } - - JID contactJID = contact->getJID(); - - std::vector messages; - for (int it = HistoryMessage::Chat; it <= HistoryMessage::PrivateMessage; it++) { - HistoryMessage::Type type = static_cast(it); - - if (contacts_[type].count(contactJID)) { - currentResultDate_ = *contacts_[type][contactJID].rbegin(); - selectedItemType_ = type; - messages = historyController_->getMessagesFromDate(selfJID_, contactJID, type, currentResultDate_); - } - } - - historyWindow_->setDate(currentResultDate_); - - foreach (const HistoryMessage& message, messages) { - addNewMessage(message, false); - } + // FIXME: signal is triggerd twice. + ContactRosterItem* contact = dynamic_cast(newContact); + + if (contact && selectedItem_ != contact) { + selectedItem_ = contact; + historyWindow_->resetConversationView(); + } + else { + return; + } + + JID contactJID = contact->getJID(); + + std::vector messages; + for (int it = HistoryMessage::Chat; it <= HistoryMessage::PrivateMessage; it++) { + HistoryMessage::Type type = static_cast(it); + + if (contacts_[type].count(contactJID)) { + currentResultDate_ = *contacts_[type][contactJID].rbegin(); + selectedItemType_ = type; + messages = historyController_->getMessagesFromDate(selfJID_, contactJID, type, currentResultDate_); + } + } + + historyWindow_->setDate(currentResultDate_); + + foreach (const HistoryMessage& message, messages) { + addNewMessage(message, false); + } } void HistoryViewController::handleNewMessage(const HistoryMessage& message) { - JID contactJID = message.getFromJID().toBare() == selfJID_ ? message.getToJID() : message.getFromJID(); - - JID displayJID; - if (message.getType() == HistoryMessage::PrivateMessage) { - displayJID = contactJID; - } - else { - displayJID = contactJID.toBare(); - } - - // check current conversation - if (selectedItem_ && selectedItem_->getJID() == displayJID) { - if (historyWindow_->getLastVisibleDate() == message.getTime().date()) { - addNewMessage(message, false); - } - } - - // check if the new message matches the query - if (message.getMessage().find(historyWindow_->getSearchBoxText()) == std::string::npos) { - return; - } - - // update contacts - if (!contacts_[message.getType()].count(displayJID)) { - roster_->addContact(displayJID, displayJID, nickResolver_->jidToNick(displayJID), category[message.getType()], avatarManager_->getAvatarPath(displayJID)); - } - - contacts_[message.getType()][displayJID].insert(message.getTime().date()); + JID contactJID = message.getFromJID().toBare() == selfJID_ ? message.getToJID() : message.getFromJID(); + + JID displayJID; + if (message.getType() == HistoryMessage::PrivateMessage) { + displayJID = contactJID; + } + else { + displayJID = contactJID.toBare(); + } + + // check current conversation + if (selectedItem_ && selectedItem_->getJID() == displayJID) { + if (historyWindow_->getLastVisibleDate() == message.getTime().date()) { + addNewMessage(message, false); + } + } + + // check if the new message matches the query + if (message.getMessage().find(historyWindow_->getSearchBoxText()) == std::string::npos) { + return; + } + + // update contacts + if (!contacts_[message.getType()].count(displayJID)) { + roster_->addContact(displayJID, displayJID, nickResolver_->jidToNick(displayJID), category[message.getType()], avatarManager_->getAvatarPath(displayJID)); + } + + contacts_[message.getType()][displayJID].insert(message.getTime().date()); } void HistoryViewController::addNewMessage(const HistoryMessage& message, bool addAtTheTop) { - bool senderIsSelf = message.getFromJID().toBare() == selfJID_; - std::string avatarPath = pathToString(avatarManager_->getAvatarPath(message.getFromJID())); + bool senderIsSelf = message.getFromJID().toBare() == selfJID_; + std::string avatarPath = pathToString(avatarManager_->getAvatarPath(message.getFromJID())); - std::string nick = message.getType() != HistoryMessage::Groupchat ? nickResolver_->jidToNick(message.getFromJID()) : message.getFromJID().getResource(); - historyWindow_->addMessage(message.getMessage(), nick, senderIsSelf, avatarPath, message.getTime(), addAtTheTop); + std::string nick = message.getType() != HistoryMessage::Groupchat ? nickResolver_->jidToNick(message.getFromJID()) : message.getFromJID().getResource(); + historyWindow_->addMessage(message.getMessage(), nick, senderIsSelf, avatarPath, message.getTime(), addAtTheTop); } void HistoryViewController::handleReturnPressed(const std::string& keyword) { - reset(); - - for (int it = HistoryMessage::Chat; it <= HistoryMessage::PrivateMessage; it++) { - HistoryMessage::Type type = static_cast(it); - - contacts_[type] = historyController_->getContacts(selfJID_, type, keyword); - - for (ContactsMap::const_iterator contact = contacts_[type].begin(); contact != contacts_[type].end(); contact++) { - const JID& jid = contact->first; - std::string nick; - if (type == HistoryMessage::PrivateMessage) { - nick = jid.toString(); - } - else { - nick = nickResolver_->jidToNick(jid); - } - roster_->addContact(jid, jid, nick, category[type], avatarManager_->getAvatarPath(jid)); - - Presence::ref presence = getPresence(jid, type == HistoryMessage::Groupchat); - - if (presence.get()) { - roster_->applyOnItem(SetPresence(presence, JID::WithoutResource), jid); - } - } - } + reset(); + + for (int it = HistoryMessage::Chat; it <= HistoryMessage::PrivateMessage; it++) { + HistoryMessage::Type type = static_cast(it); + + contacts_[type] = historyController_->getContacts(selfJID_, type, keyword); + + for (ContactsMap::const_iterator contact = contacts_[type].begin(); contact != contacts_[type].end(); contact++) { + const JID& jid = contact->first; + std::string nick; + if (type == HistoryMessage::PrivateMessage) { + nick = jid.toString(); + } + else { + nick = nickResolver_->jidToNick(jid); + } + roster_->addContact(jid, jid, nick, category[type], avatarManager_->getAvatarPath(jid)); + + Presence::ref presence = getPresence(jid, type == HistoryMessage::Groupchat); + + if (presence.get()) { + roster_->applyOnItem(SetPresence(presence, JID::WithoutResource), jid); + } + } + } } void HistoryViewController::handleScrollReachedTop(const boost::gregorian::date& date) { - if (!selectedItem_) { - return; - } + if (!selectedItem_) { + return; + } - std::vector messages = historyController_->getMessagesFromPreviousDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date); + std::vector messages = historyController_->getMessagesFromPreviousDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date); - foreach (const HistoryMessage& message, messages) { - addNewMessage(message, true); - } - historyWindow_->resetConversationViewTopInsertPoint(); + foreach (const HistoryMessage& message, messages) { + addNewMessage(message, true); + } + historyWindow_->resetConversationViewTopInsertPoint(); } void HistoryViewController::handleScrollReachedBottom(const boost::gregorian::date& date) { - if (!selectedItem_) { - return; - } + if (!selectedItem_) { + return; + } - std::vector messages = historyController_->getMessagesFromNextDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date); + std::vector messages = historyController_->getMessagesFromNextDate(selfJID_, selectedItem_->getJID(), selectedItemType_, date); - foreach (const HistoryMessage& message, messages) { - addNewMessage(message, false); - } + foreach (const HistoryMessage& message, messages) { + addNewMessage(message, false); + } } void HistoryViewController::handleNextButtonClicked() { - if (!selectedItem_) { - return; - } + if (!selectedItem_) { + return; + } - std::set::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_); + std::set::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_); - if (*date == *contacts_[selectedItemType_][selectedItem_->getJID()].rbegin()) { - return; - } + if (*date == *contacts_[selectedItemType_][selectedItem_->getJID()].rbegin()) { + return; + } - historyWindow_->resetConversationView(); - currentResultDate_ = *(++date); - std::vector messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_); - historyWindow_->setDate(currentResultDate_); + historyWindow_->resetConversationView(); + currentResultDate_ = *(++date); + std::vector messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_); + historyWindow_->setDate(currentResultDate_); - foreach (const HistoryMessage& message, messages) { - addNewMessage(message, false); - } + foreach (const HistoryMessage& message, messages) { + addNewMessage(message, false); + } } void HistoryViewController::handlePreviousButtonClicked() { - if (!selectedItem_) { - return; - } + if (!selectedItem_) { + return; + } - std::set::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_); + std::set::iterator date = contacts_[selectedItemType_][selectedItem_->getJID()].find(currentResultDate_); - if (date == contacts_[selectedItemType_][selectedItem_->getJID()].begin()) { - return; - } + if (date == contacts_[selectedItemType_][selectedItem_->getJID()].begin()) { + return; + } - historyWindow_->resetConversationView(); - currentResultDate_ = *(--date); - std::vector messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_); - historyWindow_->setDate(currentResultDate_); + historyWindow_->resetConversationView(); + currentResultDate_ = *(--date); + std::vector messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_); + historyWindow_->setDate(currentResultDate_); - foreach (const HistoryMessage& message, messages) { - addNewMessage(message, false); - } + foreach (const HistoryMessage& message, messages) { + addNewMessage(message, false); + } } void HistoryViewController::reset() { - roster_->removeAll(); - contacts_.clear(); - selectedItem_ = NULL; - historyWindow_->resetConversationView(); + roster_->removeAll(); + contacts_.clear(); + selectedItem_ = NULL; + historyWindow_->resetConversationView(); } void HistoryViewController::handleCalendarClicked(const boost::gregorian::date& date) { - if (!selectedItem_) { - return; - } - - boost::gregorian::date newDate; - if (contacts_[selectedItemType_][selectedItem_->getJID()].count(date)) { - newDate = date; - } - else if (date < currentResultDate_) { - foreach(const boost::gregorian::date& current, contacts_[selectedItemType_][selectedItem_->getJID()]) { - if (current > date) { - newDate = current; - break; - } - } - } - else { - reverse_foreach(const boost::gregorian::date& current, contacts_[selectedItemType_][selectedItem_->getJID()]) { - if (current < date) { - newDate = current; - break; - } - } - } - - historyWindow_->setDate(newDate); - if (newDate == currentResultDate_) { - return; - } - currentResultDate_ = newDate; - historyWindow_->resetConversationView(); - - std::vector messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_); - historyWindow_->setDate(currentResultDate_); - - foreach (const HistoryMessage& message, messages) { - addNewMessage(message, false); - } + if (!selectedItem_) { + return; + } + + boost::gregorian::date newDate; + if (contacts_[selectedItemType_][selectedItem_->getJID()].count(date)) { + newDate = date; + } + else if (date < currentResultDate_) { + foreach(const boost::gregorian::date& current, contacts_[selectedItemType_][selectedItem_->getJID()]) { + if (current > date) { + newDate = current; + break; + } + } + } + else { + reverse_foreach(const boost::gregorian::date& current, contacts_[selectedItemType_][selectedItem_->getJID()]) { + if (current < date) { + newDate = current; + break; + } + } + } + + historyWindow_->setDate(newDate); + if (newDate == currentResultDate_) { + return; + } + currentResultDate_ = newDate; + historyWindow_->resetConversationView(); + + std::vector messages = historyController_->getMessagesFromDate(selfJID_, selectedItem_->getJID(), selectedItemType_, currentResultDate_); + historyWindow_->setDate(currentResultDate_); + + foreach (const HistoryMessage& message, messages) { + addNewMessage(message, false); + } } void HistoryViewController::handlePresenceChanged(Presence::ref presence) { - JID jid = presence->getFrom(); - - if (contacts_[HistoryMessage::Chat].count(jid.toBare())) { - roster_->applyOnItems(SetPresence(presence, JID::WithoutResource)); - return; - } - - if (contacts_[HistoryMessage::Groupchat].count(jid.toBare())) { - Presence::ref availablePresence = boost::make_shared(Presence()); - availablePresence->setFrom(jid.toBare()); - roster_->applyOnItems(SetPresence(availablePresence, JID::WithResource)); - } - - if (contacts_[HistoryMessage::PrivateMessage].count(jid)) { - roster_->applyOnItems(SetPresence(presence, JID::WithResource)); - } + JID jid = presence->getFrom(); + + if (contacts_[HistoryMessage::Chat].count(jid.toBare())) { + roster_->applyOnItems(SetPresence(presence, JID::WithoutResource)); + return; + } + + if (contacts_[HistoryMessage::Groupchat].count(jid.toBare())) { + Presence::ref availablePresence = boost::make_shared(Presence()); + availablePresence->setFrom(jid.toBare()); + roster_->applyOnItems(SetPresence(availablePresence, JID::WithResource)); + } + + if (contacts_[HistoryMessage::PrivateMessage].count(jid)) { + roster_->applyOnItems(SetPresence(presence, JID::WithResource)); + } } void HistoryViewController::handleAvatarChanged(const JID& jid) { - roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid))); + roster_->applyOnItems(SetAvatar(jid, avatarManager_->getAvatarPath(jid))); } Presence::ref HistoryViewController::getPresence(const JID& jid, bool isMUC) { - if (jid.isBare() && !isMUC) { - return presenceOracle_->getHighestPriorityPresence(jid); - } + if (jid.isBare() && !isMUC) { + return presenceOracle_->getHighestPriorityPresence(jid); + } - std::vector mucPresence = presenceOracle_->getAllPresence(jid.toBare()); + std::vector mucPresence = presenceOracle_->getAllPresence(jid.toBare()); - if (isMUC && !mucPresence.empty()) { - Presence::ref presence = boost::make_shared(Presence()); - presence->setFrom(jid); - return presence; - } + if (isMUC && !mucPresence.empty()) { + Presence::ref presence = boost::make_shared(Presence()); + presence->setFrom(jid); + return presence; + } - foreach (Presence::ref presence, mucPresence) { - if (presence.get() && presence->getFrom() == jid) { - return presence; - } - } + foreach (Presence::ref presence, mucPresence) { + if (presence.get() && presence->getFrom() == jid) { + return presence; + } + } - return Presence::create(); + return Presence::create(); } } diff --git a/Swift/Controllers/HistoryViewController.h b/Swift/Controllers/HistoryViewController.h index b388160..463ee06 100644 --- a/Swift/Controllers/HistoryViewController.h +++ b/Swift/Controllers/HistoryViewController.h @@ -25,51 +25,51 @@ #include namespace Swift { - class HistoryWindowFactory; - class HistoryWindow; - class Roster; - class RosterItem; - class ContactRosterItem; - class HistoryController; - class NickResolver; - class AvatarManager; + class HistoryWindowFactory; + class HistoryWindow; + class Roster; + class RosterItem; + class ContactRosterItem; + class HistoryController; + class NickResolver; + class AvatarManager; - class HistoryViewController { - public: - HistoryViewController(const JID& selfJID, UIEventStream* uiEventStream, HistoryController* historyController, NickResolver* nickResolver, AvatarManager* avatarManager, PresenceOracle* presenceOracle, HistoryWindowFactory* historyWindowFactory); - ~HistoryViewController(); + class HistoryViewController { + public: + HistoryViewController(const JID& selfJID, UIEventStream* uiEventStream, HistoryController* historyController, NickResolver* nickResolver, AvatarManager* avatarManager, PresenceOracle* presenceOracle, HistoryWindowFactory* historyWindowFactory); + ~HistoryViewController(); - private: - void handleUIEvent(boost::shared_ptr event); - void handleSelectedContactChanged(RosterItem* item); - void handleNewMessage(const HistoryMessage& message); - void handleReturnPressed(const std::string& keyword); - void handleScrollReachedTop(const boost::gregorian::date& date); - void handleScrollReachedBottom(const boost::gregorian::date& date); - void handlePreviousButtonClicked(); - void handleNextButtonClicked(); - void handleCalendarClicked(const boost::gregorian::date& date); - void handlePresenceChanged(Presence::ref presence); - void handleAvatarChanged(const JID& jid); + private: + void handleUIEvent(boost::shared_ptr event); + void handleSelectedContactChanged(RosterItem* item); + void handleNewMessage(const HistoryMessage& message); + void handleReturnPressed(const std::string& keyword); + void handleScrollReachedTop(const boost::gregorian::date& date); + void handleScrollReachedBottom(const boost::gregorian::date& date); + void handlePreviousButtonClicked(); + void handleNextButtonClicked(); + void handleCalendarClicked(const boost::gregorian::date& date); + void handlePresenceChanged(Presence::ref presence); + void handleAvatarChanged(const JID& jid); - void addNewMessage(const HistoryMessage& message, bool addAtTheTop); - void reset(); - Presence::ref getPresence(const JID& jid, bool isMUC); + void addNewMessage(const HistoryMessage& message, bool addAtTheTop); + void reset(); + Presence::ref getPresence(const JID& jid, bool isMUC); - private: - JID selfJID_; - UIEventStream* uiEventStream_; - HistoryController* historyController_; - NickResolver* nickResolver_; - AvatarManager* avatarManager_; - PresenceOracle* presenceOracle_; - HistoryWindowFactory* historyWindowFactory_; - HistoryWindow* historyWindow_; - Roster* roster_; + private: + JID selfJID_; + UIEventStream* uiEventStream_; + HistoryController* historyController_; + NickResolver* nickResolver_; + AvatarManager* avatarManager_; + PresenceOracle* presenceOracle_; + HistoryWindowFactory* historyWindowFactory_; + HistoryWindow* historyWindow_; + Roster* roster_; - std::map contacts_; - ContactRosterItem* selectedItem_; - HistoryMessage::Type selectedItemType_; - boost::gregorian::date currentResultDate_; - }; + std::map contacts_; + ContactRosterItem* selectedItem_; + HistoryMessage::Type selectedItemType_; + boost::gregorian::date currentResultDate_; + }; } diff --git a/Swift/Controllers/Intl.h b/Swift/Controllers/Intl.h index 386696a..c599493 100644 --- a/Swift/Controllers/Intl.h +++ b/Swift/Controllers/Intl.h @@ -8,4 +8,4 @@ #include #define QT_TRANSLATE_NOOP(context, text) \ - Swift::Translator::getInstance()->translate(text, context) + Swift::Translator::getInstance()->translate(text, context) diff --git a/Swift/Controllers/MainController.cpp b/Swift/Controllers/MainController.cpp index 9f61b2b..b48059c 100644 --- a/Swift/Controllers/MainController.cpp +++ b/Swift/Controllers/MainController.cpp @@ -99,749 +99,749 @@ static const std::string CLIENT_NODE = "http://swift.im"; MainController::MainController( - EventLoop* eventLoop, - NetworkFactories* networkFactories, - UIFactory* uiFactories, - SettingsProvider* settings, - SystemTray* systemTray, - SoundPlayer* soundPlayer, - StoragesFactory* storagesFactory, - CertificateStorageFactory* certificateStorageFactory, - Dock* dock, - Notifier* notifier, - URIHandler* uriHandler, - IdleDetector* idleDetector, - const std::map& emoticons, - bool useDelayForLatency) : - eventLoop_(eventLoop), - networkFactories_(networkFactories), - uiFactory_(uiFactories), - storagesFactory_(storagesFactory), - certificateStorageFactory_(certificateStorageFactory), - settings_(settings), - uriHandler_(uriHandler), - idleDetector_(idleDetector), - loginWindow_(NULL) , - useDelayForLatency_(useDelayForLatency), - ftOverview_(NULL), - emoticons_(emoticons) { - storages_ = NULL; - certificateStorage_ = NULL; - certificateTrustChecker_ = NULL; - statusTracker_ = NULL; - presenceNotifier_ = NULL; - eventNotifier_ = NULL; - rosterController_ = NULL; - chatsManager_ = NULL; - historyController_ = NULL; - historyViewController_ = NULL; - eventWindowController_ = NULL; - profileController_ = NULL; - blockListController_ = NULL; - showProfileController_ = NULL; - contactEditController_ = NULL; - userSearchControllerChat_ = NULL; - userSearchControllerAdd_ = NULL; - userSearchControllerInvite_ = NULL; - contactsFromRosterProvider_ = NULL; - contactSuggesterWithoutRoster_ = NULL; - contactSuggesterWithRoster_ = NULL; - whiteboardManager_ = NULL; - adHocManager_ = NULL; - quitRequested_ = false; - clientInitialized_ = false; - offlineRequested_ = false; - - timeBeforeNextReconnect_ = -1; - dock_ = dock; - uiEventStream_ = new UIEventStream(); - - notifier_ = new TogglableNotifier(notifier); - notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); - eventController_ = new EventController(); - eventController_->onEventQueueLengthChange.connect(boost::bind(&MainController::handleEventQueueLengthChange, this, _1)); - - systemTrayController_ = new SystemTrayController(eventController_, systemTray); - loginWindow_ = uiFactory_->createLoginWindow(uiEventStream_); - loginWindow_->setShowNotificationToggle(!notifier->isExternallyConfigured()); - - highlightManager_ = new HighlightManager(settings_); - highlightEditorController_ = new HighlightEditorController(uiEventStream_, uiFactory_, highlightManager_); - - soundEventController_ = new SoundEventController(eventController_, soundPlayer, settings, highlightManager_); - - xmppURIController_ = new XMPPURIController(uriHandler_, uiEventStream_); - - std::string selectedLoginJID = settings_->getSetting(SettingConstants::LAST_LOGIN_JID); - bool loginAutomatically = settings_->getSetting(SettingConstants::LOGIN_AUTOMATICALLY); - std::string cachedPassword; - std::string cachedCertificate; - ClientOptions cachedOptions; - bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); - if (!eagle) { - foreach (std::string profile, settings->getAvailableProfiles()) { - ProfileSettingsProvider profileSettings(profile, settings); - std::string password = profileSettings.getStringSetting("pass"); - std::string certificate = profileSettings.getStringSetting("certificate"); - std::string jid = profileSettings.getStringSetting("jid"); - ClientOptions clientOptions = parseClientOptions(profileSettings.getStringSetting("options")); + EventLoop* eventLoop, + NetworkFactories* networkFactories, + UIFactory* uiFactories, + SettingsProvider* settings, + SystemTray* systemTray, + SoundPlayer* soundPlayer, + StoragesFactory* storagesFactory, + CertificateStorageFactory* certificateStorageFactory, + Dock* dock, + Notifier* notifier, + URIHandler* uriHandler, + IdleDetector* idleDetector, + const std::map& emoticons, + bool useDelayForLatency) : + eventLoop_(eventLoop), + networkFactories_(networkFactories), + uiFactory_(uiFactories), + storagesFactory_(storagesFactory), + certificateStorageFactory_(certificateStorageFactory), + settings_(settings), + uriHandler_(uriHandler), + idleDetector_(idleDetector), + loginWindow_(NULL) , + useDelayForLatency_(useDelayForLatency), + ftOverview_(NULL), + emoticons_(emoticons) { + storages_ = NULL; + certificateStorage_ = NULL; + certificateTrustChecker_ = NULL; + statusTracker_ = NULL; + presenceNotifier_ = NULL; + eventNotifier_ = NULL; + rosterController_ = NULL; + chatsManager_ = NULL; + historyController_ = NULL; + historyViewController_ = NULL; + eventWindowController_ = NULL; + profileController_ = NULL; + blockListController_ = NULL; + showProfileController_ = NULL; + contactEditController_ = NULL; + userSearchControllerChat_ = NULL; + userSearchControllerAdd_ = NULL; + userSearchControllerInvite_ = NULL; + contactsFromRosterProvider_ = NULL; + contactSuggesterWithoutRoster_ = NULL; + contactSuggesterWithRoster_ = NULL; + whiteboardManager_ = NULL; + adHocManager_ = NULL; + quitRequested_ = false; + clientInitialized_ = false; + offlineRequested_ = false; + + timeBeforeNextReconnect_ = -1; + dock_ = dock; + uiEventStream_ = new UIEventStream(); + + notifier_ = new TogglableNotifier(notifier); + notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); + eventController_ = new EventController(); + eventController_->onEventQueueLengthChange.connect(boost::bind(&MainController::handleEventQueueLengthChange, this, _1)); + + systemTrayController_ = new SystemTrayController(eventController_, systemTray); + loginWindow_ = uiFactory_->createLoginWindow(uiEventStream_); + loginWindow_->setShowNotificationToggle(!notifier->isExternallyConfigured()); + + highlightManager_ = new HighlightManager(settings_); + highlightEditorController_ = new HighlightEditorController(uiEventStream_, uiFactory_, highlightManager_); + + soundEventController_ = new SoundEventController(eventController_, soundPlayer, settings, highlightManager_); + + xmppURIController_ = new XMPPURIController(uriHandler_, uiEventStream_); + + std::string selectedLoginJID = settings_->getSetting(SettingConstants::LAST_LOGIN_JID); + bool loginAutomatically = settings_->getSetting(SettingConstants::LOGIN_AUTOMATICALLY); + std::string cachedPassword; + std::string cachedCertificate; + ClientOptions cachedOptions; + bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); + if (!eagle) { + foreach (std::string profile, settings->getAvailableProfiles()) { + ProfileSettingsProvider profileSettings(profile, settings); + std::string password = profileSettings.getStringSetting("pass"); + std::string certificate = profileSettings.getStringSetting("certificate"); + std::string jid = profileSettings.getStringSetting("jid"); + ClientOptions clientOptions = parseClientOptions(profileSettings.getStringSetting("options")); #ifdef SWIFTEN_PLATFORM_WIN32 - clientOptions.singleSignOn = settings_->getSetting(SettingConstants::SINGLE_SIGN_ON); + clientOptions.singleSignOn = settings_->getSetting(SettingConstants::SINGLE_SIGN_ON); #endif - loginWindow_->addAvailableAccount(jid, password, certificate, clientOptions); - if (jid == selectedLoginJID) { - cachedPassword = password; - cachedCertificate = certificate; - cachedOptions = clientOptions; - } - } - loginWindow_->selectUser(selectedLoginJID); - loginWindow_->setLoginAutomatically(loginAutomatically); - } + loginWindow_->addAvailableAccount(jid, password, certificate, clientOptions); + if (jid == selectedLoginJID) { + cachedPassword = password; + cachedCertificate = certificate; + cachedOptions = clientOptions; + } + } + loginWindow_->selectUser(selectedLoginJID); + loginWindow_->setLoginAutomatically(loginAutomatically); + } - loginWindow_->onLoginRequest.connect(boost::bind(&MainController::handleLoginRequest, this, _1, _2, _3, _4, _5, _6, _7)); - loginWindow_->onPurgeSavedLoginRequest.connect(boost::bind(&MainController::handlePurgeSavedLoginRequest, this, _1)); - loginWindow_->onCancelLoginRequest.connect(boost::bind(&MainController::handleCancelLoginRequest, this)); - loginWindow_->onQuitRequest.connect(boost::bind(&MainController::handleQuitRequest, this)); + loginWindow_->onLoginRequest.connect(boost::bind(&MainController::handleLoginRequest, this, _1, _2, _3, _4, _5, _6, _7)); + loginWindow_->onPurgeSavedLoginRequest.connect(boost::bind(&MainController::handlePurgeSavedLoginRequest, this, _1)); + loginWindow_->onCancelLoginRequest.connect(boost::bind(&MainController::handleCancelLoginRequest, this)); + loginWindow_->onQuitRequest.connect(boost::bind(&MainController::handleQuitRequest, this)); - idleDetector_->setIdleTimeSeconds(settings->getSetting(SettingConstants::IDLE_TIMEOUT)); - idleDetector_->onIdleChanged.connect(boost::bind(&MainController::handleInputIdleChanged, this, _1)); + idleDetector_->setIdleTimeSeconds(settings->getSetting(SettingConstants::IDLE_TIMEOUT)); + idleDetector_->onIdleChanged.connect(boost::bind(&MainController::handleInputIdleChanged, this, _1)); - xmlConsoleController_ = new XMLConsoleController(uiEventStream_, uiFactory_); + xmlConsoleController_ = new XMLConsoleController(uiEventStream_, uiFactory_); - fileTransferListController_ = new FileTransferListController(uiEventStream_, uiFactory_); + fileTransferListController_ = new FileTransferListController(uiEventStream_, uiFactory_); - settings_->onSettingChanged.connect(boost::bind(&MainController::handleSettingChanged, this, _1)); + settings_->onSettingChanged.connect(boost::bind(&MainController::handleSettingChanged, this, _1)); - if (loginAutomatically) { - profileSettings_ = new ProfileSettingsProvider(selectedLoginJID, settings_); - /* FIXME: deal with autologin with a cert*/ - handleLoginRequest(selectedLoginJID, cachedPassword, cachedCertificate, CertificateWithKey::ref(), cachedOptions, true, true); - } else { - profileSettings_ = NULL; - } + if (loginAutomatically) { + profileSettings_ = new ProfileSettingsProvider(selectedLoginJID, settings_); + /* FIXME: deal with autologin with a cert*/ + handleLoginRequest(selectedLoginJID, cachedPassword, cachedCertificate, CertificateWithKey::ref(), cachedOptions, true, true); + } else { + profileSettings_ = NULL; + } } MainController::~MainController() { - idleDetector_->onIdleChanged.disconnect(boost::bind(&MainController::handleInputIdleChanged, this, _1)); - - purgeCachedCredentials(); - //setManagersOffline(); - eventController_->disconnectAll(); - - resetClient(); - delete highlightEditorController_; - delete highlightManager_; - delete fileTransferListController_; - delete xmlConsoleController_; - delete xmppURIController_; - delete soundEventController_; - delete systemTrayController_; - delete eventController_; - delete notifier_; - delete uiEventStream_; + idleDetector_->onIdleChanged.disconnect(boost::bind(&MainController::handleInputIdleChanged, this, _1)); + + purgeCachedCredentials(); + //setManagersOffline(); + eventController_->disconnectAll(); + + resetClient(); + delete highlightEditorController_; + delete highlightManager_; + delete fileTransferListController_; + delete xmlConsoleController_; + delete xmppURIController_; + delete soundEventController_; + delete systemTrayController_; + delete eventController_; + delete notifier_; + delete uiEventStream_; } void MainController::purgeCachedCredentials() { - safeClear(password_); + safeClear(password_); } void MainController::resetClient() { - purgeCachedCredentials(); - resetCurrentError(); - resetPendingReconnects(); - vCardPhotoHash_.clear(); - delete contactEditController_; - contactEditController_ = NULL; - delete profileController_; - profileController_ = NULL; - delete showProfileController_; - showProfileController_ = NULL; - delete eventWindowController_; - eventWindowController_ = NULL; - delete chatsManager_; - chatsManager_ = NULL; + purgeCachedCredentials(); + resetCurrentError(); + resetPendingReconnects(); + vCardPhotoHash_.clear(); + delete contactEditController_; + contactEditController_ = NULL; + delete profileController_; + profileController_ = NULL; + delete showProfileController_; + showProfileController_ = NULL; + delete eventWindowController_; + eventWindowController_ = NULL; + delete chatsManager_; + chatsManager_ = NULL; #ifdef SWIFT_EXPERIMENTAL_HISTORY - delete historyViewController_; - historyViewController_ = NULL; - delete historyController_; - historyController_ = NULL; + delete historyViewController_; + historyViewController_ = NULL; + delete historyController_; + historyController_ = NULL; #endif - fileTransferListController_->setFileTransferOverview(NULL); - delete ftOverview_; - ftOverview_ = NULL; - delete blockListController_; - blockListController_ = NULL; - delete rosterController_; - rosterController_ = NULL; - delete eventNotifier_; - eventNotifier_ = NULL; - delete presenceNotifier_; - presenceNotifier_ = NULL; - delete certificateTrustChecker_; - certificateTrustChecker_ = NULL; - delete certificateStorage_; - certificateStorage_ = NULL; - delete storages_; - storages_ = NULL; - delete statusTracker_; - statusTracker_ = NULL; - delete profileSettings_; - profileSettings_ = NULL; - delete userSearchControllerChat_; - userSearchControllerChat_ = NULL; - delete userSearchControllerAdd_; - userSearchControllerAdd_ = NULL; - delete userSearchControllerInvite_; - userSearchControllerInvite_ = NULL; - delete contactSuggesterWithoutRoster_; - contactSuggesterWithoutRoster_ = NULL; - delete contactSuggesterWithRoster_; - contactSuggesterWithRoster_ = NULL; - delete contactsFromRosterProvider_; - contactsFromRosterProvider_ = NULL; - delete adHocManager_; - adHocManager_ = NULL; - delete whiteboardManager_; - whiteboardManager_ = NULL; - clientInitialized_ = false; + fileTransferListController_->setFileTransferOverview(NULL); + delete ftOverview_; + ftOverview_ = NULL; + delete blockListController_; + blockListController_ = NULL; + delete rosterController_; + rosterController_ = NULL; + delete eventNotifier_; + eventNotifier_ = NULL; + delete presenceNotifier_; + presenceNotifier_ = NULL; + delete certificateTrustChecker_; + certificateTrustChecker_ = NULL; + delete certificateStorage_; + certificateStorage_ = NULL; + delete storages_; + storages_ = NULL; + delete statusTracker_; + statusTracker_ = NULL; + delete profileSettings_; + profileSettings_ = NULL; + delete userSearchControllerChat_; + userSearchControllerChat_ = NULL; + delete userSearchControllerAdd_; + userSearchControllerAdd_ = NULL; + delete userSearchControllerInvite_; + userSearchControllerInvite_ = NULL; + delete contactSuggesterWithoutRoster_; + contactSuggesterWithoutRoster_ = NULL; + delete contactSuggesterWithRoster_; + contactSuggesterWithRoster_ = NULL; + delete contactsFromRosterProvider_; + contactsFromRosterProvider_ = NULL; + delete adHocManager_; + adHocManager_ = NULL; + delete whiteboardManager_; + whiteboardManager_ = NULL; + clientInitialized_ = false; } void MainController::handleSettingChanged(const std::string& settingPath) { - if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) { - notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); - } + if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) { + notifier_->setPersistentEnabled(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); + } } void MainController::resetPendingReconnects() { - timeBeforeNextReconnect_ = -1; - if (reconnectTimer_) { - reconnectTimer_->stop(); - reconnectTimer_.reset(); - } - resetCurrentError(); + timeBeforeNextReconnect_ = -1; + if (reconnectTimer_) { + reconnectTimer_->stop(); + reconnectTimer_.reset(); + } + resetCurrentError(); } void MainController::resetCurrentError() { - if (lastDisconnectError_) { - lastDisconnectError_->conclude(); - lastDisconnectError_ = boost::shared_ptr(); - } + if (lastDisconnectError_) { + lastDisconnectError_->conclude(); + lastDisconnectError_ = boost::shared_ptr(); + } } void MainController::handleConnected() { - boundJID_ = client_->getJID(); - resetCurrentError(); - resetPendingReconnects(); - - if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { - purgeCachedCredentials(); - } - - bool freshLogin = rosterController_ == NULL; - myStatusLooksOnline_ = true; - if (freshLogin) { - profileController_ = new ProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_); - showProfileController_ = new ShowProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_); - ftOverview_ = new FileTransferOverview(client_->getFileTransferManager()); - fileTransferListController_->setFileTransferOverview(ftOverview_); - rosterController_ = new RosterController(boundJID_, client_->getRoster(), client_->getAvatarManager(), uiFactory_, client_->getNickManager(), client_->getNickResolver(), client_->getPresenceOracle(), client_->getSubscriptionManager(), eventController_, uiEventStream_, client_->getIQRouter(), settings_, client_->getEntityCapsProvider(), ftOverview_, client_->getClientBlockListManager(), client_->getVCardManager()); - rosterController_->onChangeStatusRequest.connect(boost::bind(&MainController::handleChangeStatusRequest, this, _1, _2)); - rosterController_->onSignOutRequest.connect(boost::bind(&MainController::signOut, this)); - rosterController_->getWindow()->onShowCertificateRequest.connect(boost::bind(&MainController::handleShowCertificateRequest, this)); - - blockListController_ = new BlockListController(client_->getClientBlockListManager(), uiEventStream_, uiFactory_, eventController_); - - contactEditController_ = new ContactEditController(rosterController_, client_->getVCardManager(), uiFactory_, uiEventStream_); - whiteboardManager_ = new WhiteboardManager(uiFactory_, uiEventStream_, client_->getNickResolver(), client_->getWhiteboardSessionManager()); - - /* Doing this early as an ordering fix. Various things later will - * want to have the user's nick available and this means it will - * be before they receive stanzas that need it (e.g. bookmarks).*/ - client_->getVCardManager()->requestOwnVCard(); - - contactSuggesterWithoutRoster_ = new ContactSuggester(); - contactSuggesterWithRoster_ = new ContactSuggester(); - - userSearchControllerInvite_ = new UserSearchController(UserSearchController::InviteToChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_); + boundJID_ = client_->getJID(); + resetCurrentError(); + resetPendingReconnects(); + + if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { + purgeCachedCredentials(); + } + + bool freshLogin = rosterController_ == NULL; + myStatusLooksOnline_ = true; + if (freshLogin) { + profileController_ = new ProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_); + showProfileController_ = new ShowProfileController(client_->getVCardManager(), uiFactory_, uiEventStream_); + ftOverview_ = new FileTransferOverview(client_->getFileTransferManager()); + fileTransferListController_->setFileTransferOverview(ftOverview_); + rosterController_ = new RosterController(boundJID_, client_->getRoster(), client_->getAvatarManager(), uiFactory_, client_->getNickManager(), client_->getNickResolver(), client_->getPresenceOracle(), client_->getSubscriptionManager(), eventController_, uiEventStream_, client_->getIQRouter(), settings_, client_->getEntityCapsProvider(), ftOverview_, client_->getClientBlockListManager(), client_->getVCardManager()); + rosterController_->onChangeStatusRequest.connect(boost::bind(&MainController::handleChangeStatusRequest, this, _1, _2)); + rosterController_->onSignOutRequest.connect(boost::bind(&MainController::signOut, this)); + rosterController_->getWindow()->onShowCertificateRequest.connect(boost::bind(&MainController::handleShowCertificateRequest, this)); + + blockListController_ = new BlockListController(client_->getClientBlockListManager(), uiEventStream_, uiFactory_, eventController_); + + contactEditController_ = new ContactEditController(rosterController_, client_->getVCardManager(), uiFactory_, uiEventStream_); + whiteboardManager_ = new WhiteboardManager(uiFactory_, uiEventStream_, client_->getNickResolver(), client_->getWhiteboardSessionManager()); + + /* Doing this early as an ordering fix. Various things later will + * want to have the user's nick available and this means it will + * be before they receive stanzas that need it (e.g. bookmarks).*/ + client_->getVCardManager()->requestOwnVCard(); + + contactSuggesterWithoutRoster_ = new ContactSuggester(); + contactSuggesterWithRoster_ = new ContactSuggester(); + + userSearchControllerInvite_ = new UserSearchController(UserSearchController::InviteToChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_); #ifdef SWIFT_EXPERIMENTAL_HISTORY - historyController_ = new HistoryController(storages_->getHistoryStorage()); - historyViewController_ = new HistoryViewController(jid_, uiEventStream_, historyController_, client_->getNickResolver(), client_->getAvatarManager(), client_->getPresenceOracle(), uiFactory_); - chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, historyController_, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager()); + historyController_ = new HistoryController(storages_->getHistoryStorage()); + historyViewController_ = new HistoryViewController(jid_, uiEventStream_, historyController_, client_->getNickResolver(), client_->getAvatarManager(), client_->getPresenceOracle(), uiFactory_); + chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, historyController_, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager()); #else - chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, NULL, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager()); + chatsManager_ = new ChatsManager(jid_, client_->getStanzaChannel(), client_->getIQRouter(), eventController_, uiFactory_, uiFactory_, client_->getNickResolver(), client_->getPresenceOracle(), client_->getPresenceSender(), uiEventStream_, uiFactory_, useDelayForLatency_, networkFactories_->getTimerFactory(), client_->getMUCRegistry(), client_->getEntityCapsProvider(), client_->getMUCManager(), uiFactory_, profileSettings_, ftOverview_, client_->getRoster(), !settings_->getSetting(SettingConstants::REMEMBER_RECENT_CHATS), settings_, NULL, whiteboardManager_, highlightManager_, client_->getClientBlockListManager(), emoticons_, client_->getVCardManager()); #endif - contactsFromRosterProvider_ = new ContactsFromXMPPRoster(client_->getRoster(), client_->getAvatarManager(), client_->getPresenceOracle()); - contactSuggesterWithoutRoster_->addContactProvider(chatsManager_); - contactSuggesterWithRoster_->addContactProvider(chatsManager_); - contactSuggesterWithRoster_->addContactProvider(contactsFromRosterProvider_); - highlightEditorController_->setContactSuggester(contactSuggesterWithoutRoster_); + contactsFromRosterProvider_ = new ContactsFromXMPPRoster(client_->getRoster(), client_->getAvatarManager(), client_->getPresenceOracle()); + contactSuggesterWithoutRoster_->addContactProvider(chatsManager_); + contactSuggesterWithRoster_->addContactProvider(chatsManager_); + contactSuggesterWithRoster_->addContactProvider(contactsFromRosterProvider_); + highlightEditorController_->setContactSuggester(contactSuggesterWithoutRoster_); - client_->onMessageReceived.connect(boost::bind(&ChatsManager::handleIncomingMessage, chatsManager_, _1)); - chatsManager_->setAvatarManager(client_->getAvatarManager()); + client_->onMessageReceived.connect(boost::bind(&ChatsManager::handleIncomingMessage, chatsManager_, _1)); + chatsManager_->setAvatarManager(client_->getAvatarManager()); - eventWindowController_ = new EventWindowController(eventController_, uiFactory_); + eventWindowController_ = new EventWindowController(eventController_, uiFactory_); - loginWindow_->morphInto(rosterController_->getWindow()); + loginWindow_->morphInto(rosterController_->getWindow()); - DiscoInfo discoInfo; - discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc")); - discoInfo.addFeature(DiscoInfo::ChatStatesFeature); - discoInfo.addFeature(DiscoInfo::SecurityLabelsFeature); - discoInfo.addFeature(DiscoInfo::MessageCorrectionFeature); + DiscoInfo discoInfo; + discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc")); + discoInfo.addFeature(DiscoInfo::ChatStatesFeature); + discoInfo.addFeature(DiscoInfo::SecurityLabelsFeature); + discoInfo.addFeature(DiscoInfo::MessageCorrectionFeature); #ifdef SWIFT_EXPERIMENTAL_FT - discoInfo.addFeature(DiscoInfo::JingleFeature); - discoInfo.addFeature(DiscoInfo::JingleFTFeature); - discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature); - discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature); + discoInfo.addFeature(DiscoInfo::JingleFeature); + discoInfo.addFeature(DiscoInfo::JingleFTFeature); + discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature); + discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature); #endif #ifdef SWIFT_EXPERIMENTAL_WB - discoInfo.addFeature(DiscoInfo::WhiteboardFeature); + discoInfo.addFeature(DiscoInfo::WhiteboardFeature); #endif - discoInfo.addFeature(DiscoInfo::MessageDeliveryReceiptsFeature); - client_->getDiscoManager()->setCapsNode(CLIENT_NODE); - client_->getDiscoManager()->setDiscoInfo(discoInfo); - - userSearchControllerChat_ = new UserSearchController(UserSearchController::StartChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_); - userSearchControllerAdd_ = new UserSearchController(UserSearchController::AddContact, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithoutRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_); - adHocManager_ = new AdHocManager(JID(boundJID_.getDomain()), uiFactory_, client_->getIQRouter(), uiEventStream_, rosterController_->getWindow()); - - chatsManager_->onImpromptuMUCServiceDiscovered.connect(boost::bind(&UserSearchController::setCanInitiateImpromptuMUC, userSearchControllerChat_, _1)); - } - loginWindow_->setIsLoggingIn(false); - - client_->requestRoster(); - - GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(boundJID_.getDomain()), client_->getIQRouter()); - discoInfoRequest->onResponse.connect(boost::bind(&MainController::handleServerDiscoInfoResponse, this, _1, _2)); - discoInfoRequest->send(); - - client_->getVCardManager()->requestOwnVCard(); - - rosterController_->setJID(boundJID_); - rosterController_->setEnabled(true); - rosterController_->getWindow()->setStreamEncryptionStatus(client_->isStreamEncrypted()); - profileController_->setAvailable(true); - contactEditController_->setAvailable(true); - /* Send presence later to catch all the incoming presences. */ - sendPresence(statusTracker_->getNextPresence()); - - /* Enable chats last of all, so rejoining MUCs has the right sent presence */ - assert(chatsManager_); - chatsManager_->setOnline(true); - adHocManager_->setOnline(true); + discoInfo.addFeature(DiscoInfo::MessageDeliveryReceiptsFeature); + client_->getDiscoManager()->setCapsNode(CLIENT_NODE); + client_->getDiscoManager()->setDiscoInfo(discoInfo); + + userSearchControllerChat_ = new UserSearchController(UserSearchController::StartChat, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_); + userSearchControllerAdd_ = new UserSearchController(UserSearchController::AddContact, jid_, uiEventStream_, client_->getVCardManager(), uiFactory_, client_->getIQRouter(), rosterController_, contactSuggesterWithoutRoster_, client_->getAvatarManager(), client_->getPresenceOracle(), profileSettings_); + adHocManager_ = new AdHocManager(JID(boundJID_.getDomain()), uiFactory_, client_->getIQRouter(), uiEventStream_, rosterController_->getWindow()); + + chatsManager_->onImpromptuMUCServiceDiscovered.connect(boost::bind(&UserSearchController::setCanInitiateImpromptuMUC, userSearchControllerChat_, _1)); + } + loginWindow_->setIsLoggingIn(false); + + client_->requestRoster(); + + GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(JID(boundJID_.getDomain()), client_->getIQRouter()); + discoInfoRequest->onResponse.connect(boost::bind(&MainController::handleServerDiscoInfoResponse, this, _1, _2)); + discoInfoRequest->send(); + + client_->getVCardManager()->requestOwnVCard(); + + rosterController_->setJID(boundJID_); + rosterController_->setEnabled(true); + rosterController_->getWindow()->setStreamEncryptionStatus(client_->isStreamEncrypted()); + profileController_->setAvailable(true); + contactEditController_->setAvailable(true); + /* Send presence later to catch all the incoming presences. */ + sendPresence(statusTracker_->getNextPresence()); + + /* Enable chats last of all, so rejoining MUCs has the right sent presence */ + assert(chatsManager_); + chatsManager_->setOnline(true); + adHocManager_->setOnline(true); } void MainController::handleEventQueueLengthChange(int count) { - dock_->setNumberOfPendingMessages(count); + dock_->setNumberOfPendingMessages(count); } void MainController::reconnectAfterError() { - if (reconnectTimer_) { - reconnectTimer_->stop(); - } - performLoginFromCachedCredentials(); + if (reconnectTimer_) { + reconnectTimer_->stop(); + } + performLoginFromCachedCredentials(); } void MainController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) { - boost::shared_ptr presence(new Presence()); - if (show == StatusShow::None) { - // Note: this is misleading, None doesn't mean unavailable on the wire. - presence->setType(Presence::Unavailable); - resetPendingReconnects(); - myStatusLooksOnline_ = false; - offlineRequested_ = true; - } - else { - offlineRequested_ = false; - presence->setShow(show); - } - presence->setStatus(statusText); - statusTracker_->setRequestedPresence(presence); - if (presence->getType() != Presence::Unavailable) { - profileSettings_->storeInt("lastShow", presence->getShow()); - profileSettings_->storeString("lastStatus", presence->getStatus()); - } - if (presence->getType() != Presence::Unavailable && !client_->isAvailable()) { - performLoginFromCachedCredentials(); - } else { - sendPresence(presence); - } + boost::shared_ptr presence(new Presence()); + if (show == StatusShow::None) { + // Note: this is misleading, None doesn't mean unavailable on the wire. + presence->setType(Presence::Unavailable); + resetPendingReconnects(); + myStatusLooksOnline_ = false; + offlineRequested_ = true; + } + else { + offlineRequested_ = false; + presence->setShow(show); + } + presence->setStatus(statusText); + statusTracker_->setRequestedPresence(presence); + if (presence->getType() != Presence::Unavailable) { + profileSettings_->storeInt("lastShow", presence->getShow()); + profileSettings_->storeString("lastStatus", presence->getStatus()); + } + if (presence->getType() != Presence::Unavailable && !client_->isAvailable()) { + performLoginFromCachedCredentials(); + } else { + sendPresence(presence); + } } void MainController::sendPresence(boost::shared_ptr presence) { - rosterController_->getWindow()->setMyStatusType(presence->getShow()); - rosterController_->getWindow()->setMyStatusText(presence->getStatus()); - systemTrayController_->setMyStatusType(presence->getShow()); - notifier_->setTemporarilyDisabled(presence->getShow() == StatusShow::DND); - - // Add information and send - presence->updatePayload(boost::make_shared(vCardPhotoHash_)); - client_->getPresenceSender()->sendPresence(presence); - if (presence->getType() == Presence::Unavailable) { - logout(); - } + rosterController_->getWindow()->setMyStatusType(presence->getShow()); + rosterController_->getWindow()->setMyStatusText(presence->getStatus()); + systemTrayController_->setMyStatusType(presence->getShow()); + notifier_->setTemporarilyDisabled(presence->getShow() == StatusShow::DND); + + // Add information and send + presence->updatePayload(boost::make_shared(vCardPhotoHash_)); + client_->getPresenceSender()->sendPresence(presence); + if (presence->getType() == Presence::Unavailable) { + logout(); + } } void MainController::handleInputIdleChanged(bool idle) { - if (!statusTracker_) { - //Haven't logged in yet. - return; - } - - if (settings_->getSetting(SettingConstants::IDLE_GOES_OFFLINE)) { - if (idle) { - logout(); - } - } - else { - if (idle) { - if (statusTracker_->goAutoAway(idleDetector_->getIdleTimeSeconds())) { - if (client_ && client_->isAvailable()) { - sendPresence(statusTracker_->getNextPresence()); - } - } - } else { - if (statusTracker_->goAutoUnAway()) { - if (client_ && client_->isAvailable()) { - sendPresence(statusTracker_->getNextPresence()); - } - } - } - } + if (!statusTracker_) { + //Haven't logged in yet. + return; + } + + if (settings_->getSetting(SettingConstants::IDLE_GOES_OFFLINE)) { + if (idle) { + logout(); + } + } + else { + if (idle) { + if (statusTracker_->goAutoAway(idleDetector_->getIdleTimeSeconds())) { + if (client_ && client_->isAvailable()) { + sendPresence(statusTracker_->getNextPresence()); + } + } + } else { + if (statusTracker_->goAutoUnAway()) { + if (client_ && client_->isAvailable()) { + sendPresence(statusTracker_->getNextPresence()); + } + } + } + } } void MainController::handleShowCertificateRequest() { - std::vector chain = client_->getStanzaChannel()->getPeerCertificateChain(); - rosterController_->getWindow()->openCertificateDialog(chain); + std::vector chain = client_->getStanzaChannel()->getPeerCertificateChain(); + rosterController_->getWindow()->openCertificateDialog(chain); } void MainController::handleLoginRequest(const std::string &username, const std::string &password, const std::string& certificatePath, CertificateWithKey::ref certificate, const ClientOptions& options, bool remember, bool loginAutomatically) { - jid_ = JID(username); - if (options.singleSignOn && (!jid_.isValid() || !jid_.getNode().empty())) { - loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'wonderland.lit'")); - loginWindow_->setIsLoggingIn(false); - } else if (!options.singleSignOn && (!jid_.isValid() || jid_.getNode().empty())) { - loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'alice@wonderland.lit'")); - loginWindow_->setIsLoggingIn(false); - } else { + jid_ = JID(username); + if (options.singleSignOn && (!jid_.isValid() || !jid_.getNode().empty())) { + loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'wonderland.lit'")); + loginWindow_->setIsLoggingIn(false); + } else if (!options.singleSignOn && (!jid_.isValid() || jid_.getNode().empty())) { + loginWindow_->setMessage(QT_TRANSLATE_NOOP("", "User address invalid. User address should be of the form 'alice@wonderland.lit'")); + loginWindow_->setIsLoggingIn(false); + } else { #ifdef SWIFTEN_PLATFORM_WIN32 - if (options.singleSignOn) { - std::string userName; - std::string clientName; - std::string serverName; - boost::shared_ptr errorCode = getUserNameEx(userName, clientName, serverName); - - if (!errorCode) { - /* Create JID using the Windows logon name and user provided domain name */ - jid_ = JID(clientName, username); - } - else { - loginWindow_->setMessage(str(format(QT_TRANSLATE_NOOP("", "Error obtaining Windows user name (%1%)")) % errorCode->message())); - loginWindow_->setIsLoggingIn(false); - return; - } - } + if (options.singleSignOn) { + std::string userName; + std::string clientName; + std::string serverName; + boost::shared_ptr errorCode = getUserNameEx(userName, clientName, serverName); + + if (!errorCode) { + /* Create JID using the Windows logon name and user provided domain name */ + jid_ = JID(clientName, username); + } + else { + loginWindow_->setMessage(str(format(QT_TRANSLATE_NOOP("", "Error obtaining Windows user name (%1%)")) % errorCode->message())); + loginWindow_->setIsLoggingIn(false); + return; + } + } #endif - loginWindow_->setMessage(""); - loginWindow_->setIsLoggingIn(true); - profileSettings_ = new ProfileSettingsProvider(username, settings_); - if (!settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { - profileSettings_->storeString("jid", username); - profileSettings_->storeString("certificate", certificatePath); - profileSettings_->storeString("pass", (remember || loginAutomatically) ? password : ""); - std::string optionString = serializeClientOptions(options); - profileSettings_->storeString("options", optionString); - settings_->storeSetting(SettingConstants::LAST_LOGIN_JID, username); - settings_->storeSetting(SettingConstants::LOGIN_AUTOMATICALLY, loginAutomatically); - loginWindow_->addAvailableAccount(profileSettings_->getStringSetting("jid"), profileSettings_->getStringSetting("pass"), profileSettings_->getStringSetting("certificate"), options); - } - - password_ = password; - certificate_ = certificate; - clientOptions_ = options; - performLoginFromCachedCredentials(); - } + loginWindow_->setMessage(""); + loginWindow_->setIsLoggingIn(true); + profileSettings_ = new ProfileSettingsProvider(username, settings_); + if (!settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { + profileSettings_->storeString("jid", username); + profileSettings_->storeString("certificate", certificatePath); + profileSettings_->storeString("pass", (remember || loginAutomatically) ? password : ""); + std::string optionString = serializeClientOptions(options); + profileSettings_->storeString("options", optionString); + settings_->storeSetting(SettingConstants::LAST_LOGIN_JID, username); + settings_->storeSetting(SettingConstants::LOGIN_AUTOMATICALLY, loginAutomatically); + loginWindow_->addAvailableAccount(profileSettings_->getStringSetting("jid"), profileSettings_->getStringSetting("pass"), profileSettings_->getStringSetting("certificate"), options); + } + + password_ = password; + certificate_ = certificate; + clientOptions_ = options; + performLoginFromCachedCredentials(); + } } void MainController::handlePurgeSavedLoginRequest(const std::string& username) { - settings_->removeProfile(username); - loginWindow_->removeAvailableAccount(username); + settings_->removeProfile(username); + loginWindow_->removeAvailableAccount(username); } void MainController::performLoginFromCachedCredentials() { - if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS) && password_.empty()) { - /* Then we can't try to login again. */ - return; - } - /* If we logged in with a bare JID, and we have a full bound JID, re-login with the - * bound JID to try and keep dynamically assigned resources */ - JID clientJID = jid_; - if (boundJID_.isValid() && jid_.isBare() && boundJID_.toBare() == jid_) { - clientJID = boundJID_; - } - - if (!statusTracker_) { - statusTracker_ = new StatusTracker(); - } - if (!clientInitialized_) { - storages_ = storagesFactory_->createStorages(jid_.toBare()); - certificateStorage_ = certificateStorageFactory_->createCertificateStorage(jid_.toBare()); - certificateTrustChecker_ = new CertificateStorageTrustChecker(certificateStorage_); - - client_ = boost::make_shared(clientJID, createSafeByteArray(password_.c_str()), networkFactories_, storages_); - clientInitialized_ = true; - client_->setCertificateTrustChecker(certificateTrustChecker_); - client_->onDataRead.connect(boost::bind(&XMLConsoleController::handleDataRead, xmlConsoleController_, _1)); - client_->onDataWritten.connect(boost::bind(&XMLConsoleController::handleDataWritten, xmlConsoleController_, _1)); - client_->onDisconnected.connect(boost::bind(&MainController::handleDisconnected, this, _1)); - client_->onConnected.connect(boost::bind(&MainController::handleConnected, this)); - - client_->setSoftwareVersion(CLIENT_NAME, buildVersion); - - client_->getVCardManager()->onVCardChanged.connect(boost::bind(&MainController::handleVCardReceived, this, _1, _2)); - presenceNotifier_ = new PresenceNotifier(client_->getStanzaChannel(), notifier_, client_->getMUCRegistry(), client_->getAvatarManager(), client_->getNickResolver(), client_->getPresenceOracle(), networkFactories_->getTimerFactory()); - presenceNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1)); - eventNotifier_ = new EventNotifier(eventController_, notifier_, client_->getAvatarManager(), client_->getNickResolver()); - eventNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1)); - if (certificate_) { - client_->setCertificate(certificate_); - } - boost::shared_ptr presence(new Presence()); - presence->setShow(static_cast(profileSettings_->getIntSetting("lastShow", StatusShow::Online))); - presence->setStatus(profileSettings_->getStringSetting("lastStatus")); - statusTracker_->setRequestedPresence(presence); - } else { - /* In case we're in the middle of another login, make sure they don't overlap */ - client_->disconnect(); - } - systemTrayController_->setConnecting(); - if (rosterController_) { - rosterController_->getWindow()->setConnecting(); - } - ClientOptions clientOptions = clientOptions_; - bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); - clientOptions.forgetPassword = eagle; - clientOptions.useTLS = eagle ? ClientOptions::RequireTLS : clientOptions_.useTLS; - client_->connect(clientOptions); + if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS) && password_.empty()) { + /* Then we can't try to login again. */ + return; + } + /* If we logged in with a bare JID, and we have a full bound JID, re-login with the + * bound JID to try and keep dynamically assigned resources */ + JID clientJID = jid_; + if (boundJID_.isValid() && jid_.isBare() && boundJID_.toBare() == jid_) { + clientJID = boundJID_; + } + + if (!statusTracker_) { + statusTracker_ = new StatusTracker(); + } + if (!clientInitialized_) { + storages_ = storagesFactory_->createStorages(jid_.toBare()); + certificateStorage_ = certificateStorageFactory_->createCertificateStorage(jid_.toBare()); + certificateTrustChecker_ = new CertificateStorageTrustChecker(certificateStorage_); + + client_ = boost::make_shared(clientJID, createSafeByteArray(password_.c_str()), networkFactories_, storages_); + clientInitialized_ = true; + client_->setCertificateTrustChecker(certificateTrustChecker_); + client_->onDataRead.connect(boost::bind(&XMLConsoleController::handleDataRead, xmlConsoleController_, _1)); + client_->onDataWritten.connect(boost::bind(&XMLConsoleController::handleDataWritten, xmlConsoleController_, _1)); + client_->onDisconnected.connect(boost::bind(&MainController::handleDisconnected, this, _1)); + client_->onConnected.connect(boost::bind(&MainController::handleConnected, this)); + + client_->setSoftwareVersion(CLIENT_NAME, buildVersion); + + client_->getVCardManager()->onVCardChanged.connect(boost::bind(&MainController::handleVCardReceived, this, _1, _2)); + presenceNotifier_ = new PresenceNotifier(client_->getStanzaChannel(), notifier_, client_->getMUCRegistry(), client_->getAvatarManager(), client_->getNickResolver(), client_->getPresenceOracle(), networkFactories_->getTimerFactory()); + presenceNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1)); + eventNotifier_ = new EventNotifier(eventController_, notifier_, client_->getAvatarManager(), client_->getNickResolver()); + eventNotifier_->onNotificationActivated.connect(boost::bind(&MainController::handleNotificationClicked, this, _1)); + if (certificate_) { + client_->setCertificate(certificate_); + } + boost::shared_ptr presence(new Presence()); + presence->setShow(static_cast(profileSettings_->getIntSetting("lastShow", StatusShow::Online))); + presence->setStatus(profileSettings_->getStringSetting("lastStatus")); + statusTracker_->setRequestedPresence(presence); + } else { + /* In case we're in the middle of another login, make sure they don't overlap */ + client_->disconnect(); + } + systemTrayController_->setConnecting(); + if (rosterController_) { + rosterController_->getWindow()->setConnecting(); + } + ClientOptions clientOptions = clientOptions_; + bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); + clientOptions.forgetPassword = eagle; + clientOptions.useTLS = eagle ? ClientOptions::RequireTLS : clientOptions_.useTLS; + client_->connect(clientOptions); } void MainController::handleDisconnected(const boost::optional& error) { - if (rosterController_) { - rosterController_->getWindow()->setStreamEncryptionStatus(false); - } - if (adHocManager_) { - adHocManager_->setOnline(false); - } - if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { - purgeCachedCredentials(); - } - if (quitRequested_) { - resetClient(); - loginWindow_->quit(); - } - else if (error) { - std::string message; - std::string certificateErrorMessage; - bool forceSignout = false; - switch(error->getType()) { - case ClientError::UnknownError: message = QT_TRANSLATE_NOOP("", "Unknown Error"); break; - case ClientError::DomainNameResolveError: message = QT_TRANSLATE_NOOP("", "Unable to find server"); break; - case ClientError::ConnectionError: message = QT_TRANSLATE_NOOP("", "Error connecting to server"); break; - case ClientError::ConnectionReadError: message = QT_TRANSLATE_NOOP("", "Error while receiving server data"); break; - case ClientError::ConnectionWriteError: message = QT_TRANSLATE_NOOP("", "Error while sending data to the server"); break; - case ClientError::XMLError: message = QT_TRANSLATE_NOOP("", "Error parsing server data"); break; - case ClientError::AuthenticationFailedError: message = QT_TRANSLATE_NOOP("", "Login/password invalid"); break; - case ClientError::CompressionFailedError: message = QT_TRANSLATE_NOOP("", "Error while compressing stream"); break; - case ClientError::ServerVerificationFailedError: message = QT_TRANSLATE_NOOP("", "Server verification failed"); break; - case ClientError::NoSupportedAuthMechanismsError: message = QT_TRANSLATE_NOOP("", "Authentication mechanisms not supported"); break; - case ClientError::UnexpectedElementError: message = QT_TRANSLATE_NOOP("", "Unexpected response"); break; - case ClientError::ResourceBindError: message = QT_TRANSLATE_NOOP("", "Error binding resource"); break; - case ClientError::SessionStartError: message = QT_TRANSLATE_NOOP("", "Error starting session"); break; - case ClientError::StreamError: message = QT_TRANSLATE_NOOP("", "Stream error"); break; - case ClientError::TLSError: message = QT_TRANSLATE_NOOP("", "Encryption error"); break; - case ClientError::ClientCertificateLoadError: message = QT_TRANSLATE_NOOP("", "Error loading certificate (Invalid file or password?)"); break; - case ClientError::ClientCertificateError: message = QT_TRANSLATE_NOOP("", "Certificate not authorized"); break; - case ClientError::CertificateCardRemoved: message = QT_TRANSLATE_NOOP("", "Certificate card removed"); forceSignout = true; break; - - case ClientError::UnknownCertificateError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unknown certificate"); break; - case ClientError::CertificateExpiredError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has expired"); break; - case ClientError::CertificateNotYetValidError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not yet valid"); break; - case ClientError::CertificateSelfSignedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is self-signed"); break; - case ClientError::CertificateRejectedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been rejected"); break; - case ClientError::CertificateUntrustedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not trusted"); break; - case ClientError::InvalidCertificatePurposeError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate cannot be used for encrypting your connection"); break; - case ClientError::CertificatePathLengthExceededError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate path length constraint exceeded"); break; - case ClientError::InvalidCertificateSignatureError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid certificate signature"); break; - case ClientError::InvalidCAError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid Certificate Authority"); break; - case ClientError::InvalidServerIdentityError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate does not match the host identity"); break; - case ClientError::RevokedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been revoked"); break; - case ClientError::RevocationCheckFailedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unable to determine certificate revocation state"); break; - } - bool forceReconnectAfterCertificateTrust = false; - if (!certificateErrorMessage.empty()) { - std::vector certificates = certificateTrustChecker_->getLastCertificateChain(); - if (!certificates.empty() && loginWindow_->askUserToTrustCertificatePermanently(certificateErrorMessage, certificates)) { - certificateStorage_->addCertificate(certificates[0]); - forceReconnectAfterCertificateTrust = true; - } - else { - message = QT_TRANSLATE_NOOP("", "Certificate error"); - } - } - - if (!message.empty() && error->getErrorCode()) { - message = str(format(QT_TRANSLATE_NOOP("", "%1% (%2%)")) % message % error->getErrorCode()->message()); - } - - if (forceReconnectAfterCertificateTrust && settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { - forceReconnectAfterCertificateTrust = false; - forceSignout = true; - message = QT_TRANSLATE_NOOP("", "Re-enter credentials and retry"); - } - - if (forceReconnectAfterCertificateTrust) { - performLoginFromCachedCredentials(); - } - else if (forceSignout || !rosterController_) { //hasn't been logged in yet or permanent error - signOut(); - loginWindow_->setMessage(message); - loginWindow_->setIsLoggingIn(false); - } else { - logout(); - if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { - message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%. To reconnect, Sign Out and provide your password again.")) % jid_.getDomain() % message); - } else { - if (!offlineRequested_) { - setReconnectTimer(); - } - if (lastDisconnectError_) { - message = str(format(QT_TRANSLATE_NOOP("", "Reconnect to %1% failed: %2%. Will retry in %3% seconds.")) % jid_.getDomain() % message % boost::lexical_cast(timeBeforeNextReconnect_)); - lastDisconnectError_->conclude(); - } else { - message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%.")) % jid_.getDomain() % message); - } - lastDisconnectError_ = boost::make_shared(JID(jid_.getDomain()), message); - eventController_->handleIncomingEvent(lastDisconnectError_); - } - } - } - else if (!rosterController_) { //hasn't been logged in yet - loginWindow_->setIsLoggingIn(false); - } + if (rosterController_) { + rosterController_->getWindow()->setStreamEncryptionStatus(false); + } + if (adHocManager_) { + adHocManager_->setOnline(false); + } + if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { + purgeCachedCredentials(); + } + if (quitRequested_) { + resetClient(); + loginWindow_->quit(); + } + else if (error) { + std::string message; + std::string certificateErrorMessage; + bool forceSignout = false; + switch(error->getType()) { + case ClientError::UnknownError: message = QT_TRANSLATE_NOOP("", "Unknown Error"); break; + case ClientError::DomainNameResolveError: message = QT_TRANSLATE_NOOP("", "Unable to find server"); break; + case ClientError::ConnectionError: message = QT_TRANSLATE_NOOP("", "Error connecting to server"); break; + case ClientError::ConnectionReadError: message = QT_TRANSLATE_NOOP("", "Error while receiving server data"); break; + case ClientError::ConnectionWriteError: message = QT_TRANSLATE_NOOP("", "Error while sending data to the server"); break; + case ClientError::XMLError: message = QT_TRANSLATE_NOOP("", "Error parsing server data"); break; + case ClientError::AuthenticationFailedError: message = QT_TRANSLATE_NOOP("", "Login/password invalid"); break; + case ClientError::CompressionFailedError: message = QT_TRANSLATE_NOOP("", "Error while compressing stream"); break; + case ClientError::ServerVerificationFailedError: message = QT_TRANSLATE_NOOP("", "Server verification failed"); break; + case ClientError::NoSupportedAuthMechanismsError: message = QT_TRANSLATE_NOOP("", "Authentication mechanisms not supported"); break; + case ClientError::UnexpectedElementError: message = QT_TRANSLATE_NOOP("", "Unexpected response"); break; + case ClientError::ResourceBindError: message = QT_TRANSLATE_NOOP("", "Error binding resource"); break; + case ClientError::SessionStartError: message = QT_TRANSLATE_NOOP("", "Error starting session"); break; + case ClientError::StreamError: message = QT_TRANSLATE_NOOP("", "Stream error"); break; + case ClientError::TLSError: message = QT_TRANSLATE_NOOP("", "Encryption error"); break; + case ClientError::ClientCertificateLoadError: message = QT_TRANSLATE_NOOP("", "Error loading certificate (Invalid file or password?)"); break; + case ClientError::ClientCertificateError: message = QT_TRANSLATE_NOOP("", "Certificate not authorized"); break; + case ClientError::CertificateCardRemoved: message = QT_TRANSLATE_NOOP("", "Certificate card removed"); forceSignout = true; break; + + case ClientError::UnknownCertificateError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unknown certificate"); break; + case ClientError::CertificateExpiredError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has expired"); break; + case ClientError::CertificateNotYetValidError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not yet valid"); break; + case ClientError::CertificateSelfSignedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is self-signed"); break; + case ClientError::CertificateRejectedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been rejected"); break; + case ClientError::CertificateUntrustedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate is not trusted"); break; + case ClientError::InvalidCertificatePurposeError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate cannot be used for encrypting your connection"); break; + case ClientError::CertificatePathLengthExceededError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate path length constraint exceeded"); break; + case ClientError::InvalidCertificateSignatureError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid certificate signature"); break; + case ClientError::InvalidCAError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Invalid Certificate Authority"); break; + case ClientError::InvalidServerIdentityError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate does not match the host identity"); break; + case ClientError::RevokedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate has been revoked"); break; + case ClientError::RevocationCheckFailedError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Unable to determine certificate revocation state"); break; + } + bool forceReconnectAfterCertificateTrust = false; + if (!certificateErrorMessage.empty()) { + std::vector certificates = certificateTrustChecker_->getLastCertificateChain(); + if (!certificates.empty() && loginWindow_->askUserToTrustCertificatePermanently(certificateErrorMessage, certificates)) { + certificateStorage_->addCertificate(certificates[0]); + forceReconnectAfterCertificateTrust = true; + } + else { + message = QT_TRANSLATE_NOOP("", "Certificate error"); + } + } + + if (!message.empty() && error->getErrorCode()) { + message = str(format(QT_TRANSLATE_NOOP("", "%1% (%2%)")) % message % error->getErrorCode()->message()); + } + + if (forceReconnectAfterCertificateTrust && settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { + forceReconnectAfterCertificateTrust = false; + forceSignout = true; + message = QT_TRANSLATE_NOOP("", "Re-enter credentials and retry"); + } + + if (forceReconnectAfterCertificateTrust) { + performLoginFromCachedCredentials(); + } + else if (forceSignout || !rosterController_) { //hasn't been logged in yet or permanent error + signOut(); + loginWindow_->setMessage(message); + loginWindow_->setIsLoggingIn(false); + } else { + logout(); + if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { + message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%. To reconnect, Sign Out and provide your password again.")) % jid_.getDomain() % message); + } else { + if (!offlineRequested_) { + setReconnectTimer(); + } + if (lastDisconnectError_) { + message = str(format(QT_TRANSLATE_NOOP("", "Reconnect to %1% failed: %2%. Will retry in %3% seconds.")) % jid_.getDomain() % message % boost::lexical_cast(timeBeforeNextReconnect_)); + lastDisconnectError_->conclude(); + } else { + message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%.")) % jid_.getDomain() % message); + } + lastDisconnectError_ = boost::make_shared(JID(jid_.getDomain()), message); + eventController_->handleIncomingEvent(lastDisconnectError_); + } + } + } + else if (!rosterController_) { //hasn't been logged in yet + loginWindow_->setIsLoggingIn(false); + } } void MainController::setReconnectTimer() { - if (timeBeforeNextReconnect_ < 0) { - timeBeforeNextReconnect_ = 1; - } else { - timeBeforeNextReconnect_ = timeBeforeNextReconnect_ >= 150 ? 300 : timeBeforeNextReconnect_ * 2; // Randomly selected by roll of a die, as required by 3920bis - } - if (reconnectTimer_) { - reconnectTimer_->stop(); - } - reconnectTimer_ = networkFactories_->getTimerFactory()->createTimer(timeBeforeNextReconnect_ * 1000); - reconnectTimer_->onTick.connect(boost::bind(&MainController::reconnectAfterError, this)); - reconnectTimer_->start(); + if (timeBeforeNextReconnect_ < 0) { + timeBeforeNextReconnect_ = 1; + } else { + timeBeforeNextReconnect_ = timeBeforeNextReconnect_ >= 150 ? 300 : timeBeforeNextReconnect_ * 2; // Randomly selected by roll of a die, as required by 3920bis + } + if (reconnectTimer_) { + reconnectTimer_->stop(); + } + reconnectTimer_ = networkFactories_->getTimerFactory()->createTimer(timeBeforeNextReconnect_ * 1000); + reconnectTimer_->onTick.connect(boost::bind(&MainController::reconnectAfterError, this)); + reconnectTimer_->start(); } void MainController::handleCancelLoginRequest() { - signOut(); + signOut(); } void MainController::signOut() { - if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { - purgeCachedCredentials(); - } - eventController_->clear(); - logout(); - loginWindow_->loggedOut(); - resetClient(); + if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { + purgeCachedCredentials(); + } + eventController_->clear(); + logout(); + loginWindow_->loggedOut(); + resetClient(); } void MainController::logout() { - if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { - purgeCachedCredentials(); - } - systemTrayController_->setMyStatusType(StatusShow::None); - if (clientInitialized_ /*&& client_->isAvailable()*/) { - client_->disconnect(); - } - if (rosterController_ && myStatusLooksOnline_) { - rosterController_->getWindow()->setMyStatusType(StatusShow::None); - rosterController_->getWindow()->setMyStatusText(""); - myStatusLooksOnline_ = false; - } - setManagersOffline(); + if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { + purgeCachedCredentials(); + } + systemTrayController_->setMyStatusType(StatusShow::None); + if (clientInitialized_ /*&& client_->isAvailable()*/) { + client_->disconnect(); + } + if (rosterController_ && myStatusLooksOnline_) { + rosterController_->getWindow()->setMyStatusType(StatusShow::None); + rosterController_->getWindow()->setMyStatusText(""); + myStatusLooksOnline_ = false; + } + setManagersOffline(); } void MainController::setManagersOffline() { - if (chatsManager_) { - chatsManager_->setOnline(false); - } - if (rosterController_) { - rosterController_->setEnabled(false); - } - if (profileController_) { - profileController_->setAvailable(false); - } - if (contactEditController_) { - contactEditController_->setAvailable(false); - } + if (chatsManager_) { + chatsManager_->setOnline(false); + } + if (rosterController_) { + rosterController_->setEnabled(false); + } + if (profileController_) { + profileController_->setAvailable(false); + } + if (contactEditController_) { + contactEditController_->setAvailable(false); + } } void MainController::handleServerDiscoInfoResponse(boost::shared_ptr info, ErrorPayload::ref error) { - if (!error) { - chatsManager_->setServerDiscoInfo(info); - adHocManager_->setServerDiscoInfo(info); - if (info->hasFeature(DiscoInfo::BlockingCommandFeature)) { - rosterController_->getWindow()->setBlockingCommandAvailable(true); - rosterController_->initBlockingCommand(); - } - } + if (!error) { + chatsManager_->setServerDiscoInfo(info); + adHocManager_->setServerDiscoInfo(info); + if (info->hasFeature(DiscoInfo::BlockingCommandFeature)) { + rosterController_->getWindow()->setBlockingCommandAvailable(true); + rosterController_->initBlockingCommand(); + } + } } void MainController::handleVCardReceived(const JID& jid, VCard::ref vCard) { - if (!jid.equals(jid_, JID::WithoutResource) || !vCard) { - return; - } - std::string hash; - if (!vCard->getPhoto().empty()) { - hash = Hexify::hexify(networkFactories_->getCryptoProvider()->getSHA1Hash(vCard->getPhoto())); - } - if (hash != vCardPhotoHash_) { - vCardPhotoHash_ = hash; - if (client_ && client_->isAvailable()) { - sendPresence(statusTracker_->getNextPresence()); - } - } + if (!jid.equals(jid_, JID::WithoutResource) || !vCard) { + return; + } + std::string hash; + if (!vCard->getPhoto().empty()) { + hash = Hexify::hexify(networkFactories_->getCryptoProvider()->getSHA1Hash(vCard->getPhoto())); + } + if (hash != vCardPhotoHash_) { + vCardPhotoHash_ = hash; + if (client_ && client_->isAvailable()) { + sendPresence(statusTracker_->getNextPresence()); + } + } } void MainController::handleNotificationClicked(const JID& jid) { - assert(chatsManager_); - if (clientInitialized_) { - if (client_->getMUCRegistry()->isMUC(jid)) { - uiEventStream_->send(boost::make_shared(jid)); - } - else { - uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(jid))); - } - } + assert(chatsManager_); + if (clientInitialized_) { + if (client_->getMUCRegistry()->isMUC(jid)) { + uiEventStream_->send(boost::make_shared(jid)); + } + else { + uiEventStream_->send(boost::shared_ptr(new RequestChatUIEvent(jid))); + } + } } void MainController::handleQuitRequest() { - if (client_ && client_->isActive()) { - quitRequested_ = true; - client_->disconnect(); - } - else { - resetClient(); - loginWindow_->quit(); - } + if (client_ && client_->isActive()) { + quitRequested_ = true; + client_->disconnect(); + } + else { + resetClient(); + loginWindow_->quit(); + } } #define SERIALIZE_BOOL(option) result += options.option ? "1" : "0"; result += ","; @@ -851,34 +851,34 @@ void MainController::handleQuitRequest() { #define SERIALIZE_URL(option) SERIALIZE_STRING(option.toString()) std::string MainController::serializeClientOptions(const ClientOptions& options) { - std::string result; - SERIALIZE_BOOL(useStreamCompression); - switch (options.useTLS) { - case ClientOptions::NeverUseTLS: result += "1";break; - case ClientOptions::UseTLSWhenAvailable: result += "2";break; - case ClientOptions::RequireTLS: result += "3";break; - } - result += ","; - SERIALIZE_BOOL(allowPLAINWithoutTLS); - SERIALIZE_BOOL(useStreamResumption); - SERIALIZE_BOOL(useAcks); - SERIALIZE_STRING(manualHostname); - SERIALIZE_INT(manualPort); - switch (options.proxyType) { - case ClientOptions::NoProxy: result += "1";break; - case ClientOptions::SystemConfiguredProxy: result += "2";break; - case ClientOptions::SOCKS5Proxy: result += "3";break; - case ClientOptions::HTTPConnectProxy: result += "4";break; - } - result += ","; - SERIALIZE_STRING(manualProxyHostname); - SERIALIZE_INT(manualProxyPort); - SERIALIZE_URL(boshURL); - SERIALIZE_URL(boshHTTPConnectProxyURL); - SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthID); - SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthPassword); - SERIALIZE_BOOL(tlsOptions.schannelTLS1_0Workaround); - return result; + std::string result; + SERIALIZE_BOOL(useStreamCompression); + switch (options.useTLS) { + case ClientOptions::NeverUseTLS: result += "1";break; + case ClientOptions::UseTLSWhenAvailable: result += "2";break; + case ClientOptions::RequireTLS: result += "3";break; + } + result += ","; + SERIALIZE_BOOL(allowPLAINWithoutTLS); + SERIALIZE_BOOL(useStreamResumption); + SERIALIZE_BOOL(useAcks); + SERIALIZE_STRING(manualHostname); + SERIALIZE_INT(manualPort); + switch (options.proxyType) { + case ClientOptions::NoProxy: result += "1";break; + case ClientOptions::SystemConfiguredProxy: result += "2";break; + case ClientOptions::SOCKS5Proxy: result += "3";break; + case ClientOptions::HTTPConnectProxy: result += "4";break; + } + result += ","; + SERIALIZE_STRING(manualProxyHostname); + SERIALIZE_INT(manualProxyPort); + SERIALIZE_URL(boshURL); + SERIALIZE_URL(boshHTTPConnectProxyURL); + SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthID); + SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthPassword); + SERIALIZE_BOOL(tlsOptions.schannelTLS1_0Workaround); + return result; } #define CHECK_PARSE_LENGTH if (i >= segments.size()) {return result;} @@ -893,41 +893,41 @@ std::string MainController::serializeClientOptions(const ClientOptions& options) ClientOptions MainController::parseClientOptions(const std::string& optionString) { - ClientOptions result; - size_t i = 0; - int intVal = 0; - std::string stringVal; - std::vector segments = String::split(optionString, ','); - - PARSE_BOOL(useStreamCompression, 1); - PARSE_INT_RAW(-1); - switch (intVal) { - case 1: result.useTLS = ClientOptions::NeverUseTLS;break; - case 2: result.useTLS = ClientOptions::UseTLSWhenAvailable;break; - case 3: result.useTLS = ClientOptions::RequireTLS;break; - default:; - } - PARSE_BOOL(allowPLAINWithoutTLS, 0); - PARSE_BOOL(useStreamResumption, 0); - PARSE_BOOL(useAcks, 1); - PARSE_STRING(manualHostname); - PARSE_INT(manualPort, -1); - PARSE_INT_RAW(-1); - switch (intVal) { - case 1: result.proxyType = ClientOptions::NoProxy;break; - case 2: result.proxyType = ClientOptions::SystemConfiguredProxy;break; - case 3: result.proxyType = ClientOptions::SOCKS5Proxy;break; - case 4: result.proxyType = ClientOptions::HTTPConnectProxy;break; - } - PARSE_STRING(manualProxyHostname); - PARSE_INT(manualProxyPort, -1); - PARSE_URL(boshURL); - PARSE_URL(boshHTTPConnectProxyURL); - PARSE_SAFE_STRING(boshHTTPConnectProxyAuthID); - PARSE_SAFE_STRING(boshHTTPConnectProxyAuthPassword); - PARSE_BOOL(tlsOptions.schannelTLS1_0Workaround, false); - - return result; + ClientOptions result; + size_t i = 0; + int intVal = 0; + std::string stringVal; + std::vector segments = String::split(optionString, ','); + + PARSE_BOOL(useStreamCompression, 1); + PARSE_INT_RAW(-1); + switch (intVal) { + case 1: result.useTLS = ClientOptions::NeverUseTLS;break; + case 2: result.useTLS = ClientOptions::UseTLSWhenAvailable;break; + case 3: result.useTLS = ClientOptions::RequireTLS;break; + default:; + } + PARSE_BOOL(allowPLAINWithoutTLS, 0); + PARSE_BOOL(useStreamResumption, 0); + PARSE_BOOL(useAcks, 1); + PARSE_STRING(manualHostname); + PARSE_INT(manualPort, -1); + PARSE_INT_RAW(-1); + switch (intVal) { + case 1: result.proxyType = ClientOptions::NoProxy;break; + case 2: result.proxyType = ClientOptions::SystemConfiguredProxy;break; + case 3: result.proxyType = ClientOptions::SOCKS5Proxy;break; + case 4: result.proxyType = ClientOptions::HTTPConnectProxy;break; + } + PARSE_STRING(manualProxyHostname); + PARSE_INT(manualProxyPort, -1); + PARSE_URL(boshURL); + PARSE_URL(boshHTTPConnectProxyURL); + PARSE_SAFE_STRING(boshHTTPConnectProxyAuthID); + PARSE_SAFE_STRING(boshHTTPConnectProxyAuthPassword); + PARSE_BOOL(tlsOptions.schannelTLS1_0Workaround, false); + + return result; } } diff --git a/Swift/Controllers/MainController.h b/Swift/Controllers/MainController.h index e8a915e..ed7765a 100644 --- a/Swift/Controllers/MainController.h +++ b/Swift/Controllers/MainController.h @@ -29,171 +29,171 @@ #include namespace Swift { - class IdleDetector; - class UIFactory; - class EventLoop; - class Client; - class ChatController; - class ChatsManager; - class CertificateStorageFactory; - class CertificateStorage; - class CertificateStorageTrustChecker; - class EventController; - class MainWindow; - class RosterController; - class LoginWindow; - class EventLoop; - class MUCController; - class Notifier; - class ProfileController; - class ShowProfileController; - class ContactEditController; - class TogglableNotifier; - class PresenceNotifier; - class EventNotifier; - class SystemTray; - class SystemTrayController; - class SoundEventController; - class SoundPlayer; - class XMLConsoleController; - class HistoryViewController; - class HistoryController; - class FileTransferListController; - class UIEventStream; - class EventWindowFactory; - class EventWindowController; - class MUCSearchController; - class UserSearchController; - class StatusTracker; - class Dock; - class Storages; - class StoragesFactory; - class NetworkFactories; - class URIHandler; - class XMPPURIController; - class AdHocManager; - class AdHocCommandWindowFactory; - class FileTransferOverview; - class WhiteboardManager; - class HighlightManager; - class HighlightEditorController; - class BlockListController; - class ContactSuggester; - class ContactsFromXMPPRoster; + class IdleDetector; + class UIFactory; + class EventLoop; + class Client; + class ChatController; + class ChatsManager; + class CertificateStorageFactory; + class CertificateStorage; + class CertificateStorageTrustChecker; + class EventController; + class MainWindow; + class RosterController; + class LoginWindow; + class EventLoop; + class MUCController; + class Notifier; + class ProfileController; + class ShowProfileController; + class ContactEditController; + class TogglableNotifier; + class PresenceNotifier; + class EventNotifier; + class SystemTray; + class SystemTrayController; + class SoundEventController; + class SoundPlayer; + class XMLConsoleController; + class HistoryViewController; + class HistoryController; + class FileTransferListController; + class UIEventStream; + class EventWindowFactory; + class EventWindowController; + class MUCSearchController; + class UserSearchController; + class StatusTracker; + class Dock; + class Storages; + class StoragesFactory; + class NetworkFactories; + class URIHandler; + class XMPPURIController; + class AdHocManager; + class AdHocCommandWindowFactory; + class FileTransferOverview; + class WhiteboardManager; + class HighlightManager; + class HighlightEditorController; + class BlockListController; + class ContactSuggester; + class ContactsFromXMPPRoster; - class MainController { - public: - MainController( - EventLoop* eventLoop, - NetworkFactories* networkFactories, - UIFactory* uiFactories, - SettingsProvider *settings, - SystemTray* systemTray, - SoundPlayer* soundPlayer, - StoragesFactory* storagesFactory, - CertificateStorageFactory* certificateStorageFactory, - Dock* dock, - Notifier* notifier, - URIHandler* uriHandler, - IdleDetector* idleDetector, - const std::map& emoticons, - bool useDelayForLatency); - ~MainController(); + class MainController { + public: + MainController( + EventLoop* eventLoop, + NetworkFactories* networkFactories, + UIFactory* uiFactories, + SettingsProvider *settings, + SystemTray* systemTray, + SoundPlayer* soundPlayer, + StoragesFactory* storagesFactory, + CertificateStorageFactory* certificateStorageFactory, + Dock* dock, + Notifier* notifier, + URIHandler* uriHandler, + IdleDetector* idleDetector, + const std::map& emoticons, + bool useDelayForLatency); + ~MainController(); - private: - void resetClient(); - void handleConnected(); - void handleLoginRequest(const std::string& username, const std::string& password, const std::string& certificatePath, CertificateWithKey::ref certificate, const ClientOptions& options, bool remember, bool loginAutomatically); - void handleCancelLoginRequest(); - void handleQuitRequest(); - void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText); - void handleDisconnected(const boost::optional& error); - void handleServerDiscoInfoResponse(boost::shared_ptr, ErrorPayload::ref); - void handleEventQueueLengthChange(int count); - void handleVCardReceived(const JID& j, VCard::ref vCard); - void handleSettingChanged(const std::string& settingPath); - void handlePurgeSavedLoginRequest(const std::string& username); - void sendPresence(boost::shared_ptr presence); - void handleInputIdleChanged(bool); - void handleShowCertificateRequest(); - void logout(); - void signOut(); - void setReconnectTimer(); - void resetPendingReconnects(); - void resetCurrentError(); - - void performLoginFromCachedCredentials(); - void reconnectAfterError(); - void setManagersOffline(); - void handleNotificationClicked(const JID& jid); - void handleForceQuit(); - void purgeCachedCredentials(); - std::string serializeClientOptions(const ClientOptions& options); - ClientOptions parseClientOptions(const std::string& optionString); + private: + void resetClient(); + void handleConnected(); + void handleLoginRequest(const std::string& username, const std::string& password, const std::string& certificatePath, CertificateWithKey::ref certificate, const ClientOptions& options, bool remember, bool loginAutomatically); + void handleCancelLoginRequest(); + void handleQuitRequest(); + void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText); + void handleDisconnected(const boost::optional& error); + void handleServerDiscoInfoResponse(boost::shared_ptr, ErrorPayload::ref); + void handleEventQueueLengthChange(int count); + void handleVCardReceived(const JID& j, VCard::ref vCard); + void handleSettingChanged(const std::string& settingPath); + void handlePurgeSavedLoginRequest(const std::string& username); + void sendPresence(boost::shared_ptr presence); + void handleInputIdleChanged(bool); + void handleShowCertificateRequest(); + void logout(); + void signOut(); + void setReconnectTimer(); + void resetPendingReconnects(); + void resetCurrentError(); - private: - EventLoop* eventLoop_; - NetworkFactories* networkFactories_; - UIFactory* uiFactory_; - StoragesFactory* storagesFactory_; - Storages* storages_; - CertificateStorageFactory* certificateStorageFactory_; - CertificateStorage* certificateStorage_; - CertificateStorageTrustChecker* certificateTrustChecker_; - bool clientInitialized_; - boost::shared_ptr client_; - SettingsProvider *settings_; - ProfileSettingsProvider* profileSettings_; - Dock* dock_; - URIHandler* uriHandler_; - IdleDetector* idleDetector_; - TogglableNotifier* notifier_; - PresenceNotifier* presenceNotifier_; - EventNotifier* eventNotifier_; - RosterController* rosterController_; - EventController* eventController_; - EventWindowController* eventWindowController_; - AdHocManager* adHocManager_; - LoginWindow* loginWindow_; - UIEventStream* uiEventStream_; - XMLConsoleController* xmlConsoleController_; - HistoryViewController* historyViewController_; - HistoryController* historyController_; - FileTransferListController* fileTransferListController_; - BlockListController* blockListController_; - ChatsManager* chatsManager_; - ProfileController* profileController_; - ShowProfileController* showProfileController_; - ContactEditController* contactEditController_; - ContactsFromXMPPRoster* contactsFromRosterProvider_; - ContactSuggester* contactSuggesterWithoutRoster_; - ContactSuggester* contactSuggesterWithRoster_; - JID jid_; - JID boundJID_; - SystemTrayController* systemTrayController_; - SoundEventController* soundEventController_; - XMPPURIController* xmppURIController_; - std::string vCardPhotoHash_; - std::string password_; - CertificateWithKey::ref certificate_; - ClientOptions clientOptions_; - boost::shared_ptr lastDisconnectError_; - bool useDelayForLatency_; - UserSearchController* userSearchControllerChat_; - UserSearchController* userSearchControllerAdd_; - UserSearchController* userSearchControllerInvite_; - int timeBeforeNextReconnect_; - Timer::ref reconnectTimer_; - StatusTracker* statusTracker_; - bool myStatusLooksOnline_; - bool quitRequested_; - bool offlineRequested_; - static const int SecondsToWaitBeforeForceQuitting; - FileTransferOverview* ftOverview_; - WhiteboardManager* whiteboardManager_; - HighlightManager* highlightManager_; - HighlightEditorController* highlightEditorController_; - std::map emoticons_; - }; + void performLoginFromCachedCredentials(); + void reconnectAfterError(); + void setManagersOffline(); + void handleNotificationClicked(const JID& jid); + void handleForceQuit(); + void purgeCachedCredentials(); + std::string serializeClientOptions(const ClientOptions& options); + ClientOptions parseClientOptions(const std::string& optionString); + + private: + EventLoop* eventLoop_; + NetworkFactories* networkFactories_; + UIFactory* uiFactory_; + StoragesFactory* storagesFactory_; + Storages* storages_; + CertificateStorageFactory* certificateStorageFactory_; + CertificateStorage* certificateStorage_; + CertificateStorageTrustChecker* certificateTrustChecker_; + bool clientInitialized_; + boost::shared_ptr client_; + SettingsProvider *settings_; + ProfileSettingsProvider* profileSettings_; + Dock* dock_; + URIHandler* uriHandler_; + IdleDetector* idleDetector_; + TogglableNotifier* notifier_; + PresenceNotifier* presenceNotifier_; + EventNotifier* eventNotifier_; + RosterController* rosterController_; + EventController* eventController_; + EventWindowController* eventWindowController_; + AdHocManager* adHocManager_; + LoginWindow* loginWindow_; + UIEventStream* uiEventStream_; + XMLConsoleController* xmlConsoleController_; + HistoryViewController* historyViewController_; + HistoryController* historyController_; + FileTransferListController* fileTransferListController_; + BlockListController* blockListController_; + ChatsManager* chatsManager_; + ProfileController* profileController_; + ShowProfileController* showProfileController_; + ContactEditController* contactEditController_; + ContactsFromXMPPRoster* contactsFromRosterProvider_; + ContactSuggester* contactSuggesterWithoutRoster_; + ContactSuggester* contactSuggesterWithRoster_; + JID jid_; + JID boundJID_; + SystemTrayController* systemTrayController_; + SoundEventController* soundEventController_; + XMPPURIController* xmppURIController_; + std::string vCardPhotoHash_; + std::string password_; + CertificateWithKey::ref certificate_; + ClientOptions clientOptions_; + boost::shared_ptr lastDisconnectError_; + bool useDelayForLatency_; + UserSearchController* userSearchControllerChat_; + UserSearchController* userSearchControllerAdd_; + UserSearchController* userSearchControllerInvite_; + int timeBeforeNextReconnect_; + Timer::ref reconnectTimer_; + StatusTracker* statusTracker_; + bool myStatusLooksOnline_; + bool quitRequested_; + bool offlineRequested_; + static const int SecondsToWaitBeforeForceQuitting; + FileTransferOverview* ftOverview_; + WhiteboardManager* whiteboardManager_; + HighlightManager* highlightManager_; + HighlightEditorController* highlightEditorController_; + std::map emoticons_; + }; } diff --git a/Swift/Controllers/PresenceNotifier.cpp b/Swift/Controllers/PresenceNotifier.cpp index b579187..c000107 100644 --- a/Swift/Controllers/PresenceNotifier.cpp +++ b/Swift/Controllers/PresenceNotifier.cpp @@ -21,117 +21,117 @@ namespace Swift { PresenceNotifier::PresenceNotifier(StanzaChannel* stanzaChannel, Notifier* notifier, const MUCRegistry* mucRegistry, AvatarManager* avatarManager, NickResolver* nickResolver, const PresenceOracle* presenceOracle, TimerFactory* timerFactory) : stanzaChannel(stanzaChannel), notifier(notifier), mucRegistry(mucRegistry), avatarManager(avatarManager), nickResolver(nickResolver), presenceOracle(presenceOracle), timerFactory(timerFactory) { - justInitialized = true; - inQuietPeriod = false; - stanzaChannel->onPresenceReceived.connect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1)); - stanzaChannel->onAvailableChanged.connect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1)); - setInitialQuietPeriodMS(3000); + justInitialized = true; + inQuietPeriod = false; + stanzaChannel->onPresenceReceived.connect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1)); + stanzaChannel->onAvailableChanged.connect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1)); + setInitialQuietPeriodMS(3000); } PresenceNotifier::~PresenceNotifier() { - if (timer) { - timer->stop(); - timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this)); - timer.reset(); - } - stanzaChannel->onAvailableChanged.disconnect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1)); - stanzaChannel->onPresenceReceived.disconnect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1)); + if (timer) { + timer->stop(); + timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this)); + timer.reset(); + } + stanzaChannel->onAvailableChanged.disconnect(boost::bind(&PresenceNotifier::handleStanzaChannelAvailableChanged, this, _1)); + stanzaChannel->onPresenceReceived.disconnect(boost::bind(&PresenceNotifier::handlePresenceReceived, this, _1)); } void PresenceNotifier::handlePresenceReceived(boost::shared_ptr presence) { - JID from = presence->getFrom(); - - if (mucRegistry->isMUC(from.toBare())) { - return; - } - - if (justInitialized) { - justInitialized = false; - if (timer) { - inQuietPeriod = true; - } - } - - if (inQuietPeriod) { - timer->stop(); - timer->start(); - return; - } - - std::set::iterator i = availableUsers.find(from); - if (presence->isAvailable()) { - if (i != availableUsers.end()) { - showNotification(from, Notifier::ContactStatusChange); - } - else { - showNotification(from, Notifier::ContactAvailable); - availableUsers.insert(from); - } - } - else { - if (i != availableUsers.end()) { - showNotification(from, Notifier::ContactUnavailable); - availableUsers.erase(i); - } - } + JID from = presence->getFrom(); + + if (mucRegistry->isMUC(from.toBare())) { + return; + } + + if (justInitialized) { + justInitialized = false; + if (timer) { + inQuietPeriod = true; + } + } + + if (inQuietPeriod) { + timer->stop(); + timer->start(); + return; + } + + std::set::iterator i = availableUsers.find(from); + if (presence->isAvailable()) { + if (i != availableUsers.end()) { + showNotification(from, Notifier::ContactStatusChange); + } + else { + showNotification(from, Notifier::ContactAvailable); + availableUsers.insert(from); + } + } + else { + if (i != availableUsers.end()) { + showNotification(from, Notifier::ContactUnavailable); + availableUsers.erase(i); + } + } } void PresenceNotifier::handleStanzaChannelAvailableChanged(bool available) { - if (available) { - availableUsers.clear(); - justInitialized = true; - if (timer) { - timer->stop(); - } - } + if (available) { + availableUsers.clear(); + justInitialized = true; + if (timer) { + timer->stop(); + } + } } void PresenceNotifier::showNotification(const JID& jid, Notifier::Type type) { - std::string name = nickResolver->jidToNick(jid); - std::string title = name + " (" + getStatusType(jid) + ")"; - std::string message = getStatusMessage(jid); - notifier->showMessage(type, title, message, avatarManager->getAvatarPath(jid), boost::bind(&PresenceNotifier::handleNotificationActivated, this, jid)); + std::string name = nickResolver->jidToNick(jid); + std::string title = name + " (" + getStatusType(jid) + ")"; + std::string message = getStatusMessage(jid); + notifier->showMessage(type, title, message, avatarManager->getAvatarPath(jid), boost::bind(&PresenceNotifier::handleNotificationActivated, this, jid)); } void PresenceNotifier::handleNotificationActivated(JID jid) { - onNotificationActivated(jid); + onNotificationActivated(jid); } std::string PresenceNotifier::getStatusType(const JID& jid) const { - Presence::ref presence = presenceOracle->getLastPresence(jid); - if (presence) { - return statusShowTypeToFriendlyName(presence->getShow()); - } - else { - return "Unavailable"; - } + Presence::ref presence = presenceOracle->getLastPresence(jid); + if (presence) { + return statusShowTypeToFriendlyName(presence->getShow()); + } + else { + return "Unavailable"; + } } std::string PresenceNotifier::getStatusMessage(const JID& jid) const { - Presence::ref presence = presenceOracle->getLastPresence(jid); - if (presence) { - return presence->getStatus(); - } - else { - return std::string(); - } + Presence::ref presence = presenceOracle->getLastPresence(jid); + if (presence) { + return presence->getStatus(); + } + else { + return std::string(); + } } void PresenceNotifier::setInitialQuietPeriodMS(int ms) { - if (timer) { - timer->stop(); - timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this)); - timer.reset(); - } - if (ms > 0) { - timer = timerFactory->createTimer(ms); - timer->onTick.connect(boost::bind(&PresenceNotifier::handleTimerTick, this)); - } + if (timer) { + timer->stop(); + timer->onTick.disconnect(boost::bind(&PresenceNotifier::handleTimerTick, this)); + timer.reset(); + } + if (ms > 0) { + timer = timerFactory->createTimer(ms); + timer->onTick.connect(boost::bind(&PresenceNotifier::handleTimerTick, this)); + } } void PresenceNotifier::handleTimerTick() { - inQuietPeriod = false; - timer->stop(); + inQuietPeriod = false; + timer->stop(); } diff --git a/Swift/Controllers/PresenceNotifier.h b/Swift/Controllers/PresenceNotifier.h index b02f8a2..3d498bd 100644 --- a/Swift/Controllers/PresenceNotifier.h +++ b/Swift/Controllers/PresenceNotifier.h @@ -19,44 +19,44 @@ #include namespace Swift { - class TimerFactory; - class StanzaChannel; - class MUCRegistry; - class NickResolver; - class PresenceOracle; - - class PresenceNotifier { - public: - PresenceNotifier(StanzaChannel* stanzaChannel, Notifier* notifier, const MUCRegistry* mucRegistry, AvatarManager* avatarManager, NickResolver* nickResolver, const PresenceOracle* presenceOracle, TimerFactory* timerFactory); - ~PresenceNotifier(); - - void setInitialQuietPeriodMS(int ms); - - boost::signal onNotificationActivated; - - private: - void handlePresenceReceived(boost::shared_ptr); - void handleStanzaChannelAvailableChanged(bool); - void handleNotificationActivated(JID jid); - void handleTimerTick(); - std::string getStatusType(const JID&) const; - std::string getStatusMessage(const JID&) const; - - private: - void showNotification(const JID& jid, Notifier::Type type); - - private: - StanzaChannel* stanzaChannel; - Notifier* notifier; - const MUCRegistry* mucRegistry; - AvatarManager* avatarManager; - NickResolver* nickResolver; - const PresenceOracle* presenceOracle; - TimerFactory* timerFactory; - boost::shared_ptr timer; - bool justInitialized; - bool inQuietPeriod; - std::set availableUsers; - }; + class TimerFactory; + class StanzaChannel; + class MUCRegistry; + class NickResolver; + class PresenceOracle; + + class PresenceNotifier { + public: + PresenceNotifier(StanzaChannel* stanzaChannel, Notifier* notifier, const MUCRegistry* mucRegistry, AvatarManager* avatarManager, NickResolver* nickResolver, const PresenceOracle* presenceOracle, TimerFactory* timerFactory); + ~PresenceNotifier(); + + void setInitialQuietPeriodMS(int ms); + + boost::signal onNotificationActivated; + + private: + void handlePresenceReceived(boost::shared_ptr); + void handleStanzaChannelAvailableChanged(bool); + void handleNotificationActivated(JID jid); + void handleTimerTick(); + std::string getStatusType(const JID&) const; + std::string getStatusMessage(const JID&) const; + + private: + void showNotification(const JID& jid, Notifier::Type type); + + private: + StanzaChannel* stanzaChannel; + Notifier* notifier; + const MUCRegistry* mucRegistry; + AvatarManager* avatarManager; + NickResolver* nickResolver; + const PresenceOracle* presenceOracle; + TimerFactory* timerFactory; + boost::shared_ptr timer; + bool justInitialized; + bool inQuietPeriod; + std::set availableUsers; + }; } diff --git a/Swift/Controllers/PreviousStatusStore.cpp b/Swift/Controllers/PreviousStatusStore.cpp index 6564ab5..4806f9c 100644 --- a/Swift/Controllers/PreviousStatusStore.cpp +++ b/Swift/Controllers/PreviousStatusStore.cpp @@ -19,35 +19,35 @@ PreviousStatusStore::~PreviousStatusStore() { } void PreviousStatusStore::addStatus(StatusShow::Type status, const std::string& message) { - //FIXME: remove old entries - store_.push_back(TypeStringPair(status, message)); + //FIXME: remove old entries + store_.push_back(TypeStringPair(status, message)); } std::vector PreviousStatusStore::exactMatchSuggestions(StatusShow::Type status, const std::string& message) { - std::vector suggestions; - suggestions.push_back(TypeStringPair(status, message)); - return suggestions; + std::vector suggestions; + suggestions.push_back(TypeStringPair(status, message)); + return suggestions; } std::vector PreviousStatusStore::getSuggestions(const std::string& message) { - std::vector suggestions; - foreach (TypeStringPair status, store_) { - if (status.second == message) { - suggestions.clear(); - suggestions.push_back(status); - break; - } else if (status.second.find(message) != std::string::npos) { - suggestions.push_back(status); - } - } - if (suggestions.empty()) { - TypeStringPair suggestion(StatusShow::Online, message); - suggestions.push_back(suggestion); - } - if (suggestions.size() == 1) { - suggestions = exactMatchSuggestions(suggestions[0].first, suggestions[0].second); - } - return suggestions; + std::vector suggestions; + foreach (TypeStringPair status, store_) { + if (status.second == message) { + suggestions.clear(); + suggestions.push_back(status); + break; + } else if (status.second.find(message) != std::string::npos) { + suggestions.push_back(status); + } + } + if (suggestions.empty()) { + TypeStringPair suggestion(StatusShow::Online, message); + suggestions.push_back(suggestion); + } + if (suggestions.size() == 1) { + suggestions = exactMatchSuggestions(suggestions[0].first, suggestions[0].second); + } + return suggestions; } } diff --git a/Swift/Controllers/PreviousStatusStore.h b/Swift/Controllers/PreviousStatusStore.h index 51c2dd9..eb1fb59 100644 --- a/Swift/Controllers/PreviousStatusStore.h +++ b/Swift/Controllers/PreviousStatusStore.h @@ -13,16 +13,16 @@ #include namespace Swift { - typedef std::pair TypeStringPair; - class PreviousStatusStore { - public: - PreviousStatusStore(); - ~PreviousStatusStore(); - void addStatus(StatusShow::Type status, const std::string& message); - std::vector getSuggestions(const std::string& message); + typedef std::pair TypeStringPair; + class PreviousStatusStore { + public: + PreviousStatusStore(); + ~PreviousStatusStore(); + void addStatus(StatusShow::Type status, const std::string& message); + std::vector getSuggestions(const std::string& message); - private: - std::vector exactMatchSuggestions(StatusShow::Type status, const std::string& message); - std::vector store_; - }; + private: + std::vector exactMatchSuggestions(StatusShow::Type status, const std::string& message); + std::vector store_; + }; } diff --git a/Swift/Controllers/ProfileController.cpp b/Swift/Controllers/ProfileController.cpp index a1aa5f9..756aaff 100644 --- a/Swift/Controllers/ProfileController.cpp +++ b/Swift/Controllers/ProfileController.cpp @@ -18,97 +18,97 @@ namespace Swift { ProfileController::ProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream) : vcardManager(vcardManager), profileWindowFactory(profileWindowFactory), uiEventStream(uiEventStream), available(true), profileWindow(NULL), gettingVCard(false) { - uiEventStream->onUIEvent.connect(boost::bind(&ProfileController::handleUIEvent, this, _1)); + uiEventStream->onUIEvent.connect(boost::bind(&ProfileController::handleUIEvent, this, _1)); } ProfileController::~ProfileController() { - if (profileWindow) { - vcardManager->onOwnVCardChanged.disconnect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1)); - vcardManager->onVCardRetrievalError.disconnect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2)); - profileWindow->onVCardChangeRequest.disconnect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1)); - profileWindow->onWindowAboutToBeClosed.disconnect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1)); - } - uiEventStream->onUIEvent.disconnect(boost::bind(&ProfileController::handleUIEvent, this, _1)); - delete profileWindow; + if (profileWindow) { + vcardManager->onOwnVCardChanged.disconnect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1)); + vcardManager->onVCardRetrievalError.disconnect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2)); + profileWindow->onVCardChangeRequest.disconnect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1)); + profileWindow->onWindowAboutToBeClosed.disconnect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1)); + } + uiEventStream->onUIEvent.disconnect(boost::bind(&ProfileController::handleUIEvent, this, _1)); + delete profileWindow; } void ProfileController::handleUIEvent(UIEvent::ref event) { - if (!boost::dynamic_pointer_cast(event)) { - return; - } - - if (!profileWindow) { - profileWindow = profileWindowFactory->createProfileWindow(); - profileWindow->setEditable(true); - profileWindow->onVCardChangeRequest.connect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1)); - profileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1)); - vcardManager->onOwnVCardChanged.connect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1)); - vcardManager->onVCardRetrievalError.connect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2)); - } - gettingVCard = true; - updateDialogStatus(); - vcardManager->requestOwnVCard(); - profileWindow->show(); + if (!boost::dynamic_pointer_cast(event)) { + return; + } + + if (!profileWindow) { + profileWindow = profileWindowFactory->createProfileWindow(); + profileWindow->setEditable(true); + profileWindow->onVCardChangeRequest.connect(boost::bind(&ProfileController::handleVCardChangeRequest, this, _1)); + profileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ProfileController::handleProfileWindowAboutToBeClosed, this, _1)); + vcardManager->onOwnVCardChanged.connect(boost::bind(&ProfileController::handleOwnVCardChanged, this, _1)); + vcardManager->onVCardRetrievalError.connect(boost::bind(&ProfileController::handleVCardRetrievalError, this, _1, _2)); + } + gettingVCard = true; + updateDialogStatus(); + vcardManager->requestOwnVCard(); + profileWindow->show(); } void ProfileController::handleVCardChangeRequest(VCard::ref vcard) { - assert(!pendingSetVCardRequest); - profileWindow->setError(""); - pendingSetVCardRequest = vcardManager->createSetVCardRequest(vcard); - pendingSetVCardRequest->onResponse.connect(boost::bind(&ProfileController::handleSetVCardResponse, this, _2)); - pendingSetVCardRequest->send(); - updateDialogStatus(); + assert(!pendingSetVCardRequest); + profileWindow->setError(""); + pendingSetVCardRequest = vcardManager->createSetVCardRequest(vcard); + pendingSetVCardRequest->onResponse.connect(boost::bind(&ProfileController::handleSetVCardResponse, this, _2)); + pendingSetVCardRequest->send(); + updateDialogStatus(); } void ProfileController::handleSetVCardResponse(ErrorPayload::ref error) { - pendingSetVCardRequest.reset(); - updateDialogStatus(); - if (error) { - profileWindow->setVCard(vcardBeforeEdit); - profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error publishing your profile data")); - } - else { - profileWindow->setError(""); - profileWindow->hide(); - } + pendingSetVCardRequest.reset(); + updateDialogStatus(); + if (error) { + profileWindow->setVCard(vcardBeforeEdit); + profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error publishing your profile data")); + } + else { + profileWindow->setError(""); + profileWindow->hide(); + } } void ProfileController::handleVCardRetrievalError(const JID& jid, ErrorPayload::ref /* error */) { - if ((jid == JID()) && profileWindow) { - profileWindow->setProcessing(false); - profileWindow->setEnabled(false); - profileWindow->setVCard(boost::make_shared()); - profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error fetching your current profile data")); - } + if ((jid == JID()) && profileWindow) { + profileWindow->setProcessing(false); + profileWindow->setEnabled(false); + profileWindow->setVCard(boost::make_shared()); + profileWindow->setError(QT_TRANSLATE_NOOP("", "There was an error fetching your current profile data")); + } } void ProfileController::handleOwnVCardChanged(VCard::ref vcard) { - if (profileWindow) { - profileWindow->setVCard(vcard); - vcardBeforeEdit = vcard; - gettingVCard = false; - updateDialogStatus(); - } + if (profileWindow) { + profileWindow->setVCard(vcard); + vcardBeforeEdit = vcard; + gettingVCard = false; + updateDialogStatus(); + } } void ProfileController::handleProfileWindowAboutToBeClosed(const JID&) { - profileWindow = NULL; + profileWindow = NULL; } void ProfileController::setAvailable(bool b) { - available = b; - if (!available) { - pendingSetVCardRequest.reset(); - } - updateDialogStatus(); + available = b; + if (!available) { + pendingSetVCardRequest.reset(); + } + updateDialogStatus(); } void ProfileController::updateDialogStatus() { - if (profileWindow) { - profileWindow->setEnabled(available && !gettingVCard && !pendingSetVCardRequest); - profileWindow->setProcessing(gettingVCard || pendingSetVCardRequest); - } + if (profileWindow) { + profileWindow->setEnabled(available && !gettingVCard && !pendingSetVCardRequest); + profileWindow->setProcessing(gettingVCard || pendingSetVCardRequest); + } } } diff --git a/Swift/Controllers/ProfileController.h b/Swift/Controllers/ProfileController.h index ebb569d..3bb1fce 100644 --- a/Swift/Controllers/ProfileController.h +++ b/Swift/Controllers/ProfileController.h @@ -13,36 +13,36 @@ #include namespace Swift { - class ProfileWindow; - class ProfileWindowFactory; - class UIEventStream; - class VCardManager; - - class ProfileController { - public: - ProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream); - ~ProfileController(); - - void setAvailable(bool b); - - private: - void handleUIEvent(UIEvent::ref event); - void handleVCardChangeRequest(VCard::ref vcard); - void handleSetVCardResponse(ErrorPayload::ref); - void handleOwnVCardChanged(VCard::ref vcard); - void handleVCardRetrievalError(const JID& jid, ErrorPayload::ref error); - void handleProfileWindowAboutToBeClosed(const JID&); - void updateDialogStatus(); - - private: - VCardManager* vcardManager; - ProfileWindowFactory* profileWindowFactory; - UIEventStream* uiEventStream; - bool available; - SetVCardRequest::ref pendingSetVCardRequest; - ProfileWindow* profileWindow; - bool gettingVCard; - VCard::ref vcardBeforeEdit; - }; + class ProfileWindow; + class ProfileWindowFactory; + class UIEventStream; + class VCardManager; + + class ProfileController { + public: + ProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream); + ~ProfileController(); + + void setAvailable(bool b); + + private: + void handleUIEvent(UIEvent::ref event); + void handleVCardChangeRequest(VCard::ref vcard); + void handleSetVCardResponse(ErrorPayload::ref); + void handleOwnVCardChanged(VCard::ref vcard); + void handleVCardRetrievalError(const JID& jid, ErrorPayload::ref error); + void handleProfileWindowAboutToBeClosed(const JID&); + void updateDialogStatus(); + + private: + VCardManager* vcardManager; + ProfileWindowFactory* profileWindowFactory; + UIEventStream* uiEventStream; + bool available; + SetVCardRequest::ref pendingSetVCardRequest; + ProfileWindow* profileWindow; + bool gettingVCard; + VCard::ref vcardBeforeEdit; + }; } diff --git a/Swift/Controllers/ProfileSettingsProvider.cpp b/Swift/Controllers/ProfileSettingsProvider.cpp index 86f4c99..bb186fc 100644 --- a/Swift/Controllers/ProfileSettingsProvider.cpp +++ b/Swift/Controllers/ProfileSettingsProvider.cpp @@ -9,58 +9,58 @@ namespace Swift { ProfileSettingsProvider::ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider) : - profile_(profile) { - provider_ = provider; - bool found = false; - foreach (std::string existingProfile, provider->getAvailableProfiles()) { - if (existingProfile == profile) { - found = true; - } - } - if (!found) { - provider_->createProfile(profile); - } + profile_(profile) { + provider_ = provider; + bool found = false; + foreach (std::string existingProfile, provider->getAvailableProfiles()) { + if (existingProfile == profile) { + found = true; + } + } + if (!found) { + provider_->createProfile(profile); + } } ProfileSettingsProvider::~ProfileSettingsProvider() { } std::string ProfileSettingsProvider::getStringSetting(const std::string &settingPath) { - //FIXME: Remove shim - SettingsProvider::Setting setting(profileSettingPath(settingPath), ""); - return provider_->getSetting(setting); + //FIXME: Remove shim + SettingsProvider::Setting setting(profileSettingPath(settingPath), ""); + return provider_->getSetting(setting); } void ProfileSettingsProvider::storeString(const std::string &settingPath, const std::string &settingValue) { - //FIXME: Remove shim - if (!getIsSettingFinal(settingPath)) { - SettingsProvider::Setting setting(profileSettingPath(settingPath), ""); - provider_->storeSetting(setting, settingValue); - } + //FIXME: Remove shim + if (!getIsSettingFinal(settingPath)) { + SettingsProvider::Setting setting(profileSettingPath(settingPath), ""); + provider_->storeSetting(setting, settingValue); + } } int ProfileSettingsProvider::getIntSetting(const std::string& settingPath, int defaultValue) { - //FIXME: Remove shim - SettingsProvider::Setting setting(profileSettingPath(settingPath), defaultValue); - return provider_->getSetting(setting); + //FIXME: Remove shim + SettingsProvider::Setting setting(profileSettingPath(settingPath), defaultValue); + return provider_->getSetting(setting); } void ProfileSettingsProvider::storeInt(const std::string& settingPath, int settingValue) { - //FIXME: Remove shim - if (!getIsSettingFinal(settingPath)) { - SettingsProvider::Setting setting(profileSettingPath(settingPath), 0); - provider_->storeSetting(setting, settingValue); - } + //FIXME: Remove shim + if (!getIsSettingFinal(settingPath)) { + SettingsProvider::Setting setting(profileSettingPath(settingPath), 0); + provider_->storeSetting(setting, settingValue); + } } bool ProfileSettingsProvider::getIsSettingFinal(const std::string& settingPath) { - //FIXME: Remove shim - SettingsProvider::Setting setting(settingPath, 0); - return provider_->getIsSettingFinal(setting); + //FIXME: Remove shim + SettingsProvider::Setting setting(settingPath, 0); + return provider_->getIsSettingFinal(setting); } std::string ProfileSettingsProvider::profileSettingPath(const std::string &settingPath) { - return profile_ + ":" + settingPath; + return profile_ + ":" + settingPath; } diff --git a/Swift/Controllers/ProfileSettingsProvider.h b/Swift/Controllers/ProfileSettingsProvider.h index 02e1e81..f3c3156 100644 --- a/Swift/Controllers/ProfileSettingsProvider.h +++ b/Swift/Controllers/ProfileSettingsProvider.h @@ -13,20 +13,20 @@ namespace Swift { class ProfileSettingsProvider { - public: - ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider); - virtual ~ProfileSettingsProvider(); - virtual std::string getStringSetting(const std::string &settingPath); - virtual void storeString(const std::string &settingPath, const std::string &settingValue); - virtual int getIntSetting(const std::string& settingPath, int defaultValue); - virtual void storeInt(const std::string& settingPath, int settingValue); - /** See \ref SettingsProvider::getIsSettingFinal for discussion of what this means.*/ - virtual bool getIsSettingFinal(const std::string& settingPath); - - private: - std::string profileSettingPath(const std::string &settingPath); - SettingsProvider* provider_; - std::string profile_; + public: + ProfileSettingsProvider(const std::string& profile, SettingsProvider* provider); + virtual ~ProfileSettingsProvider(); + virtual std::string getStringSetting(const std::string &settingPath); + virtual void storeString(const std::string &settingPath, const std::string &settingValue); + virtual int getIntSetting(const std::string& settingPath, int defaultValue); + virtual void storeInt(const std::string& settingPath, int settingValue); + /** See \ref SettingsProvider::getIsSettingFinal for discussion of what this means.*/ + virtual bool getIsSettingFinal(const std::string& settingPath); + + private: + std::string profileSettingPath(const std::string &settingPath); + SettingsProvider* provider_; + std::string profile_; }; } diff --git a/Swift/Controllers/Roster/ContactRosterItem.cpp b/Swift/Controllers/Roster/ContactRosterItem.cpp index 3258fb5..89053e6 100644 --- a/Swift/Controllers/Roster/ContactRosterItem.cpp +++ b/Swift/Controllers/Roster/ContactRosterItem.cpp @@ -27,149 +27,149 @@ ContactRosterItem::~ContactRosterItem() { } StatusShow::Type ContactRosterItem::getStatusShow() const { - return presence_ ? presence_->getShow() : StatusShow::None; + return presence_ ? presence_->getShow() : StatusShow::None; } StatusShow::Type ContactRosterItem::getSimplifiedStatusShow() const { - switch (presence_ ? presence_->getShow() : StatusShow::None) { - case StatusShow::Online: return StatusShow::Online; - case StatusShow::Away: return StatusShow::Away; - case StatusShow::XA: return StatusShow::Away; - case StatusShow::FFC: return StatusShow::Online; - case StatusShow::DND: return StatusShow::DND; - case StatusShow::None: return StatusShow::None; - } - assert(false); - return StatusShow::None; + switch (presence_ ? presence_->getShow() : StatusShow::None) { + case StatusShow::Online: return StatusShow::Online; + case StatusShow::Away: return StatusShow::Away; + case StatusShow::XA: return StatusShow::Away; + case StatusShow::FFC: return StatusShow::Online; + case StatusShow::DND: return StatusShow::DND; + case StatusShow::None: return StatusShow::None; + } + assert(false); + return StatusShow::None; } std::string ContactRosterItem::getStatusText() const { - return presence_ ? presence_->getStatus() : ""; + return presence_ ? presence_->getStatus() : ""; } std::string ContactRosterItem::getIdleText() const { - Idle::ref idle = presence_ ? presence_->getPayload() : Idle::ref(); - if (!idle || idle->getSince().is_not_a_date_time()) { - return ""; - } else { - return dateTimeToLocalString(idle->getSince()); - } + Idle::ref idle = presence_ ? presence_->getPayload() : Idle::ref(); + if (!idle || idle->getSince().is_not_a_date_time()) { + return ""; + } else { + return dateTimeToLocalString(idle->getSince()); + } } std::string ContactRosterItem::getOfflineSinceText() const { - if (presence_ && presence_->getType() == Presence::Unavailable) { - boost::optional delay = presence_->getTimestamp(); - if (delay) { - return dateTimeToLocalString(*delay); - } - } - return ""; + if (presence_ && presence_->getType() == Presence::Unavailable) { + boost::optional delay = presence_->getTimestamp(); + if (delay) { + return dateTimeToLocalString(*delay); + } + } + return ""; } void ContactRosterItem::setAvatarPath(const boost::filesystem::path& path) { - avatarPath_ = path; - onDataChanged(); + avatarPath_ = path; + onDataChanged(); } const boost::filesystem::path& ContactRosterItem::getAvatarPath() const { - return avatarPath_; + return avatarPath_; } const JID& ContactRosterItem::getJID() const { - return jid_; + return jid_; } void ContactRosterItem::setDisplayJID(const JID& jid) { - displayJID_ = jid; + displayJID_ = jid; } const JID& ContactRosterItem::getDisplayJID() const { - return displayJID_; + return displayJID_; } typedef std::pair > StringPresencePair; void ContactRosterItem::clearPresence() { - presence_.reset(); - onDataChanged(); + presence_.reset(); + onDataChanged(); } void ContactRosterItem::applyPresence(boost::shared_ptr presence) { - presence_ = presence; - onDataChanged(); + presence_ = presence; + onDataChanged(); } const std::vector& ContactRosterItem::getGroups() const { - return groups_; + return groups_; } /** Only used so a contact can know about the groups it's in*/ void ContactRosterItem::addGroup(const std::string& group) { - groups_.push_back(group); + groups_.push_back(group); } void ContactRosterItem::removeGroup(const std::string& group) { - groups_.erase(std::remove(groups_.begin(), groups_.end(), group), groups_.end()); + groups_.erase(std::remove(groups_.begin(), groups_.end(), group), groups_.end()); } MUCOccupant::Role ContactRosterItem::getMUCRole() const { - return mucRole_; + return mucRole_; } void ContactRosterItem::setMUCRole(const MUCOccupant::Role& role) { - mucRole_ = role; + mucRole_ = role; } MUCOccupant::Affiliation ContactRosterItem::getMUCAffiliation() const { - return mucAffiliation_; + return mucAffiliation_; } void ContactRosterItem::setMUCAffiliation(const MUCOccupant::Affiliation& affiliation) { - mucAffiliation_ = affiliation; + mucAffiliation_ = affiliation; } std::string ContactRosterItem::getMUCAffiliationText() const { - std::string affiliationString; - switch (mucAffiliation_) { - case MUCOccupant::Owner: affiliationString = QT_TRANSLATE_NOOP("", "Owner"); break; - case MUCOccupant::Admin: affiliationString = QT_TRANSLATE_NOOP("", "Admin"); break; - case MUCOccupant::Member: affiliationString = QT_TRANSLATE_NOOP("", "Member"); break; - case MUCOccupant::Outcast: affiliationString = QT_TRANSLATE_NOOP("", "Outcast"); break; - case MUCOccupant::NoAffiliation: affiliationString = ""; break; - } + std::string affiliationString; + switch (mucAffiliation_) { + case MUCOccupant::Owner: affiliationString = QT_TRANSLATE_NOOP("", "Owner"); break; + case MUCOccupant::Admin: affiliationString = QT_TRANSLATE_NOOP("", "Admin"); break; + case MUCOccupant::Member: affiliationString = QT_TRANSLATE_NOOP("", "Member"); break; + case MUCOccupant::Outcast: affiliationString = QT_TRANSLATE_NOOP("", "Outcast"); break; + case MUCOccupant::NoAffiliation: affiliationString = ""; break; + } - return affiliationString; + return affiliationString; } void ContactRosterItem::setSupportedFeatures(const std::set& features) { - features_ = features; - onDataChanged(); + features_ = features; + onDataChanged(); } bool ContactRosterItem::supportsFeature(const Feature feature) const { - return features_.find(feature) != features_.end(); + return features_.find(feature) != features_.end(); } void ContactRosterItem::setBlockState(BlockState state) { - blockState_ = state; - onDataChanged(); + blockState_ = state; + onDataChanged(); } ContactRosterItem::BlockState ContactRosterItem::blockState() const { - return blockState_; + return blockState_; } VCard::ref ContactRosterItem::getVCard() const { - return vcard_; + return vcard_; } void ContactRosterItem::setVCard(VCard::ref vcard) { - vcard_ = vcard; - onDataChanged(); + vcard_ = vcard; + onDataChanged(); } } diff --git a/Swift/Controllers/Roster/ContactRosterItem.h b/Swift/Controllers/Roster/ContactRosterItem.h index d21935c..d77ba2d 100644 --- a/Swift/Controllers/Roster/ContactRosterItem.h +++ b/Swift/Controllers/Roster/ContactRosterItem.h @@ -28,69 +28,69 @@ namespace Swift { class GroupRosterItem; class ContactRosterItem : public RosterItem { - public: - enum Feature { - FileTransferFeature, - WhiteboardFeature - }; - - enum BlockState { - BlockingNotSupported, - IsBlocked, - IsUnblocked, - IsDomainBlocked - }; - - public: - ContactRosterItem(const JID& jid, const JID& displayJID, const std::string& name, GroupRosterItem* parent); - virtual ~ContactRosterItem(); - - StatusShow::Type getStatusShow() const; - StatusShow::Type getSimplifiedStatusShow() const; - std::string getStatusText() const; - std::string getIdleText() const; - std::string getOfflineSinceText() const; - void setAvatarPath(const boost::filesystem::path& path); - const boost::filesystem::path& getAvatarPath() const; - const JID& getJID() const; - void setDisplayJID(const JID& jid); - const JID& getDisplayJID() const; - void applyPresence(boost::shared_ptr presence); - const std::vector& getGroups() const; - /** Only used so a contact can know about the groups it's in*/ - void addGroup(const std::string& group); - void removeGroup(const std::string& group); - void clearPresence(); - - MUCOccupant::Role getMUCRole() const; - void setMUCRole(const MUCOccupant::Role& role); - MUCOccupant::Affiliation getMUCAffiliation() const; - void setMUCAffiliation(const MUCOccupant::Affiliation& affiliation); - std::string getMUCAffiliationText() const; - - void setSupportedFeatures(const std::set& features); - bool supportsFeature(Feature feature) const; - - void setBlockState(BlockState state); - BlockState blockState() const; - - VCard::ref getVCard() const; - void setVCard(VCard::ref vcard); - - boost::signal onVCardRequested; - - private: - JID jid_; - JID displayJID_; - boost::posix_time::ptime lastAvailableTime_; - boost::filesystem::path avatarPath_; - boost::shared_ptr presence_; - std::vector groups_; - MUCOccupant::Role mucRole_; - MUCOccupant::Affiliation mucAffiliation_; - std::set features_; - BlockState blockState_; - VCard::ref vcard_; + public: + enum Feature { + FileTransferFeature, + WhiteboardFeature + }; + + enum BlockState { + BlockingNotSupported, + IsBlocked, + IsUnblocked, + IsDomainBlocked + }; + + public: + ContactRosterItem(const JID& jid, const JID& displayJID, const std::string& name, GroupRosterItem* parent); + virtual ~ContactRosterItem(); + + StatusShow::Type getStatusShow() const; + StatusShow::Type getSimplifiedStatusShow() const; + std::string getStatusText() const; + std::string getIdleText() const; + std::string getOfflineSinceText() const; + void setAvatarPath(const boost::filesystem::path& path); + const boost::filesystem::path& getAvatarPath() const; + const JID& getJID() const; + void setDisplayJID(const JID& jid); + const JID& getDisplayJID() const; + void applyPresence(boost::shared_ptr presence); + const std::vector& getGroups() const; + /** Only used so a contact can know about the groups it's in*/ + void addGroup(const std::string& group); + void removeGroup(const std::string& group); + void clearPresence(); + + MUCOccupant::Role getMUCRole() const; + void setMUCRole(const MUCOccupant::Role& role); + MUCOccupant::Affiliation getMUCAffiliation() const; + void setMUCAffiliation(const MUCOccupant::Affiliation& affiliation); + std::string getMUCAffiliationText() const; + + void setSupportedFeatures(const std::set& features); + bool supportsFeature(Feature feature) const; + + void setBlockState(BlockState state); + BlockState blockState() const; + + VCard::ref getVCard() const; + void setVCard(VCard::ref vcard); + + boost::signal onVCardRequested; + + private: + JID jid_; + JID displayJID_; + boost::posix_time::ptime lastAvailableTime_; + boost::filesystem::path avatarPath_; + boost::shared_ptr presence_; + std::vector groups_; + MUCOccupant::Role mucRole_; + MUCOccupant::Affiliation mucAffiliation_; + std::set features_; + BlockState blockState_; + VCard::ref vcard_; }; } diff --git a/Swift/Controllers/Roster/FuzzyRosterFilter.h b/Swift/Controllers/Roster/FuzzyRosterFilter.h index 14e0f62..8c45935 100644 --- a/Swift/Controllers/Roster/FuzzyRosterFilter.h +++ b/Swift/Controllers/Roster/FuzzyRosterFilter.h @@ -22,21 +22,21 @@ namespace Swift { class FuzzyRosterFilter : public RosterFilter { - public: - FuzzyRosterFilter(const std::string& query) : query_(query) { } - virtual ~FuzzyRosterFilter() {} - virtual bool operator() (RosterItem* item) const { - ContactRosterItem *contactItem = dynamic_cast(item); - if (contactItem) { - const bool itemMatched = ContactSuggester::fuzzyMatch(contactItem->getDisplayName(), query_) || ContactSuggester::fuzzyMatch(contactItem->getDisplayJID(), query_); - return !itemMatched; - } else { - return false; - } - } - - private: - std::string query_; + public: + FuzzyRosterFilter(const std::string& query) : query_(query) { } + virtual ~FuzzyRosterFilter() {} + virtual bool operator() (RosterItem* item) const { + ContactRosterItem *contactItem = dynamic_cast(item); + if (contactItem) { + const bool itemMatched = ContactSuggester::fuzzyMatch(contactItem->getDisplayName(), query_) || ContactSuggester::fuzzyMatch(contactItem->getDisplayJID(), query_); + return !itemMatched; + } else { + return false; + } + } + + private: + std::string query_; }; } diff --git a/Swift/Controllers/Roster/GroupRosterItem.cpp b/Swift/Controllers/Roster/GroupRosterItem.cpp index 6c68851..82e43df 100644 --- a/Swift/Controllers/Roster/GroupRosterItem.cpp +++ b/Swift/Controllers/Roster/GroupRosterItem.cpp @@ -12,7 +12,7 @@ namespace Swift { GroupRosterItem::GroupRosterItem(const std::string& name, GroupRosterItem* parent, bool sortByStatus) : RosterItem(name, parent), sortByStatus_(sortByStatus), manualSort_(false) { - expanded_ = true; + expanded_ = true; } GroupRosterItem::~GroupRosterItem() { @@ -20,77 +20,77 @@ GroupRosterItem::~GroupRosterItem() { } void GroupRosterItem::setManualSort(const std::string& manualSortValue) { - manualSort_ = true; - bool changed = manualSortValue_ != manualSortValue; - manualSortValue_ = manualSortValue; - if (changed) { - onChildrenChanged(); - onDataChanged(); - } + manualSort_ = true; + bool changed = manualSortValue_ != manualSortValue; + manualSortValue_ = manualSortValue; + if (changed) { + onChildrenChanged(); + onDataChanged(); + } } const std::string& GroupRosterItem::getSortableDisplayName() const { - return manualSort_ ? manualSortValue_ : RosterItem::getSortableDisplayName(); + return manualSort_ ? manualSortValue_ : RosterItem::getSortableDisplayName(); } bool GroupRosterItem::isExpanded() const { - return expanded_; + return expanded_; } /** - This has no effect, and is only used by the UI. - If reTransmit is specified, dataChanged will be emitted on a change - - This may be undesireable if called from the UI, so you can use reTransmit=false - to avoid a loop in this case. + This has no effect, and is only used by the UI. + If reTransmit is specified, dataChanged will be emitted on a change - + This may be undesireable if called from the UI, so you can use reTransmit=false + to avoid a loop in this case. */ void GroupRosterItem::setExpanded(bool expanded) { - bool old = expanded_; - expanded_ = expanded; - if (expanded != old) { - onExpandedChanged(expanded); - } + bool old = expanded_; + expanded_ = expanded; + if (expanded != old) { + onExpandedChanged(expanded); + } } const std::vector& GroupRosterItem::getChildren() const { - return children_; + return children_; } const std::vector& GroupRosterItem::getDisplayedChildren() const { - return displayedChildren_; + return displayedChildren_; } void GroupRosterItem::addChild(RosterItem* item) { - children_.push_back(item); - GroupRosterItem* group = dynamic_cast(item); - if (group) { - group->onChildrenChanged.connect(boost::bind(&GroupRosterItem::handleChildrenChanged, this, group)); - } else { - item->onDataChanged.connect(boost::bind(&GroupRosterItem::handleDataChanged, this, item)); - } - onChildrenChanged(); - onDataChanged(); + children_.push_back(item); + GroupRosterItem* group = dynamic_cast(item); + if (group) { + group->onChildrenChanged.connect(boost::bind(&GroupRosterItem::handleChildrenChanged, this, group)); + } else { + item->onDataChanged.connect(boost::bind(&GroupRosterItem::handleDataChanged, this, item)); + } + onChildrenChanged(); + onDataChanged(); } /** * Does not emit a changed signal. */ void GroupRosterItem::removeAll() { - std::vector::iterator it = children_.begin(); - displayedChildren_.clear(); - while (it != children_.end()) { - ContactRosterItem* contact = dynamic_cast(*it); - if (contact) { - delete contact; - } else { - GroupRosterItem* group = dynamic_cast(*it); - if (group) { - group->removeAll(); - delete group; - } - } - ++it; - } - children_.clear(); + std::vector::iterator it = children_.begin(); + displayedChildren_.clear(); + while (it != children_.end()) { + ContactRosterItem* contact = dynamic_cast(*it); + if (contact) { + delete contact; + } else { + GroupRosterItem* group = dynamic_cast(*it); + if (group) { + group->removeAll(); + delete group; + } + } + ++it; + } + children_.clear(); } /** @@ -98,136 +98,136 @@ void GroupRosterItem::removeAll() { * the return result is undefined. */ ContactRosterItem* GroupRosterItem::removeChild(const JID& jid) { - std::vector::iterator it = children_.begin(); - ContactRosterItem* removed = NULL; - while (it != children_.end()) { - ContactRosterItem* contact = dynamic_cast(*it); - if (contact && contact->getJID() == jid) { - displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), contact), displayedChildren_.end()); - removed = contact; - delete contact; - it = children_.erase(it); - continue; - } - GroupRosterItem* group = dynamic_cast(*it); - if (group) { - ContactRosterItem* groupRemoved = group->removeChild(jid); - if (groupRemoved) { - removed = groupRemoved; - } - } - ++it; - } - onChildrenChanged(); - onDataChanged(); - return removed; + std::vector::iterator it = children_.begin(); + ContactRosterItem* removed = NULL; + while (it != children_.end()) { + ContactRosterItem* contact = dynamic_cast(*it); + if (contact && contact->getJID() == jid) { + displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), contact), displayedChildren_.end()); + removed = contact; + delete contact; + it = children_.erase(it); + continue; + } + GroupRosterItem* group = dynamic_cast(*it); + if (group) { + ContactRosterItem* groupRemoved = group->removeChild(jid); + if (groupRemoved) { + removed = groupRemoved; + } + } + ++it; + } + onChildrenChanged(); + onDataChanged(); + return removed; } GroupRosterItem* GroupRosterItem::removeGroupChild(const std::string& groupName) { - std::vector::iterator it = children_.begin(); - GroupRosterItem* removed = NULL; - while (it != children_.end()) { - GroupRosterItem* group = dynamic_cast(*it); - if (group && group->getDisplayName() == groupName) { - displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end()); - removed = group; - delete group; - it = children_.erase(it); - continue; - } - ++it; - } - onChildrenChanged(); - onDataChanged(); - return removed; + std::vector::iterator it = children_.begin(); + GroupRosterItem* removed = NULL; + while (it != children_.end()) { + GroupRosterItem* group = dynamic_cast(*it); + if (group && group->getDisplayName() == groupName) { + displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end()); + removed = group; + delete group; + it = children_.erase(it); + continue; + } + ++it; + } + onChildrenChanged(); + onDataChanged(); + return removed; } /** * Returns false if the list didn't need a resort */ bool GroupRosterItem::sortDisplayed() { - /* Not doing this until we import boost::algorithm*/ -// if (boost::is_sorted(displayedChildren_begin(), displayedChildren_.end(), itemLessThan)) { -// return false; -// } - //Sholudn't need stable_sort here - std::sort(displayedChildren_.begin(), displayedChildren_.end(), sortByStatus_? itemLessThanWithStatus : itemLessThanWithoutStatus); - return true; + /* Not doing this until we import boost::algorithm*/ +// if (boost::is_sorted(displayedChildren_begin(), displayedChildren_.end(), itemLessThan)) { +// return false; +// } + //Sholudn't need stable_sort here + std::sort(displayedChildren_.begin(), displayedChildren_.end(), sortByStatus_? itemLessThanWithStatus : itemLessThanWithoutStatus); + return true; } bool GroupRosterItem::itemLessThanWithoutStatus(const RosterItem* left, const RosterItem* right) { - return left->getSortableDisplayName() < right->getSortableDisplayName(); + return left->getSortableDisplayName() < right->getSortableDisplayName(); } bool GroupRosterItem::itemLessThanWithStatus(const RosterItem* left, const RosterItem* right) { - const ContactRosterItem* leftContact = dynamic_cast(left); - const ContactRosterItem* rightContact = dynamic_cast(right); - if (leftContact) { - if (!rightContact) { - return false; - } - StatusShow::Type leftType = leftContact->getSimplifiedStatusShow(); - StatusShow::Type rightType = rightContact->getSimplifiedStatusShow(); - if (leftType == rightType) { - return left->getSortableDisplayName() < right->getSortableDisplayName(); - } else { - return leftType < rightType; - } - } else { - if (rightContact) { - return true; - } - return left->getSortableDisplayName() < right->getSortableDisplayName(); - } + const ContactRosterItem* leftContact = dynamic_cast(left); + const ContactRosterItem* rightContact = dynamic_cast(right); + if (leftContact) { + if (!rightContact) { + return false; + } + StatusShow::Type leftType = leftContact->getSimplifiedStatusShow(); + StatusShow::Type rightType = rightContact->getSimplifiedStatusShow(); + if (leftType == rightType) { + return left->getSortableDisplayName() < right->getSortableDisplayName(); + } else { + return leftType < rightType; + } + } else { + if (rightContact) { + return true; + } + return left->getSortableDisplayName() < right->getSortableDisplayName(); + } } void GroupRosterItem::setDisplayed(RosterItem* item, bool displayed) { - bool found = false; - for (size_t i = 0; i < displayedChildren_.size(); i++) { - if (displayedChildren_[i] == item) { - found = true; - } - } - if (found == displayed) { - return; - } - if (displayed) { - displayedChildren_.push_back(item); - sortDisplayed(); - } else { - displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), item), displayedChildren_.end()); - } - onChildrenChanged(); - onDataChanged(); + bool found = false; + for (size_t i = 0; i < displayedChildren_.size(); i++) { + if (displayedChildren_[i] == item) { + found = true; + } + } + if (found == displayed) { + return; + } + if (displayed) { + displayedChildren_.push_back(item); + sortDisplayed(); + } else { + displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), item), displayedChildren_.end()); + } + onChildrenChanged(); + onDataChanged(); } void GroupRosterItem::handleDataChanged(RosterItem* /*item*/) { - if (sortDisplayed()) { - onChildrenChanged(); - } + if (sortDisplayed()) { + onChildrenChanged(); + } } void GroupRosterItem::handleChildrenChanged(GroupRosterItem* group) { - size_t oldSize = getDisplayedChildren().size(); - if (group->getDisplayedChildren().size() > 0) { - bool found = false; - for (size_t i = 0; i < displayedChildren_.size(); i++) { - if (displayedChildren_[i] == group) { - found = true; - } - } - if (!found) { - displayedChildren_.push_back(group); - sortDisplayed(); - } - } else { - displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end()); - } - - if (oldSize != getDisplayedChildren().size() || sortDisplayed()) { - onChildrenChanged(); - onDataChanged(); - } + size_t oldSize = getDisplayedChildren().size(); + if (group->getDisplayedChildren().size() > 0) { + bool found = false; + for (size_t i = 0; i < displayedChildren_.size(); i++) { + if (displayedChildren_[i] == group) { + found = true; + } + } + if (!found) { + displayedChildren_.push_back(group); + sortDisplayed(); + } + } else { + displayedChildren_.erase(std::remove(displayedChildren_.begin(), displayedChildren_.end(), group), displayedChildren_.end()); + } + + if (oldSize != getDisplayedChildren().size() || sortDisplayed()) { + onChildrenChanged(); + onDataChanged(); + } } diff --git a/Swift/Controllers/Roster/GroupRosterItem.h b/Swift/Controllers/Roster/GroupRosterItem.h index 9b4024f..760b008 100644 --- a/Swift/Controllers/Roster/GroupRosterItem.h +++ b/Swift/Controllers/Roster/GroupRosterItem.h @@ -15,35 +15,35 @@ namespace Swift { class GroupRosterItem : public RosterItem { - public: - GroupRosterItem(const std::string& name, GroupRosterItem* parent, bool sortByStatus); - virtual ~GroupRosterItem(); - const std::vector& getChildren() const; - const std::vector& getDisplayedChildren() const; - void addChild(RosterItem* item); - ContactRosterItem* removeChild(const JID& jid); - GroupRosterItem* removeGroupChild(const std::string& group); - void removeAll(); - void setDisplayed(RosterItem* item, bool displayed); - boost::signal onChildrenChanged; - static bool itemLessThanWithStatus(const RosterItem* left, const RosterItem* right); - static bool itemLessThanWithoutStatus(const RosterItem* left, const RosterItem* right); - void setExpanded(bool expanded); - bool isExpanded() const; - boost::signal onExpandedChanged; - void setManualSort(const std::string& manualSortValue); - virtual const std::string& getSortableDisplayName() const; - private: - void handleChildrenChanged(GroupRosterItem* group); - void handleDataChanged(RosterItem* item); - bool sortDisplayed(); - std::string name_; - bool expanded_; - std::vector children_; - std::vector displayedChildren_; - bool sortByStatus_; - bool manualSort_; - std::string manualSortValue_; + public: + GroupRosterItem(const std::string& name, GroupRosterItem* parent, bool sortByStatus); + virtual ~GroupRosterItem(); + const std::vector& getChildren() const; + const std::vector& getDisplayedChildren() const; + void addChild(RosterItem* item); + ContactRosterItem* removeChild(const JID& jid); + GroupRosterItem* removeGroupChild(const std::string& group); + void removeAll(); + void setDisplayed(RosterItem* item, bool displayed); + boost::signal onChildrenChanged; + static bool itemLessThanWithStatus(const RosterItem* left, const RosterItem* right); + static bool itemLessThanWithoutStatus(const RosterItem* left, const RosterItem* right); + void setExpanded(bool expanded); + bool isExpanded() const; + boost::signal onExpandedChanged; + void setManualSort(const std::string& manualSortValue); + virtual const std::string& getSortableDisplayName() const; + private: + void handleChildrenChanged(GroupRosterItem* group); + void handleDataChanged(RosterItem* item); + bool sortDisplayed(); + std::string name_; + bool expanded_; + std::vector children_; + std::vector displayedChildren_; + bool sortByStatus_; + bool manualSort_; + std::string manualSortValue_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/AppearOffline.h b/Swift/Controllers/Roster/ItemOperations/AppearOffline.h index e59e01b..c57974b 100644 --- a/Swift/Controllers/Roster/ItemOperations/AppearOffline.h +++ b/Swift/Controllers/Roster/ItemOperations/AppearOffline.h @@ -14,16 +14,16 @@ namespace Swift { class RosterItem; class AppearOffline : public RosterItemOperation { - public: - AppearOffline() { - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (contact) { - contact->clearPresence(); - } - } + public: + AppearOffline() { + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (contact) { + contact->clearPresence(); + } + } }; diff --git a/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h b/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h index 833c863..76227c0 100644 --- a/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h +++ b/Swift/Controllers/Roster/ItemOperations/RosterItemOperation.h @@ -11,20 +11,20 @@ namespace Swift { class RosterItemOperation { - public: - RosterItemOperation(bool requiresLookup = false, const JID& lookupJID = JID()) : requiresLookup_(requiresLookup), lookupJID_(lookupJID) {} - virtual ~RosterItemOperation() {} - bool requiresLookup() const {return requiresLookup_;} - const JID& lookupJID() const {return lookupJID_;} - /** - * This is called when iterating over possible subjects, so must check it's - * applying to the right items - even if requiresLookup() is true an item - * with the same bare JID but different full JID may be passed. - */ - virtual void operator() (RosterItem*) const = 0; - private: - bool requiresLookup_; - JID lookupJID_; + public: + RosterItemOperation(bool requiresLookup = false, const JID& lookupJID = JID()) : requiresLookup_(requiresLookup), lookupJID_(lookupJID) {} + virtual ~RosterItemOperation() {} + bool requiresLookup() const {return requiresLookup_;} + const JID& lookupJID() const {return lookupJID_;} + /** + * This is called when iterating over possible subjects, so must check it's + * applying to the right items - even if requiresLookup() is true an item + * with the same bare JID but different full JID may be passed. + */ + virtual void operator() (RosterItem*) const = 0; + private: + bool requiresLookup_; + JID lookupJID_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h b/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h index b19b95a..29f9722 100644 --- a/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h +++ b/Swift/Controllers/Roster/ItemOperations/SetAvailableFeatures.h @@ -22,21 +22,21 @@ namespace Swift { class RosterItem; class SetAvailableFeatures : public RosterItemOperation { - public: - SetAvailableFeatures(const JID& jid, const std::set& availableFeatures, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), availableFeatures_(availableFeatures), compareType_(compareType) { - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (contact && contact->getJID().equals(jid_, compareType_)) { - contact->setSupportedFeatures(availableFeatures_); - } - } - - private: - JID jid_; - std::set availableFeatures_; - JID::CompareType compareType_; + public: + SetAvailableFeatures(const JID& jid, const std::set& availableFeatures, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), availableFeatures_(availableFeatures), compareType_(compareType) { + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (contact && contact->getJID().equals(jid_, compareType_)) { + contact->setSupportedFeatures(availableFeatures_); + } + } + + private: + JID jid_; + std::set availableFeatures_; + JID::CompareType compareType_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/SetAvatar.h b/Swift/Controllers/Roster/ItemOperations/SetAvatar.h index 211321e..d47c921 100644 --- a/Swift/Controllers/Roster/ItemOperations/SetAvatar.h +++ b/Swift/Controllers/Roster/ItemOperations/SetAvatar.h @@ -19,21 +19,21 @@ namespace Swift { class RosterItem; class SetAvatar : public RosterItemOperation { - public: - SetAvatar(const JID& jid, const boost::filesystem::path& path, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), path_(path), compareType_(compareType) { - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (contact && contact->getJID().equals(jid_, compareType_)) { - contact->setAvatarPath(path_); - } - } - - private: - JID jid_; - boost::filesystem::path path_; - JID::CompareType compareType_; + public: + SetAvatar(const JID& jid, const boost::filesystem::path& path, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), path_(path), compareType_(compareType) { + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (contact && contact->getJID().equals(jid_, compareType_)) { + contact->setAvatarPath(path_); + } + } + + private: + JID jid_; + boost::filesystem::path path_; + JID::CompareType compareType_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h b/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h index 098eeb5..818d9b4 100644 --- a/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h +++ b/Swift/Controllers/Roster/ItemOperations/SetBlockingState.h @@ -22,30 +22,30 @@ namespace Swift { class RosterItem; class SetBlockingState : public RosterItemOperation { - public: - SetBlockingState(const JID& jid, ContactRosterItem::BlockState state, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(!jid.getNode().empty(), jid), jid_(jid), state_(state), compareType_(compareType) { - if (state_ == ContactRosterItem::IsBlocked && jid.getNode().empty()) { - state_ = ContactRosterItem::IsDomainBlocked; - } - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (jid_.getNode().empty()) { - if (contact && contact->getJID().getDomain() == jid_.getDomain()) { - contact->setBlockState(state_); - } - } else { - if (contact && contact->getJID().equals(jid_, compareType_)) { - contact->setBlockState(state_); - } - } - } - - private: - JID jid_; - ContactRosterItem::BlockState state_; - JID::CompareType compareType_; + public: + SetBlockingState(const JID& jid, ContactRosterItem::BlockState state, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(!jid.getNode().empty(), jid), jid_(jid), state_(state), compareType_(compareType) { + if (state_ == ContactRosterItem::IsBlocked && jid.getNode().empty()) { + state_ = ContactRosterItem::IsDomainBlocked; + } + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (jid_.getNode().empty()) { + if (contact && contact->getJID().getDomain() == jid_.getDomain()) { + contact->setBlockState(state_); + } + } else { + if (contact && contact->getJID().equals(jid_, compareType_)) { + contact->setBlockState(state_); + } + } + } + + private: + JID jid_; + ContactRosterItem::BlockState state_; + JID::CompareType compareType_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/SetMUC.h b/Swift/Controllers/Roster/ItemOperations/SetMUC.h index 8a4a0c6..7640c24 100644 --- a/Swift/Controllers/Roster/ItemOperations/SetMUC.h +++ b/Swift/Controllers/Roster/ItemOperations/SetMUC.h @@ -16,23 +16,23 @@ namespace Swift { class RosterItem; class SetMUC : public RosterItemOperation { - public: - SetMUC(const JID& jid, const MUCOccupant::Role& role, const MUCOccupant::Affiliation& affiliation) - : RosterItemOperation(true, jid), jid_(jid), mucRole_(role), mucAffiliation_(affiliation) { - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (contact && contact->getJID().equals(jid_, JID::WithResource)) { - contact->setMUCRole(mucRole_); - contact->setMUCAffiliation(mucAffiliation_); - } - } - - private: - JID jid_; - MUCOccupant::Role mucRole_; - MUCOccupant::Affiliation mucAffiliation_; + public: + SetMUC(const JID& jid, const MUCOccupant::Role& role, const MUCOccupant::Affiliation& affiliation) + : RosterItemOperation(true, jid), jid_(jid), mucRole_(role), mucAffiliation_(affiliation) { + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (contact && contact->getJID().equals(jid_, JID::WithResource)) { + contact->setMUCRole(mucRole_); + contact->setMUCAffiliation(mucAffiliation_); + } + } + + private: + JID jid_; + MUCOccupant::Role mucRole_; + MUCOccupant::Affiliation mucAffiliation_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/SetName.h b/Swift/Controllers/Roster/ItemOperations/SetName.h index 9f8a0b9..fa0694d 100644 --- a/Swift/Controllers/Roster/ItemOperations/SetName.h +++ b/Swift/Controllers/Roster/ItemOperations/SetName.h @@ -16,21 +16,21 @@ namespace Swift { class RosterItem; class SetName : public RosterItemOperation { - public: - SetName(const std::string& name, const JID& jid, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), name_(name), jid_(jid), compareType_(compareType) { - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (contact && contact->getJID().equals(jid_, compareType_)) { - contact->setDisplayName(name_); - } - } - - private: - std::string name_; - JID jid_; - JID::CompareType compareType_; + public: + SetName(const std::string& name, const JID& jid, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), name_(name), jid_(jid), compareType_(compareType) { + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (contact && contact->getJID().equals(jid_, compareType_)) { + contact->setDisplayName(name_); + } + } + + private: + std::string name_; + JID jid_; + JID::CompareType compareType_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/SetPresence.h b/Swift/Controllers/Roster/ItemOperations/SetPresence.h index 2b5bbbe..fc39e5c 100644 --- a/Swift/Controllers/Roster/ItemOperations/SetPresence.h +++ b/Swift/Controllers/Roster/ItemOperations/SetPresence.h @@ -17,20 +17,20 @@ namespace Swift { class RosterItem; class SetPresence : public RosterItemOperation { - public: - SetPresence(Presence::ref presence, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, compareType == JID::WithoutResource ? presence->getFrom().toBare() : presence->getFrom()), presence_(presence), compareType_(compareType) { - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (contact && contact->getJID().equals(presence_->getFrom(), compareType_)) { - contact->applyPresence(presence_); - } - } - - private: - Presence::ref presence_; - JID::CompareType compareType_; + public: + SetPresence(Presence::ref presence, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, compareType == JID::WithoutResource ? presence->getFrom().toBare() : presence->getFrom()), presence_(presence), compareType_(compareType) { + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (contact && contact->getJID().equals(presence_->getFrom(), compareType_)) { + contact->applyPresence(presence_); + } + } + + private: + Presence::ref presence_; + JID::CompareType compareType_; }; } diff --git a/Swift/Controllers/Roster/ItemOperations/SetVCard.h b/Swift/Controllers/Roster/ItemOperations/SetVCard.h index e1744b9..278ae56 100644 --- a/Swift/Controllers/Roster/ItemOperations/SetVCard.h +++ b/Swift/Controllers/Roster/ItemOperations/SetVCard.h @@ -23,21 +23,21 @@ namespace Swift { class RosterItem; class SetVCard : public RosterItemOperation { - public: - SetVCard(const JID& jid, VCard::ref vcard, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), vcard_(vcard), compareType_(compareType) { - } - - virtual void operator() (RosterItem* item) const { - ContactRosterItem* contact = dynamic_cast(item); - if (contact && contact->getJID().equals(jid_, compareType_)) { - contact->setVCard(vcard_); - } - } - - private: - JID jid_; - VCard::ref vcard_; - JID::CompareType compareType_; + public: + SetVCard(const JID& jid, VCard::ref vcard, JID::CompareType compareType = JID::WithoutResource) : RosterItemOperation(true, jid), jid_(jid), vcard_(vcard), compareType_(compareType) { + } + + virtual void operator() (RosterItem* item) const { + ContactRosterItem* contact = dynamic_cast(item); + if (contact && contact->getJID().equals(jid_, compareType_)) { + contact->setVCard(vcard_); + } + } + + private: + JID jid_; + VCard::ref vcard_; + JID::CompareType compareType_; }; } diff --git a/Swift/Controllers/Roster/LeastCommonSubsequence.h b/Swift/Controllers/Roster/LeastCommonSubsequence.h index e7b9370..8daa20c 100644 --- a/Swift/Controllers/Roster/LeastCommonSubsequence.h +++ b/Swift/Controllers/Roster/LeastCommonSubsequence.h @@ -11,98 +11,98 @@ #include namespace Swift { - using std::equal_to; + using std::equal_to; - namespace Detail { - template - void computeLeastCommonSubsequenceMatrix(XIt xBegin, XIt xEnd, YIt yBegin, YIt yEnd, std::vector& result) { - size_t width = static_cast(std::distance(xBegin, xEnd) + 1); - size_t height = static_cast(std::distance(yBegin, yEnd) + 1); - result.resize(width * height); + namespace Detail { + template + void computeLeastCommonSubsequenceMatrix(XIt xBegin, XIt xEnd, YIt yBegin, YIt yEnd, std::vector& result) { + size_t width = static_cast(std::distance(xBegin, xEnd) + 1); + size_t height = static_cast(std::distance(yBegin, yEnd) + 1); + result.resize(width * height); - // Initialize first row & column - for (size_t i = 0; i < width; ++i) { - result[i] = 0; - } - for (size_t j = 0; j < height; ++j) { - result[j*width] = 0; - } + // Initialize first row & column + for (size_t i = 0; i < width; ++i) { + result[i] = 0; + } + for (size_t j = 0; j < height; ++j) { + result[j*width] = 0; + } - // Compute the LCS lengths for subsets - Predicate predicate; - for (size_t i = 1; i < width; ++i) { - for (size_t j = 1; j < height; ++j) { - result[i + j*width] = predicate(*(xBegin + boost::numeric_cast(i)-1), *(yBegin + boost::numeric_cast(j)-1)) ? result[(i-1) + (j-1)*width] + 1 : std::max(result[i + (j-1)*width], result[i-1 + (j*width)]); - } - } - } - } + // Compute the LCS lengths for subsets + Predicate predicate; + for (size_t i = 1; i < width; ++i) { + for (size_t j = 1; j < height; ++j) { + result[i + j*width] = predicate(*(xBegin + boost::numeric_cast(i)-1), *(yBegin + boost::numeric_cast(j)-1)) ? result[(i-1) + (j-1)*width] + 1 : std::max(result[i + (j-1)*width], result[i-1 + (j*width)]); + } + } + } + } - template - void computeIndexDiff(const std::vector& x, const std::vector& y, std::vector& updates, std::vector& postUpdates, std::vector& removes, std::vector& inserts) { - InsertRemovePredicate insertRemovePredicate; - UpdatePredicate updatePredicate; + template + void computeIndexDiff(const std::vector& x, const std::vector& y, std::vector& updates, std::vector& postUpdates, std::vector& removes, std::vector& inserts) { + InsertRemovePredicate insertRemovePredicate; + UpdatePredicate updatePredicate; - // Find & handle common prefix (Optimization to reduce LCS matrix size) - typename std::vector::const_iterator xBegin = x.begin(); - typename std::vector::const_iterator yBegin = y.begin(); - while (xBegin < x.end() && yBegin < y.end() && insertRemovePredicate(*xBegin, *yBegin)) { - if (updatePredicate(*xBegin, *yBegin)) { - updates.push_back(static_cast(std::distance(x.begin(), xBegin))); - postUpdates.push_back(static_cast(std::distance(y.begin(), yBegin))); - } - ++xBegin; - ++yBegin; - } - size_t prefixLength = static_cast(std::distance(x.begin(), xBegin)); + // Find & handle common prefix (Optimization to reduce LCS matrix size) + typename std::vector::const_iterator xBegin = x.begin(); + typename std::vector::const_iterator yBegin = y.begin(); + while (xBegin < x.end() && yBegin < y.end() && insertRemovePredicate(*xBegin, *yBegin)) { + if (updatePredicate(*xBegin, *yBegin)) { + updates.push_back(static_cast(std::distance(x.begin(), xBegin))); + postUpdates.push_back(static_cast(std::distance(y.begin(), yBegin))); + } + ++xBegin; + ++yBegin; + } + size_t prefixLength = static_cast(std::distance(x.begin(), xBegin)); - // Find & handle common suffix (Optimization to reduce LCS matrix size) - typename std::vector::const_reverse_iterator xEnd = x.rbegin(); - typename std::vector::const_reverse_iterator yEnd = y.rbegin(); - while (xEnd.base() > xBegin && yEnd.base() > yBegin && insertRemovePredicate(*xEnd, *yEnd)) { - if (updatePredicate(*xEnd, *yEnd)) { - updates.push_back(static_cast(std::distance(x.begin(), xEnd.base()) - 1)); - postUpdates.push_back(static_cast(std::distance(y.begin(), yEnd.base()) - 1)); - } - ++xEnd; - ++yEnd; - } + // Find & handle common suffix (Optimization to reduce LCS matrix size) + typename std::vector::const_reverse_iterator xEnd = x.rbegin(); + typename std::vector::const_reverse_iterator yEnd = y.rbegin(); + while (xEnd.base() > xBegin && yEnd.base() > yBegin && insertRemovePredicate(*xEnd, *yEnd)) { + if (updatePredicate(*xEnd, *yEnd)) { + updates.push_back(static_cast(std::distance(x.begin(), xEnd.base()) - 1)); + postUpdates.push_back(static_cast(std::distance(y.begin(), yEnd.base()) - 1)); + } + ++xEnd; + ++yEnd; + } - // Compute lengths - size_t xLength = static_cast(std::distance(xBegin, xEnd.base())); - size_t yLength = static_cast(std::distance(yBegin, yEnd.base())); + // Compute lengths + size_t xLength = static_cast(std::distance(xBegin, xEnd.base())); + size_t yLength = static_cast(std::distance(yBegin, yEnd.base())); - // Compute LCS matrix - std::vector lcs; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, typename std::vector::const_iterator, unsigned int, InsertRemovePredicate>(xBegin, xEnd.base(), yBegin, yEnd.base(), lcs); + // Compute LCS matrix + std::vector lcs; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, typename std::vector::const_iterator, unsigned int, InsertRemovePredicate>(xBegin, xEnd.base(), yBegin, yEnd.base(), lcs); - // Process LCS matrix - size_t i = xLength; - size_t j = yLength; - size_t width = xLength + 1; - while (true) { - if (i > 0 && j > 0 && insertRemovePredicate(x[prefixLength + i-1], y[prefixLength + j-1])) { - // x[i-1] same - if (updatePredicate(x[prefixLength + i - 1], y[prefixLength + j - 1])) { - updates.push_back(prefixLength + i-1); - postUpdates.push_back(prefixLength + j-1); - } - i -= 1; - j -= 1; - } - else if (j > 0 && (i == 0 || lcs[i + (j-1)*width] >= lcs[i-1 + j*width])) { - // y[j-1] added - inserts.push_back(prefixLength + j-1); - j -= 1; - } - else if (i > 0 && (j == 0 || lcs[i + (j-1)*width] < lcs[i-1 + j*width])) { - // x[i-1] removed - removes.push_back(prefixLength + i-1); - i -= 1; - } - else { - break; - } - } - } + // Process LCS matrix + size_t i = xLength; + size_t j = yLength; + size_t width = xLength + 1; + while (true) { + if (i > 0 && j > 0 && insertRemovePredicate(x[prefixLength + i-1], y[prefixLength + j-1])) { + // x[i-1] same + if (updatePredicate(x[prefixLength + i - 1], y[prefixLength + j - 1])) { + updates.push_back(prefixLength + i-1); + postUpdates.push_back(prefixLength + j-1); + } + i -= 1; + j -= 1; + } + else if (j > 0 && (i == 0 || lcs[i + (j-1)*width] >= lcs[i-1 + j*width])) { + // y[j-1] added + inserts.push_back(prefixLength + j-1); + j -= 1; + } + else if (i > 0 && (j == 0 || lcs[i + (j-1)*width] < lcs[i-1 + j*width])) { + // x[i-1] removed + removes.push_back(prefixLength + i-1); + i -= 1; + } + else { + break; + } + } + } } diff --git a/Swift/Controllers/Roster/OfflineRosterFilter.h b/Swift/Controllers/Roster/OfflineRosterFilter.h index d25d073..033eecb 100644 --- a/Swift/Controllers/Roster/OfflineRosterFilter.h +++ b/Swift/Controllers/Roster/OfflineRosterFilter.h @@ -15,12 +15,12 @@ namespace Swift { class OfflineRosterFilter : public RosterFilter { - public: - virtual ~OfflineRosterFilter() {} - virtual bool operator() (RosterItem *item) const { - ContactRosterItem *contactItem = dynamic_cast(item); - return contactItem && contactItem->getStatusShow() == StatusShow::None; - } + public: + virtual ~OfflineRosterFilter() {} + virtual bool operator() (RosterItem *item) const { + ContactRosterItem *contactItem = dynamic_cast(item); + return contactItem && contactItem->getStatusShow() == StatusShow::None; + } }; } diff --git a/Swift/Controllers/Roster/Roster.cpp b/Swift/Controllers/Roster/Roster.cpp index 77d6b78..2e68fd4 100644 --- a/Swift/Controllers/Roster/Roster.cpp +++ b/Swift/Controllers/Roster/Roster.cpp @@ -23,252 +23,252 @@ namespace Swift { Roster::Roster(bool sortByStatus, bool fullJIDMapping) : blockingSupported_(false) { - sortByStatus_ = sortByStatus; - fullJIDMapping_ = fullJIDMapping; - root_ = new GroupRosterItem("Dummy-Root", NULL, sortByStatus_); - root_->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, root_)); + sortByStatus_ = sortByStatus; + fullJIDMapping_ = fullJIDMapping; + root_ = new GroupRosterItem("Dummy-Root", NULL, sortByStatus_); + root_->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, root_)); } Roster::~Roster() { - std::deque queue; - queue.push_back(root_); - while (!queue.empty()) { - RosterItem* item = *queue.begin(); - queue.pop_front(); - GroupRosterItem* group = dynamic_cast(item); - if (group) { - queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); - } - ContactRosterItem* contact = dynamic_cast(item); - if (contact) { - contact->onVCardRequested.disconnect(boost::bind(boost::ref(onVCardUpdateRequested), contact->getJID())); - } - delete item; - } + std::deque queue; + queue.push_back(root_); + while (!queue.empty()) { + RosterItem* item = *queue.begin(); + queue.pop_front(); + GroupRosterItem* group = dynamic_cast(item); + if (group) { + queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); + } + ContactRosterItem* contact = dynamic_cast(item); + if (contact) { + contact->onVCardRequested.disconnect(boost::bind(boost::ref(onVCardUpdateRequested), contact->getJID())); + } + delete item; + } } GroupRosterItem* Roster::getRoot() const { - return root_; + return root_; } std::set Roster::getJIDs() const { - std::set jids; - - std::deque queue; - queue.push_back(root_); - while (!queue.empty()) { - RosterItem* item = *queue.begin(); - queue.pop_front(); - GroupRosterItem* group = dynamic_cast(item); - ContactRosterItem *contact = dynamic_cast(item); - if (contact) { - jids.insert(contact->getJID()); - jids.insert(contact->getDisplayJID()); - } - else if (group) { - queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); - } - } - - return jids; + std::set jids; + + std::deque queue; + queue.push_back(root_); + while (!queue.empty()) { + RosterItem* item = *queue.begin(); + queue.pop_front(); + GroupRosterItem* group = dynamic_cast(item); + ContactRosterItem *contact = dynamic_cast(item); + if (contact) { + jids.insert(contact->getJID()); + jids.insert(contact->getDisplayJID()); + } + else if (group) { + queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); + } + } + + return jids; } GroupRosterItem* Roster::getGroup(const std::string& groupName) { - foreach (RosterItem *item, root_->getChildren()) { - GroupRosterItem *group = dynamic_cast(item); - if (group && group->getDisplayName() == groupName) { - return group; - } - } - GroupRosterItem* group = new GroupRosterItem(groupName, root_, sortByStatus_); - root_->addChild(group); - group->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, group)); - group->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, group)); - return group; + foreach (RosterItem *item, root_->getChildren()) { + GroupRosterItem *group = dynamic_cast(item); + if (group && group->getDisplayName() == groupName) { + return group; + } + } + GroupRosterItem* group = new GroupRosterItem(groupName, root_, sortByStatus_); + root_->addChild(group); + group->onChildrenChanged.connect(boost::bind(&Roster::handleChildrenChanged, this, group)); + group->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, group)); + return group; } void Roster::setBlockingSupported(bool isSupported) { - if (!blockingSupported_) { - foreach(ItemMap::value_type i, itemMap_) { - foreach(ContactRosterItem* item, i.second) { - item->setBlockState(ContactRosterItem::IsUnblocked); - } - } - } - blockingSupported_ = isSupported; + if (!blockingSupported_) { + foreach(ItemMap::value_type i, itemMap_) { + foreach(ContactRosterItem* item, i.second) { + item->setBlockState(ContactRosterItem::IsUnblocked); + } + } + } + blockingSupported_ = isSupported; } void Roster::removeGroup(const std::string& group) { - root_->removeGroupChild(group); + root_->removeGroupChild(group); } void Roster::handleDataChanged(RosterItem* item) { - onDataChanged(item); + onDataChanged(item); } void Roster::handleChildrenChanged(GroupRosterItem* item) { - onChildrenChanged(item); + onChildrenChanged(item); } void Roster::addContact(const JID& jid, const JID& displayJID, const std::string& name, const std::string& groupName, const boost::filesystem::path& avatarPath) { - GroupRosterItem* group(getGroup(groupName)); - ContactRosterItem *item = new ContactRosterItem(jid, displayJID, name, group); - item->onVCardRequested.connect(boost::bind(boost::ref(onVCardUpdateRequested), jid)); - item->setAvatarPath(avatarPath); - if (blockingSupported_) { - item->setBlockState(ContactRosterItem::IsUnblocked); - } - group->addChild(item); - ItemMap::iterator i = itemMap_.insert(std::make_pair(fullJIDMapping_ ? jid : jid.toBare(), std::vector())).first; - if (!i->second.empty()) { - foreach (const std::string& existingGroup, i->second[0]->getGroups()) { - item->addGroup(existingGroup); - } - } - i->second.push_back(item); - item->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, item)); - filterContact(item, group); - - foreach (ContactRosterItem* item, i->second) { - item->addGroup(groupName); - } + GroupRosterItem* group(getGroup(groupName)); + ContactRosterItem *item = new ContactRosterItem(jid, displayJID, name, group); + item->onVCardRequested.connect(boost::bind(boost::ref(onVCardUpdateRequested), jid)); + item->setAvatarPath(avatarPath); + if (blockingSupported_) { + item->setBlockState(ContactRosterItem::IsUnblocked); + } + group->addChild(item); + ItemMap::iterator i = itemMap_.insert(std::make_pair(fullJIDMapping_ ? jid : jid.toBare(), std::vector())).first; + if (!i->second.empty()) { + foreach (const std::string& existingGroup, i->second[0]->getGroups()) { + item->addGroup(existingGroup); + } + } + i->second.push_back(item); + item->onDataChanged.connect(boost::bind(&Roster::handleDataChanged, this, item)); + filterContact(item, group); + + foreach (ContactRosterItem* item, i->second) { + item->addGroup(groupName); + } } struct JIDEqualsTo { - JIDEqualsTo(const JID& jid) : jid(jid) {} - bool operator()(ContactRosterItem* i) const { return jid == i->getJID(); } - JID jid; + JIDEqualsTo(const JID& jid) : jid(jid) {} + bool operator()(ContactRosterItem* i) const { return jid == i->getJID(); } + JID jid; }; void Roster::removeAll() { - root_->removeAll(); - itemMap_.clear(); - onChildrenChanged(root_); - onDataChanged(root_); + root_->removeAll(); + itemMap_.clear(); + onChildrenChanged(root_); + onDataChanged(root_); } void Roster::removeContact(const JID& jid) { - ItemMap::iterator item = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare()); - if (item != itemMap_.end()) { - std::vector& items = item->second; - items.erase(std::remove_if(items.begin(), items.end(), JIDEqualsTo(jid)), items.end()); - if (items.empty()) { - itemMap_.erase(item); - } - } - //Causes the delete - root_->removeChild(jid); + ItemMap::iterator item = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare()); + if (item != itemMap_.end()) { + std::vector& items = item->second; + items.erase(std::remove_if(items.begin(), items.end(), JIDEqualsTo(jid)), items.end()); + if (items.empty()) { + itemMap_.erase(item); + } + } + //Causes the delete + root_->removeChild(jid); } void Roster::removeContactFromGroup(const JID& jid, const std::string& groupName) { - std::vector children = root_->getChildren(); - std::vector::iterator it = children.begin(); - ItemMap::iterator itemIt = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare()); - while (it != children.end()) { - GroupRosterItem* group = dynamic_cast(*it); - if (group && group->getDisplayName() == groupName) { - ContactRosterItem* deleted = group->removeChild(jid); - if (itemIt != itemMap_.end()) { - std::vector& items = itemIt->second; - items.erase(std::remove(items.begin(), items.end(), deleted), items.end()); - } - } - ++it; - } - - if (itemIt != itemMap_.end()) { - foreach (ContactRosterItem* item, itemIt->second) { - item->removeGroup(groupName); - } - } + std::vector children = root_->getChildren(); + std::vector::iterator it = children.begin(); + ItemMap::iterator itemIt = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare()); + while (it != children.end()) { + GroupRosterItem* group = dynamic_cast(*it); + if (group && group->getDisplayName() == groupName) { + ContactRosterItem* deleted = group->removeChild(jid); + if (itemIt != itemMap_.end()) { + std::vector& items = itemIt->second; + items.erase(std::remove(items.begin(), items.end(), deleted), items.end()); + } + } + ++it; + } + + if (itemIt != itemMap_.end()) { + foreach (ContactRosterItem* item, itemIt->second) { + item->removeGroup(groupName); + } + } } void Roster::applyOnItems(const RosterItemOperation& operation) { - if (operation.requiresLookup()) { - applyOnItem(operation, operation.lookupJID()); - } else { - applyOnAllItems(operation); - } + if (operation.requiresLookup()) { + applyOnItem(operation, operation.lookupJID()); + } else { + applyOnAllItems(operation); + } } void Roster::applyOnItem(const RosterItemOperation& operation, const JID& jid) { - ItemMap::iterator i = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare()); - if (i == itemMap_.end()) { - return; - } - foreach (ContactRosterItem* item, i->second) { - operation(item); - filterContact(item, item->getParent()); - } + ItemMap::iterator i = itemMap_.find(fullJIDMapping_ ? jid : jid.toBare()); + if (i == itemMap_.end()) { + return; + } + foreach (ContactRosterItem* item, i->second) { + operation(item); + filterContact(item, item->getParent()); + } } void Roster::applyOnAllItems(const RosterItemOperation& operation) { - std::deque queue; - queue.push_back(root_); - while (!queue.empty()) { - RosterItem* item = *queue.begin(); - queue.pop_front(); - operation(item); - GroupRosterItem* group = dynamic_cast(item); - if (group) { - queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); - } - } - filterAll(); + std::deque queue; + queue.push_back(root_); + while (!queue.empty()) { + RosterItem* item = *queue.begin(); + queue.pop_front(); + operation(item); + GroupRosterItem* group = dynamic_cast(item); + if (group) { + queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); + } + } + filterAll(); } void Roster::addFilter(RosterFilter* filter) { - filters_.push_back(filter); - filterAll(); - onFilterAdded(filter); + filters_.push_back(filter); + filterAll(); + onFilterAdded(filter); } void Roster::removeFilter(RosterFilter* filter) { - for (unsigned int i = 0; i < filters_.size(); i++) { - if (filters_[i] == filter) { - filters_.erase(filters_.begin() + i); - break; - } - } - filterAll(); - onFilterRemoved(filter); + for (unsigned int i = 0; i < filters_.size(); i++) { + if (filters_[i] == filter) { + filters_.erase(filters_.begin() + i); + break; + } + } + filterAll(); + onFilterRemoved(filter); } void Roster::filterContact(ContactRosterItem* contact, GroupRosterItem* group) { - size_t oldDisplayedSize = group->getDisplayedChildren().size(); - bool hide = true; - foreach (RosterFilter *filter, filters_) { - hide &= (*filter)(contact); - } - group->setDisplayed(contact, filters_.empty() || !hide); - size_t newDisplayedSize = group->getDisplayedChildren().size(); - if (oldDisplayedSize == 0 && newDisplayedSize > 0) { - onGroupAdded(group); - } + size_t oldDisplayedSize = group->getDisplayedChildren().size(); + bool hide = true; + foreach (RosterFilter *filter, filters_) { + hide &= (*filter)(contact); + } + group->setDisplayed(contact, filters_.empty() || !hide); + size_t newDisplayedSize = group->getDisplayedChildren().size(); + if (oldDisplayedSize == 0 && newDisplayedSize > 0) { + onGroupAdded(group); + } } void Roster::filterGroup(GroupRosterItem* group) { - foreach (RosterItem* child, group->getChildren()) { - ContactRosterItem* contact = dynamic_cast(child); - if (contact) { - filterContact(contact, group); - } - } + foreach (RosterItem* child, group->getChildren()) { + ContactRosterItem* contact = dynamic_cast(child); + if (contact) { + filterContact(contact, group); + } + } } void Roster::filterAll() { - std::deque queue; - queue.push_back(root_); - while (!queue.empty()) { - RosterItem *item = *queue.begin(); - queue.pop_front(); - GroupRosterItem* group = dynamic_cast(item); - if (group) { - queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); - filterGroup(group); - } - } + std::deque queue; + queue.push_back(root_); + while (!queue.empty()) { + RosterItem *item = *queue.begin(); + queue.pop_front(); + GroupRosterItem* group = dynamic_cast(item); + if (group) { + queue.insert(queue.begin(), group->getChildren().begin(), group->getChildren().end()); + filterGroup(group); + } + } } } diff --git a/Swift/Controllers/Roster/Roster.h b/Swift/Controllers/Roster/Roster.h index 269ec4d..70e5bab 100644 --- a/Swift/Controllers/Roster/Roster.h +++ b/Swift/Controllers/Roster/Roster.h @@ -27,46 +27,46 @@ class GroupRosterItem; class ContactRosterItem; class Roster { - public: - Roster(bool sortByStatus = true, bool fullJIDMapping = false); - ~Roster(); + public: + Roster(bool sortByStatus = true, bool fullJIDMapping = false); + ~Roster(); - void addContact(const JID& jid, const JID& displayJID, const std::string& name, const std::string& group, const boost::filesystem::path& avatarPath); - void removeContact(const JID& jid); - void removeContactFromGroup(const JID& jid, const std::string& group); - void removeGroup(const std::string& group); - void removeAll(); - void applyOnItems(const RosterItemOperation& operation); - void applyOnAllItems(const RosterItemOperation& operation); - void applyOnItem(const RosterItemOperation& operation, const JID& jid); - void addFilter(RosterFilter* filter); - void removeFilter(RosterFilter* filter); - GroupRosterItem* getRoot() const; - std::set getJIDs() const; + void addContact(const JID& jid, const JID& displayJID, const std::string& name, const std::string& group, const boost::filesystem::path& avatarPath); + void removeContact(const JID& jid); + void removeContactFromGroup(const JID& jid, const std::string& group); + void removeGroup(const std::string& group); + void removeAll(); + void applyOnItems(const RosterItemOperation& operation); + void applyOnAllItems(const RosterItemOperation& operation); + void applyOnItem(const RosterItemOperation& operation, const JID& jid); + void addFilter(RosterFilter* filter); + void removeFilter(RosterFilter* filter); + GroupRosterItem* getRoot() const; + std::set getJIDs() const; - std::vector getFilters() {return filters_;} - boost::signal onChildrenChanged; - boost::signal onGroupAdded; - boost::signal onDataChanged; - boost::signal onVCardUpdateRequested; - boost::signal onFilterAdded; - boost::signal onFilterRemoved; - GroupRosterItem* getGroup(const std::string& groupName); - void setBlockingSupported(bool isSupported); + std::vector getFilters() {return filters_;} + boost::signal onChildrenChanged; + boost::signal onGroupAdded; + boost::signal onDataChanged; + boost::signal onVCardUpdateRequested; + boost::signal onFilterAdded; + boost::signal onFilterRemoved; + GroupRosterItem* getGroup(const std::string& groupName); + void setBlockingSupported(bool isSupported); - private: - void handleDataChanged(RosterItem* item); - void handleChildrenChanged(GroupRosterItem* item); - void filterGroup(GroupRosterItem* item); - void filterContact(ContactRosterItem* contact, GroupRosterItem* group); - void filterAll(); - GroupRosterItem* root_; - std::vector filters_; - typedef std::map > ItemMap; - ItemMap itemMap_; - bool fullJIDMapping_; - bool sortByStatus_; - bool blockingSupported_; + private: + void handleDataChanged(RosterItem* item); + void handleChildrenChanged(GroupRosterItem* item); + void filterGroup(GroupRosterItem* item); + void filterContact(ContactRosterItem* contact, GroupRosterItem* group); + void filterAll(); + GroupRosterItem* root_; + std::vector filters_; + typedef std::map > ItemMap; + ItemMap itemMap_; + bool fullJIDMapping_; + bool sortByStatus_; + bool blockingSupported_; }; } diff --git a/Swift/Controllers/Roster/RosterController.cpp b/Swift/Controllers/Roster/RosterController.cpp index 4fbdea4..e391f41 100644 --- a/Swift/Controllers/Roster/RosterController.cpp +++ b/Swift/Controllers/Roster/RosterController.cpp @@ -62,354 +62,354 @@ namespace Swift { * The controller does not gain ownership of these parameters. */ RosterController::RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter, SettingsProvider* settings, EntityCapsProvider* entityCapsManager, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager) - : myJID_(jid), xmppRoster_(xmppRoster), mainWindowFactory_(mainWindowFactory), mainWindow_(mainWindowFactory_->createMainWindow(uiEventStream)), roster_(new Roster()), offlineFilter_(new OfflineRosterFilter()), vcardManager_(vcardManager), avatarManager_(avatarManager), nickManager_(nickManager), nickResolver_(nickResolver), presenceOracle_(presenceOracle), uiEventStream_(uiEventStream), entityCapsManager_(entityCapsManager), ftOverview_(fileTransferOverview), clientBlockListManager_(clientBlockListManager) { - assert(fileTransferOverview); - iqRouter_ = iqRouter; - subscriptionManager_ = subscriptionManager; - eventController_ = eventController; - settings_ = settings; - expandiness_ = new RosterGroupExpandinessPersister(roster_, settings); - mainWindow_->setRosterModel(roster_); - rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithoutResource); - - changeStatusConnection_ = mainWindow_->onChangeStatusRequest.connect(boost::bind(&RosterController::handleChangeStatusRequest, this, _1, _2)); - signOutConnection_ = mainWindow_->onSignOutRequest.connect(boost::bind(boost::ref(onSignOutRequest))); - xmppRoster_->onJIDAdded.connect(boost::bind(&RosterController::handleOnJIDAdded, this, _1)); - xmppRoster_->onJIDUpdated.connect(boost::bind(&RosterController::handleOnJIDUpdated, this, _1, _2, _3)); - xmppRoster_->onJIDRemoved.connect(boost::bind(&RosterController::handleOnJIDRemoved, this, _1)); - xmppRoster_->onRosterCleared.connect(boost::bind(&RosterController::handleRosterCleared, this)); - subscriptionManager_->onPresenceSubscriptionRequest.connect(boost::bind(&RosterController::handleSubscriptionRequest, this, _1, _2)); - uiEventConnection_ = uiEventStream->onUIEvent.connect(boost::bind(&RosterController::handleUIEvent, this, _1)); - - vcardManager_->onOwnVCardChanged.connect(boost::bind(&RosterController::handleOwnVCardChanged, this, _1)); - avatarManager_->onAvatarChanged.connect(boost::bind(&RosterController::handleAvatarChanged, this, _1)); - presenceOracle_->onPresenceChange.connect(boost::bind(&RosterController::handlePresenceChanged, this, _1)); - mainWindow_->setMyAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare()))); - - nickManager_->onOwnNickChanged.connect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1)); - mainWindow_->setMyJID(jid); - mainWindow_->setMyNick(nickManager_->getOwnNick()); - - entityCapsManager_->onCapsChanged.connect(boost::bind(&RosterController::handleOnCapsChanged, this, _1)); - - settings_->onSettingChanged.connect(boost::bind(&RosterController::handleSettingChanged, this, _1)); - - handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); - - ownContact_ = boost::make_shared(myJID_.toBare(), myJID_.toBare(), nickManager_->getOwnNick(), static_cast(0)); - ownContact_->setVCard(vcardManager_->getVCard(myJID_.toBare())); - ownContact_->setAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare()))); - mainWindow_->setMyContactRosterItem(ownContact_); + : myJID_(jid), xmppRoster_(xmppRoster), mainWindowFactory_(mainWindowFactory), mainWindow_(mainWindowFactory_->createMainWindow(uiEventStream)), roster_(new Roster()), offlineFilter_(new OfflineRosterFilter()), vcardManager_(vcardManager), avatarManager_(avatarManager), nickManager_(nickManager), nickResolver_(nickResolver), presenceOracle_(presenceOracle), uiEventStream_(uiEventStream), entityCapsManager_(entityCapsManager), ftOverview_(fileTransferOverview), clientBlockListManager_(clientBlockListManager) { + assert(fileTransferOverview); + iqRouter_ = iqRouter; + subscriptionManager_ = subscriptionManager; + eventController_ = eventController; + settings_ = settings; + expandiness_ = new RosterGroupExpandinessPersister(roster_, settings); + mainWindow_->setRosterModel(roster_); + rosterVCardProvider_ = new RosterVCardProvider(roster_, vcardManager, JID::WithoutResource); + + changeStatusConnection_ = mainWindow_->onChangeStatusRequest.connect(boost::bind(&RosterController::handleChangeStatusRequest, this, _1, _2)); + signOutConnection_ = mainWindow_->onSignOutRequest.connect(boost::bind(boost::ref(onSignOutRequest))); + xmppRoster_->onJIDAdded.connect(boost::bind(&RosterController::handleOnJIDAdded, this, _1)); + xmppRoster_->onJIDUpdated.connect(boost::bind(&RosterController::handleOnJIDUpdated, this, _1, _2, _3)); + xmppRoster_->onJIDRemoved.connect(boost::bind(&RosterController::handleOnJIDRemoved, this, _1)); + xmppRoster_->onRosterCleared.connect(boost::bind(&RosterController::handleRosterCleared, this)); + subscriptionManager_->onPresenceSubscriptionRequest.connect(boost::bind(&RosterController::handleSubscriptionRequest, this, _1, _2)); + uiEventConnection_ = uiEventStream->onUIEvent.connect(boost::bind(&RosterController::handleUIEvent, this, _1)); + + vcardManager_->onOwnVCardChanged.connect(boost::bind(&RosterController::handleOwnVCardChanged, this, _1)); + avatarManager_->onAvatarChanged.connect(boost::bind(&RosterController::handleAvatarChanged, this, _1)); + presenceOracle_->onPresenceChange.connect(boost::bind(&RosterController::handlePresenceChanged, this, _1)); + mainWindow_->setMyAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare()))); + + nickManager_->onOwnNickChanged.connect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1)); + mainWindow_->setMyJID(jid); + mainWindow_->setMyNick(nickManager_->getOwnNick()); + + entityCapsManager_->onCapsChanged.connect(boost::bind(&RosterController::handleOnCapsChanged, this, _1)); + + settings_->onSettingChanged.connect(boost::bind(&RosterController::handleSettingChanged, this, _1)); + + handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); + + ownContact_ = boost::make_shared(myJID_.toBare(), myJID_.toBare(), nickManager_->getOwnNick(), static_cast(0)); + ownContact_->setVCard(vcardManager_->getVCard(myJID_.toBare())); + ownContact_->setAvatarPath(pathToString(avatarManager_->getAvatarPath(myJID_.toBare()))); + mainWindow_->setMyContactRosterItem(ownContact_); } -RosterController::~RosterController() { - settings_->onSettingChanged.disconnect(boost::bind(&RosterController::handleSettingChanged, this, _1)); - nickManager_->onOwnNickChanged.disconnect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1)); - - delete offlineFilter_; - delete expandiness_; +RosterController::~RosterController() { + settings_->onSettingChanged.disconnect(boost::bind(&RosterController::handleSettingChanged, this, _1)); + nickManager_->onOwnNickChanged.disconnect(boost::bind(&MainWindow::setMyNick, mainWindow_, _1)); - mainWindow_->setRosterModel(NULL); - if (mainWindow_->canDelete()) { - delete mainWindow_; - } - delete rosterVCardProvider_; - delete roster_; + delete offlineFilter_; + delete expandiness_; + + mainWindow_->setRosterModel(NULL); + if (mainWindow_->canDelete()) { + delete mainWindow_; + } + delete rosterVCardProvider_; + delete roster_; } void RosterController::setEnabled(bool enabled) { - if (!enabled) { - roster_->applyOnItems(AppearOffline()); - } + if (!enabled) { + roster_->applyOnItems(AppearOffline()); + } } void RosterController::handleShowOfflineToggled(bool state) { - if (state) { - roster_->removeFilter(offlineFilter_); - } else { - roster_->addFilter(offlineFilter_); - } + if (state) { + roster_->removeFilter(offlineFilter_); + } else { + roster_->addFilter(offlineFilter_); + } } void RosterController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) { - onChangeStatusRequest(show, statusText); + onChangeStatusRequest(show, statusText); } void RosterController::handleOnJIDAdded(const JID& jid) { - std::vector groups = xmppRoster_->getGroupsForJID(jid); - std::string name = nickResolver_->jidToNick(jid); - if (!groups.empty()) { - foreach(const std::string& group, groups) { - roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid)); - } - } - else { - roster_->addContact(jid, jid, name, QT_TRANSLATE_NOOP("", "Contacts"), avatarManager_->getAvatarPath(jid)); - } - applyAllPresenceTo(jid); + std::vector groups = xmppRoster_->getGroupsForJID(jid); + std::string name = nickResolver_->jidToNick(jid); + if (!groups.empty()) { + foreach(const std::string& group, groups) { + roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid)); + } + } + else { + roster_->addContact(jid, jid, name, QT_TRANSLATE_NOOP("", "Contacts"), avatarManager_->getAvatarPath(jid)); + } + applyAllPresenceTo(jid); } void RosterController::applyAllPresenceTo(const JID& jid) { - foreach (Presence::ref presence, presenceOracle_->getAllPresence(jid)) { - roster_->applyOnItems(SetPresence(presence)); - } + foreach (Presence::ref presence, presenceOracle_->getAllPresence(jid)) { + roster_->applyOnItems(SetPresence(presence)); + } } void RosterController::handleRosterCleared() { - roster_->removeAll(); + roster_->removeAll(); } void RosterController::handleOnJIDRemoved(const JID& jid) { - roster_->removeContact(jid); + roster_->removeContact(jid); } void RosterController::handleOnJIDUpdated(const JID& jid, const std::string& oldName, const std::vector& passedOldGroups) { - if (oldName != xmppRoster_->getNameForJID(jid)) { - roster_->applyOnItems(SetName(nickResolver_->jidToNick(jid), jid)); - } - std::vector groups = xmppRoster_->getGroupsForJID(jid); - std::vector oldGroups = passedOldGroups; - std::string name = nickResolver_->jidToNick(jid); - std::string contactsGroup = QT_TRANSLATE_NOOP("", "Contacts"); - if (oldGroups.empty()) { - oldGroups.push_back(contactsGroup); - } - if (groups.empty()) { - groups.push_back(contactsGroup); - } - foreach(const std::string& group, groups) { - if (std::find(oldGroups.begin(), oldGroups.end(), group) == oldGroups.end()) { - roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid)); - } - } - foreach(const std::string& group, oldGroups) { - if (std::find(groups.begin(), groups.end(), group) == groups.end()) { - roster_->removeContactFromGroup(jid, group); - if (roster_->getGroup(group)->getChildren().size() == 0) { - roster_->removeGroup(group); - } - } - } - applyAllPresenceTo(jid); + if (oldName != xmppRoster_->getNameForJID(jid)) { + roster_->applyOnItems(SetName(nickResolver_->jidToNick(jid), jid)); + } + std::vector groups = xmppRoster_->getGroupsForJID(jid); + std::vector oldGroups = passedOldGroups; + std::string name = nickResolver_->jidToNick(jid); + std::string contactsGroup = QT_TRANSLATE_NOOP("", "Contacts"); + if (oldGroups.empty()) { + oldGroups.push_back(contactsGroup); + } + if (groups.empty()) { + groups.push_back(contactsGroup); + } + foreach(const std::string& group, groups) { + if (std::find(oldGroups.begin(), oldGroups.end(), group) == oldGroups.end()) { + roster_->addContact(jid, jid, name, group, avatarManager_->getAvatarPath(jid)); + } + } + foreach(const std::string& group, oldGroups) { + if (std::find(groups.begin(), groups.end(), group) == groups.end()) { + roster_->removeContactFromGroup(jid, group); + if (roster_->getGroup(group)->getChildren().size() == 0) { + roster_->removeGroup(group); + } + } + } + applyAllPresenceTo(jid); } void RosterController::handleSettingChanged(const std::string& settingPath) { - if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) { - handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); - } + if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) { + handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); + } } void RosterController::handleBlockingStateChanged() { - if (clientBlockListManager_->getBlockList()->getState() == BlockList::Available) { - foreach(const JID& jid, clientBlockListManager_->getBlockList()->getItems()) { - roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked)); - } - } + if (clientBlockListManager_->getBlockList()->getState() == BlockList::Available) { + foreach(const JID& jid, clientBlockListManager_->getBlockList()->getItems()) { + roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked)); + } + } } void RosterController::handleBlockingItemAdded(const JID& jid) { - roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked)); + roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked)); } void RosterController::handleBlockingItemRemoved(const JID& jid) { - roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsUnblocked)); + roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsUnblocked)); } void RosterController::handleUIEvent(boost::shared_ptr event) { - if (boost::shared_ptr addContactEvent = boost::dynamic_pointer_cast(event)) { - RosterItemPayload item; - item.setName(addContactEvent->getName()); - item.setJID(addContactEvent->getJID()); - item.setGroups(std::vector(addContactEvent->getGroups().begin(), addContactEvent->getGroups().end())); - boost::shared_ptr roster(new RosterPayload()); - roster->addItem(item); - SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); - request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster)); - request->send(); - subscriptionManager_->requestSubscription(addContactEvent->getJID()); - } - else if (boost::shared_ptr removeEvent = boost::dynamic_pointer_cast(event)) { - RosterItemPayload item(removeEvent->getJID(), "", RosterItemPayload::Remove); - boost::shared_ptr roster(new RosterPayload()); - roster->addItem(item); - SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); - request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster)); - request->send(); - - } - else if (boost::shared_ptr renameEvent = boost::dynamic_pointer_cast(event)) { - JID contact(renameEvent->getJID()); - RosterItemPayload item(contact, renameEvent->getNewName(), xmppRoster_->getSubscriptionStateForJID(contact)); - item.setGroups(xmppRoster_->getGroupsForJID(contact)); - boost::shared_ptr roster(new RosterPayload()); - roster->addItem(item); - SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); - request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster)); - request->send(); - } - else if (boost::shared_ptr renameGroupEvent = boost::dynamic_pointer_cast(event)) { - std::vector items = xmppRoster_->getItems(); - std::string group = renameGroupEvent->getGroup(); - // FIXME: We should handle contacts groups specially to avoid clashes - if (group == QT_TRANSLATE_NOOP("", "Contacts")) { - group = ""; - } - foreach(XMPPRosterItem& item, items) { - std::vector groups = item.getGroups(); - if ( (group.empty() && groups.empty()) || std::find(groups.begin(), groups.end(), group) != groups.end()) { - groups.erase(std::remove(groups.begin(), groups.end(), group), groups.end()); - if (std::find(groups.begin(), groups.end(), renameGroupEvent->getNewName()) == groups.end()) { - groups.push_back(renameGroupEvent->getNewName()); - } - item.setGroups(groups); - updateItem(item); - } - } - } - else if (boost::shared_ptr sendFileEvent = boost::dynamic_pointer_cast(event)) { - //TODO add send file dialog to ChatView of receipient jid - ftOverview_->sendFile(sendFileEvent->getJID(), sendFileEvent->getFilename()); - } + if (boost::shared_ptr addContactEvent = boost::dynamic_pointer_cast(event)) { + RosterItemPayload item; + item.setName(addContactEvent->getName()); + item.setJID(addContactEvent->getJID()); + item.setGroups(std::vector(addContactEvent->getGroups().begin(), addContactEvent->getGroups().end())); + boost::shared_ptr roster(new RosterPayload()); + roster->addItem(item); + SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); + request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster)); + request->send(); + subscriptionManager_->requestSubscription(addContactEvent->getJID()); + } + else if (boost::shared_ptr removeEvent = boost::dynamic_pointer_cast(event)) { + RosterItemPayload item(removeEvent->getJID(), "", RosterItemPayload::Remove); + boost::shared_ptr roster(new RosterPayload()); + roster->addItem(item); + SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); + request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster)); + request->send(); + + } + else if (boost::shared_ptr renameEvent = boost::dynamic_pointer_cast(event)) { + JID contact(renameEvent->getJID()); + RosterItemPayload item(contact, renameEvent->getNewName(), xmppRoster_->getSubscriptionStateForJID(contact)); + item.setGroups(xmppRoster_->getGroupsForJID(contact)); + boost::shared_ptr roster(new RosterPayload()); + roster->addItem(item); + SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); + request->onResponse.connect(boost::bind(&RosterController::handleRosterSetError, this, _1, roster)); + request->send(); + } + else if (boost::shared_ptr renameGroupEvent = boost::dynamic_pointer_cast(event)) { + std::vector items = xmppRoster_->getItems(); + std::string group = renameGroupEvent->getGroup(); + // FIXME: We should handle contacts groups specially to avoid clashes + if (group == QT_TRANSLATE_NOOP("", "Contacts")) { + group = ""; + } + foreach(XMPPRosterItem& item, items) { + std::vector groups = item.getGroups(); + if ( (group.empty() && groups.empty()) || std::find(groups.begin(), groups.end(), group) != groups.end()) { + groups.erase(std::remove(groups.begin(), groups.end(), group), groups.end()); + if (std::find(groups.begin(), groups.end(), renameGroupEvent->getNewName()) == groups.end()) { + groups.push_back(renameGroupEvent->getNewName()); + } + item.setGroups(groups); + updateItem(item); + } + } + } + else if (boost::shared_ptr sendFileEvent = boost::dynamic_pointer_cast(event)) { + //TODO add send file dialog to ChatView of receipient jid + ftOverview_->sendFile(sendFileEvent->getJID(), sendFileEvent->getFilename()); + } } void RosterController::setContactGroups(const JID& jid, const std::vector& groups) { - updateItem(XMPPRosterItem(jid, xmppRoster_->getNameForJID(jid), groups, xmppRoster_->getSubscriptionStateForJID(jid))); + updateItem(XMPPRosterItem(jid, xmppRoster_->getNameForJID(jid), groups, xmppRoster_->getSubscriptionStateForJID(jid))); } void RosterController::updateItem(const XMPPRosterItem& item) { - RosterItemPayload itemPayload(item.getJID(), item.getName(), item.getSubscription()); - itemPayload.setGroups(item.getGroups()); + RosterItemPayload itemPayload(item.getJID(), item.getName(), item.getSubscription()); + itemPayload.setGroups(item.getGroups()); - RosterPayload::ref roster = boost::make_shared(); - roster->addItem(itemPayload); + RosterPayload::ref roster = boost::make_shared(); + roster->addItem(itemPayload); - SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); - request->onResponse.connect(boost::bind(&RosterController::handleRosterItemUpdated, this, _1, roster)); - request->send(); + SetRosterRequest::ref request = SetRosterRequest::create(roster, iqRouter_); + request->onResponse.connect(boost::bind(&RosterController::handleRosterItemUpdated, this, _1, roster)); + request->send(); } void RosterController::initBlockingCommand() { - boost::shared_ptr blockList = clientBlockListManager_->requestBlockList(); - - blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&RosterController::handleBlockingStateChanged, this)); - blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&RosterController::handleBlockingItemAdded, this, _1)); - blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&RosterController::handleBlockingItemRemoved, this, _1)); - roster_->setBlockingSupported(true); - if (blockList->getState() == BlockList::Available) { - foreach(const JID& jid, blockList->getItems()) { - roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked)); - } - } + boost::shared_ptr blockList = clientBlockListManager_->requestBlockList(); + + blockingOnStateChangedConnection_ = blockList->onStateChanged.connect(boost::bind(&RosterController::handleBlockingStateChanged, this)); + blockingOnItemAddedConnection_ = blockList->onItemAdded.connect(boost::bind(&RosterController::handleBlockingItemAdded, this, _1)); + blockingOnItemRemovedConnection_ = blockList->onItemRemoved.connect(boost::bind(&RosterController::handleBlockingItemRemoved, this, _1)); + roster_->setBlockingSupported(true); + if (blockList->getState() == BlockList::Available) { + foreach(const JID& jid, blockList->getItems()) { + roster_->applyOnItems(SetBlockingState(jid, ContactRosterItem::IsBlocked)); + } + } } void RosterController::handleRosterItemUpdated(ErrorPayload::ref error, boost::shared_ptr rosterPayload) { - if (!!error) { - handleRosterSetError(error, rosterPayload); - } - boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); - std::vector items = rosterPayload->getItems(); - if (blockList->getState() == BlockList::Available && items.size() > 0) { - std::vector jids = blockList->getItems(); - if (std::find(jids.begin(), jids.end(), items[0].getJID()) != jids.end()) { - roster_->applyOnItems(SetBlockingState(items[0].getJID(), ContactRosterItem::IsBlocked)); - } - } + if (!!error) { + handleRosterSetError(error, rosterPayload); + } + boost::shared_ptr blockList = clientBlockListManager_->getBlockList(); + std::vector items = rosterPayload->getItems(); + if (blockList->getState() == BlockList::Available && items.size() > 0) { + std::vector jids = blockList->getItems(); + if (std::find(jids.begin(), jids.end(), items[0].getJID()) != jids.end()) { + roster_->applyOnItems(SetBlockingState(items[0].getJID(), ContactRosterItem::IsBlocked)); + } + } } void RosterController::handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr rosterPayload) { - if (!error) { - return; - } - std::string text = str(format(QT_TRANSLATE_NOOP("", "Server %1% rejected contact list change to item '%2%'")) % myJID_.getDomain() % rosterPayload->getItems()[0].getJID().toString()); - if (!error->getText().empty()) { - text += ": " + error->getText(); - } - boost::shared_ptr errorEvent(new ErrorEvent(JID(myJID_.getDomain()), text)); - eventController_->handleIncomingEvent(errorEvent); + if (!error) { + return; + } + std::string text = str(format(QT_TRANSLATE_NOOP("", "Server %1% rejected contact list change to item '%2%'")) % myJID_.getDomain() % rosterPayload->getItems()[0].getJID().toString()); + if (!error->getText().empty()) { + text += ": " + error->getText(); + } + boost::shared_ptr errorEvent(new ErrorEvent(JID(myJID_.getDomain()), text)); + eventController_->handleIncomingEvent(errorEvent); } void RosterController::handleIncomingPresence(Presence::ref newPresence) { - if (newPresence->getType() == Presence::Error) { - return; - } - Presence::ref accountPresence = presenceOracle_->getAccountPresence(newPresence->getFrom().toBare()); - if (!accountPresence) { - accountPresence = Presence::create(); - accountPresence->setFrom(newPresence->getFrom()); - accountPresence->setType(Presence::Unavailable); - } - roster_->applyOnItems(SetPresence(accountPresence)); + if (newPresence->getType() == Presence::Error) { + return; + } + Presence::ref accountPresence = presenceOracle_->getAccountPresence(newPresence->getFrom().toBare()); + if (!accountPresence) { + accountPresence = Presence::create(); + accountPresence->setFrom(newPresence->getFrom()); + accountPresence->setType(Presence::Unavailable); + } + roster_->applyOnItems(SetPresence(accountPresence)); } void RosterController::handleSubscriptionRequest(const JID& jid, const std::string& message) { - if (xmppRoster_->containsJID(jid) && (xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::To || xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::Both)) { - subscriptionManager_->confirmSubscription(jid); - return; - } - SubscriptionRequestEvent* eventPointer = new SubscriptionRequestEvent(jid, message); - eventPointer->onAccept.connect(boost::bind(&RosterController::handleSubscriptionRequestAccepted, this, eventPointer)); - eventPointer->onDecline.connect(boost::bind(&RosterController::handleSubscriptionRequestDeclined, this, eventPointer)); - boost::shared_ptr event(eventPointer); - eventController_->handleIncomingEvent(event); + if (xmppRoster_->containsJID(jid) && (xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::To || xmppRoster_->getSubscriptionStateForJID(jid) == RosterItemPayload::Both)) { + subscriptionManager_->confirmSubscription(jid); + return; + } + SubscriptionRequestEvent* eventPointer = new SubscriptionRequestEvent(jid, message); + eventPointer->onAccept.connect(boost::bind(&RosterController::handleSubscriptionRequestAccepted, this, eventPointer)); + eventPointer->onDecline.connect(boost::bind(&RosterController::handleSubscriptionRequestDeclined, this, eventPointer)); + boost::shared_ptr event(eventPointer); + eventController_->handleIncomingEvent(event); } void RosterController::handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event) { - subscriptionManager_->confirmSubscription(event->getJID()); - if (!xmppRoster_->containsJID(event->getJID()) || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::None || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::From) { - subscriptionManager_->requestSubscription(event->getJID()); - } + subscriptionManager_->confirmSubscription(event->getJID()); + if (!xmppRoster_->containsJID(event->getJID()) || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::None || xmppRoster_->getSubscriptionStateForJID(event->getJID()) == RosterItemPayload::From) { + subscriptionManager_->requestSubscription(event->getJID()); + } } void RosterController::handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event) { - subscriptionManager_->cancelSubscription(event->getJID()); + subscriptionManager_->cancelSubscription(event->getJID()); } void RosterController::handleOwnVCardChanged(VCard::ref vcard) { - ownContact_->setVCard(vcard); - mainWindow_->setMyContactRosterItem(ownContact_); + ownContact_->setVCard(vcard); + mainWindow_->setMyContactRosterItem(ownContact_); } void RosterController::handleAvatarChanged(const JID& jid) { - boost::filesystem::path path = avatarManager_->getAvatarPath(jid); - roster_->applyOnItems(SetAvatar(jid, path)); - if (jid.equals(myJID_, JID::WithoutResource)) { - mainWindow_->setMyAvatarPath(pathToString(path)); - ownContact_->setAvatarPath(pathToString(path)); - mainWindow_->setMyContactRosterItem(ownContact_); - } + boost::filesystem::path path = avatarManager_->getAvatarPath(jid); + roster_->applyOnItems(SetAvatar(jid, path)); + if (jid.equals(myJID_, JID::WithoutResource)) { + mainWindow_->setMyAvatarPath(pathToString(path)); + ownContact_->setAvatarPath(pathToString(path)); + mainWindow_->setMyContactRosterItem(ownContact_); + } } void RosterController::handlePresenceChanged(Presence::ref presence) { - if (presence->getFrom().equals(myJID_, JID::WithResource)) { - ownContact_->applyPresence(presence); - mainWindow_->setMyContactRosterItem(ownContact_); - } - else { - handleIncomingPresence(presence); - } + if (presence->getFrom().equals(myJID_, JID::WithResource)) { + ownContact_->applyPresence(presence); + mainWindow_->setMyContactRosterItem(ownContact_); + } + else { + handleIncomingPresence(presence); + } } boost::optional RosterController::getItem(const JID& jid) const { - return xmppRoster_->getItem(jid); + return xmppRoster_->getItem(jid); } std::set RosterController::getGroups() const { - return xmppRoster_->getGroups(); + return xmppRoster_->getGroups(); } void RosterController::handleOnCapsChanged(const JID& jid) { - DiscoInfo::ref info = entityCapsManager_->getCaps(jid); - if (info) { - std::set features; - if (FileTransferManager::isSupportedBy(info)) { - features.insert(ContactRosterItem::FileTransferFeature); - } - if (info->hasFeature(DiscoInfo::WhiteboardFeature)) { - features.insert(ContactRosterItem::WhiteboardFeature); - } - roster_->applyOnItems(SetAvailableFeatures(jid, features)); - } + DiscoInfo::ref info = entityCapsManager_->getCaps(jid); + if (info) { + std::set features; + if (FileTransferManager::isSupportedBy(info)) { + features.insert(ContactRosterItem::FileTransferFeature); + } + if (info->hasFeature(DiscoInfo::WhiteboardFeature)) { + features.insert(ContactRosterItem::WhiteboardFeature); + } + roster_->applyOnItems(SetAvailableFeatures(jid, features)); + } } } diff --git a/Swift/Controllers/Roster/RosterController.h b/Swift/Controllers/Roster/RosterController.h index 545abfc..f1660a8 100644 --- a/Swift/Controllers/Roster/RosterController.h +++ b/Swift/Controllers/Roster/RosterController.h @@ -23,104 +23,104 @@ #include namespace Swift { - class AvatarManager; - class ClientBlockListManager; - class EntityCapsProvider; - class EventController; - class FileTransferManager; - class FileTransferOverview; - class IQRouter; - class MainWindow; - class MainWindowFactory; - class NickManager; - class NickResolver; - class OfflineRosterFilter; - class PresenceOracle; - class Roster; - class RosterGroupExpandinessPersister; - class RosterVCardProvider; - class SettingsProvider; - class SubscriptionManager; - class SubscriptionRequestEvent; - class UIEventStream; - class VCardManager; - class XMPPRoster; - class XMPPRosterItem; + class AvatarManager; + class ClientBlockListManager; + class EntityCapsProvider; + class EventController; + class FileTransferManager; + class FileTransferOverview; + class IQRouter; + class MainWindow; + class MainWindowFactory; + class NickManager; + class NickResolver; + class OfflineRosterFilter; + class PresenceOracle; + class Roster; + class RosterGroupExpandinessPersister; + class RosterVCardProvider; + class SettingsProvider; + class SubscriptionManager; + class SubscriptionRequestEvent; + class UIEventStream; + class VCardManager; + class XMPPRoster; + class XMPPRosterItem; - class RosterController { - public: - RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter, SettingsProvider* settings, EntityCapsProvider* entityCapsProvider, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager); - ~RosterController(); - void showRosterWindow(); - void setJID(const JID& jid) { myJID_ = jid; } - MainWindow* getWindow() {return mainWindow_;} - boost::signal onChangeStatusRequest; - boost::signal onSignOutRequest; - void handleOwnVCardChanged(VCard::ref vcard); - void handleAvatarChanged(const JID& jid); - void handlePresenceChanged(Presence::ref presence); - void setEnabled(bool enabled); + class RosterController { + public: + RosterController(const JID& jid, XMPPRoster* xmppRoster, AvatarManager* avatarManager, MainWindowFactory* mainWindowFactory, NickManager* nickManager, NickResolver* nickResolver, PresenceOracle* presenceOracle, SubscriptionManager* subscriptionManager, EventController* eventController, UIEventStream* uiEventStream, IQRouter* iqRouter, SettingsProvider* settings, EntityCapsProvider* entityCapsProvider, FileTransferOverview* fileTransferOverview, ClientBlockListManager* clientBlockListManager, VCardManager* vcardManager); + ~RosterController(); + void showRosterWindow(); + void setJID(const JID& jid) { myJID_ = jid; } + MainWindow* getWindow() {return mainWindow_;} + boost::signal onChangeStatusRequest; + boost::signal onSignOutRequest; + void handleOwnVCardChanged(VCard::ref vcard); + void handleAvatarChanged(const JID& jid); + void handlePresenceChanged(Presence::ref presence); + void setEnabled(bool enabled); - boost::optional getItem(const JID&) const; - std::set getGroups() const; + boost::optional getItem(const JID&) const; + std::set getGroups() const; - void setContactGroups(const JID& jid, const std::vector& groups); - void updateItem(const XMPPRosterItem&); + void setContactGroups(const JID& jid, const std::vector& groups); + void updateItem(const XMPPRosterItem&); - void initBlockingCommand(); + void initBlockingCommand(); - private: - void handleOnJIDAdded(const JID &jid); - void handleRosterCleared(); - void handleOnJIDRemoved(const JID &jid); - void handleOnJIDUpdated(const JID &jid, const std::string& oldName, const std::vector& oldGroups); - void handleStartChatRequest(const JID& contact); - void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText); - void handleShowOfflineToggled(bool state); - void handleIncomingPresence(boost::shared_ptr newPresence); - void handleSubscriptionRequest(const JID& jid, const std::string& message); - void handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event); - void handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event); - void handleUIEvent(boost::shared_ptr event); - void handleRosterItemUpdated(ErrorPayload::ref error, boost::shared_ptr rosterPayload); - void handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr rosterPayload); - void applyAllPresenceTo(const JID& jid); - void handleEditProfileRequest(); - void handleOnCapsChanged(const JID& jid); - void handleSettingChanged(const std::string& settingPath); + private: + void handleOnJIDAdded(const JID &jid); + void handleRosterCleared(); + void handleOnJIDRemoved(const JID &jid); + void handleOnJIDUpdated(const JID &jid, const std::string& oldName, const std::vector& oldGroups); + void handleStartChatRequest(const JID& contact); + void handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText); + void handleShowOfflineToggled(bool state); + void handleIncomingPresence(boost::shared_ptr newPresence); + void handleSubscriptionRequest(const JID& jid, const std::string& message); + void handleSubscriptionRequestAccepted(SubscriptionRequestEvent* event); + void handleSubscriptionRequestDeclined(SubscriptionRequestEvent* event); + void handleUIEvent(boost::shared_ptr event); + void handleRosterItemUpdated(ErrorPayload::ref error, boost::shared_ptr rosterPayload); + void handleRosterSetError(ErrorPayload::ref error, boost::shared_ptr rosterPayload); + void applyAllPresenceTo(const JID& jid); + void handleEditProfileRequest(); + void handleOnCapsChanged(const JID& jid); + void handleSettingChanged(const std::string& settingPath); - void handleBlockingStateChanged(); - void handleBlockingItemAdded(const JID& jid); - void handleBlockingItemRemoved(const JID& jid); + void handleBlockingStateChanged(); + void handleBlockingItemAdded(const JID& jid); + void handleBlockingItemRemoved(const JID& jid); - JID myJID_; - XMPPRoster* xmppRoster_; - MainWindowFactory* mainWindowFactory_; - MainWindow* mainWindow_; - Roster* roster_; - OfflineRosterFilter* offlineFilter_; - VCardManager* vcardManager_; - AvatarManager* avatarManager_; - NickManager* nickManager_; - NickResolver* nickResolver_; - PresenceOracle* presenceOracle_; - SubscriptionManager* subscriptionManager_; - EventController* eventController_; - RosterGroupExpandinessPersister* expandiness_; - IQRouter* iqRouter_; - SettingsProvider* settings_; - UIEventStream* uiEventStream_; - EntityCapsProvider* entityCapsManager_; - FileTransferOverview* ftOverview_; - ClientBlockListManager* clientBlockListManager_; - RosterVCardProvider* rosterVCardProvider_; - boost::shared_ptr ownContact_; - - boost::bsignals::scoped_connection blockingOnStateChangedConnection_; - boost::bsignals::scoped_connection blockingOnItemAddedConnection_; - boost::bsignals::scoped_connection blockingOnItemRemovedConnection_; - boost::bsignals::scoped_connection changeStatusConnection_; - boost::bsignals::scoped_connection signOutConnection_; - boost::bsignals::scoped_connection uiEventConnection_; - }; + JID myJID_; + XMPPRoster* xmppRoster_; + MainWindowFactory* mainWindowFactory_; + MainWindow* mainWindow_; + Roster* roster_; + OfflineRosterFilter* offlineFilter_; + VCardManager* vcardManager_; + AvatarManager* avatarManager_; + NickManager* nickManager_; + NickResolver* nickResolver_; + PresenceOracle* presenceOracle_; + SubscriptionManager* subscriptionManager_; + EventController* eventController_; + RosterGroupExpandinessPersister* expandiness_; + IQRouter* iqRouter_; + SettingsProvider* settings_; + UIEventStream* uiEventStream_; + EntityCapsProvider* entityCapsManager_; + FileTransferOverview* ftOverview_; + ClientBlockListManager* clientBlockListManager_; + RosterVCardProvider* rosterVCardProvider_; + boost::shared_ptr ownContact_; + + boost::bsignals::scoped_connection blockingOnStateChangedConnection_; + boost::bsignals::scoped_connection blockingOnItemAddedConnection_; + boost::bsignals::scoped_connection blockingOnItemRemovedConnection_; + boost::bsignals::scoped_connection changeStatusConnection_; + boost::bsignals::scoped_connection signOutConnection_; + boost::bsignals::scoped_connection uiEventConnection_; + }; } diff --git a/Swift/Controllers/Roster/RosterFilter.h b/Swift/Controllers/Roster/RosterFilter.h index e68ab57..6075c66 100644 --- a/Swift/Controllers/Roster/RosterFilter.h +++ b/Swift/Controllers/Roster/RosterFilter.h @@ -11,9 +11,9 @@ namespace Swift { class RosterFilter { - public: - virtual ~RosterFilter() {} - virtual bool operator() (RosterItem* item) const = 0; + public: + virtual ~RosterFilter() {} + virtual bool operator() (RosterItem* item) const = 0; }; } diff --git a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp index a39667c..af89b54 100644 --- a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp +++ b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.cpp @@ -19,45 +19,45 @@ namespace Swift { RosterGroupExpandinessPersister::RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings) : roster_(roster), settings_(settings) { - load(); - roster_->onGroupAdded.connect(boost::bind(&RosterGroupExpandinessPersister::handleGroupAdded, this, _1)); + load(); + roster_->onGroupAdded.connect(boost::bind(&RosterGroupExpandinessPersister::handleGroupAdded, this, _1)); } void RosterGroupExpandinessPersister::handleGroupAdded(GroupRosterItem* group) { - if (collapsed_.find(group->getDisplayName()) != collapsed_.end()) { - group->setExpanded(false); - } else { - group->setExpanded(true); - } - group->onExpandedChanged.connect(boost::bind(&RosterGroupExpandinessPersister::handleExpandedChanged, this, group, _1)); + if (collapsed_.find(group->getDisplayName()) != collapsed_.end()) { + group->setExpanded(false); + } else { + group->setExpanded(true); + } + group->onExpandedChanged.connect(boost::bind(&RosterGroupExpandinessPersister::handleExpandedChanged, this, group, _1)); } void RosterGroupExpandinessPersister::handleExpandedChanged(GroupRosterItem* group, bool expanded) { - if (expanded) { - std::string displayName = group->getDisplayName(); - //collapsed_.erase(std::remove(collapsed_.begin(), collapsed_.end(), displayName), collapsed_.end()); - collapsed_.erase(displayName); - } else { - collapsed_.insert(group->getDisplayName()); - } - save(); + if (expanded) { + std::string displayName = group->getDisplayName(); + //collapsed_.erase(std::remove(collapsed_.begin(), collapsed_.end(), displayName), collapsed_.end()); + collapsed_.erase(displayName); + } else { + collapsed_.insert(group->getDisplayName()); + } + save(); } void RosterGroupExpandinessPersister::save() { - std::string setting; - foreach (const std::string& group, collapsed_) { - if (!setting.empty()) { - setting += "\n"; - } - setting += group; - } - settings_->storeSetting(SettingConstants::EXPANDED_ROSTER_GROUPS, setting); + std::string setting; + foreach (const std::string& group, collapsed_) { + if (!setting.empty()) { + setting += "\n"; + } + setting += group; + } + settings_->storeSetting(SettingConstants::EXPANDED_ROSTER_GROUPS, setting); } void RosterGroupExpandinessPersister::load() { - std::string saved = settings_->getSetting(SettingConstants::EXPANDED_ROSTER_GROUPS); - std::vector collapsed = String::split(saved, '\n'); - collapsed_.insert(collapsed.begin(), collapsed.end()); + std::string saved = settings_->getSetting(SettingConstants::EXPANDED_ROSTER_GROUPS); + std::vector collapsed = String::split(saved, '\n'); + collapsed_.insert(collapsed.begin(), collapsed.end()); } diff --git a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h index c3d5c12..4cc08a7 100644 --- a/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h +++ b/Swift/Controllers/Roster/RosterGroupExpandinessPersister.h @@ -12,16 +12,16 @@ #include namespace Swift { - class RosterGroupExpandinessPersister { - public: - RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings); - private: - void handleExpandedChanged(GroupRosterItem* group, bool expanded); - void handleGroupAdded(GroupRosterItem* group); - void load(); - void save(); - std::set collapsed_; - Roster* roster_; - SettingsProvider* settings_; - }; + class RosterGroupExpandinessPersister { + public: + RosterGroupExpandinessPersister(Roster* roster, SettingsProvider* settings); + private: + void handleExpandedChanged(GroupRosterItem* group, bool expanded); + void handleGroupAdded(GroupRosterItem* group); + void load(); + void save(); + std::set collapsed_; + Roster* roster_; + SettingsProvider* settings_; + }; } diff --git a/Swift/Controllers/Roster/RosterItem.cpp b/Swift/Controllers/Roster/RosterItem.cpp index 51478c3..685613f 100644 --- a/Swift/Controllers/Roster/RosterItem.cpp +++ b/Swift/Controllers/Roster/RosterItem.cpp @@ -13,10 +13,10 @@ namespace Swift { RosterItem::RosterItem(const std::string& name, GroupRosterItem* parent) : name_(name), sortableDisplayName_(boost::to_lower_copy(name_)), parent_(parent) { - /* The following would be good, but because of C++'s inheritance not working in constructors, it's not going to work. */ - //if (parent) { - // parent_->addChild(this); - //} + /* The following would be good, but because of C++'s inheritance not working in constructors, it's not going to work. */ + //if (parent) { + // parent_->addChild(this); + //} } RosterItem::~RosterItem() { @@ -24,21 +24,21 @@ RosterItem::~RosterItem() { } GroupRosterItem* RosterItem::getParent() const { - return parent_; + return parent_; } void RosterItem::setDisplayName(const std::string& name) { - name_ = name; - sortableDisplayName_ = boost::to_lower_copy(name_); - onDataChanged(); + name_ = name; + sortableDisplayName_ = boost::to_lower_copy(name_); + onDataChanged(); } const std::string& RosterItem::getDisplayName() const { - return name_; + return name_; } const std::string& RosterItem::getSortableDisplayName() const { - return sortableDisplayName_; + return sortableDisplayName_; } diff --git a/Swift/Controllers/Roster/RosterItem.h b/Swift/Controllers/Roster/RosterItem.h index 736c6af..e7a3e20 100644 --- a/Swift/Controllers/Roster/RosterItem.h +++ b/Swift/Controllers/Roster/RosterItem.h @@ -15,18 +15,18 @@ namespace Swift { class GroupRosterItem; class RosterItem { - public: - RosterItem(const std::string& name, GroupRosterItem* parent); - virtual ~RosterItem(); - boost::signal onDataChanged; - GroupRosterItem* getParent() const; - void setDisplayName(const std::string& name); - const std::string& getDisplayName() const; - virtual const std::string& getSortableDisplayName() const; - private: - std::string name_; - std::string sortableDisplayName_; - GroupRosterItem* parent_; + public: + RosterItem(const std::string& name, GroupRosterItem* parent); + virtual ~RosterItem(); + boost::signal onDataChanged; + GroupRosterItem* getParent() const; + void setDisplayName(const std::string& name); + const std::string& getDisplayName() const; + virtual const std::string& getSortableDisplayName() const; + private: + std::string name_; + std::string sortableDisplayName_; + GroupRosterItem* parent_; }; } diff --git a/Swift/Controllers/Roster/RosterVCardProvider.cpp b/Swift/Controllers/Roster/RosterVCardProvider.cpp index d00d318..2aa82a9 100644 --- a/Swift/Controllers/Roster/RosterVCardProvider.cpp +++ b/Swift/Controllers/Roster/RosterVCardProvider.cpp @@ -20,22 +20,22 @@ namespace Swift { RosterVCardProvider::RosterVCardProvider(Roster* roster, VCardManager* vcardManager, JID::CompareType compareType) : roster_(roster), vcardManager_(vcardManager), compareType_(compareType) { - vcardUpdateRequestedConnection = roster_->onVCardUpdateRequested.connect(boost::bind(&RosterVCardProvider::handleVCardUpdateRequested, this, _1)); - vcardChangedConnection = vcardManager_->onVCardChanged.connect(boost::bind(&RosterVCardProvider::handleVCardChanged, this, _1, _2)); + vcardUpdateRequestedConnection = roster_->onVCardUpdateRequested.connect(boost::bind(&RosterVCardProvider::handleVCardUpdateRequested, this, _1)); + vcardChangedConnection = vcardManager_->onVCardChanged.connect(boost::bind(&RosterVCardProvider::handleVCardChanged, this, _1, _2)); } RosterVCardProvider::~RosterVCardProvider() { } void RosterVCardProvider::handleVCardUpdateRequested(const JID& jid) { - VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid); - if (vcard) { - handleVCardChanged(jid, vcard); - } + VCard::ref vcard = vcardManager_->getVCardAndRequestWhenNeeded(jid); + if (vcard) { + handleVCardChanged(jid, vcard); + } } void RosterVCardProvider::handleVCardChanged(const JID& jid, VCard::ref vcard) { - roster_->applyOnItem(SetVCard(jid, vcard, compareType_), jid); + roster_->applyOnItem(SetVCard(jid, vcard, compareType_), jid); } diff --git a/Swift/Controllers/Roster/RosterVCardProvider.h b/Swift/Controllers/Roster/RosterVCardProvider.h index da41298..a697dae 100644 --- a/Swift/Controllers/Roster/RosterVCardProvider.h +++ b/Swift/Controllers/Roster/RosterVCardProvider.h @@ -18,20 +18,20 @@ class Roster; class VCardManager; class RosterVCardProvider { - public: - RosterVCardProvider(Roster* roster, VCardManager* vcardManager, JID::CompareType compareType); - ~RosterVCardProvider(); - - private: - void handleVCardUpdateRequested(const JID& jid); - void handleVCardChanged(const JID& jid, VCard::ref vcard); - - private: - Roster* roster_; - VCardManager* vcardManager_; - JID::CompareType compareType_; - boost::bsignals::scoped_connection vcardUpdateRequestedConnection; - boost::bsignals::scoped_connection vcardChangedConnection; + public: + RosterVCardProvider(Roster* roster, VCardManager* vcardManager, JID::CompareType compareType); + ~RosterVCardProvider(); + + private: + void handleVCardUpdateRequested(const JID& jid); + void handleVCardChanged(const JID& jid, VCard::ref vcard); + + private: + Roster* roster_; + VCardManager* vcardManager_; + JID::CompareType compareType_; + boost::bsignals::scoped_connection vcardUpdateRequestedConnection; + boost::bsignals::scoped_connection vcardChangedConnection; }; } diff --git a/Swift/Controllers/Roster/TableRoster.cpp b/Swift/Controllers/Roster/TableRoster.cpp index fde3304..f164a4d 100644 --- a/Swift/Controllers/Roster/TableRoster.cpp +++ b/Swift/Controllers/Roster/TableRoster.cpp @@ -21,167 +21,167 @@ #include namespace Swift { - struct SectionNameEquals { - bool operator()(const TableRoster::Section& s1, const TableRoster::Section& s2) const { - return s1.name == s2.name; - } - }; - - template - struct True { - bool operator()(const T&, const T&) const { - return true; - } - }; - - struct ItemEquals { - bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const { - return i1.jid == i2.jid; - } - }; - - - struct ItemNeedsUpdate { - bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const { - return i1.status != i2.status || i1.description != i2.description || i1.name != i2.name || i1.avatarPath.empty() != i2.avatarPath.empty(); - } - }; - - struct CreateIndexForSection { - CreateIndexForSection(size_t section) : section(section) { - } - - TableRoster::Index operator()(size_t row) const { - return TableRoster::Index(section, row); - } - - size_t section; - }; + struct SectionNameEquals { + bool operator()(const TableRoster::Section& s1, const TableRoster::Section& s2) const { + return s1.name == s2.name; + } + }; + + template + struct True { + bool operator()(const T&, const T&) const { + return true; + } + }; + + struct ItemEquals { + bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const { + return i1.jid == i2.jid; + } + }; + + + struct ItemNeedsUpdate { + bool operator()(const TableRoster::Item& i1, const TableRoster::Item& i2) const { + return i1.status != i2.status || i1.description != i2.description || i1.name != i2.name || i1.avatarPath.empty() != i2.avatarPath.empty(); + } + }; + + struct CreateIndexForSection { + CreateIndexForSection(size_t section) : section(section) { + } + + TableRoster::Index operator()(size_t row) const { + return TableRoster::Index(section, row); + } + + size_t section; + }; } using namespace Swift; TableRoster::TableRoster(Roster* model, TimerFactory* timerFactory, int updateDelay) : model(model), updatePending(false) { - updateTimer = timerFactory->createTimer(updateDelay); - updateTimer->onTick.connect(boost::bind(&TableRoster::handleUpdateTimerTick, this)); - if (model) { - model->onChildrenChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this)); - model->onGroupAdded.connect(boost::bind(&TableRoster::scheduleUpdate, this)); - model->onDataChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this)); - } + updateTimer = timerFactory->createTimer(updateDelay); + updateTimer->onTick.connect(boost::bind(&TableRoster::handleUpdateTimerTick, this)); + if (model) { + model->onChildrenChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this)); + model->onGroupAdded.connect(boost::bind(&TableRoster::scheduleUpdate, this)); + model->onDataChanged.connect(boost::bind(&TableRoster::scheduleUpdate, this)); + } } TableRoster::~TableRoster() { - updateTimer->stop(); - updateTimer->onTick.disconnect(boost::bind(&TableRoster::handleUpdateTimerTick, this)); - if (model) { - model->onDataChanged.disconnect(boost::bind(&TableRoster::scheduleUpdate, this)); - model->onGroupAdded.disconnect(boost::bind(&TableRoster::scheduleUpdate, this)); - model->onChildrenChanged.disconnect(boost::bind(&TableRoster::scheduleUpdate, this)); - } + updateTimer->stop(); + updateTimer->onTick.disconnect(boost::bind(&TableRoster::handleUpdateTimerTick, this)); + if (model) { + model->onDataChanged.disconnect(boost::bind(&TableRoster::scheduleUpdate, this)); + model->onGroupAdded.disconnect(boost::bind(&TableRoster::scheduleUpdate, this)); + model->onChildrenChanged.disconnect(boost::bind(&TableRoster::scheduleUpdate, this)); + } } - + size_t TableRoster::getNumberOfSections() const { - return sections.size(); + return sections.size(); } const std::string& TableRoster::getSectionTitle(size_t section) { - return sections[section].name; + return sections[section].name; } size_t TableRoster::getNumberOfRowsInSection(size_t section) const { - return sections[section].items.size(); + return sections[section].items.size(); } const TableRoster::Item& TableRoster::getItem(const Index& index) const { - return sections[index.section].items[index.row]; + return sections[index.section].items[index.row]; } - + void TableRoster::handleUpdateTimerTick() { - updateTimer->stop(); - updatePending = false; - - // Get a model for the new roster - std::vector
newSections; - if (model) { - foreach(RosterItem* item, model->getRoot()->getDisplayedChildren()) { - if (GroupRosterItem* groupItem = boost::polymorphic_downcast(item)) { - //std::cerr << "* " << groupItem->getDisplayName() << std::endl; - Section section(groupItem->getDisplayName()); - foreach(RosterItem* groupChildItem, groupItem->getDisplayedChildren()) { - if (ContactRosterItem* contact = boost::polymorphic_downcast(groupChildItem)) { - //std::cerr << " - " << contact->getDisplayJID() << std::endl; - section.items.push_back(Item(contact->getDisplayName(), contact->getStatusText(), contact->getDisplayJID(), contact->getStatusShow(), contact->getAvatarPath())); - } - } - newSections.push_back(section); - } - } - } - - // Do a diff with the previous roster - Update update; - std::vector sectionUpdates; - std::vector sectionPostUpdates; - computeIndexDiff >(sections, newSections, sectionUpdates, sectionPostUpdates, update.deletedSections, update.insertedSections); - assert(sectionUpdates.size() == sectionPostUpdates.size()); - for (size_t i = 0; i < sectionUpdates.size(); ++i) { - assert(sectionUpdates[i] < sections.size()); - assert(sectionPostUpdates[i] < newSections.size()); - std::vector itemUpdates; - std::vector itemPostUpdates; - std::vector itemRemoves; - std::vector itemInserts; - computeIndexDiff(sections[sectionUpdates[i]].items, newSections[sectionPostUpdates[i]].items, itemUpdates, itemPostUpdates, itemRemoves, itemInserts); - size_t end = update.insertedRows.size(); - update.insertedRows.resize(update.insertedRows.size() + itemInserts.size()); - std::transform(itemInserts.begin(), itemInserts.end(), update.insertedRows.begin() + boost::numeric_cast(end), CreateIndexForSection(sectionPostUpdates[i])); - end = update.deletedRows.size(); - update.deletedRows.resize(update.deletedRows.size() + itemRemoves.size()); - std::transform(itemRemoves.begin(), itemRemoves.end(), update.deletedRows.begin() + boost::numeric_cast(end), CreateIndexForSection(sectionUpdates[i])); - end = update.updatedRows.size(); - update.updatedRows.resize(update.updatedRows.size() + itemUpdates.size()); - std::transform(itemUpdates.begin(), itemUpdates.end(), update.updatedRows.begin() + boost::numeric_cast(end), CreateIndexForSection(sectionPostUpdates[i])); - } - - // Switch the old model with the new - sections.swap(newSections); - - /* - std::cerr << "-S: "; - for (size_t i = 0; i < update.deletedSections.size(); ++i) { - std::cerr << update.deletedSections[i] << " "; - } - std::cerr << std::endl; - std::cerr << "+S: "; - for (size_t i = 0; i < update.insertedSections.size(); ++i) { - std::cerr << update.insertedSections[i] << " "; - } - std::cerr << std::endl; - std::cerr << "-R: "; - for (size_t i = 0; i < update.deletedRows.size(); ++i) { - std::cerr << update.deletedRows[i].section << "," << update.deletedRows[i].row << " "; - } - std::cerr << std::endl; - std::cerr << "*R: "; - for (size_t i = 0; i < update.updatedRows.size(); ++i) { - std::cerr << update.updatedRows[i].section << "," << update.updatedRows[i].row << " "; - } - std::cerr << std::endl; - std::cerr << "+R: "; - for (size_t i = 0; i < update.insertedRows.size(); ++i) { - std::cerr << update.insertedRows[i].section << "," << update.insertedRows[i].row << " "; - } - std::cerr << std::endl; - */ - - // Emit the update - onUpdate(update); + updateTimer->stop(); + updatePending = false; + + // Get a model for the new roster + std::vector
newSections; + if (model) { + foreach(RosterItem* item, model->getRoot()->getDisplayedChildren()) { + if (GroupRosterItem* groupItem = boost::polymorphic_downcast(item)) { + //std::cerr << "* " << groupItem->getDisplayName() << std::endl; + Section section(groupItem->getDisplayName()); + foreach(RosterItem* groupChildItem, groupItem->getDisplayedChildren()) { + if (ContactRosterItem* contact = boost::polymorphic_downcast(groupChildItem)) { + //std::cerr << " - " << contact->getDisplayJID() << std::endl; + section.items.push_back(Item(contact->getDisplayName(), contact->getStatusText(), contact->getDisplayJID(), contact->getStatusShow(), contact->getAvatarPath())); + } + } + newSections.push_back(section); + } + } + } + + // Do a diff with the previous roster + Update update; + std::vector sectionUpdates; + std::vector sectionPostUpdates; + computeIndexDiff >(sections, newSections, sectionUpdates, sectionPostUpdates, update.deletedSections, update.insertedSections); + assert(sectionUpdates.size() == sectionPostUpdates.size()); + for (size_t i = 0; i < sectionUpdates.size(); ++i) { + assert(sectionUpdates[i] < sections.size()); + assert(sectionPostUpdates[i] < newSections.size()); + std::vector itemUpdates; + std::vector itemPostUpdates; + std::vector itemRemoves; + std::vector itemInserts; + computeIndexDiff(sections[sectionUpdates[i]].items, newSections[sectionPostUpdates[i]].items, itemUpdates, itemPostUpdates, itemRemoves, itemInserts); + size_t end = update.insertedRows.size(); + update.insertedRows.resize(update.insertedRows.size() + itemInserts.size()); + std::transform(itemInserts.begin(), itemInserts.end(), update.insertedRows.begin() + boost::numeric_cast(end), CreateIndexForSection(sectionPostUpdates[i])); + end = update.deletedRows.size(); + update.deletedRows.resize(update.deletedRows.size() + itemRemoves.size()); + std::transform(itemRemoves.begin(), itemRemoves.end(), update.deletedRows.begin() + boost::numeric_cast(end), CreateIndexForSection(sectionUpdates[i])); + end = update.updatedRows.size(); + update.updatedRows.resize(update.updatedRows.size() + itemUpdates.size()); + std::transform(itemUpdates.begin(), itemUpdates.end(), update.updatedRows.begin() + boost::numeric_cast(end), CreateIndexForSection(sectionPostUpdates[i])); + } + + // Switch the old model with the new + sections.swap(newSections); + + /* + std::cerr << "-S: "; + for (size_t i = 0; i < update.deletedSections.size(); ++i) { + std::cerr << update.deletedSections[i] << " "; + } + std::cerr << std::endl; + std::cerr << "+S: "; + for (size_t i = 0; i < update.insertedSections.size(); ++i) { + std::cerr << update.insertedSections[i] << " "; + } + std::cerr << std::endl; + std::cerr << "-R: "; + for (size_t i = 0; i < update.deletedRows.size(); ++i) { + std::cerr << update.deletedRows[i].section << "," << update.deletedRows[i].row << " "; + } + std::cerr << std::endl; + std::cerr << "*R: "; + for (size_t i = 0; i < update.updatedRows.size(); ++i) { + std::cerr << update.updatedRows[i].section << "," << update.updatedRows[i].row << " "; + } + std::cerr << std::endl; + std::cerr << "+R: "; + for (size_t i = 0; i < update.insertedRows.size(); ++i) { + std::cerr << update.insertedRows[i].section << "," << update.insertedRows[i].row << " "; + } + std::cerr << std::endl; + */ + + // Emit the update + onUpdate(update); } void TableRoster::scheduleUpdate() { - if (!updatePending) { - updatePending = true; - updateTimer->start(); - } + if (!updatePending) { + updatePending = true; + updateTimer->start(); + } } diff --git a/Swift/Controllers/Roster/TableRoster.h b/Swift/Controllers/Roster/TableRoster.h index 87f9e75..3d336ef 100644 --- a/Swift/Controllers/Roster/TableRoster.h +++ b/Swift/Controllers/Roster/TableRoster.h @@ -16,70 +16,70 @@ #include namespace Swift { - class Roster; - class TimerFactory; - class Timer; - - class TableRoster { - public: - struct Item { - Item(const std::string& name, const std::string& description, const JID& jid, StatusShow::Type status, const boost::filesystem::path& avatarPath) : name(name), description(description), jid(jid), status(status), avatarPath(avatarPath) { - } - std::string name; - std::string description; - JID jid; - StatusShow::Type status; - boost::filesystem::path avatarPath; - }; - - struct Index { - Index(size_t section = 0, size_t row = 0) : section(section), row(row) { - } - size_t section; - size_t row; - - bool operator==(const Index& o) const { - return o.section == section && o.row == row; - } - }; - - struct Update { - std::vector updatedRows; - std::vector insertedRows; - std::vector deletedRows; - std::vector insertedSections; - std::vector deletedSections; - }; - - TableRoster(Roster* model, TimerFactory* timerFactory, int updateDelay); - ~TableRoster(); - - size_t getNumberOfSections() const; - size_t getNumberOfRowsInSection(size_t section) const; - - const std::string& getSectionTitle(size_t); - - const Item& getItem(const Index&) const; - - boost::signal onUpdate; - - private: - void handleUpdateTimerTick(); - void scheduleUpdate(); - - private: - friend struct SectionNameEquals; - struct Section { - Section(const std::string& name) : name(name) { - } - - std::string name; - std::vector items; - }; - - Roster* model; - std::vector
sections; - bool updatePending; - boost::shared_ptr updateTimer; - }; + class Roster; + class TimerFactory; + class Timer; + + class TableRoster { + public: + struct Item { + Item(const std::string& name, const std::string& description, const JID& jid, StatusShow::Type status, const boost::filesystem::path& avatarPath) : name(name), description(description), jid(jid), status(status), avatarPath(avatarPath) { + } + std::string name; + std::string description; + JID jid; + StatusShow::Type status; + boost::filesystem::path avatarPath; + }; + + struct Index { + Index(size_t section = 0, size_t row = 0) : section(section), row(row) { + } + size_t section; + size_t row; + + bool operator==(const Index& o) const { + return o.section == section && o.row == row; + } + }; + + struct Update { + std::vector updatedRows; + std::vector insertedRows; + std::vector deletedRows; + std::vector insertedSections; + std::vector deletedSections; + }; + + TableRoster(Roster* model, TimerFactory* timerFactory, int updateDelay); + ~TableRoster(); + + size_t getNumberOfSections() const; + size_t getNumberOfRowsInSection(size_t section) const; + + const std::string& getSectionTitle(size_t); + + const Item& getItem(const Index&) const; + + boost::signal onUpdate; + + private: + void handleUpdateTimerTick(); + void scheduleUpdate(); + + private: + friend struct SectionNameEquals; + struct Section { + Section(const std::string& name) : name(name) { + } + + std::string name; + std::vector items; + }; + + Roster* model; + std::vector
sections; + bool updatePending; + boost::shared_ptr updateTimer; + }; } diff --git a/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp b/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp index 144de77..5844ebe 100644 --- a/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp +++ b/Swift/Controllers/Roster/UnitTest/LeastCommonSubsequenceTest.cpp @@ -18,294 +18,294 @@ using namespace Swift; struct IsBOrC { - bool operator()(char c, char c2) const { - CPPUNIT_ASSERT_EQUAL(c, c2); - return c == 'b' || c == 'c'; - } + bool operator()(char c, char c2) const { + CPPUNIT_ASSERT_EQUAL(c, c2); + return c == 'b' || c == 'c'; + } }; struct IsXOrY { - bool operator()(char c, char c2) const { - CPPUNIT_ASSERT_EQUAL(c, c2); - return c == 'x' || c == 'y'; - } + bool operator()(char c, char c2) const { + CPPUNIT_ASSERT_EQUAL(c, c2); + return c == 'x' || c == 'y'; + } }; struct IsArizonaOrNewJersey { - bool operator()(const std::string& s, const std::string& s2) const { - CPPUNIT_ASSERT_EQUAL(s, s2); - return s == "Arizona" || s == "New Jersey"; - } + bool operator()(const std::string& s, const std::string& s2) const { + CPPUNIT_ASSERT_EQUAL(s, s2); + return s == "Arizona" || s == "New Jersey"; + } }; class LeastCommonSubsequenceTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(LeastCommonSubsequenceTest); - CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_1); - CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_2); - CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence1Empty); - CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence2Empty); - CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty); - CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_NoCommonSequence); - CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_SameSequences); - CPPUNIT_TEST(testComputeIndexDiff_1); - CPPUNIT_TEST(testComputeIndexDiff_2); - CPPUNIT_TEST(testComputeIndexDiff_Sequence1Empty); - CPPUNIT_TEST(testComputeIndexDiff_Sequence2Empty); - CPPUNIT_TEST(testComputeIndexDiff_BothSequencesEmpty); - CPPUNIT_TEST(testComputeIndexDiff_NoCommonSequence); - CPPUNIT_TEST(testComputeIndexDiff_SameSequences); - CPPUNIT_TEST(testComputeIndexDiff_CommonPrefixAndSuffix); - CPPUNIT_TEST_SUITE_END(); - - public: - void testComputeLeastCommonSubsequenceMatrix_1() { - std::vector x = boost::assign::list_of('x')('m')('j')('y')('a')('u')('z'); - std::vector y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u'); - - std::vector result; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); - - std::vector expected = boost::assign::list_of - (0)(0)(0)(0)(0)(0)(0)(0) - (0)(0)(1)(1)(1)(1)(1)(1) - (0)(0)(1)(1)(1)(1)(1)(2) - (0)(0)(1)(2)(2)(2)(2)(2) - (0)(0)(1)(2)(2)(3)(3)(3) - (0)(0)(1)(2)(2)(3)(3)(3) - (0)(1)(1)(2)(2)(3)(3)(3) - (0)(1)(1)(2)(2)(3)(4)(4); - CPPUNIT_ASSERT_EQUAL(expected, result); - } - - void testComputeLeastCommonSubsequenceMatrix_2() { - std::vector x = boost::assign::list_of('x')('x')('x')('m')('j')('y')('a')('u')('z'); - std::vector y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u'); - - std::vector result; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); - - std::vector expected = boost::assign::list_of - (0)(0)(0)(0)(0)(0)(0)(0)(0)(0) - (0)(0)(0)(0)(1)(1)(1)(1)(1)(1) - (0)(0)(0)(0)(1)(1)(1)(1)(1)(2) - (0)(0)(0)(0)(1)(2)(2)(2)(2)(2) - (0)(0)(0)(0)(1)(2)(2)(3)(3)(3) - (0)(0)(0)(0)(1)(2)(2)(3)(3)(3) - (0)(1)(1)(1)(1)(2)(2)(3)(3)(3) - (0)(1)(1)(1)(1)(2)(2)(3)(4)(4); - CPPUNIT_ASSERT_EQUAL(expected, result); - } - - void testComputeLeastCommonSubsequenceMatrix_Sequence1Empty() { - std::vector x; - std::vector y = boost::assign::list_of('a')('b')('c'); - - std::vector result; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); - - std::vector expected = boost::assign::list_of - (0) - (0) - (0) - (0); - CPPUNIT_ASSERT_EQUAL(expected, result); - } - - void testComputeLeastCommonSubsequenceMatrix_Sequence2Empty() { - std::vector x = boost::assign::list_of('a')('b')('c'); - std::vector y; - - std::vector result; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); - - std::vector expected = boost::assign::list_of - (0)(0)(0)(0); - CPPUNIT_ASSERT_EQUAL(expected, result); - } - - void testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty() { - std::vector x; - std::vector y; - - std::vector result; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); - - std::vector expected = boost::assign::list_of(0); - CPPUNIT_ASSERT_EQUAL(expected, result); - } - - void testComputeLeastCommonSubsequenceMatrix_NoCommonSequence() { - std::vector x = boost::assign::list_of('a')('b')('c'); - std::vector y = boost::assign::list_of('d')('e')('f')('g'); - - std::vector result; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); - - std::vector expected = boost::assign::list_of - (0)(0)(0)(0) - (0)(0)(0)(0) - (0)(0)(0)(0) - (0)(0)(0)(0) - (0)(0)(0)(0); - CPPUNIT_ASSERT_EQUAL(expected, result); - } - - void testComputeLeastCommonSubsequenceMatrix_SameSequences() { - std::vector x = boost::assign::list_of('a')('b')('c'); - std::vector y = boost::assign::list_of('a')('b')('c'); - - std::vector result; - Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); - - std::vector expected = boost::assign::list_of - (0)(0)(0)(0) - (0)(1)(1)(1) - (0)(1)(2)(2) - (0)(1)(2)(3); - CPPUNIT_ASSERT_EQUAL(expected, result); - } - - void testComputeIndexDiff_1() { - std::vector x = boost::assign::list_of("Arizona")("California")("Delaware")("New Jersey")("Washington"); - std::vector y = boost::assign::list_of("Alaska")("Arizona")("California")("Georgia")("New Jersey")("Virginia"); - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsArizonaOrNewJersey >(x, y, updates, postUpdates, removes, inserts); - - std::vector expectedUpdates = boost::assign::list_of(3)(0); - std::vector expectedPostUpdates = boost::assign::list_of(4)(1); - std::vector expectedRemoves = boost::assign::list_of(4)(2); - std::vector expectedInserts = boost::assign::list_of(5)(3)(0); - CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates); - CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates); - CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); - CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); - } - - void testComputeIndexDiff_2() { - std::vector x = boost::assign::list_of('x')('y'); - std::vector y = boost::assign::list_of('x'); - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); - - std::vector expectedRemoves = boost::assign::list_of(1); - CPPUNIT_ASSERT(updates.empty()); - CPPUNIT_ASSERT(postUpdates.empty()); - CPPUNIT_ASSERT(inserts.empty()); - CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); - } - - void testComputeIndexDiff_Sequence1Empty() { - std::vector x; - std::vector y = boost::assign::list_of('a')('b')('c'); - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); - - std::vector expectedInserts = boost::assign::list_of(2)(1)(0); - CPPUNIT_ASSERT(updates.empty()); - CPPUNIT_ASSERT(postUpdates.empty()); - CPPUNIT_ASSERT(removes.empty()); - CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); - } - - void testComputeIndexDiff_Sequence2Empty() { - std::vector x = boost::assign::list_of('a')('b')('c'); - std::vector y; - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); - - std::vector expectedRemoves = boost::assign::list_of(2)(1)(0); - CPPUNIT_ASSERT(updates.empty()); - CPPUNIT_ASSERT(postUpdates.empty()); - CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); - CPPUNIT_ASSERT(inserts.empty()); - } - - void testComputeIndexDiff_BothSequencesEmpty() { - std::vector x; - std::vector y; - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); - - CPPUNIT_ASSERT(updates.empty()); - CPPUNIT_ASSERT(postUpdates.empty()); - CPPUNIT_ASSERT(removes.empty()); - CPPUNIT_ASSERT(inserts.empty()); - } - - void testComputeIndexDiff_NoCommonSequence() { - std::vector x = boost::assign::list_of('a')('b')('c'); - std::vector y = boost::assign::list_of('d')('e')('f')('g'); - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); - - std::vector expectedRemoves = boost::assign::list_of(2)(1)(0); - std::vector expectedInserts = boost::assign::list_of(3)(2)(1)(0); - CPPUNIT_ASSERT(updates.empty()); - CPPUNIT_ASSERT(postUpdates.empty()); - CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); - CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); - } - - void testComputeIndexDiff_SameSequences() { - std::vector x = boost::assign::list_of('a')('b')('c'); - std::vector y = boost::assign::list_of('a')('b')('c'); - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); - - std::vector expectedUpdates = boost::assign::list_of(1)(2); - CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates); - CPPUNIT_ASSERT_EQUAL(expectedUpdates, postUpdates); - CPPUNIT_ASSERT(removes.empty()); - CPPUNIT_ASSERT(inserts.empty()); - } - - void testComputeIndexDiff_CommonPrefixAndSuffix() { - std::vector x = boost::assign::list_of('x')('x')('x')('x')('a')('b')('c')('d')('e')('y')('y')('y'); - std::vector y = boost::assign::list_of('x')('x')('x')('x')('e')('a')('b')('f')('d')('g')('y')('y')('y'); - - std::vector updates; - std::vector postUpdates; - std::vector removes; - std::vector inserts; - computeIndexDiff, IsXOrY >(x, y, updates, postUpdates, removes, inserts); - - std::vector expectedUpdates = boost::assign::list_of(0)(1)(2)(3)(11)(10)(9); - std::vector expectedPostUpdates = boost::assign::list_of(0)(1)(2)(3)(12)(11)(10); - std::vector expectedRemoves = boost::assign::list_of(8)(6); - std::vector expectedInserts = boost::assign::list_of(9)(7)(4); - CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates); - CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates); - CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); - CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); - } + CPPUNIT_TEST_SUITE(LeastCommonSubsequenceTest); + CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_1); + CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_2); + CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence1Empty); + CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_Sequence2Empty); + CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty); + CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_NoCommonSequence); + CPPUNIT_TEST(testComputeLeastCommonSubsequenceMatrix_SameSequences); + CPPUNIT_TEST(testComputeIndexDiff_1); + CPPUNIT_TEST(testComputeIndexDiff_2); + CPPUNIT_TEST(testComputeIndexDiff_Sequence1Empty); + CPPUNIT_TEST(testComputeIndexDiff_Sequence2Empty); + CPPUNIT_TEST(testComputeIndexDiff_BothSequencesEmpty); + CPPUNIT_TEST(testComputeIndexDiff_NoCommonSequence); + CPPUNIT_TEST(testComputeIndexDiff_SameSequences); + CPPUNIT_TEST(testComputeIndexDiff_CommonPrefixAndSuffix); + CPPUNIT_TEST_SUITE_END(); + + public: + void testComputeLeastCommonSubsequenceMatrix_1() { + std::vector x = boost::assign::list_of('x')('m')('j')('y')('a')('u')('z'); + std::vector y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u'); + + std::vector result; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); + + std::vector expected = boost::assign::list_of + (0)(0)(0)(0)(0)(0)(0)(0) + (0)(0)(1)(1)(1)(1)(1)(1) + (0)(0)(1)(1)(1)(1)(1)(2) + (0)(0)(1)(2)(2)(2)(2)(2) + (0)(0)(1)(2)(2)(3)(3)(3) + (0)(0)(1)(2)(2)(3)(3)(3) + (0)(1)(1)(2)(2)(3)(3)(3) + (0)(1)(1)(2)(2)(3)(4)(4); + CPPUNIT_ASSERT_EQUAL(expected, result); + } + + void testComputeLeastCommonSubsequenceMatrix_2() { + std::vector x = boost::assign::list_of('x')('x')('x')('m')('j')('y')('a')('u')('z'); + std::vector y = boost::assign::list_of('m')('z')('j')('a')('w')('x')('u'); + + std::vector result; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); + + std::vector expected = boost::assign::list_of + (0)(0)(0)(0)(0)(0)(0)(0)(0)(0) + (0)(0)(0)(0)(1)(1)(1)(1)(1)(1) + (0)(0)(0)(0)(1)(1)(1)(1)(1)(2) + (0)(0)(0)(0)(1)(2)(2)(2)(2)(2) + (0)(0)(0)(0)(1)(2)(2)(3)(3)(3) + (0)(0)(0)(0)(1)(2)(2)(3)(3)(3) + (0)(1)(1)(1)(1)(2)(2)(3)(3)(3) + (0)(1)(1)(1)(1)(2)(2)(3)(4)(4); + CPPUNIT_ASSERT_EQUAL(expected, result); + } + + void testComputeLeastCommonSubsequenceMatrix_Sequence1Empty() { + std::vector x; + std::vector y = boost::assign::list_of('a')('b')('c'); + + std::vector result; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); + + std::vector expected = boost::assign::list_of + (0) + (0) + (0) + (0); + CPPUNIT_ASSERT_EQUAL(expected, result); + } + + void testComputeLeastCommonSubsequenceMatrix_Sequence2Empty() { + std::vector x = boost::assign::list_of('a')('b')('c'); + std::vector y; + + std::vector result; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); + + std::vector expected = boost::assign::list_of + (0)(0)(0)(0); + CPPUNIT_ASSERT_EQUAL(expected, result); + } + + void testComputeLeastCommonSubsequenceMatrix_BothSequencesEmpty() { + std::vector x; + std::vector y; + + std::vector result; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); + + std::vector expected = boost::assign::list_of(0); + CPPUNIT_ASSERT_EQUAL(expected, result); + } + + void testComputeLeastCommonSubsequenceMatrix_NoCommonSequence() { + std::vector x = boost::assign::list_of('a')('b')('c'); + std::vector y = boost::assign::list_of('d')('e')('f')('g'); + + std::vector result; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); + + std::vector expected = boost::assign::list_of + (0)(0)(0)(0) + (0)(0)(0)(0) + (0)(0)(0)(0) + (0)(0)(0)(0) + (0)(0)(0)(0); + CPPUNIT_ASSERT_EQUAL(expected, result); + } + + void testComputeLeastCommonSubsequenceMatrix_SameSequences() { + std::vector x = boost::assign::list_of('a')('b')('c'); + std::vector y = boost::assign::list_of('a')('b')('c'); + + std::vector result; + Detail::computeLeastCommonSubsequenceMatrix::const_iterator, std::vector::const_iterator, int, std::equal_to >(x.begin(), x.end(), y.begin(), y.end(), result); + + std::vector expected = boost::assign::list_of + (0)(0)(0)(0) + (0)(1)(1)(1) + (0)(1)(2)(2) + (0)(1)(2)(3); + CPPUNIT_ASSERT_EQUAL(expected, result); + } + + void testComputeIndexDiff_1() { + std::vector x = boost::assign::list_of("Arizona")("California")("Delaware")("New Jersey")("Washington"); + std::vector y = boost::assign::list_of("Alaska")("Arizona")("California")("Georgia")("New Jersey")("Virginia"); + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsArizonaOrNewJersey >(x, y, updates, postUpdates, removes, inserts); + + std::vector expectedUpdates = boost::assign::list_of(3)(0); + std::vector expectedPostUpdates = boost::assign::list_of(4)(1); + std::vector expectedRemoves = boost::assign::list_of(4)(2); + std::vector expectedInserts = boost::assign::list_of(5)(3)(0); + CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates); + CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates); + CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); + CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); + } + + void testComputeIndexDiff_2() { + std::vector x = boost::assign::list_of('x')('y'); + std::vector y = boost::assign::list_of('x'); + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); + + std::vector expectedRemoves = boost::assign::list_of(1); + CPPUNIT_ASSERT(updates.empty()); + CPPUNIT_ASSERT(postUpdates.empty()); + CPPUNIT_ASSERT(inserts.empty()); + CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); + } + + void testComputeIndexDiff_Sequence1Empty() { + std::vector x; + std::vector y = boost::assign::list_of('a')('b')('c'); + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); + + std::vector expectedInserts = boost::assign::list_of(2)(1)(0); + CPPUNIT_ASSERT(updates.empty()); + CPPUNIT_ASSERT(postUpdates.empty()); + CPPUNIT_ASSERT(removes.empty()); + CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); + } + + void testComputeIndexDiff_Sequence2Empty() { + std::vector x = boost::assign::list_of('a')('b')('c'); + std::vector y; + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); + + std::vector expectedRemoves = boost::assign::list_of(2)(1)(0); + CPPUNIT_ASSERT(updates.empty()); + CPPUNIT_ASSERT(postUpdates.empty()); + CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); + CPPUNIT_ASSERT(inserts.empty()); + } + + void testComputeIndexDiff_BothSequencesEmpty() { + std::vector x; + std::vector y; + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); + + CPPUNIT_ASSERT(updates.empty()); + CPPUNIT_ASSERT(postUpdates.empty()); + CPPUNIT_ASSERT(removes.empty()); + CPPUNIT_ASSERT(inserts.empty()); + } + + void testComputeIndexDiff_NoCommonSequence() { + std::vector x = boost::assign::list_of('a')('b')('c'); + std::vector y = boost::assign::list_of('d')('e')('f')('g'); + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); + + std::vector expectedRemoves = boost::assign::list_of(2)(1)(0); + std::vector expectedInserts = boost::assign::list_of(3)(2)(1)(0); + CPPUNIT_ASSERT(updates.empty()); + CPPUNIT_ASSERT(postUpdates.empty()); + CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); + CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); + } + + void testComputeIndexDiff_SameSequences() { + std::vector x = boost::assign::list_of('a')('b')('c'); + std::vector y = boost::assign::list_of('a')('b')('c'); + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsBOrC >(x, y, updates, postUpdates, removes, inserts); + + std::vector expectedUpdates = boost::assign::list_of(1)(2); + CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates); + CPPUNIT_ASSERT_EQUAL(expectedUpdates, postUpdates); + CPPUNIT_ASSERT(removes.empty()); + CPPUNIT_ASSERT(inserts.empty()); + } + + void testComputeIndexDiff_CommonPrefixAndSuffix() { + std::vector x = boost::assign::list_of('x')('x')('x')('x')('a')('b')('c')('d')('e')('y')('y')('y'); + std::vector y = boost::assign::list_of('x')('x')('x')('x')('e')('a')('b')('f')('d')('g')('y')('y')('y'); + + std::vector updates; + std::vector postUpdates; + std::vector removes; + std::vector inserts; + computeIndexDiff, IsXOrY >(x, y, updates, postUpdates, removes, inserts); + + std::vector expectedUpdates = boost::assign::list_of(0)(1)(2)(3)(11)(10)(9); + std::vector expectedPostUpdates = boost::assign::list_of(0)(1)(2)(3)(12)(11)(10); + std::vector expectedRemoves = boost::assign::list_of(8)(6); + std::vector expectedInserts = boost::assign::list_of(9)(7)(4); + CPPUNIT_ASSERT_EQUAL(expectedUpdates, updates); + CPPUNIT_ASSERT_EQUAL(expectedPostUpdates, postUpdates); + CPPUNIT_ASSERT_EQUAL(expectedRemoves, removes); + CPPUNIT_ASSERT_EQUAL(expectedInserts, inserts); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(LeastCommonSubsequenceTest); diff --git a/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp b/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp index d774e6d..551bd6b 100644 --- a/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp +++ b/Swift/Controllers/Roster/UnitTest/RosterControllerTest.cpp @@ -46,351 +46,351 @@ using namespace Swift; #define CHILDREN mainWindow_->roster->getRoot()->getChildren() class DummyCapsProvider : public CapsProvider { - DiscoInfo::ref getCaps(const std::string&) const {return DiscoInfo::ref(new DiscoInfo());} + DiscoInfo::ref getCaps(const std::string&) const {return DiscoInfo::ref(new DiscoInfo());} }; class RosterControllerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(RosterControllerTest); - CPPUNIT_TEST(testAdd); - CPPUNIT_TEST(testAddSubscription); - CPPUNIT_TEST(testReceiveRename); - CPPUNIT_TEST(testReceiveRegroup); - CPPUNIT_TEST(testSendRename); - CPPUNIT_TEST(testPresence); - CPPUNIT_TEST(testHighestPresence); - CPPUNIT_TEST(testNotHighestPresence); - CPPUNIT_TEST(testUnavailablePresence); - CPPUNIT_TEST(testRemoveResultsInUnavailablePresence); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - jid_ = JID("testjid@swift.im/swift"); - xmppRoster_ = new XMPPRosterImpl(); - avatarManager_ = new NullAvatarManager(); - mainWindowFactory_ = new MockMainWindowFactory(); - mucRegistry_ = new MUCRegistry(); - nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_); - channel_ = new DummyIQChannel(); - router_ = new IQRouter(channel_); - stanzaChannel_ = new DummyStanzaChannel(); - presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_); - subscriptionManager_ = new SubscriptionManager(stanzaChannel_); - eventController_ = new EventController(); - uiEventStream_ = new UIEventStream(); - settings_ = new DummySettingsProvider(); - nickManager_ = new DummyNickManager(); - capsProvider_ = new DummyCapsProvider(); - entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_); - jingleSessionManager_ = new JingleSessionManager(router_); - - ftManager_ = new DummyFileTransferManager(); - ftOverview_ = new FileTransferOverview(ftManager_); - clientBlockListManager_ = new ClientBlockListManager(router_); - crypto_ = PlatformCryptoProvider::create(); - vcardStorage_ = new VCardMemoryStorage(crypto_); - vcardManager_ = new VCardManager(jid_, router_, vcardStorage_); - rosterController_ = new RosterController(jid_, xmppRoster_, avatarManager_, mainWindowFactory_, nickManager_, nickResolver_, presenceOracle_, subscriptionManager_, eventController_, uiEventStream_, router_, settings_, entityCapsManager_, ftOverview_, clientBlockListManager_, vcardManager_); - mainWindow_ = mainWindowFactory_->last; - } - - void tearDown() { - delete rosterController_; - delete vcardManager_; - delete vcardStorage_; - delete crypto_; - delete clientBlockListManager_; - delete ftOverview_; - delete ftManager_; - delete jingleSessionManager_; - delete entityCapsManager_; - delete capsProvider_; - delete nickManager_; - delete nickResolver_; - delete mucRegistry_; - delete mainWindowFactory_; - delete avatarManager_; - delete router_; - delete channel_; - delete eventController_; - delete subscriptionManager_; - delete presenceOracle_; - delete stanzaChannel_; - delete uiEventStream_; - delete settings_; - delete xmppRoster_; - } - - GroupRosterItem* groupChild(size_t i) { - return dynamic_cast(CHILDREN[i]); - } - - JID withResource(const JID& jid, const std::string& resource) { - return JID(jid.toBare().toString() + "/" + resource); - } - - void testPresence() { - std::vector groups; - groups.push_back("testGroup1"); - groups.push_back("testGroup2"); - JID from("test@testdomain.com"); - xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); - Presence::ref presence(new Presence()); - presence->setFrom(withResource(from, "bob")); - presence->setPriority(2); - presence->setStatus("So totally here"); - stanzaChannel_->onPresenceReceived(presence); - ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); - CPPUNIT_ASSERT(item); - CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item->getStatusText()); - ContactRosterItem* item2 = dynamic_cast(dynamic_cast(CHILDREN[1])->getChildren()[0]); - CPPUNIT_ASSERT(item2); - CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item2->getStatusText()); - - } - - void testHighestPresence() { - std::vector groups; - groups.push_back("testGroup1"); - JID from("test@testdomain.com"); - xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); - Presence::ref lowPresence(new Presence()); - lowPresence->setFrom(withResource(from, "bob")); - lowPresence->setPriority(2); - lowPresence->setStatus("Not here"); - Presence::ref highPresence(new Presence()); - highPresence->setFrom(withResource(from, "bert")); - highPresence->setPriority(10); - highPresence->setStatus("So totally here"); - stanzaChannel_->onPresenceReceived(lowPresence); - stanzaChannel_->onPresenceReceived(highPresence); - ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); - CPPUNIT_ASSERT(item); - CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText()); - } - - void testNotHighestPresence() { - std::vector groups; - groups.push_back("testGroup1"); - JID from("test@testdomain.com"); - xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); - Presence::ref lowPresence(new Presence()); - lowPresence->setFrom(withResource(from, "bob")); - lowPresence->setPriority(2); - lowPresence->setStatus("Not here"); - Presence::ref highPresence(new Presence()); - highPresence->setFrom(withResource(from, "bert")); - highPresence->setPriority(10); - highPresence->setStatus("So totally here"); - stanzaChannel_->onPresenceReceived(highPresence); - stanzaChannel_->onPresenceReceived(lowPresence); - ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); - CPPUNIT_ASSERT(item); - CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText()); - } - - void testUnavailablePresence() { - std::vector groups; - groups.push_back("testGroup1"); - JID from("test@testdomain.com"); - xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); - - Presence::ref lowPresence(new Presence()); - lowPresence->setFrom(withResource(from, "bob")); - lowPresence->setPriority(2); - lowPresence->setShow(StatusShow::Away); - lowPresence->setStatus("Not here"); - Presence::ref lowPresenceOffline(new Presence()); - lowPresenceOffline->setFrom(withResource(from, "bob")); - lowPresenceOffline->setStatus("Signing out"); - lowPresenceOffline->setType(Presence::Unavailable); - - Presence::ref highPresence(new Presence()); - highPresence->setFrom(withResource(from, "bert")); - highPresence->setPriority(10); - highPresence->setStatus("So totally here"); - Presence::ref highPresenceOffline(new Presence()); - highPresenceOffline->setFrom(withResource(from, "bert")); - highPresenceOffline->setType(Presence::Unavailable); - - stanzaChannel_->onPresenceReceived(lowPresence); - Presence::ref accountPresence = presenceOracle_->getAccountPresence(from); - CPPUNIT_ASSERT_EQUAL(StatusShow::Away, accountPresence->getShow()); - - stanzaChannel_->onPresenceReceived(highPresence); - accountPresence = presenceOracle_->getAccountPresence(from); - CPPUNIT_ASSERT_EQUAL(StatusShow::Online, accountPresence->getShow()); - - stanzaChannel_->onPresenceReceived(highPresenceOffline); - - // After this, the roster should show the low presence. - ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); - CPPUNIT_ASSERT(item); - - Presence::ref low = presenceOracle_->getAccountPresence(from); - - CPPUNIT_ASSERT_EQUAL(Presence::Available, low->getType()); - CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), low->getStatus()); - CPPUNIT_ASSERT_EQUAL(lowPresence->getShow(), item->getStatusShow()); - CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), item->getStatusText()); - stanzaChannel_->onPresenceReceived(lowPresenceOffline); - item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); - CPPUNIT_ASSERT(item); - /* A verification that if the test fails, it's the RosterController, not the PresenceOracle. */ - low = presenceOracle_->getHighestPriorityPresence(from); - CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, low->getType()); - CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), low->getStatus()); - CPPUNIT_ASSERT_EQUAL(StatusShow::None, item->getStatusShow()); - CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), item->getStatusText()); - } - - void testAdd() { - std::vector groups; - groups.push_back("testGroup1"); - groups.push_back("testGroup2"); - xmppRoster_->addContact(JID("test@testdomain.com/bob"), "name", groups, RosterItemPayload::Both); - - CPPUNIT_ASSERT_EQUAL(2, static_cast(CHILDREN.size())); - //CPPUNIT_ASSERT_EQUAL(std::string("Bob"), xmppRoster_->getNameForJID(JID("foo@bar.com"))); - } - - void testAddSubscription() { - std::vector groups; - JID jid("test@testdomain.com"); - xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::None); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::To); - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - - xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both); - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - - } - - void testReceiveRename() { - std::vector groups; - JID jid("test@testdomain.com"); - xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(std::string("name"), groupChild(0)->getChildren()[0]->getDisplayName()); - xmppRoster_->addContact(jid, "NewName", groups, RosterItemPayload::Both); - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(std::string("NewName"), groupChild(0)->getChildren()[0]->getDisplayName()); - } - - void testReceiveRegroup() { - std::vector oldGroups; - std::vector newGroups; - newGroups.push_back("A Group"); - std::vector newestGroups; - newestGroups.push_back("Best Group"); - JID jid("test@testdomain.com"); - xmppRoster_->addContact(jid, "", oldGroups, RosterItemPayload::Both); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(jid.toString(), groupChild(0)->getChildren()[0]->getDisplayName()); - - xmppRoster_->addContact(jid, "new name", newGroups, RosterItemPayload::Both); - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("A Group"), groupChild(0)->getDisplayName()); - - xmppRoster_->addContact(jid, "new name", newestGroups, RosterItemPayload::Both); - CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); - CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("Best Group"), groupChild(0)->getDisplayName()); - } - - void testSendRename() { - JID jid("testling@wonderland.lit"); - std::vector groups; - groups.push_back("Friends"); - groups.push_back("Enemies"); - xmppRoster_->addContact(jid, "Bob", groups, RosterItemPayload::From); - CPPUNIT_ASSERT_EQUAL(groups.size(), xmppRoster_->getGroupsForJID(jid).size()); - uiEventStream_->send(boost::shared_ptr(new RenameRosterItemUIEvent(jid, "Robert"))); - CPPUNIT_ASSERT_EQUAL(static_cast(1), channel_->iqs_.size()); - CPPUNIT_ASSERT_EQUAL(IQ::Set, channel_->iqs_[0]->getType()); - boost::shared_ptr payload = channel_->iqs_[0]->getPayload(); - CPPUNIT_ASSERT_EQUAL(static_cast(1), payload->getItems().size()); - RosterItemPayload item = payload->getItems()[0]; - CPPUNIT_ASSERT_EQUAL(jid, item.getJID()); - CPPUNIT_ASSERT_EQUAL(std::string("Robert"), item.getName()); - - CPPUNIT_ASSERT_EQUAL(groups.size(), item.getGroups().size()); - assertVectorsEqual(groups, item.getGroups(), __LINE__); - } - - void testRemoveResultsInUnavailablePresence() { - std::vector groups; - groups.push_back("testGroup1"); - JID from("test@testdomain.com"); - xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); - Presence::ref lowPresence(new Presence()); - lowPresence->setFrom(withResource(from, "bob")); - lowPresence->setPriority(2); - lowPresence->setStatus("Not here"); - Presence::ref highPresence(new Presence()); - highPresence->setFrom(withResource(from, "bert")); - highPresence->setPriority(10); - highPresence->setStatus("So totally here"); - stanzaChannel_->onPresenceReceived(highPresence); - stanzaChannel_->onPresenceReceived(lowPresence); - - CPPUNIT_ASSERT_EQUAL(static_cast(2), presenceOracle_->getAllPresence("test@testdomain.com").size()); - - xmppRoster_->onJIDRemoved(JID("test@testdomain.com")); - CPPUNIT_ASSERT_EQUAL(static_cast(1), presenceOracle_->getAllPresence("test@testdomain.com").size()); - CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, presenceOracle_->getAllPresence("test@testdomain.com")[0]->getType()); - } - - void assertVectorsEqual(const std::vector& v1, const std::vector& v2, int line) { - foreach (const std::string& entry, v1) { - if (std::find(v2.begin(), v2.end(), entry) == v2.end()) { - std::stringstream stream; - stream << "Couldn't find " << entry << " in v2 (line " << line << ")"; - CPPUNIT_FAIL(stream.str()); - } - } - } - - private: - JID jid_; - XMPPRosterImpl* xmppRoster_; - MUCRegistry* mucRegistry_; - AvatarManager* avatarManager_; - MockMainWindowFactory* mainWindowFactory_; - NickManager* nickManager_; - NickResolver* nickResolver_; - RosterController* rosterController_; - DummyIQChannel* channel_; - DummyStanzaChannel* stanzaChannel_; - IQRouter* router_; - PresenceOracle* presenceOracle_; - SubscriptionManager* subscriptionManager_; - EventController* eventController_; - UIEventStream* uiEventStream_; - MockMainWindow* mainWindow_; - DummySettingsProvider* settings_; - DummyCapsProvider* capsProvider_; - EntityCapsManager* entityCapsManager_; - JingleSessionManager* jingleSessionManager_; - FileTransferManager* ftManager_; - FileTransferOverview* ftOverview_; - ClientBlockListManager* clientBlockListManager_; - CryptoProvider* crypto_; - VCardStorage* vcardStorage_; - VCardManager* vcardManager_; + CPPUNIT_TEST_SUITE(RosterControllerTest); + CPPUNIT_TEST(testAdd); + CPPUNIT_TEST(testAddSubscription); + CPPUNIT_TEST(testReceiveRename); + CPPUNIT_TEST(testReceiveRegroup); + CPPUNIT_TEST(testSendRename); + CPPUNIT_TEST(testPresence); + CPPUNIT_TEST(testHighestPresence); + CPPUNIT_TEST(testNotHighestPresence); + CPPUNIT_TEST(testUnavailablePresence); + CPPUNIT_TEST(testRemoveResultsInUnavailablePresence); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + jid_ = JID("testjid@swift.im/swift"); + xmppRoster_ = new XMPPRosterImpl(); + avatarManager_ = new NullAvatarManager(); + mainWindowFactory_ = new MockMainWindowFactory(); + mucRegistry_ = new MUCRegistry(); + nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_); + channel_ = new DummyIQChannel(); + router_ = new IQRouter(channel_); + stanzaChannel_ = new DummyStanzaChannel(); + presenceOracle_ = new PresenceOracle(stanzaChannel_, xmppRoster_); + subscriptionManager_ = new SubscriptionManager(stanzaChannel_); + eventController_ = new EventController(); + uiEventStream_ = new UIEventStream(); + settings_ = new DummySettingsProvider(); + nickManager_ = new DummyNickManager(); + capsProvider_ = new DummyCapsProvider(); + entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_); + jingleSessionManager_ = new JingleSessionManager(router_); + + ftManager_ = new DummyFileTransferManager(); + ftOverview_ = new FileTransferOverview(ftManager_); + clientBlockListManager_ = new ClientBlockListManager(router_); + crypto_ = PlatformCryptoProvider::create(); + vcardStorage_ = new VCardMemoryStorage(crypto_); + vcardManager_ = new VCardManager(jid_, router_, vcardStorage_); + rosterController_ = new RosterController(jid_, xmppRoster_, avatarManager_, mainWindowFactory_, nickManager_, nickResolver_, presenceOracle_, subscriptionManager_, eventController_, uiEventStream_, router_, settings_, entityCapsManager_, ftOverview_, clientBlockListManager_, vcardManager_); + mainWindow_ = mainWindowFactory_->last; + } + + void tearDown() { + delete rosterController_; + delete vcardManager_; + delete vcardStorage_; + delete crypto_; + delete clientBlockListManager_; + delete ftOverview_; + delete ftManager_; + delete jingleSessionManager_; + delete entityCapsManager_; + delete capsProvider_; + delete nickManager_; + delete nickResolver_; + delete mucRegistry_; + delete mainWindowFactory_; + delete avatarManager_; + delete router_; + delete channel_; + delete eventController_; + delete subscriptionManager_; + delete presenceOracle_; + delete stanzaChannel_; + delete uiEventStream_; + delete settings_; + delete xmppRoster_; + } + + GroupRosterItem* groupChild(size_t i) { + return dynamic_cast(CHILDREN[i]); + } + + JID withResource(const JID& jid, const std::string& resource) { + return JID(jid.toBare().toString() + "/" + resource); + } + + void testPresence() { + std::vector groups; + groups.push_back("testGroup1"); + groups.push_back("testGroup2"); + JID from("test@testdomain.com"); + xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); + Presence::ref presence(new Presence()); + presence->setFrom(withResource(from, "bob")); + presence->setPriority(2); + presence->setStatus("So totally here"); + stanzaChannel_->onPresenceReceived(presence); + ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); + CPPUNIT_ASSERT(item); + CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item->getStatusText()); + ContactRosterItem* item2 = dynamic_cast(dynamic_cast(CHILDREN[1])->getChildren()[0]); + CPPUNIT_ASSERT(item2); + CPPUNIT_ASSERT_EQUAL(presence->getStatus(), item2->getStatusText()); + + } + + void testHighestPresence() { + std::vector groups; + groups.push_back("testGroup1"); + JID from("test@testdomain.com"); + xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); + Presence::ref lowPresence(new Presence()); + lowPresence->setFrom(withResource(from, "bob")); + lowPresence->setPriority(2); + lowPresence->setStatus("Not here"); + Presence::ref highPresence(new Presence()); + highPresence->setFrom(withResource(from, "bert")); + highPresence->setPriority(10); + highPresence->setStatus("So totally here"); + stanzaChannel_->onPresenceReceived(lowPresence); + stanzaChannel_->onPresenceReceived(highPresence); + ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); + CPPUNIT_ASSERT(item); + CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText()); + } + + void testNotHighestPresence() { + std::vector groups; + groups.push_back("testGroup1"); + JID from("test@testdomain.com"); + xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); + Presence::ref lowPresence(new Presence()); + lowPresence->setFrom(withResource(from, "bob")); + lowPresence->setPriority(2); + lowPresence->setStatus("Not here"); + Presence::ref highPresence(new Presence()); + highPresence->setFrom(withResource(from, "bert")); + highPresence->setPriority(10); + highPresence->setStatus("So totally here"); + stanzaChannel_->onPresenceReceived(highPresence); + stanzaChannel_->onPresenceReceived(lowPresence); + ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); + CPPUNIT_ASSERT(item); + CPPUNIT_ASSERT_EQUAL(highPresence->getStatus(), item->getStatusText()); + } + + void testUnavailablePresence() { + std::vector groups; + groups.push_back("testGroup1"); + JID from("test@testdomain.com"); + xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); + + Presence::ref lowPresence(new Presence()); + lowPresence->setFrom(withResource(from, "bob")); + lowPresence->setPriority(2); + lowPresence->setShow(StatusShow::Away); + lowPresence->setStatus("Not here"); + Presence::ref lowPresenceOffline(new Presence()); + lowPresenceOffline->setFrom(withResource(from, "bob")); + lowPresenceOffline->setStatus("Signing out"); + lowPresenceOffline->setType(Presence::Unavailable); + + Presence::ref highPresence(new Presence()); + highPresence->setFrom(withResource(from, "bert")); + highPresence->setPriority(10); + highPresence->setStatus("So totally here"); + Presence::ref highPresenceOffline(new Presence()); + highPresenceOffline->setFrom(withResource(from, "bert")); + highPresenceOffline->setType(Presence::Unavailable); + + stanzaChannel_->onPresenceReceived(lowPresence); + Presence::ref accountPresence = presenceOracle_->getAccountPresence(from); + CPPUNIT_ASSERT_EQUAL(StatusShow::Away, accountPresence->getShow()); + + stanzaChannel_->onPresenceReceived(highPresence); + accountPresence = presenceOracle_->getAccountPresence(from); + CPPUNIT_ASSERT_EQUAL(StatusShow::Online, accountPresence->getShow()); + + stanzaChannel_->onPresenceReceived(highPresenceOffline); + + // After this, the roster should show the low presence. + ContactRosterItem* item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); + CPPUNIT_ASSERT(item); + + Presence::ref low = presenceOracle_->getAccountPresence(from); + + CPPUNIT_ASSERT_EQUAL(Presence::Available, low->getType()); + CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), low->getStatus()); + CPPUNIT_ASSERT_EQUAL(lowPresence->getShow(), item->getStatusShow()); + CPPUNIT_ASSERT_EQUAL(lowPresence->getStatus(), item->getStatusText()); + stanzaChannel_->onPresenceReceived(lowPresenceOffline); + item = dynamic_cast(dynamic_cast(CHILDREN[0])->getChildren()[0]); + CPPUNIT_ASSERT(item); + /* A verification that if the test fails, it's the RosterController, not the PresenceOracle. */ + low = presenceOracle_->getHighestPriorityPresence(from); + CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, low->getType()); + CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), low->getStatus()); + CPPUNIT_ASSERT_EQUAL(StatusShow::None, item->getStatusShow()); + CPPUNIT_ASSERT_EQUAL(lowPresenceOffline->getStatus(), item->getStatusText()); + } + + void testAdd() { + std::vector groups; + groups.push_back("testGroup1"); + groups.push_back("testGroup2"); + xmppRoster_->addContact(JID("test@testdomain.com/bob"), "name", groups, RosterItemPayload::Both); + + CPPUNIT_ASSERT_EQUAL(2, static_cast(CHILDREN.size())); + //CPPUNIT_ASSERT_EQUAL(std::string("Bob"), xmppRoster_->getNameForJID(JID("foo@bar.com"))); + } + + void testAddSubscription() { + std::vector groups; + JID jid("test@testdomain.com"); + xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::None); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::To); + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + + xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both); + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + + } + + void testReceiveRename() { + std::vector groups; + JID jid("test@testdomain.com"); + xmppRoster_->addContact(jid, "name", groups, RosterItemPayload::Both); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(std::string("name"), groupChild(0)->getChildren()[0]->getDisplayName()); + xmppRoster_->addContact(jid, "NewName", groups, RosterItemPayload::Both); + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(std::string("NewName"), groupChild(0)->getChildren()[0]->getDisplayName()); + } + + void testReceiveRegroup() { + std::vector oldGroups; + std::vector newGroups; + newGroups.push_back("A Group"); + std::vector newestGroups; + newestGroups.push_back("Best Group"); + JID jid("test@testdomain.com"); + xmppRoster_->addContact(jid, "", oldGroups, RosterItemPayload::Both); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(jid.toString(), groupChild(0)->getChildren()[0]->getDisplayName()); + + xmppRoster_->addContact(jid, "new name", newGroups, RosterItemPayload::Both); + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("A Group"), groupChild(0)->getDisplayName()); + + xmppRoster_->addContact(jid, "new name", newestGroups, RosterItemPayload::Both); + CPPUNIT_ASSERT_EQUAL(1, static_cast(CHILDREN.size())); + CPPUNIT_ASSERT_EQUAL(1, static_cast(groupChild(0)->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(std::string("new name"), groupChild(0)->getChildren()[0]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("Best Group"), groupChild(0)->getDisplayName()); + } + + void testSendRename() { + JID jid("testling@wonderland.lit"); + std::vector groups; + groups.push_back("Friends"); + groups.push_back("Enemies"); + xmppRoster_->addContact(jid, "Bob", groups, RosterItemPayload::From); + CPPUNIT_ASSERT_EQUAL(groups.size(), xmppRoster_->getGroupsForJID(jid).size()); + uiEventStream_->send(boost::shared_ptr(new RenameRosterItemUIEvent(jid, "Robert"))); + CPPUNIT_ASSERT_EQUAL(static_cast(1), channel_->iqs_.size()); + CPPUNIT_ASSERT_EQUAL(IQ::Set, channel_->iqs_[0]->getType()); + boost::shared_ptr payload = channel_->iqs_[0]->getPayload(); + CPPUNIT_ASSERT_EQUAL(static_cast(1), payload->getItems().size()); + RosterItemPayload item = payload->getItems()[0]; + CPPUNIT_ASSERT_EQUAL(jid, item.getJID()); + CPPUNIT_ASSERT_EQUAL(std::string("Robert"), item.getName()); + + CPPUNIT_ASSERT_EQUAL(groups.size(), item.getGroups().size()); + assertVectorsEqual(groups, item.getGroups(), __LINE__); + } + + void testRemoveResultsInUnavailablePresence() { + std::vector groups; + groups.push_back("testGroup1"); + JID from("test@testdomain.com"); + xmppRoster_->addContact(from, "name", groups, RosterItemPayload::Both); + Presence::ref lowPresence(new Presence()); + lowPresence->setFrom(withResource(from, "bob")); + lowPresence->setPriority(2); + lowPresence->setStatus("Not here"); + Presence::ref highPresence(new Presence()); + highPresence->setFrom(withResource(from, "bert")); + highPresence->setPriority(10); + highPresence->setStatus("So totally here"); + stanzaChannel_->onPresenceReceived(highPresence); + stanzaChannel_->onPresenceReceived(lowPresence); + + CPPUNIT_ASSERT_EQUAL(static_cast(2), presenceOracle_->getAllPresence("test@testdomain.com").size()); + + xmppRoster_->onJIDRemoved(JID("test@testdomain.com")); + CPPUNIT_ASSERT_EQUAL(static_cast(1), presenceOracle_->getAllPresence("test@testdomain.com").size()); + CPPUNIT_ASSERT_EQUAL(Presence::Unavailable, presenceOracle_->getAllPresence("test@testdomain.com")[0]->getType()); + } + + void assertVectorsEqual(const std::vector& v1, const std::vector& v2, int line) { + foreach (const std::string& entry, v1) { + if (std::find(v2.begin(), v2.end(), entry) == v2.end()) { + std::stringstream stream; + stream << "Couldn't find " << entry << " in v2 (line " << line << ")"; + CPPUNIT_FAIL(stream.str()); + } + } + } + + private: + JID jid_; + XMPPRosterImpl* xmppRoster_; + MUCRegistry* mucRegistry_; + AvatarManager* avatarManager_; + MockMainWindowFactory* mainWindowFactory_; + NickManager* nickManager_; + NickResolver* nickResolver_; + RosterController* rosterController_; + DummyIQChannel* channel_; + DummyStanzaChannel* stanzaChannel_; + IQRouter* router_; + PresenceOracle* presenceOracle_; + SubscriptionManager* subscriptionManager_; + EventController* eventController_; + UIEventStream* uiEventStream_; + MockMainWindow* mainWindow_; + DummySettingsProvider* settings_; + DummyCapsProvider* capsProvider_; + EntityCapsManager* entityCapsManager_; + JingleSessionManager* jingleSessionManager_; + FileTransferManager* ftManager_; + FileTransferOverview* ftOverview_; + ClientBlockListManager* clientBlockListManager_; + CryptoProvider* crypto_; + VCardStorage* vcardStorage_; + VCardManager* vcardManager_; }; CPPUNIT_TEST_SUITE_REGISTRATION(RosterControllerTest); diff --git a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp index 314b5c6..dd22cb7 100644 --- a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp +++ b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp @@ -16,130 +16,130 @@ using namespace Swift; class RosterTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(RosterTest); - CPPUNIT_TEST(testGetGroup); - CPPUNIT_TEST(testRemoveContact); - CPPUNIT_TEST(testRemoveSecondContact); - CPPUNIT_TEST(testRemoveSecondContactSameBare); - CPPUNIT_TEST(testApplyPresenceLikeMUC); - CPPUNIT_TEST(testReSortLikeMUC); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - jid1_ = JID("a@b.c"); - jid2_ = JID("b@c.d"); - jid3_ = JID("c@d.e"); - roster_ = new Roster(); - } - - void tearDown() { - delete roster_; - } - - void testGetGroup() { - roster_->addContact(jid1_, JID(), "Bert", "group1", ""); - roster_->addContact(jid2_, JID(), "Ernie", "group2", ""); - roster_->addContact(jid3_, JID(), "Cookie", "group1", ""); - - CPPUNIT_ASSERT_EQUAL(2, static_cast(roster_->getRoot()->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(std::string("group1"), roster_->getRoot()->getChildren()[0]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("group2"), roster_->getRoot()->getChildren()[1]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), static_cast(roster_->getRoot()->getChildren()[1])->getChildren()[0]->getDisplayName()); - - } - - void testRemoveContact() { - roster_->addContact(jid1_, jid1_, "Bert", "group1", ""); - CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); - - roster_->removeContact(jid1_); - CPPUNIT_ASSERT_EQUAL(0, static_cast(static_cast(roster_->getRoot()->getChildren()[0])->getChildren().size())); - } - - void testRemoveSecondContact() { - roster_->addContact(jid1_, jid1_, "Bert", "group1", ""); - roster_->addContact(jid2_, jid2_, "Cookie", "group1", ""); - CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName()); - - roster_->removeContact(jid2_); - CPPUNIT_ASSERT_EQUAL(1, static_cast(static_cast(roster_->getRoot()->getChildren()[0])->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); - } - - void testRemoveSecondContactSameBare() { - JID jid4a("a@b/c"); - JID jid4b("a@b/d"); - roster_->addContact(jid4a, JID(), "Bert", "group1", ""); - roster_->addContact(jid4b, JID(), "Cookie", "group1", ""); - CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName()); - - roster_->removeContact(jid4b); - CPPUNIT_ASSERT_EQUAL(1, static_cast(static_cast(roster_->getRoot()->getChildren()[0])->getChildren().size())); - CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); - } - - void testApplyPresenceLikeMUC() { - JID jid4a("a@b/c"); - JID jid4b("a@b/d"); - JID jid4c("a@b/e"); - roster_->addContact(jid4a, JID(), "Bird", "group1", ""); - roster_->addContact(jid4b, JID(), "Cookie", "group1", ""); - roster_->removeContact(jid4b); - roster_->addContact(jid4c, JID(), "Bert", "group1", ""); - roster_->addContact(jid4b, JID(), "Ernie", "group1", ""); - boost::shared_ptr presence(new Presence()); - presence->setShow(StatusShow::DND); - presence->setFrom(jid4a); - roster_->applyOnItems(SetPresence(presence, JID::WithResource)); - presence->setFrom(jid4b); - roster_->applyOnItems(SetPresence(presence, JID::WithResource)); - presence->setFrom(jid4c); - roster_->applyOnItems(SetPresence(presence, JID::WithResource)); - - presence = boost::make_shared(); - presence->setFrom(jid4b); - presence->setShow(StatusShow::Online); - roster_->applyOnItems(SetPresence(presence, JID::WithResource)); - std::vector children = static_cast(roster_->getRoot()->getDisplayedChildren()[0])->getDisplayedChildren(); - CPPUNIT_ASSERT_EQUAL(3, static_cast(children.size())); - - /* Check order */ - CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), children[0]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("Bert"), children[1]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("Bird"), children[2]->getDisplayName()); - - presence = boost::make_shared(); - presence->setFrom(jid4c); - presence->setType(Presence::Unavailable); - roster_->removeContact(jid4c); - roster_->applyOnItems(SetPresence(presence, JID::WithResource)); - - } - - void testReSortLikeMUC() { - JID jid4a("a@b/c"); - JID jid4b("a@b/d"); - JID jid4c("a@b/e"); - roster_->addContact(jid4a, JID(), "Bird", "group1", ""); - roster_->addContact(jid4b, JID(), "Cookie", "group2", ""); - roster_->addContact(jid4b, JID(), "Ernie", "group1", ""); - roster_->getGroup("group1")->setManualSort("2"); - roster_->getGroup("group2")->setManualSort("1"); - GroupRosterItem* root = roster_->getRoot(); - const std::vector kids = root->getDisplayedChildren(); - CPPUNIT_ASSERT_EQUAL(static_cast(2), kids.size()); - CPPUNIT_ASSERT_EQUAL(std::string("group2"), kids[0]->getDisplayName()); - CPPUNIT_ASSERT_EQUAL(std::string("group1"), kids[1]->getDisplayName()); - } - - private: - Roster *roster_; - JID jid1_; - JID jid2_; - JID jid3_; + CPPUNIT_TEST_SUITE(RosterTest); + CPPUNIT_TEST(testGetGroup); + CPPUNIT_TEST(testRemoveContact); + CPPUNIT_TEST(testRemoveSecondContact); + CPPUNIT_TEST(testRemoveSecondContactSameBare); + CPPUNIT_TEST(testApplyPresenceLikeMUC); + CPPUNIT_TEST(testReSortLikeMUC); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + jid1_ = JID("a@b.c"); + jid2_ = JID("b@c.d"); + jid3_ = JID("c@d.e"); + roster_ = new Roster(); + } + + void tearDown() { + delete roster_; + } + + void testGetGroup() { + roster_->addContact(jid1_, JID(), "Bert", "group1", ""); + roster_->addContact(jid2_, JID(), "Ernie", "group2", ""); + roster_->addContact(jid3_, JID(), "Cookie", "group1", ""); + + CPPUNIT_ASSERT_EQUAL(2, static_cast(roster_->getRoot()->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(std::string("group1"), roster_->getRoot()->getChildren()[0]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("group2"), roster_->getRoot()->getChildren()[1]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), static_cast(roster_->getRoot()->getChildren()[1])->getChildren()[0]->getDisplayName()); + + } + + void testRemoveContact() { + roster_->addContact(jid1_, jid1_, "Bert", "group1", ""); + CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); + + roster_->removeContact(jid1_); + CPPUNIT_ASSERT_EQUAL(0, static_cast(static_cast(roster_->getRoot()->getChildren()[0])->getChildren().size())); + } + + void testRemoveSecondContact() { + roster_->addContact(jid1_, jid1_, "Bert", "group1", ""); + roster_->addContact(jid2_, jid2_, "Cookie", "group1", ""); + CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName()); + + roster_->removeContact(jid2_); + CPPUNIT_ASSERT_EQUAL(1, static_cast(static_cast(roster_->getRoot()->getChildren()[0])->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); + } + + void testRemoveSecondContactSameBare() { + JID jid4a("a@b/c"); + JID jid4b("a@b/d"); + roster_->addContact(jid4a, JID(), "Bert", "group1", ""); + roster_->addContact(jid4b, JID(), "Cookie", "group1", ""); + CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName()); + + roster_->removeContact(jid4b); + CPPUNIT_ASSERT_EQUAL(1, static_cast(static_cast(roster_->getRoot()->getChildren()[0])->getChildren().size())); + CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName()); + } + + void testApplyPresenceLikeMUC() { + JID jid4a("a@b/c"); + JID jid4b("a@b/d"); + JID jid4c("a@b/e"); + roster_->addContact(jid4a, JID(), "Bird", "group1", ""); + roster_->addContact(jid4b, JID(), "Cookie", "group1", ""); + roster_->removeContact(jid4b); + roster_->addContact(jid4c, JID(), "Bert", "group1", ""); + roster_->addContact(jid4b, JID(), "Ernie", "group1", ""); + boost::shared_ptr presence(new Presence()); + presence->setShow(StatusShow::DND); + presence->setFrom(jid4a); + roster_->applyOnItems(SetPresence(presence, JID::WithResource)); + presence->setFrom(jid4b); + roster_->applyOnItems(SetPresence(presence, JID::WithResource)); + presence->setFrom(jid4c); + roster_->applyOnItems(SetPresence(presence, JID::WithResource)); + + presence = boost::make_shared(); + presence->setFrom(jid4b); + presence->setShow(StatusShow::Online); + roster_->applyOnItems(SetPresence(presence, JID::WithResource)); + std::vector children = static_cast(roster_->getRoot()->getDisplayedChildren()[0])->getDisplayedChildren(); + CPPUNIT_ASSERT_EQUAL(3, static_cast(children.size())); + + /* Check order */ + CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), children[0]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("Bert"), children[1]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("Bird"), children[2]->getDisplayName()); + + presence = boost::make_shared(); + presence->setFrom(jid4c); + presence->setType(Presence::Unavailable); + roster_->removeContact(jid4c); + roster_->applyOnItems(SetPresence(presence, JID::WithResource)); + + } + + void testReSortLikeMUC() { + JID jid4a("a@b/c"); + JID jid4b("a@b/d"); + JID jid4c("a@b/e"); + roster_->addContact(jid4a, JID(), "Bird", "group1", ""); + roster_->addContact(jid4b, JID(), "Cookie", "group2", ""); + roster_->addContact(jid4b, JID(), "Ernie", "group1", ""); + roster_->getGroup("group1")->setManualSort("2"); + roster_->getGroup("group2")->setManualSort("1"); + GroupRosterItem* root = roster_->getRoot(); + const std::vector kids = root->getDisplayedChildren(); + CPPUNIT_ASSERT_EQUAL(static_cast(2), kids.size()); + CPPUNIT_ASSERT_EQUAL(std::string("group2"), kids[0]->getDisplayName()); + CPPUNIT_ASSERT_EQUAL(std::string("group1"), kids[1]->getDisplayName()); + } + + private: + Roster *roster_; + JID jid1_; + JID jid2_; + JID jid3_; }; CPPUNIT_TEST_SUITE_REGISTRATION(RosterTest); diff --git a/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp b/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp index 10030ef..086bd6f 100644 --- a/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp +++ b/Swift/Controllers/Roster/UnitTest/TableRosterTest.cpp @@ -9,8 +9,8 @@ std::ostream& operator<<(std::ostream& os, const Swift::TableRoster::Index& i); std::ostream& operator<<(std::ostream& os, const Swift::TableRoster::Index& i) { - os << "(" << i.section << ", " << i.row << ")"; - return os; + os << "(" << i.section << ", " << i.row << ")"; + return os; } #include @@ -27,67 +27,67 @@ std::ostream& operator<<(std::ostream& os, const Swift::TableRoster::Index& i) { using namespace Swift; class TableRosterTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(TableRosterTest); - CPPUNIT_TEST(testAddContact_EmptyRoster); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - timerFactory = new DummyTimerFactory(); - roster = new Roster(); - jid1 = JID("jid1@example.com"); - jid2 = JID("jid2@example.com"); - } - - void tearDown() { - delete roster; - delete timerFactory; - } - - void testAddContact_EmptyRoster() { - /* - boost::shared_ptr tableRoster(createTestling()); - - addContact(jid1, "1", "group1"); - - CPPUNIT_ASSERT_EQUAL(4, static_cast(events.size())); - CPPUNIT_ASSERT(boost::get(&events[0])); - CPPUNIT_ASSERT(boost::get(&events[1])); - CPPUNIT_ASSERT_EQUAL(1, static_cast(boost::get(events[1]).sections.size())); - CPPUNIT_ASSERT_EQUAL(0, static_cast(boost::get(events[1]).sections[0])); - CPPUNIT_ASSERT(boost::get(&events[2])); - CPPUNIT_ASSERT_EQUAL(1, static_cast(boost::get(events[2]).rows.size())); - CPPUNIT_ASSERT_EQUAL(TableRoster::Index(0, 0), boost::get(events[2]).rows[0]); - CPPUNIT_ASSERT(boost::get(&events[3])); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(tableRoster->getNumberOfSections())); - CPPUNIT_ASSERT_EQUAL(std::string("group1"), tableRoster->getSectionTitle(0)); - CPPUNIT_ASSERT_EQUAL(1, static_cast(tableRoster->getNumberOfRowsInSection(0))); - CPPUNIT_ASSERT_EQUAL(jid1, tableRoster->getItem(TableRoster::Index(0, 0)).jid); - */ - } - - private: - void addContact(const JID& jid, const std::string& name, const std::string& group) { - roster->addContact(jid, JID(), name, group, ""); - } - - TableRoster* createTestling() { - TableRoster* result = new TableRoster(roster, timerFactory, 10); - result->onUpdate.connect(boost::bind(&TableRosterTest::handleUpdate, this, _1)); - return result; - } - - void handleUpdate(const TableRoster::Update& update) { - updates.push_back(update); - } - - private: - DummyTimerFactory* timerFactory; - Roster* roster; - JID jid1; - JID jid2; - std::vector updates; + CPPUNIT_TEST_SUITE(TableRosterTest); + CPPUNIT_TEST(testAddContact_EmptyRoster); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + timerFactory = new DummyTimerFactory(); + roster = new Roster(); + jid1 = JID("jid1@example.com"); + jid2 = JID("jid2@example.com"); + } + + void tearDown() { + delete roster; + delete timerFactory; + } + + void testAddContact_EmptyRoster() { + /* + boost::shared_ptr tableRoster(createTestling()); + + addContact(jid1, "1", "group1"); + + CPPUNIT_ASSERT_EQUAL(4, static_cast(events.size())); + CPPUNIT_ASSERT(boost::get(&events[0])); + CPPUNIT_ASSERT(boost::get(&events[1])); + CPPUNIT_ASSERT_EQUAL(1, static_cast(boost::get(events[1]).sections.size())); + CPPUNIT_ASSERT_EQUAL(0, static_cast(boost::get(events[1]).sections[0])); + CPPUNIT_ASSERT(boost::get(&events[2])); + CPPUNIT_ASSERT_EQUAL(1, static_cast(boost::get(events[2]).rows.size())); + CPPUNIT_ASSERT_EQUAL(TableRoster::Index(0, 0), boost::get(events[2]).rows[0]); + CPPUNIT_ASSERT(boost::get(&events[3])); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(tableRoster->getNumberOfSections())); + CPPUNIT_ASSERT_EQUAL(std::string("group1"), tableRoster->getSectionTitle(0)); + CPPUNIT_ASSERT_EQUAL(1, static_cast(tableRoster->getNumberOfRowsInSection(0))); + CPPUNIT_ASSERT_EQUAL(jid1, tableRoster->getItem(TableRoster::Index(0, 0)).jid); + */ + } + + private: + void addContact(const JID& jid, const std::string& name, const std::string& group) { + roster->addContact(jid, JID(), name, group, ""); + } + + TableRoster* createTestling() { + TableRoster* result = new TableRoster(roster, timerFactory, 10); + result->onUpdate.connect(boost::bind(&TableRosterTest::handleUpdate, this, _1)); + return result; + } + + void handleUpdate(const TableRoster::Update& update) { + updates.push_back(update); + } + + private: + DummyTimerFactory* timerFactory; + Roster* roster; + JID jid1; + JID jid2; + std::vector updates; }; CPPUNIT_TEST_SUITE_REGISTRATION(TableRosterTest); diff --git a/Swift/Controllers/SettingConstants.h b/Swift/Controllers/SettingConstants.h index c4ac4ad..9343b7b 100644 --- a/Swift/Controllers/SettingConstants.h +++ b/Swift/Controllers/SettingConstants.h @@ -9,100 +9,100 @@ #include namespace Swift { - /** - * This class contains the major setting keys for Swift. - */ - class SettingConstants { - public: - /** - * The #IDLE_GOES_OFFLINE setting specifies whether to close the XMPP connection when - * the user went idle. - * - * True for automatic close of the XMPP connection and false for only changing the presence on idle. - */ - static const SettingsProvider::Setting IDLE_GOES_OFFLINE; - /** - * The #IDLE_TIMEOUT setting specifieds the seconds the user has to be inactive at the - * desktop so the user is regarded as idle. - */ - static const SettingsProvider::Setting IDLE_TIMEOUT; - static const SettingsProvider::Setting SHOW_NOTIFICATIONS; - /** - * The #REQUEST_DELIVERYRECEIPTS settings specifies whether to request delivery receipts - * for messages to contacts that support message receipts. - */ - static const SettingsProvider::Setting REQUEST_DELIVERYRECEIPTS; - static const SettingsProvider::Setting FORGET_PASSWORDS; - static const SettingsProvider::Setting REMEMBER_RECENT_CHATS; - static const SettingsProvider::Setting LAST_LOGIN_JID; - static const SettingsProvider::Setting LOGIN_AUTOMATICALLY; - /** - * The #SHOW_OFFLINE setting specifies whether or not to show offline contacts in the - * roster. - * - * If set true Swift will show offline contacts; else not. - */ - static const SettingsProvider::Setting SHOW_OFFLINE; - /** - * The #EXPANDED_ROSTER_GROUPS setting specifies the list of groups that are expanded - * in the roster UI. - * - * Its value is a string with group names seperated by newlines. - */ - static const SettingsProvider::Setting EXPANDED_ROSTER_GROUPS; - static const SettingsProvider::Setting PLAY_SOUNDS; - /** - * The #HIGHLIGHT_RULES setting specifies the highlight rules and the associated actions. - * - * Its value is a Boost serialized representation. - */ - static const SettingsProvider::Setting HIGHLIGHT_RULES; - static const SettingsProvider::Setting SPELL_CHECKER; - static const SettingsProvider::Setting DICT_PATH; - static const SettingsProvider::Setting PERSONAL_DICT_PATH; - static const SettingsProvider::Setting DICT_FILE; - /** - * The #INVITE_AUTO_ACCEPT_MODE setting specifies how to handle invites to chat rooms. - * - * Supported values are: - * - "no" : It is up to the user whether to accept the invitation and enter a room or not. - * - "presence" : The invitation is automatically accepted if it is from a contact that is - * already allowed to see the user's presence status. - * - "domain" : The invitation is automatically accepted if it is from a contact that is - * already allowed to see the user's presence status or from a contact of user's domain. - */ - static const SettingsProvider::Setting INVITE_AUTO_ACCEPT_MODE; - /** - * The #TRELLIS_GRID_SIZE setting specifies the dimensions of the grid used for the trellis - * layout. - * - * Its value is a Qt serialized representation. - */ - static const SettingsProvider::Setting TRELLIS_GRID_SIZE; - /** - * The #TRELLIS_GRID_POSITIONS setting specifies where conversations to contacts or rooms go - * in the trellis grid. - * - * Its value is a Qt serialized representation. - */ - static const SettingsProvider::Setting TRELLIS_GRID_POSITIONS; - /** - * The #DISCONNECT_ON_CARD_REMOVAL setting - * specifies whether or not to sign out the user when - * the smartcard is removed. - * - * If set true Swift will sign out the user when the - * smart card is removed; else not. - */ - static const SettingsProvider::Setting DISCONNECT_ON_CARD_REMOVAL; - /** - * The #SINGLE_SIGN_ON setting - * specifies whether to log in using Single Sign On. - * This is currently supported on Windows. - * - * If set true Swift will use GSSAPI authentication to - * log in the user; else not. - */ - static const SettingsProvider::Setting SINGLE_SIGN_ON; - }; + /** + * This class contains the major setting keys for Swift. + */ + class SettingConstants { + public: + /** + * The #IDLE_GOES_OFFLINE setting specifies whether to close the XMPP connection when + * the user went idle. + * + * True for automatic close of the XMPP connection and false for only changing the presence on idle. + */ + static const SettingsProvider::Setting IDLE_GOES_OFFLINE; + /** + * The #IDLE_TIMEOUT setting specifieds the seconds the user has to be inactive at the + * desktop so the user is regarded as idle. + */ + static const SettingsProvider::Setting IDLE_TIMEOUT; + static const SettingsProvider::Setting SHOW_NOTIFICATIONS; + /** + * The #REQUEST_DELIVERYRECEIPTS settings specifies whether to request delivery receipts + * for messages to contacts that support message receipts. + */ + static const SettingsProvider::Setting REQUEST_DELIVERYRECEIPTS; + static const SettingsProvider::Setting FORGET_PASSWORDS; + static const SettingsProvider::Setting REMEMBER_RECENT_CHATS; + static const SettingsProvider::Setting LAST_LOGIN_JID; + static const SettingsProvider::Setting LOGIN_AUTOMATICALLY; + /** + * The #SHOW_OFFLINE setting specifies whether or not to show offline contacts in the + * roster. + * + * If set true Swift will show offline contacts; else not. + */ + static const SettingsProvider::Setting SHOW_OFFLINE; + /** + * The #EXPANDED_ROSTER_GROUPS setting specifies the list of groups that are expanded + * in the roster UI. + * + * Its value is a string with group names seperated by newlines. + */ + static const SettingsProvider::Setting EXPANDED_ROSTER_GROUPS; + static const SettingsProvider::Setting PLAY_SOUNDS; + /** + * The #HIGHLIGHT_RULES setting specifies the highlight rules and the associated actions. + * + * Its value is a Boost serialized representation. + */ + static const SettingsProvider::Setting HIGHLIGHT_RULES; + static const SettingsProvider::Setting SPELL_CHECKER; + static const SettingsProvider::Setting DICT_PATH; + static const SettingsProvider::Setting PERSONAL_DICT_PATH; + static const SettingsProvider::Setting DICT_FILE; + /** + * The #INVITE_AUTO_ACCEPT_MODE setting specifies how to handle invites to chat rooms. + * + * Supported values are: + * - "no" : It is up to the user whether to accept the invitation and enter a room or not. + * - "presence" : The invitation is automatically accepted if it is from a contact that is + * already allowed to see the user's presence status. + * - "domain" : The invitation is automatically accepted if it is from a contact that is + * already allowed to see the user's presence status or from a contact of user's domain. + */ + static const SettingsProvider::Setting INVITE_AUTO_ACCEPT_MODE; + /** + * The #TRELLIS_GRID_SIZE setting specifies the dimensions of the grid used for the trellis + * layout. + * + * Its value is a Qt serialized representation. + */ + static const SettingsProvider::Setting TRELLIS_GRID_SIZE; + /** + * The #TRELLIS_GRID_POSITIONS setting specifies where conversations to contacts or rooms go + * in the trellis grid. + * + * Its value is a Qt serialized representation. + */ + static const SettingsProvider::Setting TRELLIS_GRID_POSITIONS; + /** + * The #DISCONNECT_ON_CARD_REMOVAL setting + * specifies whether or not to sign out the user when + * the smartcard is removed. + * + * If set true Swift will sign out the user when the + * smart card is removed; else not. + */ + static const SettingsProvider::Setting DISCONNECT_ON_CARD_REMOVAL; + /** + * The #SINGLE_SIGN_ON setting + * specifies whether to log in using Single Sign On. + * This is currently supported on Windows. + * + * If set true Swift will use GSSAPI authentication to + * log in the user; else not. + */ + static const SettingsProvider::Setting SINGLE_SIGN_ON; + }; } diff --git a/Swift/Controllers/Settings/DummySettingsProvider.h b/Swift/Controllers/Settings/DummySettingsProvider.h index 605153e..63c0767 100644 --- a/Swift/Controllers/Settings/DummySettingsProvider.h +++ b/Swift/Controllers/Settings/DummySettingsProvider.h @@ -13,44 +13,44 @@ namespace Swift { class DummySettingsProvider : public SettingsProvider { - public: - virtual ~DummySettingsProvider() {} - virtual std::string getSetting(const Setting& setting) { - return stringValues.find(setting.getKey()) != stringValues.end() ? stringValues[setting.getKey()] : setting.getDefaultValue(); - } - virtual void storeSetting(const Setting& setting, const std::string& value) { - stringValues[setting.getKey()] = value; - onSettingChanged(setting.getKey()); - } - virtual bool getSetting(const Setting& setting) { - return boolValues.find(setting.getKey()) != boolValues.end() ? boolValues[setting.getKey()] : setting.getDefaultValue(); - } - virtual void storeSetting(const Setting& setting, const bool& value) { - boolValues[setting.getKey()] = value; - onSettingChanged(setting.getKey()); - } - virtual int getSetting(const Setting& setting) { - return intValues.find(setting.getKey()) != intValues.end() ? intValues[setting.getKey()] : setting.getDefaultValue(); - } - virtual void storeSetting(const Setting& setting, const int& value) { - intValues[setting.getKey()] = value; - onSettingChanged(setting.getKey()); - } - virtual std::vector getAvailableProfiles() {return std::vector();} - virtual void createProfile(const std::string& ) {} - virtual void removeProfile(const std::string& ) {} - virtual bool getIsSettingFinal(const std::string& settingPath) {return finals.count(settingPath);} - void setFinal(const std::string& settingPath) { - finals.insert(settingPath); - } - virtual bool hasSetting(const std::string& key) { - return stringValues.find(key) != stringValues.end() || intValues.find(key) != intValues.end() || boolValues.find(key) != boolValues.end(); - } - private: - std::map stringValues; - std::map intValues; - std::map boolValues; - std::set finals; + public: + virtual ~DummySettingsProvider() {} + virtual std::string getSetting(const Setting& setting) { + return stringValues.find(setting.getKey()) != stringValues.end() ? stringValues[setting.getKey()] : setting.getDefaultValue(); + } + virtual void storeSetting(const Setting& setting, const std::string& value) { + stringValues[setting.getKey()] = value; + onSettingChanged(setting.getKey()); + } + virtual bool getSetting(const Setting& setting) { + return boolValues.find(setting.getKey()) != boolValues.end() ? boolValues[setting.getKey()] : setting.getDefaultValue(); + } + virtual void storeSetting(const Setting& setting, const bool& value) { + boolValues[setting.getKey()] = value; + onSettingChanged(setting.getKey()); + } + virtual int getSetting(const Setting& setting) { + return intValues.find(setting.getKey()) != intValues.end() ? intValues[setting.getKey()] : setting.getDefaultValue(); + } + virtual void storeSetting(const Setting& setting, const int& value) { + intValues[setting.getKey()] = value; + onSettingChanged(setting.getKey()); + } + virtual std::vector getAvailableProfiles() {return std::vector();} + virtual void createProfile(const std::string& ) {} + virtual void removeProfile(const std::string& ) {} + virtual bool getIsSettingFinal(const std::string& settingPath) {return finals.count(settingPath);} + void setFinal(const std::string& settingPath) { + finals.insert(settingPath); + } + virtual bool hasSetting(const std::string& key) { + return stringValues.find(key) != stringValues.end() || intValues.find(key) != intValues.end() || boolValues.find(key) != boolValues.end(); + } + private: + std::map stringValues; + std::map intValues; + std::map boolValues; + std::set finals; }; } diff --git a/Swift/Controllers/Settings/SettingsProvider.h b/Swift/Controllers/Settings/SettingsProvider.h index 29e26b5..a804235 100644 --- a/Swift/Controllers/Settings/SettingsProvider.h +++ b/Swift/Controllers/Settings/SettingsProvider.h @@ -15,57 +15,57 @@ namespace Swift { class SettingsProvider { - public: - template - class Setting { - public: - Setting(const std::string& key, const T& defaultValue) : key(key), defaultValue(defaultValue) { - - } - - const std::string& getKey() const { - return key; - } - - const T& getDefaultValue() const { - return defaultValue; - } - - private: - std::string key; - T defaultValue; - }; - - public: - virtual ~SettingsProvider() {} - virtual std::string getSetting(const Setting& setting) = 0; - virtual void storeSetting(const Setting& setting, const std::string& value) = 0; - virtual bool getSetting(const Setting& setting) = 0; - virtual void storeSetting(const Setting& setting, const bool& value) = 0; - virtual int getSetting(const Setting& setting) = 0; - virtual void storeSetting(const Setting& setting, const int& value) = 0; - - virtual std::vector getAvailableProfiles() = 0; - virtual void createProfile(const std::string& profile) = 0; - virtual void removeProfile(const std::string& profile) = 0; - /** A final setting is one that this settings provider says may not be overriden by lower priority profiles. - * e.g. An Administrator-set configuration to disallow saving user passwords could not be overridden by the user. - */ - template - bool getIsSettingFinal(const Setting& setting) { - return getIsSettingFinal(setting.getKey()); - } - virtual bool hasSetting(const std::string& key) = 0; - - friend class SettingsProviderHierachy; - protected: - virtual bool getIsSettingFinal(const std::string& settingPath) = 0; - - public: - /** - * Emitted when a setting is changed. - */ - boost::signal onSettingChanged; + public: + template + class Setting { + public: + Setting(const std::string& key, const T& defaultValue) : key(key), defaultValue(defaultValue) { + + } + + const std::string& getKey() const { + return key; + } + + const T& getDefaultValue() const { + return defaultValue; + } + + private: + std::string key; + T defaultValue; + }; + + public: + virtual ~SettingsProvider() {} + virtual std::string getSetting(const Setting& setting) = 0; + virtual void storeSetting(const Setting& setting, const std::string& value) = 0; + virtual bool getSetting(const Setting& setting) = 0; + virtual void storeSetting(const Setting& setting, const bool& value) = 0; + virtual int getSetting(const Setting& setting) = 0; + virtual void storeSetting(const Setting& setting, const int& value) = 0; + + virtual std::vector getAvailableProfiles() = 0; + virtual void createProfile(const std::string& profile) = 0; + virtual void removeProfile(const std::string& profile) = 0; + /** A final setting is one that this settings provider says may not be overriden by lower priority profiles. + * e.g. An Administrator-set configuration to disallow saving user passwords could not be overridden by the user. + */ + template + bool getIsSettingFinal(const Setting& setting) { + return getIsSettingFinal(setting.getKey()); + } + virtual bool hasSetting(const std::string& key) = 0; + + friend class SettingsProviderHierachy; + protected: + virtual bool getIsSettingFinal(const std::string& settingPath) = 0; + + public: + /** + * Emitted when a setting is changed. + */ + boost::signal onSettingChanged; }; } diff --git a/Swift/Controllers/Settings/SettingsProviderHierachy.cpp b/Swift/Controllers/Settings/SettingsProviderHierachy.cpp index a349417..5156d14 100644 --- a/Swift/Controllers/Settings/SettingsProviderHierachy.cpp +++ b/Swift/Controllers/Settings/SettingsProviderHierachy.cpp @@ -14,102 +14,102 @@ SettingsProviderHierachy::~SettingsProviderHierachy() { } bool SettingsProviderHierachy::hasSetting(const std::string& key) { - foreach (SettingsProvider* provider, providers_) { - if (provider->hasSetting(key)) { - return true; - } - } - return false; + foreach (SettingsProvider* provider, providers_) { + if (provider->hasSetting(key)) { + return true; + } + } + return false; } std::string SettingsProviderHierachy::getSetting(const Setting& setting) { - std::string value = setting.getDefaultValue(); - foreach (SettingsProvider* provider, providers_) { - std::string providerSetting = provider->getSetting(setting); - if (provider->hasSetting(setting.getKey())) { - value = providerSetting; - } - if (provider->getIsSettingFinal(setting.getKey())) { - return value; - } - } - return value; + std::string value = setting.getDefaultValue(); + foreach (SettingsProvider* provider, providers_) { + std::string providerSetting = provider->getSetting(setting); + if (provider->hasSetting(setting.getKey())) { + value = providerSetting; + } + if (provider->getIsSettingFinal(setting.getKey())) { + return value; + } + } + return value; } void SettingsProviderHierachy::storeSetting(const Setting& setting, const std::string& settingValue) { - if (!getIsSettingFinal(setting.getKey())) { - getWritableProvider()->storeSetting(setting, settingValue); - } + if (!getIsSettingFinal(setting.getKey())) { + getWritableProvider()->storeSetting(setting, settingValue); + } } bool SettingsProviderHierachy::getSetting(const Setting& setting) { - bool value = setting.getDefaultValue(); - foreach (SettingsProvider* provider, providers_) { - bool providerSetting = provider->getSetting(setting); - if (provider->hasSetting(setting.getKey())) { - value = providerSetting; - if (provider->getIsSettingFinal(setting.getKey())) { - return providerSetting; - } - } - } - return value; + bool value = setting.getDefaultValue(); + foreach (SettingsProvider* provider, providers_) { + bool providerSetting = provider->getSetting(setting); + if (provider->hasSetting(setting.getKey())) { + value = providerSetting; + if (provider->getIsSettingFinal(setting.getKey())) { + return providerSetting; + } + } + } + return value; } void SettingsProviderHierachy::storeSetting(const Setting& setting, const bool& settingValue) { - if (!getIsSettingFinal(setting.getKey())) { - getWritableProvider()->storeSetting(setting, settingValue); - } + if (!getIsSettingFinal(setting.getKey())) { + getWritableProvider()->storeSetting(setting, settingValue); + } } int SettingsProviderHierachy::getSetting(const Setting& setting) { - int value = setting.getDefaultValue(); - foreach (SettingsProvider* provider, providers_) { - int providerSetting = provider->getSetting(setting); - if (provider->hasSetting(setting.getKey())) { - value = providerSetting; - if (provider->getIsSettingFinal(setting.getKey())) { - return providerSetting; - } - } - } - return value; + int value = setting.getDefaultValue(); + foreach (SettingsProvider* provider, providers_) { + int providerSetting = provider->getSetting(setting); + if (provider->hasSetting(setting.getKey())) { + value = providerSetting; + if (provider->getIsSettingFinal(setting.getKey())) { + return providerSetting; + } + } + } + return value; } void SettingsProviderHierachy::storeSetting(const Setting& setting, const int& settingValue) { - if (!getIsSettingFinal(setting.getKey())) { - getWritableProvider()->storeSetting(setting, settingValue); - } + if (!getIsSettingFinal(setting.getKey())) { + getWritableProvider()->storeSetting(setting, settingValue); + } } std::vector SettingsProviderHierachy::getAvailableProfiles() { - /* Always pull profiles from the topmost */ - return getWritableProvider()->getAvailableProfiles(); + /* Always pull profiles from the topmost */ + return getWritableProvider()->getAvailableProfiles(); } void SettingsProviderHierachy::createProfile(const std::string& profile) { - return getWritableProvider()->createProfile(profile); + return getWritableProvider()->createProfile(profile); } void SettingsProviderHierachy::removeProfile(const std::string& profile) { - return getWritableProvider()->removeProfile(profile); + return getWritableProvider()->removeProfile(profile); } bool SettingsProviderHierachy::getIsSettingFinal(const std::string& settingPath) { - bool isFinal = false; - foreach (SettingsProvider* provider, providers_) { - isFinal |= provider->getIsSettingFinal(settingPath); - } - return isFinal; + bool isFinal = false; + foreach (SettingsProvider* provider, providers_) { + isFinal |= provider->getIsSettingFinal(settingPath); + } + return isFinal; } SettingsProvider* SettingsProviderHierachy::getWritableProvider() { - return providers_.back(); + return providers_.back(); } void SettingsProviderHierachy::addProviderToTopOfStack(SettingsProvider* provider) { - providers_.push_back(provider); - provider->onSettingChanged.connect(onSettingChanged); + providers_.push_back(provider); + provider->onSettingChanged.connect(onSettingChanged); } } diff --git a/Swift/Controllers/Settings/SettingsProviderHierachy.h b/Swift/Controllers/Settings/SettingsProviderHierachy.h index 9efbdcb..a68ff36 100644 --- a/Swift/Controllers/Settings/SettingsProviderHierachy.h +++ b/Swift/Controllers/Settings/SettingsProviderHierachy.h @@ -11,34 +11,34 @@ namespace Swift { class SettingsProviderHierachy : public SettingsProvider { - public: - virtual ~SettingsProviderHierachy(); - virtual std::string getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const std::string& value); - virtual bool getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const bool& value); - virtual int getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const int& value); - virtual std::vector getAvailableProfiles(); - virtual void createProfile(const std::string& profile); - virtual void removeProfile(const std::string& profile); - virtual bool hasSetting(const std::string& key); - protected: - virtual bool getIsSettingFinal(const std::string& settingPath); - - public: - /** - * Adds a provider less significant than any already added. - * This means that if an existing provider has a setting, this provider won't be asked. - * Any settings will be pushed into the topmost (least significant) provider. - * Does not take ownership of provider. - */ - void addProviderToTopOfStack(SettingsProvider* provider); - private: - SettingsProvider* getWritableProvider(); - private: - /* Start/Left is most significant (lowest), left overrides right.*/ - std::vector providers_; + public: + virtual ~SettingsProviderHierachy(); + virtual std::string getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const std::string& value); + virtual bool getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const bool& value); + virtual int getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const int& value); + virtual std::vector getAvailableProfiles(); + virtual void createProfile(const std::string& profile); + virtual void removeProfile(const std::string& profile); + virtual bool hasSetting(const std::string& key); + protected: + virtual bool getIsSettingFinal(const std::string& settingPath); + + public: + /** + * Adds a provider less significant than any already added. + * This means that if an existing provider has a setting, this provider won't be asked. + * Any settings will be pushed into the topmost (least significant) provider. + * Does not take ownership of provider. + */ + void addProviderToTopOfStack(SettingsProvider* provider); + private: + SettingsProvider* getWritableProvider(); + private: + /* Start/Left is most significant (lowest), left overrides right.*/ + std::vector providers_; }; } diff --git a/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp b/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp index 11d5c11..5822add 100644 --- a/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp +++ b/Swift/Controllers/Settings/UnitTest/SettingsProviderHierachyTest.cpp @@ -15,77 +15,77 @@ using namespace Swift; using namespace std; class SettingsProviderHierachyTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(SettingsProviderHierachyTest); - CPPUNIT_TEST(testEmpty); - CPPUNIT_TEST(testTop); - CPPUNIT_TEST(testBottom); - CPPUNIT_TEST(testBoth); - CPPUNIT_TEST(testTopDefault); - CPPUNIT_TEST(testBottomOverrides); - CPPUNIT_TEST(testFinal); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(SettingsProviderHierachyTest); + CPPUNIT_TEST(testEmpty); + CPPUNIT_TEST(testTop); + CPPUNIT_TEST(testBottom); + CPPUNIT_TEST(testBoth); + CPPUNIT_TEST(testTopDefault); + CPPUNIT_TEST(testBottomOverrides); + CPPUNIT_TEST(testFinal); + CPPUNIT_TEST_SUITE_END(); public: - SettingsProviderHierachyTest() : setting1("somekey", 42) {} + SettingsProviderHierachyTest() : setting1("somekey", 42) {} - void setUp() { - bottom = new DummySettingsProvider(); - top = new DummySettingsProvider(); - testling = new SettingsProviderHierachy(); - testling->addProviderToTopOfStack(bottom); - testling->addProviderToTopOfStack(top); - } + void setUp() { + bottom = new DummySettingsProvider(); + top = new DummySettingsProvider(); + testling = new SettingsProviderHierachy(); + testling->addProviderToTopOfStack(bottom); + testling->addProviderToTopOfStack(top); + } - void tearDown() { - delete testling; - delete top; - delete bottom; - } + void tearDown() { + delete testling; + delete top; + delete bottom; + } - void testEmpty() { - CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1)); - } + void testEmpty() { + CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1)); + } - void testTop() { - top->storeSetting(setting1, 37); - CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1)); - } + void testTop() { + top->storeSetting(setting1, 37); + CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1)); + } - void testBottom() { - bottom->storeSetting(setting1, 17); - CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1)); - } + void testBottom() { + bottom->storeSetting(setting1, 17); + CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1)); + } - void testBoth() { - bottom->storeSetting(setting1, 17); - top->storeSetting(setting1, 37); - CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1)); - } + void testBoth() { + bottom->storeSetting(setting1, 17); + top->storeSetting(setting1, 37); + CPPUNIT_ASSERT_EQUAL(37, testling->getSetting(setting1)); + } - void testTopDefault() { - bottom->storeSetting(setting1, 17); - top->storeSetting(setting1, 42); - CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1)); - } + void testTopDefault() { + bottom->storeSetting(setting1, 17); + top->storeSetting(setting1, 42); + CPPUNIT_ASSERT_EQUAL(42, testling->getSetting(setting1)); + } - void testBottomOverrides() { - bottom->storeSetting(setting1, 17); - bottom->setFinal(setting1.getKey()); - top->storeSetting(setting1, 5); - CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1)); - } + void testBottomOverrides() { + bottom->storeSetting(setting1, 17); + bottom->setFinal(setting1.getKey()); + top->storeSetting(setting1, 5); + CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1)); + } - void testFinal() { - bottom->storeSetting(setting1, 17); - bottom->setFinal(setting1.getKey()); - testling->storeSetting(setting1, 5); - CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1)); - } + void testFinal() { + bottom->storeSetting(setting1, 17); + bottom->setFinal(setting1.getKey()); + testling->storeSetting(setting1, 5); + CPPUNIT_ASSERT_EQUAL(17, testling->getSetting(setting1)); + } private: - SettingsProviderHierachy* testling; - DummySettingsProvider* bottom; - DummySettingsProvider* top; - SettingsProvider::Setting setting1; + SettingsProviderHierachy* testling; + DummySettingsProvider* bottom; + DummySettingsProvider* top; + SettingsProvider::Setting setting1; }; CPPUNIT_TEST_SUITE_REGISTRATION(SettingsProviderHierachyTest); diff --git a/Swift/Controllers/Settings/XMLSettingsProvider.cpp b/Swift/Controllers/Settings/XMLSettingsProvider.cpp index 548f36f..4dfb8bd 100644 --- a/Swift/Controllers/Settings/XMLSettingsProvider.cpp +++ b/Swift/Controllers/Settings/XMLSettingsProvider.cpp @@ -16,20 +16,20 @@ namespace Swift { XMLSettingsProvider::XMLSettingsProvider(const std::string& xmlConfig) : level_(0) { - if (!xmlConfig.empty()) { - PlatformXMLParserFactory factory; - XMLParser* parser = factory.createXMLParser(this); - if (parser->parse(xmlConfig)) { - SWIFT_LOG(debug) << "Found and parsed system config" << std::endl; - } - else { - SWIFT_LOG(debug) << "Found invalid system config" << std::endl; - } - delete parser; - } - else { - SWIFT_LOG(debug) << "No system config found" << std::endl; - } + if (!xmlConfig.empty()) { + PlatformXMLParserFactory factory; + XMLParser* parser = factory.createXMLParser(this); + if (parser->parse(xmlConfig)) { + SWIFT_LOG(debug) << "Found and parsed system config" << std::endl; + } + else { + SWIFT_LOG(debug) << "Found invalid system config" << std::endl; + } + delete parser; + } + else { + SWIFT_LOG(debug) << "No system config found" << std::endl; + } } XMLSettingsProvider::~XMLSettingsProvider() { @@ -37,89 +37,89 @@ XMLSettingsProvider::~XMLSettingsProvider() { } bool XMLSettingsProvider::hasSetting(const std::string& key) { - return (values_.find(key) != values_.end()); + return (values_.find(key) != values_.end()); } std::string XMLSettingsProvider::getSetting(const Setting& setting) { - if (values_.find(setting.getKey()) != values_.end()) { - std::string value = values_[setting.getKey()]; - return value; - } - return setting.getDefaultValue(); + if (values_.find(setting.getKey()) != values_.end()) { + std::string value = values_[setting.getKey()]; + return value; + } + return setting.getDefaultValue(); } void XMLSettingsProvider::storeSetting(const Setting& /*settingPath*/, const std::string& /*settingValue*/) { - assert(false); + assert(false); } bool XMLSettingsProvider::getSetting(const Setting& setting) { - if (values_.find(setting.getKey()) != values_.end()) { - std::string value = values_[setting.getKey()]; - return boost::iequals(value, "true") || value == "1"; - } - return setting.getDefaultValue(); + if (values_.find(setting.getKey()) != values_.end()) { + std::string value = values_[setting.getKey()]; + return boost::iequals(value, "true") || value == "1"; + } + return setting.getDefaultValue(); } void XMLSettingsProvider::storeSetting(const Setting& /*settingPath*/, const bool& /*settingValue*/) { - assert(false); + assert(false); } int XMLSettingsProvider::getSetting(const Setting& setting) { - if (values_.find(setting.getKey()) != values_.end()) { - std::string value = values_[setting.getKey()]; - try { - return value.empty() ? setting.getDefaultValue() : boost::lexical_cast(value);; - } - catch(boost::bad_lexical_cast &) {} - } - return setting.getDefaultValue(); + if (values_.find(setting.getKey()) != values_.end()) { + std::string value = values_[setting.getKey()]; + try { + return value.empty() ? setting.getDefaultValue() : boost::lexical_cast(value);; + } + catch(boost::bad_lexical_cast &) {} + } + return setting.getDefaultValue(); } void XMLSettingsProvider::storeSetting(const Setting& /*settingPath*/, const int& /*settingValue*/) { - assert(false); + assert(false); } std::vector XMLSettingsProvider::getAvailableProfiles() { - assert(false); - return std::vector(); + assert(false); + return std::vector(); } void XMLSettingsProvider::createProfile(const std::string& /*profile*/) { - assert(false); + assert(false); } void XMLSettingsProvider::removeProfile(const std::string& /*profile*/) { - assert(false); + assert(false); } bool XMLSettingsProvider::getIsSettingFinal(const std::string& settingPath) { - return finals_.count(settingPath); + return finals_.count(settingPath); } void XMLSettingsProvider::handleStartElement(const std::string& element, const std::string& /*ns*/, const AttributeMap& attributes) { - level_++; - if (level_ == SettingLevel) { - if (attributes.getBoolAttribute("final", false)) { - finals_.insert(element); - } - currentElement_ = element; - currentText_ = ""; - } + level_++; + if (level_ == SettingLevel) { + if (attributes.getBoolAttribute("final", false)) { + finals_.insert(element); + } + currentElement_ = element; + currentText_ = ""; + } } void XMLSettingsProvider::handleEndElement(const std::string& /*element*/, const std::string& /*ns*/) { - if (level_ == SettingLevel) { - values_[currentElement_] = currentText_; - SWIFT_LOG(debug) << "Setting value of " << currentElement_ << " to " << currentText_ << std::endl; - } - level_--; + if (level_ == SettingLevel) { + values_[currentElement_] = currentText_; + SWIFT_LOG(debug) << "Setting value of " << currentElement_ << " to " << currentText_ << std::endl; + } + level_--; } void XMLSettingsProvider::handleCharacterData(const std::string& data) { - if (level_ >= SettingLevel) { - currentText_ += data; - } + if (level_ >= SettingLevel) { + currentText_ += data; + } } diff --git a/Swift/Controllers/Settings/XMLSettingsProvider.h b/Swift/Controllers/Settings/XMLSettingsProvider.h index 2dbb23c..5fd82cf 100644 --- a/Swift/Controllers/Settings/XMLSettingsProvider.h +++ b/Swift/Controllers/Settings/XMLSettingsProvider.h @@ -16,40 +16,40 @@ namespace Swift { class XMLSettingsProvider : public SettingsProvider, public XMLParserClient { - public: - XMLSettingsProvider(const std::string& xmlConfig); - virtual ~XMLSettingsProvider(); - virtual std::string getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const std::string& value); - virtual bool getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const bool& value); - virtual int getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const int& value); - virtual std::vector getAvailableProfiles(); - virtual void createProfile(const std::string& profile); - virtual void removeProfile(const std::string& profile); - virtual bool hasSetting(const std::string& key); - - - virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes); - virtual void handleEndElement(const std::string& element, const std::string& ns); - virtual void handleCharacterData(const std::string& data); - - protected: - virtual bool getIsSettingFinal(const std::string& settingPath); - private: - std::map values_; - /* Settings that are final*/ - std::set finals_; - - enum Level { - TopLevel = 0, - SettingLevel = 2 - }; - - int level_; - std::string currentElement_; - std::string currentText_; + public: + XMLSettingsProvider(const std::string& xmlConfig); + virtual ~XMLSettingsProvider(); + virtual std::string getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const std::string& value); + virtual bool getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const bool& value); + virtual int getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const int& value); + virtual std::vector getAvailableProfiles(); + virtual void createProfile(const std::string& profile); + virtual void removeProfile(const std::string& profile); + virtual bool hasSetting(const std::string& key); + + + virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes); + virtual void handleEndElement(const std::string& element, const std::string& ns); + virtual void handleCharacterData(const std::string& data); + + protected: + virtual bool getIsSettingFinal(const std::string& settingPath); + private: + std::map values_; + /* Settings that are final*/ + std::set finals_; + + enum Level { + TopLevel = 0, + SettingLevel = 2 + }; + + int level_; + std::string currentElement_; + std::string currentText_; }; } diff --git a/Swift/Controllers/ShowProfileController.cpp b/Swift/Controllers/ShowProfileController.cpp index 9e94392..bf5eb1e 100644 --- a/Swift/Controllers/ShowProfileController.cpp +++ b/Swift/Controllers/ShowProfileController.cpp @@ -25,57 +25,57 @@ namespace Swift { ShowProfileController::ShowProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream) : vcardManager(vcardManager), profileWindowFactory(profileWindowFactory), uiEventStream(uiEventStream) { - uiEventStream->onUIEvent.connect(boost::bind(&ShowProfileController::handleUIEvent, this, _1)); - vcardManager->onVCardChanged.connect(boost::bind(&ShowProfileController::handleVCardChanged, this, _1, _2)); + uiEventStream->onUIEvent.connect(boost::bind(&ShowProfileController::handleUIEvent, this, _1)); + vcardManager->onVCardChanged.connect(boost::bind(&ShowProfileController::handleVCardChanged, this, _1, _2)); } ShowProfileController::~ShowProfileController() { - typedef std::pair JIDProfileWindowPair; - foreach(const JIDProfileWindowPair& jidWndPair, openedProfileWindows) { - jidWndPair.second->onWindowAboutToBeClosed.disconnect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1)); - delete jidWndPair.second; - } + typedef std::pair JIDProfileWindowPair; + foreach(const JIDProfileWindowPair& jidWndPair, openedProfileWindows) { + jidWndPair.second->onWindowAboutToBeClosed.disconnect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1)); + delete jidWndPair.second; + } - vcardManager->onVCardChanged.disconnect(boost::bind(&ShowProfileController::handleVCardChanged, this, _1, _2)); - uiEventStream->onUIEvent.disconnect(boost::bind(&ShowProfileController::handleUIEvent, this, _1)); + vcardManager->onVCardChanged.disconnect(boost::bind(&ShowProfileController::handleVCardChanged, this, _1, _2)); + uiEventStream->onUIEvent.disconnect(boost::bind(&ShowProfileController::handleUIEvent, this, _1)); } void ShowProfileController::handleUIEvent(UIEvent::ref event) { - ShowProfileForRosterItemUIEvent::ref showProfileEvent = boost::dynamic_pointer_cast(event); - if (!showProfileEvent) { - return; - } + ShowProfileForRosterItemUIEvent::ref showProfileEvent = boost::dynamic_pointer_cast(event); + if (!showProfileEvent) { + return; + } - if (openedProfileWindows.find(showProfileEvent->getJID()) == openedProfileWindows.end()) { - ProfileWindow* newProfileWindow = profileWindowFactory->createProfileWindow(); - newProfileWindow->setJID(showProfileEvent->getJID()); - newProfileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1)); - openedProfileWindows[showProfileEvent->getJID()] = newProfileWindow; - VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(showProfileEvent->getJID(), boost::posix_time::minutes(5)); - if (vcard) { - newProfileWindow->setVCard(vcard); - } else { - newProfileWindow->setProcessing(true); - } - newProfileWindow->show(); - } else { - openedProfileWindows[showProfileEvent->getJID()]->show(); - } + if (openedProfileWindows.find(showProfileEvent->getJID()) == openedProfileWindows.end()) { + ProfileWindow* newProfileWindow = profileWindowFactory->createProfileWindow(); + newProfileWindow->setJID(showProfileEvent->getJID()); + newProfileWindow->onWindowAboutToBeClosed.connect(boost::bind(&ShowProfileController::handleProfileWindowAboutToBeClosed, this, _1)); + openedProfileWindows[showProfileEvent->getJID()] = newProfileWindow; + VCard::ref vcard = vcardManager->getVCardAndRequestWhenNeeded(showProfileEvent->getJID(), boost::posix_time::minutes(5)); + if (vcard) { + newProfileWindow->setVCard(vcard); + } else { + newProfileWindow->setProcessing(true); + } + newProfileWindow->show(); + } else { + openedProfileWindows[showProfileEvent->getJID()]->show(); + } } void ShowProfileController::handleVCardChanged(const JID& jid, VCard::ref vcard) { - if (openedProfileWindows.find(jid) == openedProfileWindows.end()) { - return; - } + if (openedProfileWindows.find(jid) == openedProfileWindows.end()) { + return; + } - ProfileWindow* profileWindow = openedProfileWindows[jid]; - profileWindow->setVCard(vcard); - profileWindow->setProcessing(false); - profileWindow->show(); + ProfileWindow* profileWindow = openedProfileWindows[jid]; + profileWindow->setVCard(vcard); + profileWindow->setProcessing(false); + profileWindow->show(); } void ShowProfileController::handleProfileWindowAboutToBeClosed(const JID& profileJid) { - openedProfileWindows.erase(profileJid); + openedProfileWindows.erase(profileJid); } } diff --git a/Swift/Controllers/ShowProfileController.h b/Swift/Controllers/ShowProfileController.h index 37fb615..4f23c19 100644 --- a/Swift/Controllers/ShowProfileController.h +++ b/Swift/Controllers/ShowProfileController.h @@ -18,25 +18,25 @@ #include namespace Swift { - class VCardManager; - class ProfileWindow; - class ProfileWindowFactory; - class UIEventStream; - - class ShowProfileController { - public: - ShowProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream); - ~ShowProfileController(); - - private: - void handleUIEvent(UIEvent::ref event); - void handleVCardChanged(const JID&, VCard::ref); - void handleProfileWindowAboutToBeClosed(const JID& profileJid); - - private: - VCardManager* vcardManager; - ProfileWindowFactory* profileWindowFactory; - UIEventStream* uiEventStream; - std::map openedProfileWindows; - }; + class VCardManager; + class ProfileWindow; + class ProfileWindowFactory; + class UIEventStream; + + class ShowProfileController { + public: + ShowProfileController(VCardManager* vcardManager, ProfileWindowFactory* profileWindowFactory, UIEventStream* uiEventStream); + ~ShowProfileController(); + + private: + void handleUIEvent(UIEvent::ref event); + void handleVCardChanged(const JID&, VCard::ref); + void handleProfileWindowAboutToBeClosed(const JID& profileJid); + + private: + VCardManager* vcardManager; + ProfileWindowFactory* profileWindowFactory; + UIEventStream* uiEventStream; + std::map openedProfileWindows; + }; } diff --git a/Swift/Controllers/SoundEventController.cpp b/Swift/Controllers/SoundEventController.cpp index 43c8ed0..433937b 100644 --- a/Swift/Controllers/SoundEventController.cpp +++ b/Swift/Controllers/SoundEventController.cpp @@ -18,39 +18,39 @@ namespace Swift { SoundEventController::SoundEventController(EventController* eventController, SoundPlayer* soundPlayer, SettingsProvider* settings, HighlightManager* highlightManager) { - settings_ = settings; - eventController_ = eventController; - soundPlayer_ = soundPlayer; - eventController_->onEventQueueEventAdded.connect(boost::bind(&SoundEventController::handleEventQueueEventAdded, this, _1)); - highlightManager_ = highlightManager; - highlightManager_->onHighlight.connect(boost::bind(&SoundEventController::handleHighlight, this, _1)); + settings_ = settings; + eventController_ = eventController; + soundPlayer_ = soundPlayer; + eventController_->onEventQueueEventAdded.connect(boost::bind(&SoundEventController::handleEventQueueEventAdded, this, _1)); + highlightManager_ = highlightManager; + highlightManager_->onHighlight.connect(boost::bind(&SoundEventController::handleHighlight, this, _1)); - settings_->onSettingChanged.connect(boost::bind(&SoundEventController::handleSettingChanged, this, _1)); + settings_->onSettingChanged.connect(boost::bind(&SoundEventController::handleSettingChanged, this, _1)); - playSounds_ = settings->getSetting(SettingConstants::PLAY_SOUNDS); + playSounds_ = settings->getSetting(SettingConstants::PLAY_SOUNDS); } void SoundEventController::handleEventQueueEventAdded(boost::shared_ptr event) { - if (playSounds_ && boost::dynamic_pointer_cast(event)) { - soundPlayer_->playSound(SoundPlayer::MessageReceived, ""); - } + if (playSounds_ && boost::dynamic_pointer_cast(event)) { + soundPlayer_->playSound(SoundPlayer::MessageReceived, ""); + } } void SoundEventController::handleHighlight(const HighlightAction& action) { - if (playSounds_ && action.playSound()) { - soundPlayer_->playSound(SoundPlayer::MessageReceived, action.getSoundFile()); - } + if (playSounds_ && action.playSound()) { + soundPlayer_->playSound(SoundPlayer::MessageReceived, action.getSoundFile()); + } } void SoundEventController::setPlaySounds(bool playSounds) { - playSounds_ = playSounds; - settings_->storeSetting(SettingConstants::PLAY_SOUNDS, playSounds); + playSounds_ = playSounds; + settings_->storeSetting(SettingConstants::PLAY_SOUNDS, playSounds); } void SoundEventController::handleSettingChanged(const std::string& settingPath) { - if (SettingConstants::PLAY_SOUNDS.getKey() == settingPath) { - playSounds_ = settings_->getSetting(SettingConstants::PLAY_SOUNDS); - } + if (SettingConstants::PLAY_SOUNDS.getKey() == settingPath) { + playSounds_ = settings_->getSetting(SettingConstants::PLAY_SOUNDS); + } } } diff --git a/Swift/Controllers/SoundEventController.h b/Swift/Controllers/SoundEventController.h index 88c7b00..3ea682a 100644 --- a/Swift/Controllers/SoundEventController.h +++ b/Swift/Controllers/SoundEventController.h @@ -13,22 +13,22 @@ #include namespace Swift { - class EventController; - class SoundPlayer; - class HighlightManager; - class SoundEventController { - public: - SoundEventController(EventController* eventController, SoundPlayer* soundPlayer, SettingsProvider* settings, HighlightManager* highlightManager); - void setPlaySounds(bool playSounds); - bool getSoundEnabled() {return playSounds_;} - private: - void handleSettingChanged(const std::string& settingPath); - void handleEventQueueEventAdded(boost::shared_ptr event); - void handleHighlight(const HighlightAction& action); - EventController* eventController_; - SoundPlayer* soundPlayer_; - bool playSounds_; - SettingsProvider* settings_; - HighlightManager* highlightManager_; - }; + class EventController; + class SoundPlayer; + class HighlightManager; + class SoundEventController { + public: + SoundEventController(EventController* eventController, SoundPlayer* soundPlayer, SettingsProvider* settings, HighlightManager* highlightManager); + void setPlaySounds(bool playSounds); + bool getSoundEnabled() {return playSounds_;} + private: + void handleSettingChanged(const std::string& settingPath); + void handleEventQueueEventAdded(boost::shared_ptr event); + void handleHighlight(const HighlightAction& action); + EventController* eventController_; + SoundPlayer* soundPlayer_; + bool playSounds_; + SettingsProvider* settings_; + HighlightManager* highlightManager_; + }; } diff --git a/Swift/Controllers/SoundPlayer.h b/Swift/Controllers/SoundPlayer.h index e38cd7c..8525c6c 100644 --- a/Swift/Controllers/SoundPlayer.h +++ b/Swift/Controllers/SoundPlayer.h @@ -9,10 +9,10 @@ #include namespace Swift { - class SoundPlayer { - public: - virtual ~SoundPlayer() {} - enum SoundEffect{MessageReceived}; - virtual void playSound(SoundEffect sound, const std::string& soundResource) = 0; - }; + class SoundPlayer { + public: + virtual ~SoundPlayer() {} + enum SoundEffect{MessageReceived}; + virtual void playSound(SoundEffect sound, const std::string& soundResource) = 0; + }; } diff --git a/Swift/Controllers/StatusCache.cpp b/Swift/Controllers/StatusCache.cpp index d00d7f6..ce4391d 100644 --- a/Swift/Controllers/StatusCache.cpp +++ b/Swift/Controllers/StatusCache.cpp @@ -24,9 +24,9 @@ namespace Swift { static const size_t MAX_ENTRIES = 200; StatusCache::StatusCache(ApplicationPathProvider* paths) { - paths_ = paths; - path_ = paths_->getDataDir() / "StatusCache"; - loadRecents(); + paths_ = paths; + path_ = paths_->getDataDir() / "StatusCache"; + loadRecents(); } StatusCache::~StatusCache() { @@ -34,71 +34,71 @@ StatusCache::~StatusCache() { } std::vector StatusCache::getMatches(const std::string& substring, size_t maxCount) const { - std::vector matches; - foreach (const PreviousStatus& status, previousStatuses_) { - if (substring.empty() || (boost::algorithm::ifind_first(status.first, substring) && substring != status.first)) { - matches.push_back(status); - if (matches.size() == maxCount) { - break; - } - } - } - return matches; + std::vector matches; + foreach (const PreviousStatus& status, previousStatuses_) { + if (substring.empty() || (boost::algorithm::ifind_first(status.first, substring) && substring != status.first)) { + matches.push_back(status); + if (matches.size() == maxCount) { + break; + } + } + } + return matches; } void StatusCache::addRecent(const std::string& text, StatusShow::Type type) { - if (text.empty()) { - return; - } - previousStatuses_.remove_if(lambda::bind(&PreviousStatus::first, lambda::_1) == text && lambda::bind(&PreviousStatus::second, lambda::_1) == type); - previousStatuses_.push_front(PreviousStatus(text, type)); - for (size_t i = previousStatuses_.size(); i > MAX_ENTRIES; i--) { - previousStatuses_.pop_back(); - } - saveRecents(); + if (text.empty()) { + return; + } + previousStatuses_.remove_if(lambda::bind(&PreviousStatus::first, lambda::_1) == text && lambda::bind(&PreviousStatus::second, lambda::_1) == type); + previousStatuses_.push_front(PreviousStatus(text, type)); + for (size_t i = previousStatuses_.size(); i > MAX_ENTRIES; i--) { + previousStatuses_.pop_back(); + } + saveRecents(); } void StatusCache::loadRecents() { - try { - if (boost::filesystem::exists(path_)) { - ByteArray data; - readByteArrayFromFile(data, path_); - std::string stringData = byteArrayToString(data); - std::vector lines; - boost::split(lines, stringData, boost::is_any_of("\n")); - foreach (const std::string& line, lines) { - std::vector bits; - boost::split(bits, line, boost::is_any_of("\t")); - if (bits.size() < 2) { - continue; - } - StatusShow::Type type; - type = static_cast(boost::lexical_cast(bits[0])); - previousStatuses_.push_back(PreviousStatus(boost::trim_copy(bits[1]), type)); - } - } - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } + try { + if (boost::filesystem::exists(path_)) { + ByteArray data; + readByteArrayFromFile(data, path_); + std::string stringData = byteArrayToString(data); + std::vector lines; + boost::split(lines, stringData, boost::is_any_of("\n")); + foreach (const std::string& line, lines) { + std::vector bits; + boost::split(bits, line, boost::is_any_of("\t")); + if (bits.size() < 2) { + continue; + } + StatusShow::Type type; + type = static_cast(boost::lexical_cast(bits[0])); + previousStatuses_.push_back(PreviousStatus(boost::trim_copy(bits[1]), type)); + } + } + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } } void StatusCache::saveRecents() { - try { - if (!boost::filesystem::exists(path_.parent_path())) { - boost::filesystem::create_directories(path_.parent_path()); - } - boost::filesystem::ofstream file(path_); - foreach (const PreviousStatus& recent, previousStatuses_) { - std::string message = recent.first; - boost::replace_all(message, "\t", " "); - file << recent.second << "\t" << message << std::endl; - } - file.close(); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } + try { + if (!boost::filesystem::exists(path_.parent_path())) { + boost::filesystem::create_directories(path_.parent_path()); + } + boost::filesystem::ofstream file(path_); + foreach (const PreviousStatus& recent, previousStatuses_) { + std::string message = recent.first; + boost::replace_all(message, "\t", " "); + file << recent.second << "\t" << message << std::endl; + } + file.close(); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } } } diff --git a/Swift/Controllers/StatusCache.h b/Swift/Controllers/StatusCache.h index 0ed85d6..033cde0 100644 --- a/Swift/Controllers/StatusCache.h +++ b/Swift/Controllers/StatusCache.h @@ -17,24 +17,24 @@ #include namespace Swift { - class ApplicationPathProvider; - class StatusCache { - public: - typedef std::pair PreviousStatus; - public: - StatusCache(ApplicationPathProvider* paths); - ~StatusCache(); - - std::vector getMatches(const std::string& substring, size_t maxCount) const; - void addRecent(const std::string& text, StatusShow::Type type); - private: - void saveRecents(); - void loadRecents(); - private: - boost::filesystem::path path_; - std::list previousStatuses_; - ApplicationPathProvider* paths_; - }; + class ApplicationPathProvider; + class StatusCache { + public: + typedef std::pair PreviousStatus; + public: + StatusCache(ApplicationPathProvider* paths); + ~StatusCache(); + + std::vector getMatches(const std::string& substring, size_t maxCount) const; + void addRecent(const std::string& text, StatusShow::Type type); + private: + void saveRecents(); + void loadRecents(); + private: + boost::filesystem::path path_; + std::list previousStatuses_; + ApplicationPathProvider* paths_; + }; } diff --git a/Swift/Controllers/StatusTracker.cpp b/Swift/Controllers/StatusTracker.cpp index e42b99e..51db328 100644 --- a/Swift/Controllers/StatusTracker.cpp +++ b/Swift/Controllers/StatusTracker.cpp @@ -13,46 +13,46 @@ namespace Swift { StatusTracker::StatusTracker() { - isAutoAway_ = false; - queuedPresence_ = boost::make_shared(); + isAutoAway_ = false; + queuedPresence_ = boost::make_shared(); } boost::shared_ptr StatusTracker::getNextPresence() { - boost::shared_ptr presence; - if (isAutoAway_) { - presence = boost::make_shared(); - presence->setShow(StatusShow::Away); - presence->setStatus(queuedPresence_->getStatus()); - presence->addPayload(boost::make_shared(isAutoAwaySince_)); - } else { - presence = queuedPresence_; - } - return presence; + boost::shared_ptr presence; + if (isAutoAway_) { + presence = boost::make_shared(); + presence->setShow(StatusShow::Away); + presence->setStatus(queuedPresence_->getStatus()); + presence->addPayload(boost::make_shared(isAutoAwaySince_)); + } else { + presence = queuedPresence_; + } + return presence; } void StatusTracker::setRequestedPresence(boost::shared_ptr presence) { - isAutoAway_ = false; - queuedPresence_ = presence; -// if (presence->getType() == Presence::Unavailable) { -// queuedPresence_ = boost::make_shared(); -// } + isAutoAway_ = false; + queuedPresence_ = presence; +// if (presence->getType() == Presence::Unavailable) { +// queuedPresence_ = boost::make_shared(); +// } } bool StatusTracker::goAutoAway(const int& seconds) { - if (queuedPresence_->getShow() != StatusShow::Online) { - return false; - } - isAutoAway_ = true; - isAutoAwaySince_ = boost::posix_time::second_clock::universal_time() - boost::posix_time::seconds(seconds); - return true; + if (queuedPresence_->getShow() != StatusShow::Online) { + return false; + } + isAutoAway_ = true; + isAutoAwaySince_ = boost::posix_time::second_clock::universal_time() - boost::posix_time::seconds(seconds); + return true; } bool StatusTracker::goAutoUnAway() { - if (!isAutoAway_) { - return false; - } - isAutoAway_ = false; - return true; + if (!isAutoAway_) { + return false; + } + isAutoAway_ = false; + return true; } } diff --git a/Swift/Controllers/StatusTracker.h b/Swift/Controllers/StatusTracker.h index 092ce43..cf92781 100644 --- a/Swift/Controllers/StatusTracker.h +++ b/Swift/Controllers/StatusTracker.h @@ -13,16 +13,16 @@ namespace Swift { - class StatusTracker { - public: - StatusTracker(); - boost::shared_ptr getNextPresence(); - void setRequestedPresence(boost::shared_ptr presence); - bool goAutoAway(const int& seconds); - bool goAutoUnAway(); - private: - boost::shared_ptr queuedPresence_; - bool isAutoAway_; - boost::posix_time::ptime isAutoAwaySince_; - }; + class StatusTracker { + public: + StatusTracker(); + boost::shared_ptr getNextPresence(); + void setRequestedPresence(boost::shared_ptr presence); + bool goAutoAway(const int& seconds); + bool goAutoUnAway(); + private: + boost::shared_ptr queuedPresence_; + bool isAutoAway_; + boost::posix_time::ptime isAutoAwaySince_; + }; } diff --git a/Swift/Controllers/StatusUtil.cpp b/Swift/Controllers/StatusUtil.cpp index 0c5bc21..1034863 100644 --- a/Swift/Controllers/StatusUtil.cpp +++ b/Swift/Controllers/StatusUtil.cpp @@ -13,16 +13,16 @@ namespace Swift { std::string statusShowTypeToFriendlyName(StatusShow::Type type) { - switch (type) { - case StatusShow::Online: return QT_TRANSLATE_NOOP("", "Available"); - case StatusShow::FFC: return QT_TRANSLATE_NOOP("", "Available"); - case StatusShow::Away: return QT_TRANSLATE_NOOP("", "Away"); - case StatusShow::XA: return QT_TRANSLATE_NOOP("", "Away"); - case StatusShow::DND: return QT_TRANSLATE_NOOP("", "Busy"); - case StatusShow::None: return QT_TRANSLATE_NOOP("", "Offline"); - } - assert(false); - return ""; + switch (type) { + case StatusShow::Online: return QT_TRANSLATE_NOOP("", "Available"); + case StatusShow::FFC: return QT_TRANSLATE_NOOP("", "Available"); + case StatusShow::Away: return QT_TRANSLATE_NOOP("", "Away"); + case StatusShow::XA: return QT_TRANSLATE_NOOP("", "Away"); + case StatusShow::DND: return QT_TRANSLATE_NOOP("", "Busy"); + case StatusShow::None: return QT_TRANSLATE_NOOP("", "Offline"); + } + assert(false); + return ""; } } diff --git a/Swift/Controllers/StatusUtil.h b/Swift/Controllers/StatusUtil.h index 871ca0a..6872bf7 100644 --- a/Swift/Controllers/StatusUtil.h +++ b/Swift/Controllers/StatusUtil.h @@ -11,6 +11,6 @@ #include namespace Swift { - std::string statusShowTypeToFriendlyName(StatusShow::Type type); + std::string statusShowTypeToFriendlyName(StatusShow::Type type); } diff --git a/Swift/Controllers/Storages/AvatarFileStorage.cpp b/Swift/Controllers/Storages/AvatarFileStorage.cpp index 56e27e1..cded945 100644 --- a/Swift/Controllers/Storages/AvatarFileStorage.cpp +++ b/Swift/Controllers/Storages/AvatarFileStorage.cpp @@ -19,88 +19,88 @@ namespace Swift { AvatarFileStorage::AvatarFileStorage(const boost::filesystem::path& avatarsDir, const boost::filesystem::path& avatarsFile, CryptoProvider* crypto) : avatarsDir(avatarsDir), avatarsFile(avatarsFile), crypto(crypto) { - if (boost::filesystem::exists(avatarsFile)) { - try { - boost::filesystem::ifstream file(avatarsFile); - std::string line; - if (file.is_open()) { - while (!file.eof()) { - getline(file, line); - std::pair r = String::getSplittedAtFirst(line, ' '); - JID jid(r.second); - if (jid.isValid()) { - jidAvatars.insert(std::make_pair(jid, r.first)); - } - else if (!r.first.empty() || !r.second.empty()) { - std::cerr << "Invalid entry in avatars file: " << r.second << std::endl; - } - } - } - } - catch (...) { - std::cerr << "Error reading avatars file" << std::endl; - } - } + if (boost::filesystem::exists(avatarsFile)) { + try { + boost::filesystem::ifstream file(avatarsFile); + std::string line; + if (file.is_open()) { + while (!file.eof()) { + getline(file, line); + std::pair r = String::getSplittedAtFirst(line, ' '); + JID jid(r.second); + if (jid.isValid()) { + jidAvatars.insert(std::make_pair(jid, r.first)); + } + else if (!r.first.empty() || !r.second.empty()) { + std::cerr << "Invalid entry in avatars file: " << r.second << std::endl; + } + } + } + } + catch (...) { + std::cerr << "Error reading avatars file" << std::endl; + } + } } -bool AvatarFileStorage::hasAvatar(const std::string& hash) const { - return boost::filesystem::exists(getAvatarPath(hash)); +bool AvatarFileStorage::hasAvatar(const std::string& hash) const { + return boost::filesystem::exists(getAvatarPath(hash)); } void AvatarFileStorage::addAvatar(const std::string& hash, const ByteArray& avatar) { - assert(Hexify::hexify(crypto->getSHA1Hash(avatar)) == hash); + assert(Hexify::hexify(crypto->getSHA1Hash(avatar)) == hash); - boost::filesystem::path avatarPath = getAvatarPath(hash); - if (!boost::filesystem::exists(avatarPath.parent_path())) { - try { - boost::filesystem::create_directories(avatarPath.parent_path()); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } - } - boost::filesystem::ofstream file(avatarPath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out); - file.write(reinterpret_cast(vecptr(avatar)), static_cast(avatar.size())); - file.close(); + boost::filesystem::path avatarPath = getAvatarPath(hash); + if (!boost::filesystem::exists(avatarPath.parent_path())) { + try { + boost::filesystem::create_directories(avatarPath.parent_path()); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } + } + boost::filesystem::ofstream file(avatarPath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out); + file.write(reinterpret_cast(vecptr(avatar)), static_cast(avatar.size())); + file.close(); } boost::filesystem::path AvatarFileStorage::getAvatarPath(const std::string& hash) const { - return avatarsDir / hash; + return avatarsDir / hash; } ByteArray AvatarFileStorage::getAvatar(const std::string& hash) const { - ByteArray data; - readByteArrayFromFile(data, getAvatarPath(hash)); - return data; + ByteArray data; + readByteArrayFromFile(data, getAvatarPath(hash)); + return data; } void AvatarFileStorage::setAvatarForJID(const JID& jid, const std::string& hash) { - std::pair r = jidAvatars.insert(std::make_pair(jid, hash)); - if (r.second) { - saveJIDAvatars(); - } - else if (r.first->second != hash) { - r.first->second = hash; - saveJIDAvatars(); - } + std::pair r = jidAvatars.insert(std::make_pair(jid, hash)); + if (r.second) { + saveJIDAvatars(); + } + else if (r.first->second != hash) { + r.first->second = hash; + saveJIDAvatars(); + } } std::string AvatarFileStorage::getAvatarForJID(const JID& jid) const { - JIDAvatarMap::const_iterator i = jidAvatars.find(jid); - return i == jidAvatars.end() ? "" : i->second; + JIDAvatarMap::const_iterator i = jidAvatars.find(jid); + return i == jidAvatars.end() ? "" : i->second; } void AvatarFileStorage::saveJIDAvatars() { - try { - boost::filesystem::ofstream file(avatarsFile); - for (JIDAvatarMap::const_iterator i = jidAvatars.begin(); i != jidAvatars.end(); ++i) { - file << i->second << " " << i->first.toString() << std::endl; - } - file.close(); - } - catch (...) { - std::cerr << "Error writing avatars file" << std::endl; - } + try { + boost::filesystem::ofstream file(avatarsFile); + for (JIDAvatarMap::const_iterator i = jidAvatars.begin(); i != jidAvatars.end(); ++i) { + file << i->second << " " << i->first.toString() << std::endl; + } + file.close(); + } + catch (...) { + std::cerr << "Error writing avatars file" << std::endl; + } } } diff --git a/Swift/Controllers/Storages/AvatarFileStorage.h b/Swift/Controllers/Storages/AvatarFileStorage.h index 9c6f617..41c7106 100644 --- a/Swift/Controllers/Storages/AvatarFileStorage.h +++ b/Swift/Controllers/Storages/AvatarFileStorage.h @@ -16,30 +16,30 @@ #include namespace Swift { - class CryptoProvider; + class CryptoProvider; - class AvatarFileStorage : public AvatarStorage { - public: - AvatarFileStorage(const boost::filesystem::path& avatarsDir, const boost::filesystem::path& avatarsFile, CryptoProvider* crypto); + class AvatarFileStorage : public AvatarStorage { + public: + AvatarFileStorage(const boost::filesystem::path& avatarsDir, const boost::filesystem::path& avatarsFile, CryptoProvider* crypto); - virtual bool hasAvatar(const std::string& hash) const; - virtual void addAvatar(const std::string& hash, const ByteArray& avatar); - virtual ByteArray getAvatar(const std::string& hash) const; + virtual bool hasAvatar(const std::string& hash) const; + virtual void addAvatar(const std::string& hash, const ByteArray& avatar); + virtual ByteArray getAvatar(const std::string& hash) const; - virtual boost::filesystem::path getAvatarPath(const std::string& hash) const; + virtual boost::filesystem::path getAvatarPath(const std::string& hash) const; - virtual void setAvatarForJID(const JID& jid, const std::string& hash); - virtual std::string getAvatarForJID(const JID& jid) const; + virtual void setAvatarForJID(const JID& jid, const std::string& hash); + virtual std::string getAvatarForJID(const JID& jid) const; - private: - void saveJIDAvatars(); + private: + void saveJIDAvatars(); - private: - boost::filesystem::path avatarsDir; - boost::filesystem::path avatarsFile; - CryptoProvider* crypto; - typedef std::map JIDAvatarMap; - JIDAvatarMap jidAvatars; - }; + private: + boost::filesystem::path avatarsDir; + boost::filesystem::path avatarsFile; + CryptoProvider* crypto; + typedef std::map JIDAvatarMap; + JIDAvatarMap jidAvatars; + }; } diff --git a/Swift/Controllers/Storages/CapsFileStorage.cpp b/Swift/Controllers/Storages/CapsFileStorage.cpp index 7b99fe0..21a99bc 100644 --- a/Swift/Controllers/Storages/CapsFileStorage.cpp +++ b/Swift/Controllers/Storages/CapsFileStorage.cpp @@ -20,15 +20,15 @@ CapsFileStorage::CapsFileStorage(const boost::filesystem::path& path) : path(pat } DiscoInfo::ref CapsFileStorage::getDiscoInfo(const std::string& hash) const { - return DiscoInfoPersister().loadPayloadGeneric(getCapsPath(hash)); + return DiscoInfoPersister().loadPayloadGeneric(getCapsPath(hash)); } void CapsFileStorage::setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo) { - DiscoInfo::ref bareDiscoInfo(new DiscoInfo(*discoInfo.get())); - bareDiscoInfo->setNode(""); - DiscoInfoPersister().savePayload(bareDiscoInfo, getCapsPath(hash)); + DiscoInfo::ref bareDiscoInfo(new DiscoInfo(*discoInfo.get())); + bareDiscoInfo->setNode(""); + DiscoInfoPersister().savePayload(bareDiscoInfo, getCapsPath(hash)); } boost::filesystem::path CapsFileStorage::getCapsPath(const std::string& hash) const { - return path / (Hexify::hexify(Base64::decode(hash)) + ".xml"); + return path / (Hexify::hexify(Base64::decode(hash)) + ".xml"); } diff --git a/Swift/Controllers/Storages/CapsFileStorage.h b/Swift/Controllers/Storages/CapsFileStorage.h index 06dfd91..7df23f1 100644 --- a/Swift/Controllers/Storages/CapsFileStorage.h +++ b/Swift/Controllers/Storages/CapsFileStorage.h @@ -13,17 +13,17 @@ #include namespace Swift { - class CapsFileStorage : public CapsStorage { - public: - CapsFileStorage(const boost::filesystem::path& path); + class CapsFileStorage : public CapsStorage { + public: + CapsFileStorage(const boost::filesystem::path& path); - virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const; - virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo); + virtual DiscoInfo::ref getDiscoInfo(const std::string& hash) const; + virtual void setDiscoInfo(const std::string& hash, DiscoInfo::ref discoInfo); - private: - boost::filesystem::path getCapsPath(const std::string& hash) const; + private: + boost::filesystem::path getCapsPath(const std::string& hash) const; - private: - boost::filesystem::path path; - }; + private: + boost::filesystem::path path; + }; } diff --git a/Swift/Controllers/Storages/CertificateFileStorage.cpp b/Swift/Controllers/Storages/CertificateFileStorage.cpp index a549165..3fe6d54 100644 --- a/Swift/Controllers/Storages/CertificateFileStorage.cpp +++ b/Swift/Controllers/Storages/CertificateFileStorage.cpp @@ -22,42 +22,42 @@ CertificateFileStorage::CertificateFileStorage(const boost::filesystem::path& pa } bool CertificateFileStorage::hasCertificate(Certificate::ref certificate) const { - boost::filesystem::path certificatePath = getCertificatePath(certificate); - if (boost::filesystem::exists(certificatePath)) { - ByteArray data; - readByteArrayFromFile(data, certificatePath); - Certificate::ref storedCertificate(certificateFactory->createCertificateFromDER(data)); - if (storedCertificate && storedCertificate->toDER() == certificate->toDER()) { - return true; - } - else { - SWIFT_LOG(warning) << "Stored certificate does not match received certificate" << std::endl; - return false; - } - } - else { - return false; - } + boost::filesystem::path certificatePath = getCertificatePath(certificate); + if (boost::filesystem::exists(certificatePath)) { + ByteArray data; + readByteArrayFromFile(data, certificatePath); + Certificate::ref storedCertificate(certificateFactory->createCertificateFromDER(data)); + if (storedCertificate && storedCertificate->toDER() == certificate->toDER()) { + return true; + } + else { + SWIFT_LOG(warning) << "Stored certificate does not match received certificate" << std::endl; + return false; + } + } + else { + return false; + } } void CertificateFileStorage::addCertificate(Certificate::ref certificate) { - boost::filesystem::path certificatePath = getCertificatePath(certificate); - if (!boost::filesystem::exists(certificatePath.parent_path())) { - try { - boost::filesystem::create_directories(certificatePath.parent_path()); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - } - } - boost::filesystem::ofstream file(certificatePath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out); - ByteArray data = certificate->toDER(); - file.write(reinterpret_cast(vecptr(data)), boost::numeric_cast(data.size())); - file.close(); + boost::filesystem::path certificatePath = getCertificatePath(certificate); + if (!boost::filesystem::exists(certificatePath.parent_path())) { + try { + boost::filesystem::create_directories(certificatePath.parent_path()); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + } + } + boost::filesystem::ofstream file(certificatePath, boost::filesystem::ofstream::binary|boost::filesystem::ofstream::out); + ByteArray data = certificate->toDER(); + file.write(reinterpret_cast(vecptr(data)), boost::numeric_cast(data.size())); + file.close(); } boost::filesystem::path CertificateFileStorage::getCertificatePath(Certificate::ref certificate) const { - return path / Hexify::hexify(crypto->getSHA1Hash(certificate->toDER())); + return path / Hexify::hexify(crypto->getSHA1Hash(certificate->toDER())); } } diff --git a/Swift/Controllers/Storages/CertificateFileStorage.h b/Swift/Controllers/Storages/CertificateFileStorage.h index f7d3cb3..d2c228d 100644 --- a/Swift/Controllers/Storages/CertificateFileStorage.h +++ b/Swift/Controllers/Storages/CertificateFileStorage.h @@ -11,23 +11,23 @@ #include namespace Swift { - class CertificateFactory; - class CryptoProvider; + class CertificateFactory; + class CryptoProvider; - class CertificateFileStorage : public CertificateStorage { - public: - CertificateFileStorage(const boost::filesystem::path& path, CertificateFactory* certificateFactory, CryptoProvider* crypto); + class CertificateFileStorage : public CertificateStorage { + public: + CertificateFileStorage(const boost::filesystem::path& path, CertificateFactory* certificateFactory, CryptoProvider* crypto); - virtual bool hasCertificate(Certificate::ref certificate) const; - virtual void addCertificate(Certificate::ref certificate); + virtual bool hasCertificate(Certificate::ref certificate) const; + virtual void addCertificate(Certificate::ref certificate); - private: - boost::filesystem::path getCertificatePath(Certificate::ref certificate) const; + private: + boost::filesystem::path getCertificatePath(Certificate::ref certificate) const; - private: - boost::filesystem::path path; - CertificateFactory* certificateFactory; - CryptoProvider* crypto; - }; + private: + boost::filesystem::path path; + CertificateFactory* certificateFactory; + CryptoProvider* crypto; + }; } diff --git a/Swift/Controllers/Storages/CertificateFileStorageFactory.h b/Swift/Controllers/Storages/CertificateFileStorageFactory.h index da8e66e..8ab99f4 100644 --- a/Swift/Controllers/Storages/CertificateFileStorageFactory.h +++ b/Swift/Controllers/Storages/CertificateFileStorageFactory.h @@ -10,21 +10,21 @@ #include namespace Swift { - class CertificateFactory; - class CryptoProvider; + class CertificateFactory; + class CryptoProvider; - class CertificateFileStorageFactory : public CertificateStorageFactory { - public: - CertificateFileStorageFactory(const boost::filesystem::path& basePath, CertificateFactory* certificateFactory, CryptoProvider* crypto) : basePath(basePath), certificateFactory(certificateFactory), crypto(crypto) {} + class CertificateFileStorageFactory : public CertificateStorageFactory { + public: + CertificateFileStorageFactory(const boost::filesystem::path& basePath, CertificateFactory* certificateFactory, CryptoProvider* crypto) : basePath(basePath), certificateFactory(certificateFactory), crypto(crypto) {} - virtual CertificateStorage* createCertificateStorage(const JID& profile) const { - boost::filesystem::path profilePath = basePath / profile.toString(); - return new CertificateFileStorage(profilePath / "certificates", certificateFactory, crypto); - } + virtual CertificateStorage* createCertificateStorage(const JID& profile) const { + boost::filesystem::path profilePath = basePath / profile.toString(); + return new CertificateFileStorage(profilePath / "certificates", certificateFactory, crypto); + } - private: - boost::filesystem::path basePath; - CertificateFactory* certificateFactory; - CryptoProvider* crypto; - }; + private: + boost::filesystem::path basePath; + CertificateFactory* certificateFactory; + CryptoProvider* crypto; + }; } diff --git a/Swift/Controllers/Storages/CertificateMemoryStorage.cpp b/Swift/Controllers/Storages/CertificateMemoryStorage.cpp index cd3c8fa..08c6ee7 100644 --- a/Swift/Controllers/Storages/CertificateMemoryStorage.cpp +++ b/Swift/Controllers/Storages/CertificateMemoryStorage.cpp @@ -14,14 +14,14 @@ CertificateMemoryStorage::CertificateMemoryStorage() { } bool CertificateMemoryStorage::hasCertificate(Certificate::ref certificate) const { - foreach(Certificate::ref storedCert, certificates) { - if (storedCert->toDER() == certificate->toDER()) { - return true; - } - } - return false; + foreach(Certificate::ref storedCert, certificates) { + if (storedCert->toDER() == certificate->toDER()) { + return true; + } + } + return false; } void CertificateMemoryStorage::addCertificate(Certificate::ref certificate) { - certificates.push_back(certificate); + certificates.push_back(certificate); } diff --git a/Swift/Controllers/Storages/CertificateMemoryStorage.h b/Swift/Controllers/Storages/CertificateMemoryStorage.h index 8bf7986..4870385 100644 --- a/Swift/Controllers/Storages/CertificateMemoryStorage.h +++ b/Swift/Controllers/Storages/CertificateMemoryStorage.h @@ -11,15 +11,15 @@ #include namespace Swift { - class CertificateMemoryStorage : public CertificateStorage { - public: - CertificateMemoryStorage(); + class CertificateMemoryStorage : public CertificateStorage { + public: + CertificateMemoryStorage(); - virtual bool hasCertificate(Certificate::ref certificate) const; - virtual void addCertificate(Certificate::ref certificate); + virtual bool hasCertificate(Certificate::ref certificate) const; + virtual void addCertificate(Certificate::ref certificate); - private: - std::vector certificates; - }; + private: + std::vector certificates; + }; } diff --git a/Swift/Controllers/Storages/CertificateStorage.h b/Swift/Controllers/Storages/CertificateStorage.h index 470b420..87a566b 100644 --- a/Swift/Controllers/Storages/CertificateStorage.h +++ b/Swift/Controllers/Storages/CertificateStorage.h @@ -11,12 +11,12 @@ #include namespace Swift { - class CertificateStorage { - public: - virtual ~CertificateStorage(); + class CertificateStorage { + public: + virtual ~CertificateStorage(); - virtual bool hasCertificate(Certificate::ref certificate) const = 0; - virtual void addCertificate(Certificate::ref certificate) = 0; - }; + virtual bool hasCertificate(Certificate::ref certificate) const = 0; + virtual void addCertificate(Certificate::ref certificate) = 0; + }; } diff --git a/Swift/Controllers/Storages/CertificateStorageFactory.h b/Swift/Controllers/Storages/CertificateStorageFactory.h index 44605df..25fa232 100644 --- a/Swift/Controllers/Storages/CertificateStorageFactory.h +++ b/Swift/Controllers/Storages/CertificateStorageFactory.h @@ -7,13 +7,13 @@ #pragma once namespace Swift { - class CertificateStorage; - class JID; + class CertificateStorage; + class JID; - class CertificateStorageFactory { - public: - virtual ~CertificateStorageFactory(); + class CertificateStorageFactory { + public: + virtual ~CertificateStorageFactory(); - virtual CertificateStorage* createCertificateStorage(const JID& profile) const = 0; - }; + virtual CertificateStorage* createCertificateStorage(const JID& profile) const = 0; + }; } diff --git a/Swift/Controllers/Storages/CertificateStorageTrustChecker.h b/Swift/Controllers/Storages/CertificateStorageTrustChecker.h index 7f2f43e..3c708a3 100644 --- a/Swift/Controllers/Storages/CertificateStorageTrustChecker.h +++ b/Swift/Controllers/Storages/CertificateStorageTrustChecker.h @@ -11,25 +11,25 @@ #include namespace Swift { - /** - * A certificate trust checker that trusts certificates in a certificate storage. - */ - class CertificateStorageTrustChecker : public CertificateTrustChecker { - public: - CertificateStorageTrustChecker(CertificateStorage* storage) : storage(storage) { - } + /** + * A certificate trust checker that trusts certificates in a certificate storage. + */ + class CertificateStorageTrustChecker : public CertificateTrustChecker { + public: + CertificateStorageTrustChecker(CertificateStorage* storage) : storage(storage) { + } - virtual bool isCertificateTrusted(const std::vector& certificateChain) { - lastCertificateChain = std::vector(certificateChain.begin(), certificateChain.end()); - return certificateChain.empty() ? false : storage->hasCertificate(certificateChain[0]); - } + virtual bool isCertificateTrusted(const std::vector& certificateChain) { + lastCertificateChain = std::vector(certificateChain.begin(), certificateChain.end()); + return certificateChain.empty() ? false : storage->hasCertificate(certificateChain[0]); + } - const std::vector& getLastCertificateChain() const { - return lastCertificateChain; - } + const std::vector& getLastCertificateChain() const { + return lastCertificateChain; + } - private: - CertificateStorage* storage; - std::vector lastCertificateChain; - }; + private: + CertificateStorage* storage; + std::vector lastCertificateChain; + }; } diff --git a/Swift/Controllers/Storages/FileStorages.cpp b/Swift/Controllers/Storages/FileStorages.cpp index 7e564bf..7ba2b0f 100644 --- a/Swift/Controllers/Storages/FileStorages.cpp +++ b/Swift/Controllers/Storages/FileStorages.cpp @@ -17,47 +17,47 @@ namespace Swift { FileStorages::FileStorages(const boost::filesystem::path& baseDir, const JID& jid, CryptoProvider* crypto) { - boost::filesystem::path profile = stringToPath(jid.toBare()); - vcardStorage = new VCardFileStorage(baseDir / profile / "vcards", crypto); - capsStorage = new CapsFileStorage(baseDir / "caps"); - avatarStorage = new AvatarFileStorage(baseDir / "avatars", baseDir / profile / "avatars", crypto); - rosterStorage = new RosterFileStorage(baseDir / profile / "roster.xml"); + boost::filesystem::path profile = stringToPath(jid.toBare()); + vcardStorage = new VCardFileStorage(baseDir / profile / "vcards", crypto); + capsStorage = new CapsFileStorage(baseDir / "caps"); + avatarStorage = new AvatarFileStorage(baseDir / "avatars", baseDir / profile / "avatars", crypto); + rosterStorage = new RosterFileStorage(baseDir / profile / "roster.xml"); #ifdef SWIFT_EXPERIMENTAL_HISTORY - historyStorage = new SQLiteHistoryStorage(baseDir / "history.db"); + historyStorage = new SQLiteHistoryStorage(baseDir / "history.db"); #else - historyStorage = NULL; + historyStorage = NULL; #endif } FileStorages::~FileStorages() { - delete rosterStorage; - delete avatarStorage; - delete capsStorage; - delete vcardStorage; - delete historyStorage; + delete rosterStorage; + delete avatarStorage; + delete capsStorage; + delete vcardStorage; + delete historyStorage; } VCardStorage* FileStorages::getVCardStorage() const { - return vcardStorage; + return vcardStorage; } CapsStorage* FileStorages::getCapsStorage() const { - return capsStorage; + return capsStorage; } AvatarStorage* FileStorages::getAvatarStorage() const { - return avatarStorage; + return avatarStorage; } RosterStorage* FileStorages::getRosterStorage() const { - return rosterStorage; + return rosterStorage; } HistoryStorage* FileStorages::getHistoryStorage() const { #ifdef SWIFT_EXPERIMENTAL_HISTORY - return historyStorage; + return historyStorage; #else - return NULL; + return NULL; #endif } diff --git a/Swift/Controllers/Storages/FileStorages.h b/Swift/Controllers/Storages/FileStorages.h index 195d0fa..e71d665 100644 --- a/Swift/Controllers/Storages/FileStorages.h +++ b/Swift/Controllers/Storages/FileStorages.h @@ -11,47 +11,47 @@ #include namespace Swift { - class VCardFileStorage; - class AvatarFileStorage; - class CapsFileStorage; - class RosterFileStorage; - class HistoryStorage; - class JID; - class CryptoProvider; + class VCardFileStorage; + class AvatarFileStorage; + class CapsFileStorage; + class RosterFileStorage; + class HistoryStorage; + class JID; + class CryptoProvider; - /** - * A storages implementation that stores all controller data on disk. - */ - class FileStorages : public Storages { - public: - /** - * Creates the storages interface. - * - * All data will be stored relative to a base directory, and - * for some controllers, in a subdirectory for the given profile. - * The data is stored in the following places: - * - Avatars: $basedir/avatars - * - VCards: $basedir/$profile/vcards - * - Entity capabilities: $basedir/caps - * - * \param baseDir the base dir to store data relative to - * \param jid the subdir in which profile-specific data will be stored. - * The bare JID will be used as the subdir name. - */ - FileStorages(const boost::filesystem::path& baseDir, const JID& jid, CryptoProvider*); - ~FileStorages(); + /** + * A storages implementation that stores all controller data on disk. + */ + class FileStorages : public Storages { + public: + /** + * Creates the storages interface. + * + * All data will be stored relative to a base directory, and + * for some controllers, in a subdirectory for the given profile. + * The data is stored in the following places: + * - Avatars: $basedir/avatars + * - VCards: $basedir/$profile/vcards + * - Entity capabilities: $basedir/caps + * + * \param baseDir the base dir to store data relative to + * \param jid the subdir in which profile-specific data will be stored. + * The bare JID will be used as the subdir name. + */ + FileStorages(const boost::filesystem::path& baseDir, const JID& jid, CryptoProvider*); + ~FileStorages(); - virtual VCardStorage* getVCardStorage() const; - virtual AvatarStorage* getAvatarStorage() const; - virtual CapsStorage* getCapsStorage() const; - virtual RosterStorage* getRosterStorage() const; - virtual HistoryStorage* getHistoryStorage() const; + virtual VCardStorage* getVCardStorage() const; + virtual AvatarStorage* getAvatarStorage() const; + virtual CapsStorage* getCapsStorage() const; + virtual RosterStorage* getRosterStorage() const; + virtual HistoryStorage* getHistoryStorage() const; - private: - VCardFileStorage* vcardStorage; - AvatarFileStorage* avatarStorage; - CapsFileStorage* capsStorage; - RosterFileStorage* rosterStorage; - HistoryStorage* historyStorage; - }; + private: + VCardFileStorage* vcardStorage; + AvatarFileStorage* avatarStorage; + CapsFileStorage* capsStorage; + RosterFileStorage* rosterStorage; + HistoryStorage* historyStorage; + }; } diff --git a/Swift/Controllers/Storages/FileStoragesFactory.h b/Swift/Controllers/Storages/FileStoragesFactory.h index 66b3841..ec0106e 100644 --- a/Swift/Controllers/Storages/FileStoragesFactory.h +++ b/Swift/Controllers/Storages/FileStoragesFactory.h @@ -10,18 +10,18 @@ #include namespace Swift { - class CryptoProvider; + class CryptoProvider; - class FileStoragesFactory : public StoragesFactory { - public: - FileStoragesFactory(const boost::filesystem::path& basePath, CryptoProvider* crypto) : basePath(basePath), crypto(crypto) {} + class FileStoragesFactory : public StoragesFactory { + public: + FileStoragesFactory(const boost::filesystem::path& basePath, CryptoProvider* crypto) : basePath(basePath), crypto(crypto) {} - virtual Storages* createStorages(const JID& profile) const { - return new FileStorages(basePath, profile, crypto); - } + virtual Storages* createStorages(const JID& profile) const { + return new FileStorages(basePath, profile, crypto); + } - private: - boost::filesystem::path basePath; - CryptoProvider* crypto; - }; + private: + boost::filesystem::path basePath; + CryptoProvider* crypto; + }; } diff --git a/Swift/Controllers/Storages/MemoryStoragesFactory.h b/Swift/Controllers/Storages/MemoryStoragesFactory.h index 6f6523c..28e9138 100644 --- a/Swift/Controllers/Storages/MemoryStoragesFactory.h +++ b/Swift/Controllers/Storages/MemoryStoragesFactory.h @@ -11,17 +11,17 @@ #include namespace Swift { - class JID; - class CryptoProvider; + class JID; + class CryptoProvider; - class MemoryStoragesFactory : public StoragesFactory { - public: - MemoryStoragesFactory(CryptoProvider* cryptoProvider) : cryptoProvider_(cryptoProvider) {} + class MemoryStoragesFactory : public StoragesFactory { + public: + MemoryStoragesFactory(CryptoProvider* cryptoProvider) : cryptoProvider_(cryptoProvider) {} - virtual Storages* createStorages(const JID& /*profile*/) const { - return new MemoryStorages(cryptoProvider_); - } - private: - CryptoProvider* cryptoProvider_; - }; + virtual Storages* createStorages(const JID& /*profile*/) const { + return new MemoryStorages(cryptoProvider_); + } + private: + CryptoProvider* cryptoProvider_; + }; } diff --git a/Swift/Controllers/Storages/RosterFileStorage.cpp b/Swift/Controllers/Storages/RosterFileStorage.cpp index c55bcf1..6cc5c61 100644 --- a/Swift/Controllers/Storages/RosterFileStorage.cpp +++ b/Swift/Controllers/Storages/RosterFileStorage.cpp @@ -18,9 +18,9 @@ RosterFileStorage::RosterFileStorage(const boost::filesystem::path& path) : path } boost::shared_ptr RosterFileStorage::getRoster() const { - return RosterPersister().loadPayloadGeneric(path); + return RosterPersister().loadPayloadGeneric(path); } void RosterFileStorage::setRoster(boost::shared_ptr roster) { - RosterPersister().savePayload(roster, path); + RosterPersister().savePayload(roster, path); } diff --git a/Swift/Controllers/Storages/RosterFileStorage.h b/Swift/Controllers/Storages/RosterFileStorage.h index d100793..dd1a6c9 100644 --- a/Swift/Controllers/Storages/RosterFileStorage.h +++ b/Swift/Controllers/Storages/RosterFileStorage.h @@ -11,14 +11,14 @@ #include namespace Swift { - class RosterFileStorage : public RosterStorage { - public: - RosterFileStorage(const boost::filesystem::path& path); + class RosterFileStorage : public RosterStorage { + public: + RosterFileStorage(const boost::filesystem::path& path); - virtual boost::shared_ptr getRoster() const; - virtual void setRoster(boost::shared_ptr); + virtual boost::shared_ptr getRoster() const; + virtual void setRoster(boost::shared_ptr); - private: - boost::filesystem::path path; - }; + private: + boost::filesystem::path path; + }; } diff --git a/Swift/Controllers/Storages/StoragesFactory.h b/Swift/Controllers/Storages/StoragesFactory.h index 4eb991b..771230b 100644 --- a/Swift/Controllers/Storages/StoragesFactory.h +++ b/Swift/Controllers/Storages/StoragesFactory.h @@ -7,13 +7,13 @@ #pragma once namespace Swift { - class Storages; - class JID; + class Storages; + class JID; - class StoragesFactory { - public: - virtual ~StoragesFactory() {} + class StoragesFactory { + public: + virtual ~StoragesFactory() {} - virtual Storages* createStorages(const JID& profile) const = 0; - }; + virtual Storages* createStorages(const JID& profile) const = 0; + }; } diff --git a/Swift/Controllers/Storages/VCardFileStorage.cpp b/Swift/Controllers/Storages/VCardFileStorage.cpp index a93e286..720165a 100644 --- a/Swift/Controllers/Storages/VCardFileStorage.cpp +++ b/Swift/Controllers/Storages/VCardFileStorage.cpp @@ -28,100 +28,100 @@ using namespace Swift; typedef GenericPayloadPersister VCardPersister; VCardFileStorage::VCardFileStorage(boost::filesystem::path dir, CryptoProvider* crypto) : VCardStorage(crypto), vcardsPath(dir), crypto(crypto) { - cacheFile = vcardsPath / "phashes"; - if (boost::filesystem::exists(cacheFile)) { - try { - boost::filesystem::ifstream file(cacheFile); - std::string line; - if (file.is_open()) { - while (!file.eof()) { - getline(file, line); - std::pair r = String::getSplittedAtFirst(line, ' '); - JID jid(r.second); - if (jid.isValid()) { - photoHashes.insert(std::make_pair(jid, r.first)); - } - else if (!r.first.empty() || !r.second.empty()) { - std::cerr << "Invalid entry in phashes file" << std::endl; - } - } - } - } - catch (...) { - std::cerr << "Error reading phashes file" << std::endl; - } - } + cacheFile = vcardsPath / "phashes"; + if (boost::filesystem::exists(cacheFile)) { + try { + boost::filesystem::ifstream file(cacheFile); + std::string line; + if (file.is_open()) { + while (!file.eof()) { + getline(file, line); + std::pair r = String::getSplittedAtFirst(line, ' '); + JID jid(r.second); + if (jid.isValid()) { + photoHashes.insert(std::make_pair(jid, r.first)); + } + else if (!r.first.empty() || !r.second.empty()) { + std::cerr << "Invalid entry in phashes file" << std::endl; + } + } + } + } + catch (...) { + std::cerr << "Error reading phashes file" << std::endl; + } + } } boost::shared_ptr VCardFileStorage::getVCard(const JID& jid) const { - boost::shared_ptr result = VCardPersister().loadPayloadGeneric(getVCardPath(jid)); - getAndUpdatePhotoHash(jid, result); - return result; + boost::shared_ptr result = VCardPersister().loadPayloadGeneric(getVCardPath(jid)); + getAndUpdatePhotoHash(jid, result); + return result; } boost::posix_time::ptime VCardFileStorage::getVCardWriteTime(const JID& jid) const { - if (vcardWriteTimes.find(jid) == vcardWriteTimes.end()) { - return boost::posix_time::ptime(); - } - else { - return vcardWriteTimes.at(jid); - } + if (vcardWriteTimes.find(jid) == vcardWriteTimes.end()) { + return boost::posix_time::ptime(); + } + else { + return vcardWriteTimes.at(jid); + } } void VCardFileStorage::setVCard(const JID& jid, VCard::ref v) { - vcardWriteTimes[jid] = boost::posix_time::second_clock::universal_time(); - VCardPersister().savePayload(v, getVCardPath(jid)); - getAndUpdatePhotoHash(jid, v); + vcardWriteTimes[jid] = boost::posix_time::second_clock::universal_time(); + VCardPersister().savePayload(v, getVCardPath(jid)); + getAndUpdatePhotoHash(jid, v); } boost::filesystem::path VCardFileStorage::getVCardPath(const JID& jid) const { - try { - std::string file(jid.toString()); - String::replaceAll(file, '/', "%2f"); - return boost::filesystem::path(vcardsPath / stringToPath(file + ".xml")); - } - catch (const boost::filesystem::filesystem_error& e) { - std::cerr << "ERROR: " << e.what() << std::endl; - return boost::filesystem::path(); - } + try { + std::string file(jid.toString()); + String::replaceAll(file, '/', "%2f"); + return boost::filesystem::path(vcardsPath / stringToPath(file + ".xml")); + } + catch (const boost::filesystem::filesystem_error& e) { + std::cerr << "ERROR: " << e.what() << std::endl; + return boost::filesystem::path(); + } } std::string VCardFileStorage::getPhotoHash(const JID& jid) const { - PhotoHashMap::const_iterator i = photoHashes.find(jid); - if (i != photoHashes.end()) { - return i->second; - } - else { - VCard::ref vCard = getVCard(jid); - return getAndUpdatePhotoHash(jid, vCard); - } + PhotoHashMap::const_iterator i = photoHashes.find(jid); + if (i != photoHashes.end()) { + return i->second; + } + else { + VCard::ref vCard = getVCard(jid); + return getAndUpdatePhotoHash(jid, vCard); + } } std::string VCardFileStorage::getAndUpdatePhotoHash(const JID& jid, VCard::ref vCard) const { - std::string hash; - if (vCard && !vCard->getPhoto().empty()) { - hash = Hexify::hexify(crypto->getSHA1Hash(vCard->getPhoto())); - } - std::pair r = photoHashes.insert(std::make_pair(jid, hash)); - if (r.second) { - savePhotoHashes(); - } - else if (r.first->second != hash) { - r.first->second = hash; - savePhotoHashes(); - } - return hash; + std::string hash; + if (vCard && !vCard->getPhoto().empty()) { + hash = Hexify::hexify(crypto->getSHA1Hash(vCard->getPhoto())); + } + std::pair r = photoHashes.insert(std::make_pair(jid, hash)); + if (r.second) { + savePhotoHashes(); + } + else if (r.first->second != hash) { + r.first->second = hash; + savePhotoHashes(); + } + return hash; } void VCardFileStorage::savePhotoHashes() const { - try { - boost::filesystem::ofstream file(cacheFile); - for (PhotoHashMap::const_iterator i = photoHashes.begin(); i != photoHashes.end(); ++i) { - file << i->second << " " << i->first.toString() << std::endl; - } - file.close(); - } - catch (...) { - std::cerr << "Error writing vcards file" << std::endl; - } + try { + boost::filesystem::ofstream file(cacheFile); + for (PhotoHashMap::const_iterator i = photoHashes.begin(); i != photoHashes.end(); ++i) { + file << i->second << " " << i->first.toString() << std::endl; + } + file.close(); + } + catch (...) { + std::cerr << "Error writing vcards file" << std::endl; + } } diff --git a/Swift/Controllers/Storages/VCardFileStorage.h b/Swift/Controllers/Storages/VCardFileStorage.h index 56e06f2..971a3f9 100644 --- a/Swift/Controllers/Storages/VCardFileStorage.h +++ b/Swift/Controllers/Storages/VCardFileStorage.h @@ -15,30 +15,30 @@ #include namespace Swift { - class CryptoProvider; + class CryptoProvider; - class VCardFileStorage : public VCardStorage { - public: - VCardFileStorage(boost::filesystem::path dir, CryptoProvider* crypto); + class VCardFileStorage : public VCardStorage { + public: + VCardFileStorage(boost::filesystem::path dir, CryptoProvider* crypto); - virtual VCard::ref getVCard(const JID& jid) const; - virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const; - virtual void setVCard(const JID& jid, VCard::ref v); + virtual VCard::ref getVCard(const JID& jid) const; + virtual boost::posix_time::ptime getVCardWriteTime(const JID& jid) const; + virtual void setVCard(const JID& jid, VCard::ref v); - virtual std::string getPhotoHash(const JID&) const; + virtual std::string getPhotoHash(const JID&) const; - private: - boost::filesystem::path getVCardPath(const JID&) const; + private: + boost::filesystem::path getVCardPath(const JID&) const; - std::string getAndUpdatePhotoHash(const JID& jid, VCard::ref vcard) const; - void savePhotoHashes() const; + std::string getAndUpdatePhotoHash(const JID& jid, VCard::ref vcard) const; + void savePhotoHashes() const; - private: - boost::filesystem::path vcardsPath; - CryptoProvider* crypto; - boost::filesystem::path cacheFile; - typedef std::map PhotoHashMap; - mutable PhotoHashMap photoHashes; - std::map vcardWriteTimes; - }; + private: + boost::filesystem::path vcardsPath; + CryptoProvider* crypto; + boost::filesystem::path cacheFile; + typedef std::map PhotoHashMap; + mutable PhotoHashMap photoHashes; + std::map vcardWriteTimes; + }; } diff --git a/Swift/Controllers/SystemTray.h b/Swift/Controllers/SystemTray.h index fd8fe01..094857f 100644 --- a/Swift/Controllers/SystemTray.h +++ b/Swift/Controllers/SystemTray.h @@ -9,11 +9,11 @@ #include namespace Swift { - class SystemTray { - public: - virtual ~SystemTray(){} - virtual void setUnreadMessages(bool some) = 0; - virtual void setStatusType(StatusShow::Type type) = 0; - virtual void setConnecting() = 0; - }; + class SystemTray { + public: + virtual ~SystemTray(){} + virtual void setUnreadMessages(bool some) = 0; + virtual void setStatusType(StatusShow::Type type) = 0; + virtual void setConnecting() = 0; + }; } diff --git a/Swift/Controllers/SystemTrayController.cpp b/Swift/Controllers/SystemTrayController.cpp index e4029e0..72d3403 100644 --- a/Swift/Controllers/SystemTrayController.cpp +++ b/Swift/Controllers/SystemTrayController.cpp @@ -14,29 +14,29 @@ namespace Swift { SystemTrayController::SystemTrayController(EventController* eventController, SystemTray* systemTray) { - systemTray_ = systemTray; - eventController_ = eventController; - eventController_->onEventQueueLengthChange.connect(boost::bind(&SystemTrayController::handleEventQueueLengthChange, this, _1)); + systemTray_ = systemTray; + eventController_ = eventController; + eventController_->onEventQueueLengthChange.connect(boost::bind(&SystemTrayController::handleEventQueueLengthChange, this, _1)); } void SystemTrayController::handleEventQueueLengthChange(int /*length*/) { - EventList events = eventController_->getEvents(); - bool found = false; - for (EventList::iterator it = events.begin(); it != events.end(); ++it) { - if (boost::dynamic_pointer_cast(*it)) { - found = true; - break; - } - } - systemTray_->setUnreadMessages(found); + EventList events = eventController_->getEvents(); + bool found = false; + for (EventList::iterator it = events.begin(); it != events.end(); ++it) { + if (boost::dynamic_pointer_cast(*it)) { + found = true; + break; + } + } + systemTray_->setUnreadMessages(found); } void SystemTrayController::setMyStatusType(StatusShow::Type type) { - systemTray_->setStatusType(type); + systemTray_->setStatusType(type); } void SystemTrayController::setConnecting() { - systemTray_->setConnecting(); + systemTray_->setConnecting(); } } diff --git a/Swift/Controllers/SystemTrayController.h b/Swift/Controllers/SystemTrayController.h index f19b127..850ac71 100644 --- a/Swift/Controllers/SystemTrayController.h +++ b/Swift/Controllers/SystemTrayController.h @@ -9,19 +9,19 @@ #include namespace Swift { - class EventController; - class SystemTray; + class EventController; + class SystemTray; - class SystemTrayController { - public: - SystemTrayController(EventController* eventController, SystemTray* systemTray); - void setMyStatusType(StatusShow::Type type); - void setConnecting(); - private: - void handleEventQueueLengthChange(int length); + class SystemTrayController { + public: + SystemTrayController(EventController* eventController, SystemTray* systemTray); + void setMyStatusType(StatusShow::Type type); + void setConnecting(); + private: + void handleEventQueueLengthChange(int length); - private: - EventController* eventController_; - SystemTray* systemTray_; - }; + private: + EventController* eventController_; + SystemTray* systemTray_; + }; } diff --git a/Swift/Controllers/Translator.cpp b/Swift/Controllers/Translator.cpp index 13230ab..b62fd28 100644 --- a/Swift/Controllers/Translator.cpp +++ b/Swift/Controllers/Translator.cpp @@ -11,9 +11,9 @@ namespace Swift { static struct DefaultTranslator : public Translator { - virtual std::string translate(const std::string& text, const std::string&) { - return text; - } + virtual std::string translate(const std::string& text, const std::string&) { + return text; + } } defaultTranslator; Translator* Translator::translator = &defaultTranslator; @@ -22,7 +22,7 @@ Translator::~Translator() { } void Translator::setInstance(Translator* t) { - translator = t; + translator = t; } } diff --git a/Swift/Controllers/Translator.h b/Swift/Controllers/Translator.h index 801e8b5..5c52e9f 100644 --- a/Swift/Controllers/Translator.h +++ b/Swift/Controllers/Translator.h @@ -9,19 +9,19 @@ #include namespace Swift { - class Translator { - public: - virtual ~Translator(); + class Translator { + public: + virtual ~Translator(); - virtual std::string translate(const std::string& text, const std::string& context) = 0; + virtual std::string translate(const std::string& text, const std::string& context) = 0; - static void setInstance(Translator* translator); + static void setInstance(Translator* translator); - static Translator* getInstance() { - return translator; - } + static Translator* getInstance() { + return translator; + } - private: - static Translator* translator; - }; + private: + static Translator* translator; + }; } diff --git a/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h b/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h index 93cad03..b46774c 100644 --- a/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h +++ b/Swift/Controllers/UIEvents/AcceptWhiteboardSessionUIEvent.h @@ -13,12 +13,12 @@ #include namespace Swift { - class AcceptWhiteboardSessionUIEvent : public UIEvent { - typedef boost::shared_ptr ref; - public: - AcceptWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {} - const JID& getContact() const {return jid_;} - private: - JID jid_; - }; + class AcceptWhiteboardSessionUIEvent : public UIEvent { + typedef boost::shared_ptr ref; + public: + AcceptWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {} + const JID& getContact() const {return jid_;} + private: + JID jid_; + }; } diff --git a/Swift/Controllers/UIEvents/AddContactUIEvent.h b/Swift/Controllers/UIEvents/AddContactUIEvent.h index 127dba2..d2176ac 100644 --- a/Swift/Controllers/UIEvents/AddContactUIEvent.h +++ b/Swift/Controllers/UIEvents/AddContactUIEvent.h @@ -12,25 +12,25 @@ #include namespace Swift { - class AddContactUIEvent : public UIEvent { - public: - AddContactUIEvent(const JID& jid, const std::string& name, const std::set& groups) : jid_(jid), name_(name), groups_(groups) {} - - const std::string& getName() const { - return name_; - } - - const JID& getJID() const { - return jid_; - } - - const std::set& getGroups() const { - return groups_; - } - - private: - JID jid_; - std::string name_; - std::set groups_; - }; + class AddContactUIEvent : public UIEvent { + public: + AddContactUIEvent(const JID& jid, const std::string& name, const std::set& groups) : jid_(jid), name_(name), groups_(groups) {} + + const std::string& getName() const { + return name_; + } + + const JID& getJID() const { + return jid_; + } + + const std::set& getGroups() const { + return groups_; + } + + private: + JID jid_; + std::string name_; + std::set groups_; + }; } diff --git a/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h b/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h index d19a402..526fc0d 100644 --- a/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h +++ b/Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h @@ -13,12 +13,12 @@ #include namespace Swift { - class AddMUCBookmarkUIEvent : public UIEvent { - public: - AddMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {} - const MUCBookmark& getBookmark() { return bookmark; } + class AddMUCBookmarkUIEvent : public UIEvent { + public: + AddMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {} + const MUCBookmark& getBookmark() { return bookmark; } - private: - MUCBookmark bookmark; - }; + private: + MUCBookmark bookmark; + }; } diff --git a/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h b/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h index f5c3b0e..62751b6 100644 --- a/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h +++ b/Swift/Controllers/UIEvents/CancelWhiteboardSessionUIEvent.h @@ -13,12 +13,12 @@ #include namespace Swift { - class CancelWhiteboardSessionUIEvent : public UIEvent { - typedef boost::shared_ptr ref; - public: - CancelWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {} - const JID& getContact() const {return jid_;} - private: - JID jid_; - }; + class CancelWhiteboardSessionUIEvent : public UIEvent { + typedef boost::shared_ptr ref; + public: + CancelWhiteboardSessionUIEvent(const JID& jid) : jid_(jid) {} + const JID& getContact() const {return jid_;} + private: + JID jid_; + }; } diff --git a/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h b/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h index 57e181d..b566be6 100644 --- a/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h +++ b/Swift/Controllers/UIEvents/CreateImpromptuMUCUIEvent.h @@ -11,16 +11,16 @@ namespace Swift { class CreateImpromptuMUCUIEvent : public UIEvent { - public: - CreateImpromptuMUCUIEvent(const std::vector& jids, const JID& roomJID = JID(), const std::string reason = "") : jids_(jids), roomJID_(roomJID), reason_(reason) { } + public: + CreateImpromptuMUCUIEvent(const std::vector& jids, const JID& roomJID = JID(), const std::string reason = "") : jids_(jids), roomJID_(roomJID), reason_(reason) { } - std::vector getJIDs() const { return jids_; } - JID getRoomJID() const { return roomJID_; } - std::string getReason() const { return reason_; } - private: - std::vector jids_; - JID roomJID_; - std::string reason_; + std::vector getJIDs() const { return jids_; } + JID getRoomJID() const { return roomJID_; } + std::string getReason() const { return reason_; } + private: + std::vector jids_; + JID roomJID_; + std::string reason_; }; } diff --git a/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h b/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h index 602f45e..b3d3118 100644 --- a/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h +++ b/Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h @@ -13,15 +13,15 @@ #include namespace Swift { - class EditMUCBookmarkUIEvent : public UIEvent { - public: - EditMUCBookmarkUIEvent(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) : oldBookmark(oldBookmark) , newBookmark(newBookmark) {} + class EditMUCBookmarkUIEvent : public UIEvent { + public: + EditMUCBookmarkUIEvent(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) : oldBookmark(oldBookmark) , newBookmark(newBookmark) {} - const MUCBookmark& getOldBookmark() {return oldBookmark;} - const MUCBookmark& getNewBookmark() {return newBookmark;} + const MUCBookmark& getOldBookmark() {return oldBookmark;} + const MUCBookmark& getNewBookmark() {return newBookmark;} - private: - MUCBookmark oldBookmark; - MUCBookmark newBookmark; - }; + private: + MUCBookmark oldBookmark; + MUCBookmark newBookmark; + }; } diff --git a/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h b/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h index 70c46b0..e1416de 100644 --- a/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h +++ b/Swift/Controllers/UIEvents/InviteToMUCUIEvent.h @@ -21,28 +21,28 @@ #include namespace Swift { - class InviteToMUCUIEvent : public UIEvent { - public: - typedef boost::shared_ptr ref; - - InviteToMUCUIEvent(const JID& room, const std::vector& JIDsToInvite, const std::string& reason) : room_(room), invite_(JIDsToInvite), reason_(reason) { - } - - const JID& getRoom() const { - return room_; - } - - const std::vector getInvites() const { - return invite_; - } - - const std::string getReason() const { - return reason_; - } - - private: - JID room_; - std::vector invite_; - std::string reason_; - }; + class InviteToMUCUIEvent : public UIEvent { + public: + typedef boost::shared_ptr ref; + + InviteToMUCUIEvent(const JID& room, const std::vector& JIDsToInvite, const std::string& reason) : room_(room), invite_(JIDsToInvite), reason_(reason) { + } + + const JID& getRoom() const { + return room_; + } + + const std::vector getInvites() const { + return invite_; + } + + const std::string getReason() const { + return reason_; + } + + private: + JID room_; + std::vector invite_; + std::string reason_; + }; } diff --git a/Swift/Controllers/UIEvents/JoinMUCUIEvent.h b/Swift/Controllers/UIEvents/JoinMUCUIEvent.h index 8d74858..076b5b6 100644 --- a/Swift/Controllers/UIEvents/JoinMUCUIEvent.h +++ b/Swift/Controllers/UIEvents/JoinMUCUIEvent.h @@ -16,25 +16,25 @@ #include namespace Swift { - class JoinMUCUIEvent : public UIEvent { - public: - typedef boost::shared_ptr ref; - JoinMUCUIEvent(const JID& jid, const boost::optional& password = boost::optional(), const boost::optional& nick = boost::optional(), bool joinAutomaticallyInFuture = false, bool createAsReservedRoomIfNew = false, bool isImpromptu = false, bool isContinuation = false) : jid_(jid), nick_(nick), joinAutomatically_(joinAutomaticallyInFuture), createAsReservedRoomIfNew_(createAsReservedRoomIfNew), password_(password), isImpromptuMUC_(isImpromptu), isContinuation_(isContinuation) {} - const boost::optional& getNick() const {return nick_;} - const JID& getJID() const {return jid_;} - bool getShouldJoinAutomatically() const {return joinAutomatically_;} - bool getCreateAsReservedRoomIfNew() const {return createAsReservedRoomIfNew_;} - const boost::optional& getPassword() const {return password_;} - bool isImpromptu() const {return isImpromptuMUC_;} - bool isContinuation() const {return isContinuation_;} + class JoinMUCUIEvent : public UIEvent { + public: + typedef boost::shared_ptr ref; + JoinMUCUIEvent(const JID& jid, const boost::optional& password = boost::optional(), const boost::optional& nick = boost::optional(), bool joinAutomaticallyInFuture = false, bool createAsReservedRoomIfNew = false, bool isImpromptu = false, bool isContinuation = false) : jid_(jid), nick_(nick), joinAutomatically_(joinAutomaticallyInFuture), createAsReservedRoomIfNew_(createAsReservedRoomIfNew), password_(password), isImpromptuMUC_(isImpromptu), isContinuation_(isContinuation) {} + const boost::optional& getNick() const {return nick_;} + const JID& getJID() const {return jid_;} + bool getShouldJoinAutomatically() const {return joinAutomatically_;} + bool getCreateAsReservedRoomIfNew() const {return createAsReservedRoomIfNew_;} + const boost::optional& getPassword() const {return password_;} + bool isImpromptu() const {return isImpromptuMUC_;} + bool isContinuation() const {return isContinuation_;} - private: - JID jid_; - boost::optional nick_; - bool joinAutomatically_; - bool createAsReservedRoomIfNew_; - boost::optional password_; - bool isImpromptuMUC_; - bool isContinuation_; - }; + private: + JID jid_; + boost::optional nick_; + bool joinAutomatically_; + bool createAsReservedRoomIfNew_; + boost::optional password_; + bool isImpromptuMUC_; + bool isContinuation_; + }; } diff --git a/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h b/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h index f6655e4..2803197 100644 --- a/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h +++ b/Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h @@ -13,12 +13,12 @@ #include namespace Swift { - class RemoveMUCBookmarkUIEvent : public UIEvent { - public: - RemoveMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {} - const MUCBookmark& getBookmark() { return bookmark; } + class RemoveMUCBookmarkUIEvent : public UIEvent { + public: + RemoveMUCBookmarkUIEvent(const MUCBookmark& bookmark) : bookmark(bookmark) {} + const MUCBookmark& getBookmark() { return bookmark; } - private: - MUCBookmark bookmark; - }; + private: + MUCBookmark bookmark; + }; } diff --git a/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h b/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h index 95b59b1..0f4a89d 100644 --- a/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h +++ b/Swift/Controllers/UIEvents/RemoveRosterItemUIEvent.h @@ -13,12 +13,12 @@ namespace Swift { class RemoveRosterItemUIEvent : public UIEvent { - public: - RemoveRosterItemUIEvent(const JID& jid) : jid_(jid) {} - virtual ~RemoveRosterItemUIEvent() {} - JID getJID() {return jid_;} - private: - JID jid_; + public: + RemoveRosterItemUIEvent(const JID& jid) : jid_(jid) {} + virtual ~RemoveRosterItemUIEvent() {} + JID getJID() {return jid_;} + private: + JID jid_; }; diff --git a/Swift/Controllers/UIEvents/RenameGroupUIEvent.h b/Swift/Controllers/UIEvents/RenameGroupUIEvent.h index cea1afc..ea19efe 100644 --- a/Swift/Controllers/UIEvents/RenameGroupUIEvent.h +++ b/Swift/Controllers/UIEvents/RenameGroupUIEvent.h @@ -11,21 +11,21 @@ #include namespace Swift { - class RenameGroupUIEvent : public UIEvent { - public: - RenameGroupUIEvent(const std::string& group, const std::string& newName) : group(group), newName(newName) { - } + class RenameGroupUIEvent : public UIEvent { + public: + RenameGroupUIEvent(const std::string& group, const std::string& newName) : group(group), newName(newName) { + } - const std::string& getGroup() const { - return group; - } + const std::string& getGroup() const { + return group; + } - const std::string& getNewName() const { - return newName; - } + const std::string& getNewName() const { + return newName; + } - private: - std::string group; - std::string newName; - }; + private: + std::string group; + std::string newName; + }; } diff --git a/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h b/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h index fbf3814..7d370e2 100644 --- a/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h +++ b/Swift/Controllers/UIEvents/RenameRosterItemUIEvent.h @@ -13,15 +13,15 @@ #include namespace Swift { - class RenameRosterItemUIEvent : public UIEvent { - public: - RenameRosterItemUIEvent(const JID& jid, const std::string& newName) : jid_(jid), newName_(newName) {} + class RenameRosterItemUIEvent : public UIEvent { + public: + RenameRosterItemUIEvent(const JID& jid, const std::string& newName) : jid_(jid), newName_(newName) {} - const JID& getJID() const {return jid_;} - const std::string& getNewName() const {return newName_;} + const JID& getJID() const {return jid_;} + const std::string& getNewName() const {return newName_;} - private: - JID jid_; - std::string newName_; - }; + private: + JID jid_; + std::string newName_; + }; } diff --git a/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h b/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h index afc0a34..f6fa1c7 100644 --- a/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestAdHocUIEvent.h @@ -10,11 +10,11 @@ #include namespace Swift { - class RequestAdHocUIEvent : public UIEvent { - public: - RequestAdHocUIEvent(const DiscoItems::Item& command) : command_(command) {} - const DiscoItems::Item& getCommand() const {return command_;} - private: - DiscoItems::Item command_; - }; + class RequestAdHocUIEvent : public UIEvent { + public: + RequestAdHocUIEvent(const DiscoItems::Item& command) : command_(command) {} + const DiscoItems::Item& getCommand() const {return command_;} + private: + DiscoItems::Item command_; + }; } diff --git a/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h b/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h index 5c7e97a..8d8bd19 100644 --- a/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestAdHocWithJIDUIEvent.h @@ -9,13 +9,13 @@ #include namespace Swift { - class RequestAdHocWithJIDUIEvent : public UIEvent { - public: - RequestAdHocWithJIDUIEvent(const JID& jid, const std::string& node) : jid_(jid), node_(node) {} - JID getJID() const { return jid_; } - std::string getNode() const { return node_; } - private: - JID jid_; - std::string node_; - }; + class RequestAdHocWithJIDUIEvent : public UIEvent { + public: + RequestAdHocWithJIDUIEvent(const JID& jid, const std::string& node) : jid_(jid), node_(node) {} + JID getJID() const { return jid_; } + std::string getNode() const { return node_; } + private: + JID jid_; + std::string node_; + }; } diff --git a/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h b/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h index 73ad20e..474d155 100644 --- a/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h @@ -13,18 +13,18 @@ #include namespace Swift { - class RequestAddUserDialogUIEvent : public UIEvent { + class RequestAddUserDialogUIEvent : public UIEvent { - public: - RequestAddUserDialogUIEvent(const JID& predefinedJID, const std::string& predefinedName) : preJID_(predefinedJID), preName_(predefinedName) {} - RequestAddUserDialogUIEvent() : preJID_(), preName_() {} + public: + RequestAddUserDialogUIEvent(const JID& predefinedJID, const std::string& predefinedName) : preJID_(predefinedJID), preName_(predefinedName) {} + RequestAddUserDialogUIEvent() : preJID_(), preName_() {} - const JID& getPredefinedJID() const { return preJID_; } - const std::string& getPredefinedName() const { return preName_; } + const JID& getPredefinedJID() const { return preJID_; } + const std::string& getPredefinedName() const { return preName_; } - private: - JID preJID_; - std::string preName_; + private: + JID preJID_; + std::string preName_; - }; + }; } diff --git a/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h b/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h index 6594897..4dcf8be 100644 --- a/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestChangeBlockStateUIEvent.h @@ -19,25 +19,25 @@ namespace Swift { class RequestChangeBlockStateUIEvent : public UIEvent { - public: - enum BlockState { - Blocked, - Unblocked - }; - - public: - RequestChangeBlockStateUIEvent(BlockState newState, const JID& contact) : state_(newState), contact_(contact) {} - - BlockState getBlockState() const { - return state_; - } - - JID getContact() const { - return contact_; - } - private: - BlockState state_; - JID contact_; + public: + enum BlockState { + Blocked, + Unblocked + }; + + public: + RequestChangeBlockStateUIEvent(BlockState newState, const JID& contact) : state_(newState), contact_(contact) {} + + BlockState getBlockState() const { + return state_; + } + + JID getContact() const { + return contact_; + } + private: + BlockState state_; + JID contact_; }; } diff --git a/Swift/Controllers/UIEvents/RequestChatUIEvent.h b/Swift/Controllers/UIEvents/RequestChatUIEvent.h index 95d6075..4eca5d4 100644 --- a/Swift/Controllers/UIEvents/RequestChatUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestChatUIEvent.h @@ -11,11 +11,11 @@ #include namespace Swift { - class RequestChatUIEvent : public UIEvent { - public: - RequestChatUIEvent(const JID& contact) : contact_(contact) {} - JID getContact() {return contact_;} - private: - JID contact_; - }; + class RequestChatUIEvent : public UIEvent { + public: + RequestChatUIEvent(const JID& contact) : contact_(contact) {} + JID getContact() {return contact_;} + private: + JID contact_; + }; } diff --git a/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h b/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h index 76aa1f7..08804f4 100644 --- a/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h @@ -9,7 +9,7 @@ #include namespace Swift { - class RequestChatWithUserDialogUIEvent : public UIEvent { + class RequestChatWithUserDialogUIEvent : public UIEvent { - }; + }; } diff --git a/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h b/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h index 61ddbe9..5693ab1 100644 --- a/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestContactEditorUIEvent.h @@ -11,18 +11,18 @@ #include namespace Swift { - class RequestContactEditorUIEvent : public UIEvent { - public: - typedef boost::shared_ptr ref; + class RequestContactEditorUIEvent : public UIEvent { + public: + typedef boost::shared_ptr ref; - RequestContactEditorUIEvent(const JID& jid) : jid(jid) { - } + RequestContactEditorUIEvent(const JID& jid) : jid(jid) { + } - const JID& getJID() const { - return jid; - } + const JID& getJID() const { + return jid; + } - private: - JID jid; - }; + private: + JID jid; + }; } diff --git a/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h b/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h index 42e22a2..0bfa458 100644 --- a/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestHighlightEditorUIEvent.h @@ -10,7 +10,7 @@ namespace Swift { - class RequestHighlightEditorUIEvent : public UIEvent { - }; + class RequestHighlightEditorUIEvent : public UIEvent { + }; } diff --git a/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h b/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h index 025e91f..8282204 100644 --- a/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestHistoryUIEvent.h @@ -9,6 +9,6 @@ #include namespace Swift { - class RequestHistoryUIEvent : public UIEvent { - }; + class RequestHistoryUIEvent : public UIEvent { + }; } diff --git a/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h b/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h index 3733532..9a1abb1 100644 --- a/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestInviteToMUCUIEvent.h @@ -21,34 +21,34 @@ #include namespace Swift { - class RequestInviteToMUCUIEvent : public UIEvent { - public: - typedef boost::shared_ptr ref; - - enum ImpromptuMode { - Impromptu, - NotImpromptu - }; - - RequestInviteToMUCUIEvent(const JID& room, const std::vector& JIDsToInvite, ImpromptuMode impromptu) : room_(room), invite_(JIDsToInvite) { - isImpromptu_ = impromptu == Impromptu; - } - - const JID& getRoom() const { - return room_; - } - - const std::vector getInvites() const { - return invite_; - } - - bool isImpromptu() const { - return isImpromptu_; - } - - private: - JID room_; - std::vector invite_; - bool isImpromptu_; - }; + class RequestInviteToMUCUIEvent : public UIEvent { + public: + typedef boost::shared_ptr ref; + + enum ImpromptuMode { + Impromptu, + NotImpromptu + }; + + RequestInviteToMUCUIEvent(const JID& room, const std::vector& JIDsToInvite, ImpromptuMode impromptu) : room_(room), invite_(JIDsToInvite) { + isImpromptu_ = impromptu == Impromptu; + } + + const JID& getRoom() const { + return room_; + } + + const std::vector getInvites() const { + return invite_; + } + + bool isImpromptu() const { + return isImpromptu_; + } + + private: + JID room_; + std::vector invite_; + bool isImpromptu_; + }; } diff --git a/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h b/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h index a3ba6c8..a2a4183 100644 --- a/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h @@ -15,18 +15,18 @@ #include namespace Swift { - class RequestJoinMUCUIEvent : public UIEvent { - public: - typedef boost::shared_ptr ref; + class RequestJoinMUCUIEvent : public UIEvent { + public: + typedef boost::shared_ptr ref; - RequestJoinMUCUIEvent(const JID& room = JID()) : room(room) { - } + RequestJoinMUCUIEvent(const JID& room = JID()) : room(room) { + } - const JID& getRoom() const { - return room; - } + const JID& getRoom() const { + return room; + } - private: - JID room; - }; + private: + JID room; + }; } diff --git a/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h b/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h index 1907242..1a02af4 100644 --- a/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestProfileEditorUIEvent.h @@ -9,8 +9,8 @@ #include namespace Swift { - class RequestProfileEditorUIEvent : public UIEvent { - public: - RequestProfileEditorUIEvent() {} - }; + class RequestProfileEditorUIEvent : public UIEvent { + public: + RequestProfileEditorUIEvent() {} + }; } diff --git a/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h b/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h index 625736f..9c2b01d 100644 --- a/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestWhiteboardUIEvent.h @@ -17,11 +17,11 @@ #include namespace Swift { - class RequestWhiteboardUIEvent : public UIEvent { - public: - RequestWhiteboardUIEvent(const JID& contact) : contact_(contact) {} - const JID& getContact() const {return contact_;} - private: - JID contact_; - }; + class RequestWhiteboardUIEvent : public UIEvent { + public: + RequestWhiteboardUIEvent(const JID& contact) : contact_(contact) {} + const JID& getContact() const {return contact_;} + private: + JID contact_; + }; } diff --git a/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h b/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h index 41eecc4..4d780be 100644 --- a/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h +++ b/Swift/Controllers/UIEvents/RequestXMLConsoleUIEvent.h @@ -9,6 +9,6 @@ #include namespace Swift { - class RequestXMLConsoleUIEvent : public UIEvent { - }; + class RequestXMLConsoleUIEvent : public UIEvent { + }; } diff --git a/Swift/Controllers/UIEvents/SendFileUIEvent.h b/Swift/Controllers/UIEvents/SendFileUIEvent.h index ea29453..72452df 100644 --- a/Swift/Controllers/UIEvents/SendFileUIEvent.h +++ b/Swift/Controllers/UIEvents/SendFileUIEvent.h @@ -19,23 +19,23 @@ #include namespace Swift { - class SendFileUIEvent : public UIEvent { - public: - typedef boost::shared_ptr ref; - - SendFileUIEvent(const JID& jid, const std::string& filename) : jid(jid), filename(filename) { - } - - const JID& getJID() const { - return jid; - } - - const std::string& getFilename() const { - return filename; - } - - private: - JID jid; - std::string filename; - }; + class SendFileUIEvent : public UIEvent { + public: + typedef boost::shared_ptr ref; + + SendFileUIEvent(const JID& jid, const std::string& filename) : jid(jid), filename(filename) { + } + + const JID& getJID() const { + return jid; + } + + const std::string& getFilename() const { + return filename; + } + + private: + JID jid; + std::string filename; + }; } diff --git a/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h b/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h index 586f036..88528d7 100644 --- a/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h +++ b/Swift/Controllers/UIEvents/ShowProfileForRosterItemUIEvent.h @@ -19,14 +19,14 @@ namespace Swift { class ShowProfileForRosterItemUIEvent : public UIEvent { - public: - typedef boost::shared_ptr ref; - public: - ShowProfileForRosterItemUIEvent(const JID& jid) : jid_(jid) {} - virtual ~ShowProfileForRosterItemUIEvent() {} - JID getJID() const {return jid_;} - private: - JID jid_; + public: + typedef boost::shared_ptr ref; + public: + ShowProfileForRosterItemUIEvent(const JID& jid) : jid_(jid) {} + virtual ~ShowProfileForRosterItemUIEvent() {} + JID getJID() const {return jid_;} + private: + JID jid_; }; } diff --git a/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h b/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h index 0d16cb6..a1b6efb 100644 --- a/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h +++ b/Swift/Controllers/UIEvents/ShowWhiteboardUIEvent.h @@ -17,12 +17,12 @@ #include namespace Swift { - class ShowWhiteboardUIEvent : public UIEvent { - public: - ShowWhiteboardUIEvent(const JID& contact) : contact_(contact) {} - const JID& getContact() const {return contact_;} - private: - JID contact_; - }; + class ShowWhiteboardUIEvent : public UIEvent { + public: + ShowWhiteboardUIEvent(const JID& contact) : contact_(contact) {} + const JID& getContact() const {return contact_;} + private: + JID contact_; + }; } diff --git a/Swift/Controllers/UIEvents/UIEvent.h b/Swift/Controllers/UIEvents/UIEvent.h index 548f356..333582d 100644 --- a/Swift/Controllers/UIEvents/UIEvent.h +++ b/Swift/Controllers/UIEvents/UIEvent.h @@ -9,10 +9,10 @@ #include namespace Swift { - class UIEvent { - public: - typedef boost::shared_ptr ref; + class UIEvent { + public: + typedef boost::shared_ptr ref; - virtual ~UIEvent(); - }; + virtual ~UIEvent(); + }; } diff --git a/Swift/Controllers/UIEvents/UIEventStream.h b/Swift/Controllers/UIEvents/UIEventStream.h index a630522..7ff1b54 100644 --- a/Swift/Controllers/UIEvents/UIEventStream.h +++ b/Swift/Controllers/UIEvents/UIEventStream.h @@ -13,12 +13,12 @@ #include namespace Swift { - class UIEventStream { - public: - boost::signal)> onUIEvent; + class UIEventStream { + public: + boost::signal)> onUIEvent; - void send(boost::shared_ptr event) { - onUIEvent(event); - } - }; + void send(boost::shared_ptr event) { + onUIEvent(event); + } + }; } diff --git a/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h b/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h index e5d95fa..06d3988 100644 --- a/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h +++ b/Swift/Controllers/UIInterfaces/AdHocCommandWindow.h @@ -9,10 +9,10 @@ #include namespace Swift { - class AdHocCommandWindow { - public: - virtual ~AdHocCommandWindow() {} - virtual void setOnline(bool /*online*/) {} - boost::signal onClosing; - }; + class AdHocCommandWindow { + public: + virtual ~AdHocCommandWindow() {} + virtual void setOnline(bool /*online*/) {} + boost::signal onClosing; + }; } diff --git a/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h b/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h index d7b456d..d3003f7 100644 --- a/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/AdHocCommandWindowFactory.h @@ -12,9 +12,9 @@ namespace Swift { class AdHocCommandWindow; - class AdHocCommandWindowFactory { - public: - virtual ~AdHocCommandWindowFactory() {} - virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr command) = 0; - }; + class AdHocCommandWindowFactory { + public: + virtual ~AdHocCommandWindowFactory() {} + virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr command) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h b/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h index 201377d..ebfa0c4 100644 --- a/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h +++ b/Swift/Controllers/UIInterfaces/BlockListEditorWidget.h @@ -19,22 +19,22 @@ namespace Swift { - class ClientBlockListManager; + class ClientBlockListManager; - class BlockListEditorWidget { - public: - virtual ~BlockListEditorWidget() {} + class BlockListEditorWidget { + public: + virtual ~BlockListEditorWidget() {} - virtual void show() = 0; - virtual void hide() = 0; + virtual void show() = 0; + virtual void hide() = 0; - virtual void setCurrentBlockList(const std::vector& blockedJIDs) = 0; - virtual void setBusy(bool isBusy) = 0; - virtual void setError(const std::string&) = 0; + virtual void setCurrentBlockList(const std::vector& blockedJIDs) = 0; + virtual void setBusy(bool isBusy) = 0; + virtual void setError(const std::string&) = 0; - virtual std::vector getCurrentBlockList() const = 0; + virtual std::vector getCurrentBlockList() const = 0; - boost::signal& /* blockedJID */)> onSetNewBlockList; - }; + boost::signal& /* blockedJID */)> onSetNewBlockList; + }; } diff --git a/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h b/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h index eb91ac1..05e7f3a 100644 --- a/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h +++ b/Swift/Controllers/UIInterfaces/BlockListEditorWidgetFactory.h @@ -8,13 +8,13 @@ namespace Swift { - class BlockListEditorWidget; + class BlockListEditorWidget; - class BlockListEditorWidgetFactory { - public: - virtual ~BlockListEditorWidgetFactory() {} + class BlockListEditorWidgetFactory { + public: + virtual ~BlockListEditorWidgetFactory() {} - virtual BlockListEditorWidget* createBlockListEditorWidget() = 0; - }; + virtual BlockListEditorWidget* createBlockListEditorWidget() = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/ChatListWindow.h b/Swift/Controllers/UIInterfaces/ChatListWindow.h index 8b5036b..a94e14e 100644 --- a/Swift/Controllers/UIInterfaces/ChatListWindow.h +++ b/Swift/Controllers/UIInterfaces/ChatListWindow.h @@ -19,83 +19,83 @@ #include namespace Swift { - class ChatListWindow { - public: - class Chat { - public: - Chat() : statusType(StatusShow::None), isMUC(false), unreadCount(0), isPrivateMessage(false) {} - Chat(const JID& jid, const std::string& chatName, const std::string& activity, int unreadCount, StatusShow::Type statusType, const boost::filesystem::path& avatarPath, bool isMUC, bool isPrivateMessage = false, const std::string& nick = "", const boost::optional password = boost::optional()) - : jid(jid), chatName(chatName), activity(activity), statusType(statusType), isMUC(isMUC), nick(nick), password(password), unreadCount(unreadCount), avatarPath(avatarPath), isPrivateMessage(isPrivateMessage) {} - /** Assume that nicks and other transient features aren't important for equality */ - bool operator==(const Chat& other) const { - if (impromptuJIDs.empty()) { - return jid.toBare() == other.jid.toBare() - && isMUC == other.isMUC; - } else { /* compare the chat occupant lists */ - typedef std::map JIDMap; - foreach (const JIDMap::value_type& jid, impromptuJIDs) { - bool found = false; - foreach (const JIDMap::value_type& otherJID, other.impromptuJIDs) { - if (jid.second.toBare() == otherJID.second.toBare()) { - found = true; - break; - } - } - if (!found) { - return false; - } - } - return true; - } - } - void setUnreadCount(int unread) { - unreadCount = unread; - } - void setStatusType(StatusShow::Type type) { - statusType = type; - } - void setAvatarPath(const boost::filesystem::path& path) { - avatarPath = path; - } - std::string getImpromptuTitle() const { - typedef std::pair StringJIDPair; - std::string title; - foreach(StringJIDPair pair, impromptuJIDs) { - if (title.empty()) { - title += pair.first; - } else { - title += ", " + pair.first; - } - } - return title; - } - JID jid; - std::string chatName; - std::string activity; - StatusShow::Type statusType; - bool isMUC; - std::string nick; - boost::optional password; - int unreadCount; - boost::filesystem::path avatarPath; - std::map impromptuJIDs; - bool isPrivateMessage; - }; - virtual ~ChatListWindow(); + class ChatListWindow { + public: + class Chat { + public: + Chat() : statusType(StatusShow::None), isMUC(false), unreadCount(0), isPrivateMessage(false) {} + Chat(const JID& jid, const std::string& chatName, const std::string& activity, int unreadCount, StatusShow::Type statusType, const boost::filesystem::path& avatarPath, bool isMUC, bool isPrivateMessage = false, const std::string& nick = "", const boost::optional password = boost::optional()) + : jid(jid), chatName(chatName), activity(activity), statusType(statusType), isMUC(isMUC), nick(nick), password(password), unreadCount(unreadCount), avatarPath(avatarPath), isPrivateMessage(isPrivateMessage) {} + /** Assume that nicks and other transient features aren't important for equality */ + bool operator==(const Chat& other) const { + if (impromptuJIDs.empty()) { + return jid.toBare() == other.jid.toBare() + && isMUC == other.isMUC; + } else { /* compare the chat occupant lists */ + typedef std::map JIDMap; + foreach (const JIDMap::value_type& jid, impromptuJIDs) { + bool found = false; + foreach (const JIDMap::value_type& otherJID, other.impromptuJIDs) { + if (jid.second.toBare() == otherJID.second.toBare()) { + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + } + } + void setUnreadCount(int unread) { + unreadCount = unread; + } + void setStatusType(StatusShow::Type type) { + statusType = type; + } + void setAvatarPath(const boost::filesystem::path& path) { + avatarPath = path; + } + std::string getImpromptuTitle() const { + typedef std::pair StringJIDPair; + std::string title; + foreach(StringJIDPair pair, impromptuJIDs) { + if (title.empty()) { + title += pair.first; + } else { + title += ", " + pair.first; + } + } + return title; + } + JID jid; + std::string chatName; + std::string activity; + StatusShow::Type statusType; + bool isMUC; + std::string nick; + boost::optional password; + int unreadCount; + boost::filesystem::path avatarPath; + std::map impromptuJIDs; + bool isPrivateMessage; + }; + virtual ~ChatListWindow(); - virtual void setBookmarksEnabled(bool enabled) = 0; - virtual void addMUCBookmark(const MUCBookmark& bookmark) = 0; - virtual void addWhiteboardSession(const ChatListWindow::Chat& chat) = 0; - virtual void removeWhiteboardSession(const JID& jid) = 0; - virtual void removeMUCBookmark(const MUCBookmark& bookmark) = 0; - virtual void setRecents(const std::list& recents) = 0; - virtual void setUnreadCount(int unread) = 0; - virtual void clearBookmarks() = 0; - virtual void setOnline(bool isOnline) = 0; + virtual void setBookmarksEnabled(bool enabled) = 0; + virtual void addMUCBookmark(const MUCBookmark& bookmark) = 0; + virtual void addWhiteboardSession(const ChatListWindow::Chat& chat) = 0; + virtual void removeWhiteboardSession(const JID& jid) = 0; + virtual void removeMUCBookmark(const MUCBookmark& bookmark) = 0; + virtual void setRecents(const std::list& recents) = 0; + virtual void setUnreadCount(int unread) = 0; + virtual void clearBookmarks() = 0; + virtual void setOnline(bool isOnline) = 0; - boost::signal onMUCBookmarkActivated; - boost::signal onRecentActivated; - boost::signal onWhiteboardActivated; - boost::signal onClearRecentsRequested; - }; + boost::signal onMUCBookmarkActivated; + boost::signal onRecentActivated; + boost::signal onWhiteboardActivated; + boost::signal onClearRecentsRequested; + }; } diff --git a/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h b/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h index fcd979b..3ae1ec6 100644 --- a/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/ChatListWindowFactory.h @@ -9,10 +9,10 @@ #include namespace Swift { - class UIEventStream; - class ChatListWindowFactory { - public: - virtual ~ChatListWindowFactory() {} - virtual ChatListWindow* createChatListWindow(UIEventStream* uiEventStream) = 0; - }; + class UIEventStream; + class ChatListWindowFactory { + public: + virtual ~ChatListWindowFactory() {} + virtual ChatListWindow* createChatListWindow(UIEventStream* uiEventStream) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/ChatWindow.h b/Swift/Controllers/UIInterfaces/ChatWindow.h index 05331bb..310c967 100644 --- a/Swift/Controllers/UIInterfaces/ChatWindow.h +++ b/Swift/Controllers/UIInterfaces/ChatWindow.h @@ -26,233 +26,233 @@ #include namespace Swift { - class AvatarManager; - class TreeWidget; - class Roster; - class TabComplete; - class RosterItem; - class ContactRosterItem; - class FileTransferController; - class UserSearchWindow; - - - class ChatWindow { - public: - class ChatMessagePart { - public: - virtual ~ChatMessagePart() {} - }; - - class ChatMessage { - public: - ChatMessage() {} - ChatMessage(const std::string& text) { - append(boost::make_shared(text)); - } - void append(const boost::shared_ptr& part) { - parts_.push_back(part); - } - - const std::vector >& getParts() const { - return parts_; - } - - void setFullMessageHighlightAction(const HighlightAction& action) { - fullMessageHighlightAction_ = action; - } - - const HighlightAction& getFullMessageHighlightAction() const { - return fullMessageHighlightAction_; - } - - bool isMeCommand() const { - bool isMeCommand = false; - if (!parts_.empty()) { - boost::shared_ptr textPart = boost::dynamic_pointer_cast(parts_[0]); - if (textPart) { - if (boost::starts_with(textPart->text, "/me ")) { - isMeCommand = true; - } - } - } - return isMeCommand; - } - - private: - std::vector > parts_; - HighlightAction fullMessageHighlightAction_; - }; - - class ChatTextMessagePart : public ChatMessagePart { - public: - ChatTextMessagePart(const std::string& text) : text(text) {} - std::string text; - }; - - class ChatURIMessagePart : public ChatMessagePart { - public: - ChatURIMessagePart(const std::string& target) : target(target) {} - std::string target; - }; - - class ChatEmoticonMessagePart : public ChatMessagePart { - public: - std::string imagePath; - std::string alternativeText; - }; - - class ChatHighlightingMessagePart : public ChatMessagePart { - public: - HighlightAction action; - std::string text; - }; - - - enum AckState {Pending, Received, Failed}; - enum ReceiptState {ReceiptRequested, ReceiptReceived, ReceiptFailed}; - enum OccupantAction {Kick, Ban, MakeModerator, MakeParticipant, MakeVisitor, AddContact, ShowProfile}; - enum RoomAction {ChangeSubject, Configure, Affiliations, Destroy, Invite}; - enum FileTransferState { - Initialisation, ///< Collecting information required for sending the request out. - WaitingForAccept, ///< The file transfer request was send out. - Negotiating, ///< The other party accepted the file transfer request and a suitable transfer method is negotiated. - Transferring, ///< The negotiation was successful and the file is currently transferred. - Canceled, ///< Someone actively canceled the transfer. - Finished, ///< The file was transferred successfully. - FTFailed ///< The negotiation, the transfer itself or the verification failed. - }; - enum WhiteboardSessionState {WhiteboardAccepted, WhiteboardTerminated, WhiteboardRejected}; - enum BlockingState {BlockingUnsupported, IsBlocked, IsUnblocked}; - enum Direction { UnknownDirection, DefaultDirection }; - enum MUCType { StandardMUC, ImpromptuMUC }; - enum TimestampBehaviour { KeepTimestamp, UpdateTimestamp }; - enum RoomBookmarkState { RoomNotBookmarked, RoomBookmarked, RoomAutoJoined }; - - ChatWindow() {} - virtual ~ChatWindow() {} - - /** Add message to window. - * @return id of added message (for acks). - */ - virtual std::string addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; - /** Adds action to window. - * @return id of added message (for acks); - */ - virtual std::string addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; - - /** Adds system message to window - * @return id of added message (for replacement) - */ - virtual std::string addSystemMessage(const ChatMessage& message, Direction direction) = 0; - virtual void addPresenceMessage(const ChatMessage& message, Direction direction) = 0; - - virtual void addErrorMessage(const ChatMessage& message) = 0; - virtual void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; - virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour) = 0; - virtual void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; - - // File transfer related stuff - virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0; - virtual void setFileTransferProgress(std::string, const int percentageDone) = 0; - virtual void setFileTransferStatus(std::string, const FileTransferState state, const std::string& msg = "") = 0; - virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false) = 0; - - virtual std::string addWhiteboardRequest(bool senderIsSelf) = 0; - virtual void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state) = 0; - - // message receipts - virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0; - - virtual void setContactChatState(ChatState::ChatStateType state) = 0; - virtual void setName(const std::string& name) = 0; - virtual void show() = 0; - virtual bool isVisible() const = 0; - virtual void activate() = 0; - virtual void setAvailableSecurityLabels(const std::vector& labels) = 0; - virtual void setSecurityLabelsEnabled(bool enabled) = 0; - virtual void setCorrectionEnabled(Tristate enabled) = 0; - virtual void setFileTransferEnabled(Tristate enabled) = 0; - virtual void setUnreadMessageCount(int count) = 0; - virtual void convertToMUC(MUCType mucType) = 0; -// virtual TreeWidget *getTreeWidget() = 0; - virtual void setSecurityLabelsError() = 0; - virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() = 0; - virtual void setOnline(bool online) = 0; - virtual void setRosterModel(Roster* model) = 0; - virtual void setTabComplete(TabComplete* completer) = 0; - virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour) = 0; - virtual void setAckState(const std::string& id, AckState state) = 0; - virtual void flash() = 0; - virtual void setSubject(const std::string& subject) = 0; - virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector&) = 0; - virtual void setAvailableRoomActions(const std::vector &actions) = 0; - virtual void setBlockingState(BlockingState state) = 0; - virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) = 0; - virtual void showBookmarkWindow(const MUCBookmark& bookmark) = 0; - virtual void setBookmarkState(RoomBookmarkState bookmarkState) = 0; - - /** - * A handle that uniquely identities an alert message. - */ - typedef int AlertID; - /** - * Set an alert on the window. - * @param alertText Description of alert (required). - * @param buttonText Button text to use (optional, no button is shown if empty). - * @return A handle to the alert message. - */ - virtual AlertID addAlert(const std::string& alertText) = 0; - /** - * Removes an alert. - * @param id An alert ID previously returned from setAlert - */ - virtual void removeAlert(const AlertID id) = 0; - - /** - * Actions that can be performed on the selected occupant. - */ - virtual void setAvailableOccupantActions(const std::vector& actions) = 0; - - /** - * A room configuration has been requested, show the form. - * If the form is cancelled, must emit onConfigurationFormCancelled(). - */ - virtual void showRoomConfigurationForm(Form::ref) = 0; - - boost::signal onClosed; - boost::signal onAllMessagesRead; - boost::signal onSendMessageRequest; - boost::signal onSendCorrectionMessageRequest; - boost::signal onUserTyping; - boost::signal onUserCancelsTyping; - boost::signal onAlertButtonClicked; - boost::signal onOccupantSelectionChanged; - boost::signal onOccupantActionSelected; - boost::signal onChangeSubjectRequest; - boost::signal onBookmarkRequest; - boost::signal onConfigureRequest; - boost::signal onDestroyRequest; - boost::signal&)> onInviteToChat; - boost::signal onConfigurationFormCancelled; - boost::signal onGetAffiliationsRequest; - boost::signal onSetAffiliationRequest; - boost::signal >& changes)> onChangeAffiliationsRequest; - boost::signal onLogCleared; - - // File transfer related - boost::signal onFileTransferCancel; - boost::signal onFileTransferStart; - boost::signal onFileTransferAccept; - boost::signal onSendFileRequest; - - //Whiteboard related - boost::signal onWhiteboardSessionAccept; - boost::signal onWhiteboardSessionCancel; - boost::signal onWhiteboardWindowShow; - - // Blocking Command related - boost::signal onBlockUserRequest; - boost::signal onUnblockUserRequest; - }; + class AvatarManager; + class TreeWidget; + class Roster; + class TabComplete; + class RosterItem; + class ContactRosterItem; + class FileTransferController; + class UserSearchWindow; + + + class ChatWindow { + public: + class ChatMessagePart { + public: + virtual ~ChatMessagePart() {} + }; + + class ChatMessage { + public: + ChatMessage() {} + ChatMessage(const std::string& text) { + append(boost::make_shared(text)); + } + void append(const boost::shared_ptr& part) { + parts_.push_back(part); + } + + const std::vector >& getParts() const { + return parts_; + } + + void setFullMessageHighlightAction(const HighlightAction& action) { + fullMessageHighlightAction_ = action; + } + + const HighlightAction& getFullMessageHighlightAction() const { + return fullMessageHighlightAction_; + } + + bool isMeCommand() const { + bool isMeCommand = false; + if (!parts_.empty()) { + boost::shared_ptr textPart = boost::dynamic_pointer_cast(parts_[0]); + if (textPart) { + if (boost::starts_with(textPart->text, "/me ")) { + isMeCommand = true; + } + } + } + return isMeCommand; + } + + private: + std::vector > parts_; + HighlightAction fullMessageHighlightAction_; + }; + + class ChatTextMessagePart : public ChatMessagePart { + public: + ChatTextMessagePart(const std::string& text) : text(text) {} + std::string text; + }; + + class ChatURIMessagePart : public ChatMessagePart { + public: + ChatURIMessagePart(const std::string& target) : target(target) {} + std::string target; + }; + + class ChatEmoticonMessagePart : public ChatMessagePart { + public: + std::string imagePath; + std::string alternativeText; + }; + + class ChatHighlightingMessagePart : public ChatMessagePart { + public: + HighlightAction action; + std::string text; + }; + + + enum AckState {Pending, Received, Failed}; + enum ReceiptState {ReceiptRequested, ReceiptReceived, ReceiptFailed}; + enum OccupantAction {Kick, Ban, MakeModerator, MakeParticipant, MakeVisitor, AddContact, ShowProfile}; + enum RoomAction {ChangeSubject, Configure, Affiliations, Destroy, Invite}; + enum FileTransferState { + Initialisation, ///< Collecting information required for sending the request out. + WaitingForAccept, ///< The file transfer request was send out. + Negotiating, ///< The other party accepted the file transfer request and a suitable transfer method is negotiated. + Transferring, ///< The negotiation was successful and the file is currently transferred. + Canceled, ///< Someone actively canceled the transfer. + Finished, ///< The file was transferred successfully. + FTFailed ///< The negotiation, the transfer itself or the verification failed. + }; + enum WhiteboardSessionState {WhiteboardAccepted, WhiteboardTerminated, WhiteboardRejected}; + enum BlockingState {BlockingUnsupported, IsBlocked, IsUnblocked}; + enum Direction { UnknownDirection, DefaultDirection }; + enum MUCType { StandardMUC, ImpromptuMUC }; + enum TimestampBehaviour { KeepTimestamp, UpdateTimestamp }; + enum RoomBookmarkState { RoomNotBookmarked, RoomBookmarked, RoomAutoJoined }; + + ChatWindow() {} + virtual ~ChatWindow() {} + + /** Add message to window. + * @return id of added message (for acks). + */ + virtual std::string addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; + /** Adds action to window. + * @return id of added message (for acks); + */ + virtual std::string addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; + + /** Adds system message to window + * @return id of added message (for replacement) + */ + virtual std::string addSystemMessage(const ChatMessage& message, Direction direction) = 0; + virtual void addPresenceMessage(const ChatMessage& message, Direction direction) = 0; + + virtual void addErrorMessage(const ChatMessage& message) = 0; + virtual void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; + virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour) = 0; + virtual void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; + + // File transfer related stuff + virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0; + virtual void setFileTransferProgress(std::string, const int percentageDone) = 0; + virtual void setFileTransferStatus(std::string, const FileTransferState state, const std::string& msg = "") = 0; + virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false) = 0; + + virtual std::string addWhiteboardRequest(bool senderIsSelf) = 0; + virtual void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state) = 0; + + // message receipts + virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0; + + virtual void setContactChatState(ChatState::ChatStateType state) = 0; + virtual void setName(const std::string& name) = 0; + virtual void show() = 0; + virtual bool isVisible() const = 0; + virtual void activate() = 0; + virtual void setAvailableSecurityLabels(const std::vector& labels) = 0; + virtual void setSecurityLabelsEnabled(bool enabled) = 0; + virtual void setCorrectionEnabled(Tristate enabled) = 0; + virtual void setFileTransferEnabled(Tristate enabled) = 0; + virtual void setUnreadMessageCount(int count) = 0; + virtual void convertToMUC(MUCType mucType) = 0; +// virtual TreeWidget *getTreeWidget() = 0; + virtual void setSecurityLabelsError() = 0; + virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() = 0; + virtual void setOnline(bool online) = 0; + virtual void setRosterModel(Roster* model) = 0; + virtual void setTabComplete(TabComplete* completer) = 0; + virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour) = 0; + virtual void setAckState(const std::string& id, AckState state) = 0; + virtual void flash() = 0; + virtual void setSubject(const std::string& subject) = 0; + virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector&) = 0; + virtual void setAvailableRoomActions(const std::vector &actions) = 0; + virtual void setBlockingState(BlockingState state) = 0; + virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) = 0; + virtual void showBookmarkWindow(const MUCBookmark& bookmark) = 0; + virtual void setBookmarkState(RoomBookmarkState bookmarkState) = 0; + + /** + * A handle that uniquely identities an alert message. + */ + typedef int AlertID; + /** + * Set an alert on the window. + * @param alertText Description of alert (required). + * @param buttonText Button text to use (optional, no button is shown if empty). + * @return A handle to the alert message. + */ + virtual AlertID addAlert(const std::string& alertText) = 0; + /** + * Removes an alert. + * @param id An alert ID previously returned from setAlert + */ + virtual void removeAlert(const AlertID id) = 0; + + /** + * Actions that can be performed on the selected occupant. + */ + virtual void setAvailableOccupantActions(const std::vector& actions) = 0; + + /** + * A room configuration has been requested, show the form. + * If the form is cancelled, must emit onConfigurationFormCancelled(). + */ + virtual void showRoomConfigurationForm(Form::ref) = 0; + + boost::signal onClosed; + boost::signal onAllMessagesRead; + boost::signal onSendMessageRequest; + boost::signal onSendCorrectionMessageRequest; + boost::signal onUserTyping; + boost::signal onUserCancelsTyping; + boost::signal onAlertButtonClicked; + boost::signal onOccupantSelectionChanged; + boost::signal onOccupantActionSelected; + boost::signal onChangeSubjectRequest; + boost::signal onBookmarkRequest; + boost::signal onConfigureRequest; + boost::signal onDestroyRequest; + boost::signal&)> onInviteToChat; + boost::signal onConfigurationFormCancelled; + boost::signal onGetAffiliationsRequest; + boost::signal onSetAffiliationRequest; + boost::signal >& changes)> onChangeAffiliationsRequest; + boost::signal onLogCleared; + + // File transfer related + boost::signal onFileTransferCancel; + boost::signal onFileTransferStart; + boost::signal onFileTransferAccept; + boost::signal onSendFileRequest; + + //Whiteboard related + boost::signal onWhiteboardSessionAccept; + boost::signal onWhiteboardSessionCancel; + boost::signal onWhiteboardWindowShow; + + // Blocking Command related + boost::signal onBlockUserRequest; + boost::signal onUnblockUserRequest; + }; } diff --git a/Swift/Controllers/UIInterfaces/ChatWindowFactory.h b/Swift/Controllers/UIInterfaces/ChatWindowFactory.h index 7c47e2a..38706ab 100644 --- a/Swift/Controllers/UIInterfaces/ChatWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/ChatWindowFactory.h @@ -10,17 +10,17 @@ #include "Swiften/JID/JID.h" namespace Swift { - class ChatWindow; - class UIEventStream; - class ChatWindowFactory { - public: - virtual ~ChatWindowFactory() {} - /** - * Transfers ownership of result. - */ - virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream) = 0; + class ChatWindow; + class UIEventStream; + class ChatWindowFactory { + public: + virtual ~ChatWindowFactory() {} + /** + * Transfers ownership of result. + */ + virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream) = 0; - }; + }; } #endif diff --git a/Swift/Controllers/UIInterfaces/ContactEditWindow.h b/Swift/Controllers/UIInterfaces/ContactEditWindow.h index 407959a..055c0f0 100644 --- a/Swift/Controllers/UIInterfaces/ContactEditWindow.h +++ b/Swift/Controllers/UIInterfaces/ContactEditWindow.h @@ -15,22 +15,22 @@ #include namespace Swift { - class JID; - class VCardManager; + class JID; + class VCardManager; - class ContactEditWindow { - public: - virtual ~ContactEditWindow() {} + class ContactEditWindow { + public: + virtual ~ContactEditWindow() {} - virtual void setEnabled(bool b) = 0; + virtual void setEnabled(bool b) = 0; - virtual void setNameSuggestions(const std::vector& suggestions) = 0; - virtual void setContact(const JID& jid, const std::string& name, const std::vector& groups, const std::set& allGroups) = 0; + virtual void setNameSuggestions(const std::vector& suggestions) = 0; + virtual void setContact(const JID& jid, const std::string& name, const std::vector& groups, const std::set& allGroups) = 0; - virtual void show() = 0; - virtual void hide() = 0; + virtual void show() = 0; + virtual void hide() = 0; - boost::signal onRemoveContactRequest; - boost::signal& /* groups */)> onChangeContactRequest; - }; + boost::signal onRemoveContactRequest; + boost::signal& /* groups */)> onChangeContactRequest; + }; } diff --git a/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h b/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h index 6955a69..f5a84d5 100644 --- a/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/ContactEditWindowFactory.h @@ -9,10 +9,10 @@ #include namespace Swift { - class ContactEditWindowFactory { - public: - virtual ~ContactEditWindowFactory() {} + class ContactEditWindowFactory { + public: + virtual ~ContactEditWindowFactory() {} - virtual ContactEditWindow* createContactEditWindow() = 0; - }; + virtual ContactEditWindow* createContactEditWindow() = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/EventWindow.h b/Swift/Controllers/UIInterfaces/EventWindow.h index 5ce99d8..1d254f4 100644 --- a/Swift/Controllers/UIInterfaces/EventWindow.h +++ b/Swift/Controllers/UIInterfaces/EventWindow.h @@ -11,19 +11,19 @@ #include namespace Swift { - class EventWindow { - public: - EventWindow(bool candelete = true) : canDelete_(candelete) {} + class EventWindow { + public: + EventWindow(bool candelete = true) : canDelete_(candelete) {} - bool canDelete() const { - return canDelete_; - } + bool canDelete() const { + return canDelete_; + } - virtual ~EventWindow() {} - virtual void addEvent(boost::shared_ptr event, bool active) = 0; - virtual void removeEvent(boost::shared_ptr event) = 0; + virtual ~EventWindow() {} + virtual void addEvent(boost::shared_ptr event, bool active) = 0; + virtual void removeEvent(boost::shared_ptr event) = 0; - private: - bool canDelete_; - }; + private: + bool canDelete_; + }; } diff --git a/Swift/Controllers/UIInterfaces/EventWindowFactory.h b/Swift/Controllers/UIInterfaces/EventWindowFactory.h index 7c9c87d..76638da 100644 --- a/Swift/Controllers/UIInterfaces/EventWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/EventWindowFactory.h @@ -7,17 +7,17 @@ #pragma once namespace Swift { - class EventWindow; + class EventWindow; - class EventWindowFactory { - public: - virtual ~EventWindowFactory() {} - /** - * Transfers ownership of result. - */ - virtual EventWindow* createEventWindow() = 0; + class EventWindowFactory { + public: + virtual ~EventWindowFactory() {} + /** + * Transfers ownership of result. + */ + virtual EventWindow* createEventWindow() = 0; - }; + }; } diff --git a/Swift/Controllers/UIInterfaces/FileTransferListWidget.h b/Swift/Controllers/UIInterfaces/FileTransferListWidget.h index 01dcfd3..5a9eaeb 100644 --- a/Swift/Controllers/UIInterfaces/FileTransferListWidget.h +++ b/Swift/Controllers/UIInterfaces/FileTransferListWidget.h @@ -12,12 +12,12 @@ class FileTransferOverview; class FileTransferListWidget { public: - virtual ~FileTransferListWidget() {} + virtual ~FileTransferListWidget() {} - virtual void show() = 0; - virtual void activate() = 0; + virtual void show() = 0; + virtual void activate() = 0; - virtual void setFileTransferOverview(FileTransferOverview*) = 0; + virtual void setFileTransferOverview(FileTransferOverview*) = 0; }; } diff --git a/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h b/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h index 6da2d07..da9fd37 100644 --- a/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h +++ b/Swift/Controllers/UIInterfaces/FileTransferListWidgetFactory.h @@ -18,9 +18,9 @@ namespace Swift { class FileTransferListWidgetFactory { public: - virtual ~FileTransferListWidgetFactory() {} + virtual ~FileTransferListWidgetFactory() {} - virtual FileTransferListWidget* createFileTransferListWidget() = 0; + virtual FileTransferListWidget* createFileTransferListWidget() = 0; }; } diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h b/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h index 4745035..ff888e6 100644 --- a/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h +++ b/Swift/Controllers/UIInterfaces/HighlightEditorWidget.h @@ -8,15 +8,15 @@ namespace Swift { - class HighlightManager; + class HighlightManager; - class HighlightEditorWidget { - public: - virtual ~HighlightEditorWidget() {} + class HighlightEditorWidget { + public: + virtual ~HighlightEditorWidget() {} - virtual void show() = 0; + virtual void show() = 0; - virtual void setHighlightManager(HighlightManager* highlightManager) = 0; - }; + virtual void setHighlightManager(HighlightManager* highlightManager) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h b/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h index ade575b..363e666 100644 --- a/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h +++ b/Swift/Controllers/UIInterfaces/HighlightEditorWidgetFactory.h @@ -8,13 +8,13 @@ namespace Swift { - class HighlightEditorWidget; + class HighlightEditorWidget; - class HighlightEditorWidgetFactory { - public: - virtual ~HighlightEditorWidgetFactory() {} + class HighlightEditorWidgetFactory { + public: + virtual ~HighlightEditorWidgetFactory() {} - virtual HighlightEditorWidget* createHighlightEditorWidget() = 0; - }; + virtual HighlightEditorWidget* createHighlightEditorWidget() = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h b/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h index 12adb3d..8cca4f9 100644 --- a/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h +++ b/Swift/Controllers/UIInterfaces/HighlightEditorWindow.h @@ -14,14 +14,14 @@ class HighlightManager; class HighlightEditorWindow { public: - HighlightEditorWindow(); - virtual ~HighlightEditorWindow(); - virtual void show() = 0; - virtual void setHighlightManager(HighlightManager *highlightManager) = 0; - virtual void setContactSuggestions(const std::vector& suggestions) = 0; + HighlightEditorWindow(); + virtual ~HighlightEditorWindow(); + virtual void show() = 0; + virtual void setHighlightManager(HighlightManager *highlightManager) = 0; + virtual void setContactSuggestions(const std::vector& suggestions) = 0; public: - boost::signal onContactSuggestionsRequested; + boost::signal onContactSuggestionsRequested; }; } diff --git a/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h b/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h index 18fbeb7..ea05425 100644 --- a/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/HighlightEditorWindowFactory.h @@ -13,12 +13,12 @@ #pragma once namespace Swift { - class HighlightEditorWindow; + class HighlightEditorWindow; - class HighlightEditorWindowFactory { - public : - virtual ~HighlightEditorWindowFactory() {} + class HighlightEditorWindowFactory { + public : + virtual ~HighlightEditorWindowFactory() {} - virtual HighlightEditorWindow* createHighlightEditorWindow() = 0; - }; + virtual HighlightEditorWindow* createHighlightEditorWindow() = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/HistoryWindow.h b/Swift/Controllers/UIInterfaces/HistoryWindow.h index 6d50f4b..db1a4b1 100644 --- a/Swift/Controllers/UIInterfaces/HistoryWindow.h +++ b/Swift/Controllers/UIInterfaces/HistoryWindow.h @@ -9,26 +9,26 @@ #include namespace Swift { - class HistoryWindow { - public: - virtual ~HistoryWindow() {} + class HistoryWindow { + public: + virtual ~HistoryWindow() {} - virtual void activate() = 0; - virtual void setRosterModel(Roster*) = 0; - virtual void addMessage(const std::string &message, const std::string &senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop) = 0; - virtual void resetConversationView() = 0; - virtual void resetConversationViewTopInsertPoint() = 0; // this is a temporary fix used in adding messages at the top - virtual void setDate(const boost::gregorian::date& date) = 0; + virtual void activate() = 0; + virtual void setRosterModel(Roster*) = 0; + virtual void addMessage(const std::string &message, const std::string &senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop) = 0; + virtual void resetConversationView() = 0; + virtual void resetConversationViewTopInsertPoint() = 0; // this is a temporary fix used in adding messages at the top + virtual void setDate(const boost::gregorian::date& date) = 0; - virtual std::string getSearchBoxText() = 0; - virtual boost::gregorian::date getLastVisibleDate() = 0; + virtual std::string getSearchBoxText() = 0; + virtual boost::gregorian::date getLastVisibleDate() = 0; - boost::signal onSelectedContactChanged; - boost::signal onReturnPressed; - boost::signal onScrollReachedTop; - boost::signal onScrollReachedBottom; - boost::signal onPreviousButtonClicked; - boost::signal onNextButtonClicked; - boost::signal onCalendarClicked; - }; + boost::signal onSelectedContactChanged; + boost::signal onReturnPressed; + boost::signal onScrollReachedTop; + boost::signal onScrollReachedBottom; + boost::signal onPreviousButtonClicked; + boost::signal onNextButtonClicked; + boost::signal onCalendarClicked; + }; } diff --git a/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h b/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h index 807fec5..ab4cf0d 100644 --- a/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/HistoryWindowFactory.h @@ -9,10 +9,10 @@ #include namespace Swift { - class UIEventStream; - class HistoryWindowFactory { - public: - virtual ~HistoryWindowFactory() {} - virtual HistoryWindow* createHistoryWindow(UIEventStream* eventStream) = 0; - }; + class UIEventStream; + class HistoryWindowFactory { + public: + virtual ~HistoryWindowFactory() {} + virtual HistoryWindow* createHistoryWindow(UIEventStream* eventStream) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/JoinMUCWindow.h b/Swift/Controllers/UIInterfaces/JoinMUCWindow.h index 62818c5..4d6cea1 100644 --- a/Swift/Controllers/UIInterfaces/JoinMUCWindow.h +++ b/Swift/Controllers/UIInterfaces/JoinMUCWindow.h @@ -13,14 +13,14 @@ #include namespace Swift { - class JoinMUCWindow { - public: - virtual ~JoinMUCWindow() {} + class JoinMUCWindow { + public: + virtual ~JoinMUCWindow() {} - virtual void setNick(const std::string& nick) = 0; - virtual void setMUC(const std::string& nick) = 0; - virtual void show() = 0; + virtual void setNick(const std::string& nick) = 0; + virtual void setMUC(const std::string& nick) = 0; + virtual void show() = 0; - boost::signal onSearchMUC; - }; + boost::signal onSearchMUC; + }; } diff --git a/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h b/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h index a711294..5e8b1d0 100644 --- a/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h @@ -9,11 +9,11 @@ #include namespace Swift { - class UIEventStream; - class JoinMUCWindowFactory { - public: - virtual ~JoinMUCWindowFactory() {} + class UIEventStream; + class JoinMUCWindowFactory { + public: + virtual ~JoinMUCWindowFactory() {} - virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream) = 0; - }; + virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/LoginWindow.h b/Swift/Controllers/UIInterfaces/LoginWindow.h index 5a7e178..cedc549 100644 --- a/Swift/Controllers/UIInterfaces/LoginWindow.h +++ b/Swift/Controllers/UIInterfaces/LoginWindow.h @@ -16,27 +16,27 @@ #include namespace Swift { - class MainWindow; - class LoginWindow { - public: - virtual ~LoginWindow() {} - virtual void selectUser(const std::string&) = 0; - virtual void morphInto(MainWindow *mainWindow) = 0; - virtual void loggedOut() = 0; - virtual void setShowNotificationToggle(bool) = 0; - virtual void setMessage(const std::string&) = 0; - virtual void setIsLoggingIn(bool loggingIn) = 0; - virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options) = 0; - virtual void removeAvailableAccount(const std::string& jid) = 0; - /** The certificate is what is used for login, the certificatePath is used for remembering paths to populate the loginwindow with*/ - boost::signal onLoginRequest; - virtual void setLoginAutomatically(bool loginAutomatically) = 0; - virtual void quit() = 0; - /** Blocking request whether a cert should be permanently trusted.*/ - virtual bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector& certificateChain) = 0; + class MainWindow; + class LoginWindow { + public: + virtual ~LoginWindow() {} + virtual void selectUser(const std::string&) = 0; + virtual void morphInto(MainWindow *mainWindow) = 0; + virtual void loggedOut() = 0; + virtual void setShowNotificationToggle(bool) = 0; + virtual void setMessage(const std::string&) = 0; + virtual void setIsLoggingIn(bool loggingIn) = 0; + virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options) = 0; + virtual void removeAvailableAccount(const std::string& jid) = 0; + /** The certificate is what is used for login, the certificatePath is used for remembering paths to populate the loginwindow with*/ + boost::signal onLoginRequest; + virtual void setLoginAutomatically(bool loginAutomatically) = 0; + virtual void quit() = 0; + /** Blocking request whether a cert should be permanently trusted.*/ + virtual bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector& certificateChain) = 0; - boost::signal onCancelLoginRequest; - boost::signal onQuitRequest; - boost::signal onPurgeSavedLoginRequest; - }; + boost::signal onCancelLoginRequest; + boost::signal onQuitRequest; + boost::signal onPurgeSavedLoginRequest; + }; } diff --git a/Swift/Controllers/UIInterfaces/LoginWindowFactory.h b/Swift/Controllers/UIInterfaces/LoginWindowFactory.h index c040833..485f975 100644 --- a/Swift/Controllers/UIInterfaces/LoginWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/LoginWindowFactory.h @@ -10,20 +10,20 @@ namespace Swift { - class LoginWindow; - - class UIEventStream; - - class LoginWindowFactory { - public: - virtual ~LoginWindowFactory() {} - - /** - * Transfers ownership of result. - */ - virtual LoginWindow* createLoginWindow(UIEventStream* uiEventStream) = 0; - - }; + class LoginWindow; + + class UIEventStream; + + class LoginWindowFactory { + public: + virtual ~LoginWindowFactory() {} + + /** + * Transfers ownership of result. + */ + virtual LoginWindow* createLoginWindow(UIEventStream* uiEventStream) = 0; + + }; } #endif diff --git a/Swift/Controllers/UIInterfaces/MUCSearchWindow.h b/Swift/Controllers/UIInterfaces/MUCSearchWindow.h index 10c6b38..d6c0065 100644 --- a/Swift/Controllers/UIInterfaces/MUCSearchWindow.h +++ b/Swift/Controllers/UIInterfaces/MUCSearchWindow.h @@ -18,18 +18,18 @@ namespace Swift { - class MUCSearchWindow { - public: - virtual ~MUCSearchWindow() {} + class MUCSearchWindow { + public: + virtual ~MUCSearchWindow() {} - virtual void clearList() = 0; - virtual void addService(const MUCService& service) = 0; - virtual void addSavedServices(const std::list& services) = 0; - virtual void setSearchInProgress(bool searching) = 0; + virtual void clearList() = 0; + virtual void addService(const MUCService& service) = 0; + virtual void addSavedServices(const std::list& services) = 0; + virtual void setSearchInProgress(bool searching) = 0; - virtual void show() = 0; + virtual void show() = 0; - boost::signal onSearchService; - boost::signal&)> onFinished; - }; + boost::signal onSearchService; + boost::signal&)> onFinished; + }; } diff --git a/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h b/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h index 38492cd..6e26ac3 100644 --- a/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/MUCSearchWindowFactory.h @@ -9,11 +9,11 @@ #include namespace Swift { - class UIEventStream; - class MUCSearchWindowFactory { - public: - virtual ~MUCSearchWindowFactory() {} + class UIEventStream; + class MUCSearchWindowFactory { + public: + virtual ~MUCSearchWindowFactory() {} - virtual MUCSearchWindow* createMUCSearchWindow() = 0; - }; + virtual MUCSearchWindow* createMUCSearchWindow() = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/MainWindow.h b/Swift/Controllers/UIInterfaces/MainWindow.h index aa8314d..d8bcb58 100644 --- a/Swift/Controllers/UIInterfaces/MainWindow.h +++ b/Swift/Controllers/UIInterfaces/MainWindow.h @@ -19,36 +19,36 @@ #include namespace Swift { - class Roster; - - class MainWindow { - public: - MainWindow(bool candelete = true) : canDelete_(candelete) {} - virtual ~MainWindow() {} - - bool canDelete() const { - return canDelete_; - } - - virtual void setMyNick(const std::string& name) = 0; - virtual void setMyJID(const JID& jid) = 0; - virtual void setMyAvatarPath(const std::string& path) = 0; - virtual void setMyStatusText(const std::string& status) = 0; - virtual void setMyStatusType(StatusShow::Type type) = 0; - virtual void setMyContactRosterItem(boost::shared_ptr contact) = 0; - /** Must be able to cope with NULL to clear the roster */ - virtual void setRosterModel(Roster* roster) = 0; - virtual void setConnecting() = 0; - virtual void setBlockingCommandAvailable(bool isAvailable) = 0; - virtual void setAvailableAdHocCommands(const std::vector& commands) = 0; - virtual void setStreamEncryptionStatus(bool tlsInPlaceAndValid) = 0; - virtual void openCertificateDialog(const std::vector& chain) = 0; - - boost::signal onChangeStatusRequest; - boost::signal onSignOutRequest; - boost::signal onShowCertificateRequest; - - private: - bool canDelete_; - }; + class Roster; + + class MainWindow { + public: + MainWindow(bool candelete = true) : canDelete_(candelete) {} + virtual ~MainWindow() {} + + bool canDelete() const { + return canDelete_; + } + + virtual void setMyNick(const std::string& name) = 0; + virtual void setMyJID(const JID& jid) = 0; + virtual void setMyAvatarPath(const std::string& path) = 0; + virtual void setMyStatusText(const std::string& status) = 0; + virtual void setMyStatusType(StatusShow::Type type) = 0; + virtual void setMyContactRosterItem(boost::shared_ptr contact) = 0; + /** Must be able to cope with NULL to clear the roster */ + virtual void setRosterModel(Roster* roster) = 0; + virtual void setConnecting() = 0; + virtual void setBlockingCommandAvailable(bool isAvailable) = 0; + virtual void setAvailableAdHocCommands(const std::vector& commands) = 0; + virtual void setStreamEncryptionStatus(bool tlsInPlaceAndValid) = 0; + virtual void openCertificateDialog(const std::vector& chain) = 0; + + boost::signal onChangeStatusRequest; + boost::signal onSignOutRequest; + boost::signal onShowCertificateRequest; + + private: + bool canDelete_; + }; } diff --git a/Swift/Controllers/UIInterfaces/MainWindowFactory.h b/Swift/Controllers/UIInterfaces/MainWindowFactory.h index 5c24187..c0110cf 100644 --- a/Swift/Controllers/UIInterfaces/MainWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/MainWindowFactory.h @@ -11,17 +11,17 @@ #include "Swift/Controllers/UIEvents/UIEventStream.h" namespace Swift { - class MainWindow; + class MainWindow; - class MainWindowFactory { - public: - virtual ~MainWindowFactory() {} - /** - * Transfers ownership of result. - */ - virtual MainWindow* createMainWindow(UIEventStream* eventStream) = 0; + class MainWindowFactory { + public: + virtual ~MainWindowFactory() {} + /** + * Transfers ownership of result. + */ + virtual MainWindow* createMainWindow(UIEventStream* eventStream) = 0; - }; + }; } #endif diff --git a/Swift/Controllers/UIInterfaces/ProfileWindow.h b/Swift/Controllers/UIInterfaces/ProfileWindow.h index f396499..8aa620c 100644 --- a/Swift/Controllers/UIInterfaces/ProfileWindow.h +++ b/Swift/Controllers/UIInterfaces/ProfileWindow.h @@ -12,24 +12,24 @@ #include namespace Swift { - class JID; + class JID; - class ProfileWindow { - public: - virtual ~ProfileWindow() {} + class ProfileWindow { + public: + virtual ~ProfileWindow() {} - virtual void setJID(const JID& jid) = 0; - virtual void setVCard(VCard::ref vcard) = 0; + virtual void setJID(const JID& jid) = 0; + virtual void setVCard(VCard::ref vcard) = 0; - virtual void setEnabled(bool b) = 0; - virtual void setProcessing(bool b) = 0; - virtual void setError(const std::string&) = 0; - virtual void setEditable(bool b) = 0; + virtual void setEnabled(bool b) = 0; + virtual void setProcessing(bool b) = 0; + virtual void setError(const std::string&) = 0; + virtual void setEditable(bool b) = 0; - virtual void show() = 0; - virtual void hide() = 0; + virtual void show() = 0; + virtual void hide() = 0; - boost::signal onVCardChangeRequest; - boost::signal onWindowAboutToBeClosed; - }; + boost::signal onVCardChangeRequest; + boost::signal onWindowAboutToBeClosed; + }; } diff --git a/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h b/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h index 5137151..6c2c6e5 100644 --- a/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/ProfileWindowFactory.h @@ -9,10 +9,10 @@ #include namespace Swift { - class ProfileWindowFactory { - public: - virtual ~ProfileWindowFactory() {} + class ProfileWindowFactory { + public: + virtual ~ProfileWindowFactory() {} - virtual ProfileWindow* createProfileWindow() = 0; - }; + virtual ProfileWindow* createProfileWindow() = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/UIFactory.h b/Swift/Controllers/UIInterfaces/UIFactory.h index dd9d0df..a0976dc 100644 --- a/Swift/Controllers/UIInterfaces/UIFactory.h +++ b/Swift/Controllers/UIInterfaces/UIFactory.h @@ -25,25 +25,25 @@ #include namespace Swift { - class UIFactory : - public ChatListWindowFactory, - public ChatWindowFactory, - public HistoryWindowFactory, - public EventWindowFactory, - public LoginWindowFactory, - public MainWindowFactory, - public MUCSearchWindowFactory, - public XMLConsoleWidgetFactory, - public UserSearchWindowFactory, - public JoinMUCWindowFactory, - public ProfileWindowFactory, - public ContactEditWindowFactory, - public AdHocCommandWindowFactory, - public FileTransferListWidgetFactory, - public WhiteboardWindowFactory, - public HighlightEditorWindowFactory, - public BlockListEditorWidgetFactory { - public: - virtual ~UIFactory() {} - }; + class UIFactory : + public ChatListWindowFactory, + public ChatWindowFactory, + public HistoryWindowFactory, + public EventWindowFactory, + public LoginWindowFactory, + public MainWindowFactory, + public MUCSearchWindowFactory, + public XMLConsoleWidgetFactory, + public UserSearchWindowFactory, + public JoinMUCWindowFactory, + public ProfileWindowFactory, + public ContactEditWindowFactory, + public AdHocCommandWindowFactory, + public FileTransferListWidgetFactory, + public WhiteboardWindowFactory, + public HighlightEditorWindowFactory, + public BlockListEditorWidgetFactory { + public: + virtual ~UIFactory() {} + }; } diff --git a/Swift/Controllers/UIInterfaces/UserSearchWindow.h b/Swift/Controllers/UIInterfaces/UserSearchWindow.h index da33db3..4ddc29b 100644 --- a/Swift/Controllers/UIInterfaces/UserSearchWindow.h +++ b/Swift/Controllers/UIInterfaces/UserSearchWindow.h @@ -17,40 +17,40 @@ namespace Swift { - class UserSearchWindow { - public: - enum Type {AddContact, ChatToContact, InviteToChat}; - virtual ~UserSearchWindow() {} - - virtual void clear() = 0; - virtual void setResults(const std::vector& results) = 0; - virtual void setResultsForm(const Form::ref results) = 0; - virtual void addSavedServices(const std::vector& services) = 0; - virtual void setSelectedService(const JID& service) = 0; - virtual void setServerSupportsSearch(bool support) = 0; - virtual void setSearchError(bool support) = 0; - virtual void setSearchFields(boost::shared_ptr fields) = 0; - virtual void setNameSuggestions(const std::vector& suggestions) = 0; - virtual void prepopulateJIDAndName(const JID& jid, const std::string& name) = 0; - virtual void setContactSuggestions(const std::vector& suggestions) = 0; - virtual void setJIDs(const std::vector&) = 0; - virtual void setRoomJID(const JID& roomJID) = 0; - virtual std::string getReason() const = 0; - virtual std::vector getJIDs() const = 0; - virtual void setCanStartImpromptuChats(bool supportsImpromptu) = 0; - virtual void updateContacts(const std::vector& contacts) = 0; - virtual void addContacts(const std::vector& contacts) = 0; - virtual void setCanSupplyDescription(bool allowed) = 0; - virtual void setWarning(const boost::optional& message) = 0; - - virtual void show() = 0; - - boost::signal onFormRequested; - boost::signal, const JID&)> onSearchRequested; - boost::signal onNameSuggestionRequested; - boost::signal onContactSuggestionsRequested; - boost::signal&)> onJIDUpdateRequested; - boost::signal&)> onJIDAddRequested; - boost::signal onJIDEditFieldChanged; - }; + class UserSearchWindow { + public: + enum Type {AddContact, ChatToContact, InviteToChat}; + virtual ~UserSearchWindow() {} + + virtual void clear() = 0; + virtual void setResults(const std::vector& results) = 0; + virtual void setResultsForm(const Form::ref results) = 0; + virtual void addSavedServices(const std::vector& services) = 0; + virtual void setSelectedService(const JID& service) = 0; + virtual void setServerSupportsSearch(bool support) = 0; + virtual void setSearchError(bool support) = 0; + virtual void setSearchFields(boost::shared_ptr fields) = 0; + virtual void setNameSuggestions(const std::vector& suggestions) = 0; + virtual void prepopulateJIDAndName(const JID& jid, const std::string& name) = 0; + virtual void setContactSuggestions(const std::vector& suggestions) = 0; + virtual void setJIDs(const std::vector&) = 0; + virtual void setRoomJID(const JID& roomJID) = 0; + virtual std::string getReason() const = 0; + virtual std::vector getJIDs() const = 0; + virtual void setCanStartImpromptuChats(bool supportsImpromptu) = 0; + virtual void updateContacts(const std::vector& contacts) = 0; + virtual void addContacts(const std::vector& contacts) = 0; + virtual void setCanSupplyDescription(bool allowed) = 0; + virtual void setWarning(const boost::optional& message) = 0; + + virtual void show() = 0; + + boost::signal onFormRequested; + boost::signal, const JID&)> onSearchRequested; + boost::signal onNameSuggestionRequested; + boost::signal onContactSuggestionsRequested; + boost::signal&)> onJIDUpdateRequested; + boost::signal&)> onJIDAddRequested; + boost::signal onJIDEditFieldChanged; + }; } diff --git a/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h b/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h index 4eee510..d5d6135 100644 --- a/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h @@ -11,11 +11,11 @@ #include namespace Swift { - class UIEventStream; - class UserSearchWindowFactory { - public: - virtual ~UserSearchWindowFactory() {} + class UIEventStream; + class UserSearchWindowFactory { + public: + virtual ~UserSearchWindowFactory() {} - virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set& groups) = 0; - }; + virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set& groups) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/WhiteboardWindow.h b/Swift/Controllers/UIInterfaces/WhiteboardWindow.h index 84aefde..f3b35db 100644 --- a/Swift/Controllers/UIInterfaces/WhiteboardWindow.h +++ b/Swift/Controllers/UIInterfaces/WhiteboardWindow.h @@ -17,16 +17,16 @@ #include namespace Swift { - class WhiteboardSession; - class WhiteboardElement; + class WhiteboardSession; + class WhiteboardElement; - class WhiteboardWindow { - public: - virtual ~WhiteboardWindow() {} + class WhiteboardWindow { + public: + virtual ~WhiteboardWindow() {} - virtual void show() = 0; - virtual void setSession(boost::shared_ptr session) = 0; - virtual void activateWindow() = 0; - virtual void setName(const std::string& name) = 0; - }; + virtual void show() = 0; + virtual void setSession(boost::shared_ptr session) = 0; + virtual void activateWindow() = 0; + virtual void setName(const std::string& name) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h b/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h index 2be0f9c..163368b 100644 --- a/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h +++ b/Swift/Controllers/UIInterfaces/WhiteboardWindowFactory.h @@ -7,13 +7,13 @@ #pragma once namespace Swift { - class WhiteboardSession; - class WhiteboardWindow; + class WhiteboardSession; + class WhiteboardWindow; - class WhiteboardWindowFactory { - public : - virtual ~WhiteboardWindowFactory() {} + class WhiteboardWindowFactory { + public : + virtual ~WhiteboardWindowFactory() {} - virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr whiteboardSession) = 0; - }; + virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr whiteboardSession) = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h b/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h index 7e477a9..872b9de 100644 --- a/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h +++ b/Swift/Controllers/UIInterfaces/XMLConsoleWidget.h @@ -9,14 +9,14 @@ #include namespace Swift { - class XMLConsoleWidget { - public: - virtual ~XMLConsoleWidget(); + class XMLConsoleWidget { + public: + virtual ~XMLConsoleWidget(); - virtual void handleDataRead(const SafeByteArray& data) = 0; - virtual void handleDataWritten(const SafeByteArray& data) = 0; + virtual void handleDataRead(const SafeByteArray& data) = 0; + virtual void handleDataWritten(const SafeByteArray& data) = 0; - virtual void show() = 0; - virtual void activate() = 0; - }; + virtual void show() = 0; + virtual void activate() = 0; + }; } diff --git a/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h b/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h index 69b3e16..bbc055e 100644 --- a/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h +++ b/Swift/Controllers/UIInterfaces/XMLConsoleWidgetFactory.h @@ -9,11 +9,11 @@ #include namespace Swift { - class UIEventStream; - class XMLConsoleWidgetFactory { - public: - virtual ~XMLConsoleWidgetFactory() {} + class UIEventStream; + class XMLConsoleWidgetFactory { + public: + virtual ~XMLConsoleWidgetFactory() {} - virtual XMLConsoleWidget* createXMLConsoleWidget() = 0; - }; + virtual XMLConsoleWidget* createXMLConsoleWidget() = 0; + }; } diff --git a/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp b/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp index 118c502..59c57b9 100644 --- a/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp +++ b/Swift/Controllers/UnitTest/ChatMessageSummarizerTest.cpp @@ -13,109 +13,109 @@ using namespace Swift; using namespace std; class ChatMessageSummarizerTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ChatMessageSummarizerTest); - CPPUNIT_TEST(testEmpty); - CPPUNIT_TEST(testCurrentNone); - CPPUNIT_TEST(testCurrentCount); - CPPUNIT_TEST(testCurrentCountOthersNone); - CPPUNIT_TEST(testCurrentCountOtherCount); - CPPUNIT_TEST(testCurrentNoneOtherCount); - CPPUNIT_TEST(testCurrentCountOthersCount); - CPPUNIT_TEST(testCurrentNoneOthersCount); - CPPUNIT_TEST(testCurrentCountSomeOthersCount); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(ChatMessageSummarizerTest); + CPPUNIT_TEST(testEmpty); + CPPUNIT_TEST(testCurrentNone); + CPPUNIT_TEST(testCurrentCount); + CPPUNIT_TEST(testCurrentCountOthersNone); + CPPUNIT_TEST(testCurrentCountOtherCount); + CPPUNIT_TEST(testCurrentNoneOtherCount); + CPPUNIT_TEST(testCurrentCountOthersCount); + CPPUNIT_TEST(testCurrentNoneOthersCount); + CPPUNIT_TEST(testCurrentCountSomeOthersCount); + CPPUNIT_TEST_SUITE_END(); public: - ChatMessageSummarizerTest() {} - - void setUp() { - - } - - void testEmpty() { - string current(""); - vector unreads; - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads)); - } - - void testCurrentNone() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bob", 0)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads)); - } - - void testCurrentCount() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bob", 3)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads)); - } - - void testCurrentCountOthersNone() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bert", 0)); - unreads.push_back(UnreadPair("Bob", 3)); - unreads.push_back(UnreadPair("Betty", 0)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads)); - } - - void testCurrentCountOtherCount() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bert", 0)); - unreads.push_back(UnreadPair("Bob", 3)); - unreads.push_back(UnreadPair("Betty", 7)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(string("Bob (3); Betty (7)"), summary.getSummary(current, unreads)); - } - - void testCurrentNoneOtherCount() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bert", 0)); - unreads.push_back(UnreadPair("Bob", 0)); - unreads.push_back(UnreadPair("Betty", 7)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(string("Bob; Betty (7)"), summary.getSummary(current, unreads)); - } - - void testCurrentNoneOthersCount() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bert", 2)); - unreads.push_back(UnreadPair("Bob", 0)); - unreads.push_back(UnreadPair("Betty", 7)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(string("Bob and 2 others (9)"), summary.getSummary(current, unreads)); - } - - void testCurrentCountOthersCount() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bert", 2)); - unreads.push_back(UnreadPair("Bob", 11)); - unreads.push_back(UnreadPair("Betty", 7)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads)); - } - - void testCurrentCountSomeOthersCount() { - string current("Bob"); - vector unreads; - unreads.push_back(UnreadPair("Bert", 2)); - unreads.push_back(UnreadPair("Beverly", 0)); - unreads.push_back(UnreadPair("Bob", 11)); - unreads.push_back(UnreadPair("Beatrice", 0)); - unreads.push_back(UnreadPair("Betty", 7)); - ChatMessageSummarizer summary; - CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads)); - } + ChatMessageSummarizerTest() {} + + void setUp() { + + } + + void testEmpty() { + string current(""); + vector unreads; + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads)); + } + + void testCurrentNone() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bob", 0)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(current, summary.getSummary(current, unreads)); + } + + void testCurrentCount() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bob", 3)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads)); + } + + void testCurrentCountOthersNone() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bert", 0)); + unreads.push_back(UnreadPair("Bob", 3)); + unreads.push_back(UnreadPair("Betty", 0)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(string("Bob (3)"), summary.getSummary(current, unreads)); + } + + void testCurrentCountOtherCount() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bert", 0)); + unreads.push_back(UnreadPair("Bob", 3)); + unreads.push_back(UnreadPair("Betty", 7)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(string("Bob (3); Betty (7)"), summary.getSummary(current, unreads)); + } + + void testCurrentNoneOtherCount() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bert", 0)); + unreads.push_back(UnreadPair("Bob", 0)); + unreads.push_back(UnreadPair("Betty", 7)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(string("Bob; Betty (7)"), summary.getSummary(current, unreads)); + } + + void testCurrentNoneOthersCount() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bert", 2)); + unreads.push_back(UnreadPair("Bob", 0)); + unreads.push_back(UnreadPair("Betty", 7)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(string("Bob and 2 others (9)"), summary.getSummary(current, unreads)); + } + + void testCurrentCountOthersCount() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bert", 2)); + unreads.push_back(UnreadPair("Bob", 11)); + unreads.push_back(UnreadPair("Betty", 7)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads)); + } + + void testCurrentCountSomeOthersCount() { + string current("Bob"); + vector unreads; + unreads.push_back(UnreadPair("Bert", 2)); + unreads.push_back(UnreadPair("Beverly", 0)); + unreads.push_back(UnreadPair("Bob", 11)); + unreads.push_back(UnreadPair("Beatrice", 0)); + unreads.push_back(UnreadPair("Betty", 7)); + ChatMessageSummarizer summary; + CPPUNIT_ASSERT_EQUAL(string("Bob (11) and 2 others (9)"), summary.getSummary(current, unreads)); + } }; diff --git a/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp b/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp index 9b625fe..2bfca4b 100644 --- a/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp +++ b/Swift/Controllers/UnitTest/ContactSuggesterTest.cpp @@ -18,111 +18,111 @@ using namespace Swift; class ContactSuggesterTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(ContactSuggesterTest); - CPPUNIT_TEST(equalityTest); - CPPUNIT_TEST(lexicographicalSortTest); - CPPUNIT_TEST(sortTest); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(ContactSuggesterTest); + CPPUNIT_TEST(equalityTest); + CPPUNIT_TEST(lexicographicalSortTest); + CPPUNIT_TEST(sortTest); + CPPUNIT_TEST_SUITE_END(); public: - std::vector wordList() { - const std::string words[] = { - "abc", - "ab", - "bc", - "d" - }; - - return std::vector(words, words+sizeof(words)/sizeof(*words)); - } - - std::vector statusList() { - StatusShow::Type types[] = { - StatusShow::Online, - StatusShow::Away, - StatusShow::FFC, - StatusShow::XA, - StatusShow::DND, - StatusShow::None - }; - - return std::vector(types, types+sizeof(types)/sizeof(*types)); - } - - std::vector contactList() { - std::vector contacts; - std::vector words = wordList(); - std::vector statuses = statusList(); - foreach (const std::string& name, words) { - foreach (const std::string& jid, words) { - foreach (const StatusShow::Type& status, statuses) { - contacts.push_back(boost::make_shared(name, jid, status, "")); - } - } - } - return contacts; - } - - /* a = a */ - bool isReflexive(const boost::function& comparitor) { - std::vector contacts = contactList(); - foreach (const Contact::ref& a, contacts) { - if (!comparitor(a, a)) { - return false; - } - } - return true; - } - - /* a = b -> b = a */ - bool isSymmetric(const boost::function& comparitor) { - std::vector contacts = contactList(); - foreach (const Contact::ref& a, contacts) { - foreach (const Contact::ref& b, contacts) { - if (comparitor(a, b)) { - if (!comparitor(b, a)) { - return false; - } - } - } - } - return true; - } - - /* a = b && b = c -> a = c */ - bool isTransitive(const boost::function& comparitor) { - std::vector contacts = contactList(); - foreach (const Contact::ref& a, contacts) { - foreach (const Contact::ref& b, contacts) { - foreach (const Contact::ref& c, contacts) { - if (comparitor(a, b) && comparitor(b, c)) { - if (!comparitor(a, c)) { - return false; - } - } - } - } - } - return true; - } - - void equalityTest() { - CPPUNIT_ASSERT(isReflexive(Contact::equalityPredicate)); - CPPUNIT_ASSERT(isSymmetric(Contact::equalityPredicate)); - CPPUNIT_ASSERT(isTransitive(Contact::equalityPredicate)); - } - - void lexicographicalSortTest() { - CPPUNIT_ASSERT(isTransitive(Contact::lexicographicalSortPredicate)); - } - - void sortTest() { - std::vector words = wordList(); - foreach (const std::string& word, words) { - CPPUNIT_ASSERT(isTransitive(boost::bind(Contact::sortPredicate, _1, _2, word))); - } - } + std::vector wordList() { + const std::string words[] = { + "abc", + "ab", + "bc", + "d" + }; + + return std::vector(words, words+sizeof(words)/sizeof(*words)); + } + + std::vector statusList() { + StatusShow::Type types[] = { + StatusShow::Online, + StatusShow::Away, + StatusShow::FFC, + StatusShow::XA, + StatusShow::DND, + StatusShow::None + }; + + return std::vector(types, types+sizeof(types)/sizeof(*types)); + } + + std::vector contactList() { + std::vector contacts; + std::vector words = wordList(); + std::vector statuses = statusList(); + foreach (const std::string& name, words) { + foreach (const std::string& jid, words) { + foreach (const StatusShow::Type& status, statuses) { + contacts.push_back(boost::make_shared(name, jid, status, "")); + } + } + } + return contacts; + } + + /* a = a */ + bool isReflexive(const boost::function& comparitor) { + std::vector contacts = contactList(); + foreach (const Contact::ref& a, contacts) { + if (!comparitor(a, a)) { + return false; + } + } + return true; + } + + /* a = b -> b = a */ + bool isSymmetric(const boost::function& comparitor) { + std::vector contacts = contactList(); + foreach (const Contact::ref& a, contacts) { + foreach (const Contact::ref& b, contacts) { + if (comparitor(a, b)) { + if (!comparitor(b, a)) { + return false; + } + } + } + } + return true; + } + + /* a = b && b = c -> a = c */ + bool isTransitive(const boost::function& comparitor) { + std::vector contacts = contactList(); + foreach (const Contact::ref& a, contacts) { + foreach (const Contact::ref& b, contacts) { + foreach (const Contact::ref& c, contacts) { + if (comparitor(a, b) && comparitor(b, c)) { + if (!comparitor(a, c)) { + return false; + } + } + } + } + } + return true; + } + + void equalityTest() { + CPPUNIT_ASSERT(isReflexive(Contact::equalityPredicate)); + CPPUNIT_ASSERT(isSymmetric(Contact::equalityPredicate)); + CPPUNIT_ASSERT(isTransitive(Contact::equalityPredicate)); + } + + void lexicographicalSortTest() { + CPPUNIT_ASSERT(isTransitive(Contact::lexicographicalSortPredicate)); + } + + void sortTest() { + std::vector words = wordList(); + foreach (const std::string& word, words) { + CPPUNIT_ASSERT(isTransitive(boost::bind(Contact::sortPredicate, _1, _2, word))); + } + } }; diff --git a/Swift/Controllers/UnitTest/HighlightRuleTest.cpp b/Swift/Controllers/UnitTest/HighlightRuleTest.cpp index 62c403f..8d49d5d 100644 --- a/Swift/Controllers/UnitTest/HighlightRuleTest.cpp +++ b/Swift/Controllers/UnitTest/HighlightRuleTest.cpp @@ -21,304 +21,304 @@ using namespace Swift; class HighlightRuleTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(HighlightRuleTest); - CPPUNIT_TEST(testEmptyRuleNeverMatches); - CPPUNIT_TEST(testKeyword); - CPPUNIT_TEST(testNickKeyword); - CPPUNIT_TEST(testNickWithoutOtherKeywords); - CPPUNIT_TEST(testSender); - CPPUNIT_TEST(testSenderAndKeyword); - CPPUNIT_TEST(testWholeWords); - CPPUNIT_TEST(testCase); - CPPUNIT_TEST(testWholeWordsAndCase); - CPPUNIT_TEST(testMUC); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - std::vector keywords; - keywords.push_back("keyword1"); - keywords.push_back("KEYWORD2"); - - std::vector senders; - senders.push_back("sender1"); - senders.push_back("SENDER2"); - - emptyRule = new HighlightRule(); - - keywordRule = new HighlightRule(); - keywordRule->setKeywords(keywords); - - keywordChatRule = new HighlightRule(); - keywordChatRule->setKeywords(keywords); - keywordChatRule->setMatchChat(true); - - keywordNickChatRule = new HighlightRule(); - keywordNickChatRule->setKeywords(keywords); - keywordNickChatRule->setNickIsKeyword(true); - keywordNickChatRule->setMatchChat(true); - - nickChatRule = new HighlightRule(); - nickChatRule->setNickIsKeyword(true); - nickChatRule->setMatchChat(true); - - nickRule = new HighlightRule(); - nickRule->setNickIsKeyword(true); - - senderRule = new HighlightRule(); - senderRule->setSenders(senders); - - senderChatRule = new HighlightRule(); - senderChatRule->setSenders(senders); - senderChatRule->setMatchChat(true); - - senderKeywordChatRule = new HighlightRule(); - senderKeywordChatRule->setSenders(senders); - senderKeywordChatRule->setKeywords(keywords); - senderKeywordChatRule->setMatchChat(true); - - senderKeywordNickChatRule = new HighlightRule(); - senderKeywordNickChatRule->setSenders(senders); - senderKeywordNickChatRule->setKeywords(keywords); - senderKeywordNickChatRule->setNickIsKeyword(true); - senderKeywordNickChatRule->setMatchChat(true); - - senderKeywordNickWordChatRule = new HighlightRule(); - senderKeywordNickWordChatRule->setSenders(senders); - senderKeywordNickWordChatRule->setKeywords(keywords); - senderKeywordNickWordChatRule->setNickIsKeyword(true); - senderKeywordNickWordChatRule->setMatchWholeWords(true); - senderKeywordNickWordChatRule->setMatchChat(true); - - senderKeywordNickCaseChatRule = new HighlightRule(); - senderKeywordNickCaseChatRule->setSenders(senders); - senderKeywordNickCaseChatRule->setKeywords(keywords); - senderKeywordNickCaseChatRule->setNickIsKeyword(true); - senderKeywordNickCaseChatRule->setMatchCase(true); - senderKeywordNickCaseChatRule->setMatchChat(true); - - senderKeywordNickCaseWordChatRule = new HighlightRule(); - senderKeywordNickCaseWordChatRule->setSenders(senders); - senderKeywordNickCaseWordChatRule->setKeywords(keywords); - senderKeywordNickCaseWordChatRule->setNickIsKeyword(true); - senderKeywordNickCaseWordChatRule->setMatchCase(true); - senderKeywordNickCaseWordChatRule->setMatchWholeWords(true); - senderKeywordNickCaseWordChatRule->setMatchChat(true); - - senderKeywordNickMUCRule = new HighlightRule(); - senderKeywordNickMUCRule->setSenders(senders); - senderKeywordNickMUCRule->setKeywords(keywords); - senderKeywordNickMUCRule->setNickIsKeyword(true); - senderKeywordNickMUCRule->setMatchMUC(true); - } + CPPUNIT_TEST_SUITE(HighlightRuleTest); + CPPUNIT_TEST(testEmptyRuleNeverMatches); + CPPUNIT_TEST(testKeyword); + CPPUNIT_TEST(testNickKeyword); + CPPUNIT_TEST(testNickWithoutOtherKeywords); + CPPUNIT_TEST(testSender); + CPPUNIT_TEST(testSenderAndKeyword); + CPPUNIT_TEST(testWholeWords); + CPPUNIT_TEST(testCase); + CPPUNIT_TEST(testWholeWordsAndCase); + CPPUNIT_TEST(testMUC); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + std::vector keywords; + keywords.push_back("keyword1"); + keywords.push_back("KEYWORD2"); + + std::vector senders; + senders.push_back("sender1"); + senders.push_back("SENDER2"); + + emptyRule = new HighlightRule(); + + keywordRule = new HighlightRule(); + keywordRule->setKeywords(keywords); + + keywordChatRule = new HighlightRule(); + keywordChatRule->setKeywords(keywords); + keywordChatRule->setMatchChat(true); + + keywordNickChatRule = new HighlightRule(); + keywordNickChatRule->setKeywords(keywords); + keywordNickChatRule->setNickIsKeyword(true); + keywordNickChatRule->setMatchChat(true); + + nickChatRule = new HighlightRule(); + nickChatRule->setNickIsKeyword(true); + nickChatRule->setMatchChat(true); + + nickRule = new HighlightRule(); + nickRule->setNickIsKeyword(true); + + senderRule = new HighlightRule(); + senderRule->setSenders(senders); + + senderChatRule = new HighlightRule(); + senderChatRule->setSenders(senders); + senderChatRule->setMatchChat(true); + + senderKeywordChatRule = new HighlightRule(); + senderKeywordChatRule->setSenders(senders); + senderKeywordChatRule->setKeywords(keywords); + senderKeywordChatRule->setMatchChat(true); + + senderKeywordNickChatRule = new HighlightRule(); + senderKeywordNickChatRule->setSenders(senders); + senderKeywordNickChatRule->setKeywords(keywords); + senderKeywordNickChatRule->setNickIsKeyword(true); + senderKeywordNickChatRule->setMatchChat(true); + + senderKeywordNickWordChatRule = new HighlightRule(); + senderKeywordNickWordChatRule->setSenders(senders); + senderKeywordNickWordChatRule->setKeywords(keywords); + senderKeywordNickWordChatRule->setNickIsKeyword(true); + senderKeywordNickWordChatRule->setMatchWholeWords(true); + senderKeywordNickWordChatRule->setMatchChat(true); + + senderKeywordNickCaseChatRule = new HighlightRule(); + senderKeywordNickCaseChatRule->setSenders(senders); + senderKeywordNickCaseChatRule->setKeywords(keywords); + senderKeywordNickCaseChatRule->setNickIsKeyword(true); + senderKeywordNickCaseChatRule->setMatchCase(true); + senderKeywordNickCaseChatRule->setMatchChat(true); + + senderKeywordNickCaseWordChatRule = new HighlightRule(); + senderKeywordNickCaseWordChatRule->setSenders(senders); + senderKeywordNickCaseWordChatRule->setKeywords(keywords); + senderKeywordNickCaseWordChatRule->setNickIsKeyword(true); + senderKeywordNickCaseWordChatRule->setMatchCase(true); + senderKeywordNickCaseWordChatRule->setMatchWholeWords(true); + senderKeywordNickCaseWordChatRule->setMatchChat(true); + + senderKeywordNickMUCRule = new HighlightRule(); + senderKeywordNickMUCRule->setSenders(senders); + senderKeywordNickMUCRule->setKeywords(keywords); + senderKeywordNickMUCRule->setNickIsKeyword(true); + senderKeywordNickMUCRule->setMatchMUC(true); + } - void tearDown() { - delete emptyRule; + void tearDown() { + delete emptyRule; - delete keywordRule; - delete keywordChatRule; - delete keywordNickChatRule; - delete nickChatRule; - delete nickRule; - - delete senderRule; - delete senderChatRule; - delete senderKeywordChatRule; - delete senderKeywordNickChatRule; + delete keywordRule; + delete keywordChatRule; + delete keywordNickChatRule; + delete nickChatRule; + delete nickRule; + + delete senderRule; + delete senderChatRule; + delete senderKeywordChatRule; + delete senderKeywordNickChatRule; - delete senderKeywordNickWordChatRule; - delete senderKeywordNickCaseChatRule; - delete senderKeywordNickCaseWordChatRule; + delete senderKeywordNickWordChatRule; + delete senderKeywordNickCaseChatRule; + delete senderKeywordNickCaseWordChatRule; - delete senderKeywordNickMUCRule; - } + delete senderKeywordNickMUCRule; + } - void testEmptyRuleNeverMatches() { - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false); + void testEmptyRuleNeverMatches() { + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "from", "", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("body", "", "", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "from", "", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::MUCMessage), false); - } + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(emptyRule->isMatch("", "", "", HighlightRule::MUCMessage), false); + } - void testKeyword() { - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false); + void testKeyword() { + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(keywordRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "sender contains keyword1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body", "sender contains keyword1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc keyword1 xyz", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abckeyword1xyz", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc keyword1 xyz", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abckeyword1xyz", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("KEYword1", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc KEYword1 xyz", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abcKEYword1xyz", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("KEYword1", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abc KEYword1 xyz", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("abcKEYword1xyz", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword2", "from", "nick", HighlightRule::ChatMessage), true); - } + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("keyword2", "from", "nick", HighlightRule::ChatMessage), true); + } - void testNickKeyword() { - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false); + void testNickKeyword() { + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(keywordChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "sender contains nick", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "sender contains nick", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains mixed-case NiCk", "sender", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body contains mixed-case NiCk", "sender", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false); - } + CPPUNIT_ASSERT_EQUAL(keywordNickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), false); + } - void testNickWithoutOtherKeywords() { - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(nickRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false); + void testNickWithoutOtherKeywords() { + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains nick", "from", "nick", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(nickRule->isMatch("body contains nick", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "sender contains nick but it does't matter", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "sender contains nick but it does't matter", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains mixed-case NiCk", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body contains mixed-case NiCk", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("nickname", "from", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("NIckNAME", "from", "nick", HighlightRule::ChatMessage), true); - // there are no keywords in this rule and empty nick is not treated as a keyword, so we don't check for keywords to get a match - CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), true); - } + // there are no keywords in this rule and empty nick is not treated as a keyword, so we don't check for keywords to get a match + CPPUNIT_ASSERT_EQUAL(nickChatRule->isMatch("body", "from", "", HighlightRule::ChatMessage), true); + } - void testSender() { - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false); + void testSender() { + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "from", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::MUCMessage), false); - CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender1", "nick", HighlightRule::MUCMessage), false); + CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body contains sender1", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderRule->isMatch("body contains sender1", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc sender1 xyz", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcsender1xyz", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc sender1 xyz", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcsender1xyz", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "SENDer1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc SENDer1 xyz", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcSENDer1xyz", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "SENDer1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abc SENDer1 xyz", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "abcSENDer1xyz", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender2", "nick", HighlightRule::ChatMessage), true); - } + CPPUNIT_ASSERT_EQUAL(senderChatRule->isMatch("body", "sender2", "nick", HighlightRule::ChatMessage), true); + } - void testSenderAndKeyword() { - CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); - } + void testSenderAndKeyword() { + CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); + } - void testWholeWords() { - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); + void testWholeWords() { + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), true); - } + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), true); + } - void testCase() { - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); + void testCase() { + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("xkeyword1", "xsender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("xkeyword1", "xsender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false); - } + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false); + } - void testWholeWordsAndCase() { - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); + void testWholeWordsAndCase() { + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "from", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("xkeyword1", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "xsender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::ChatMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains xnick", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false); - } + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("keyword1", "SENDer1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("KEYword1", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickCaseWordChatRule->isMatch("body contains NiCk", "sender1", "nick", HighlightRule::ChatMessage), false); + } - void testMUC() { - CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); + void testMUC() { + CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body", "from", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), false); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::MUCMessage), true); - CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::MUCMessage), true); - } + CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::ChatMessage), false); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("keyword1", "sender1", "nick", HighlightRule::MUCMessage), true); + CPPUNIT_ASSERT_EQUAL(senderKeywordNickMUCRule->isMatch("body contains nick", "sender1", "nick", HighlightRule::MUCMessage), true); + } - private: - HighlightRule* emptyRule; + private: + HighlightRule* emptyRule; - HighlightRule* keywordRule; - HighlightRule* keywordChatRule; - HighlightRule* keywordNickChatRule; - HighlightRule* nickChatRule; - HighlightRule* nickRule; + HighlightRule* keywordRule; + HighlightRule* keywordChatRule; + HighlightRule* keywordNickChatRule; + HighlightRule* nickChatRule; + HighlightRule* nickRule; - HighlightRule* senderRule; - HighlightRule* senderChatRule; - HighlightRule* senderKeywordChatRule; - HighlightRule* senderKeywordNickChatRule; + HighlightRule* senderRule; + HighlightRule* senderChatRule; + HighlightRule* senderKeywordChatRule; + HighlightRule* senderKeywordNickChatRule; - HighlightRule* senderKeywordNickWordChatRule; - HighlightRule* senderKeywordNickCaseChatRule; - HighlightRule* senderKeywordNickCaseWordChatRule; + HighlightRule* senderKeywordNickWordChatRule; + HighlightRule* senderKeywordNickCaseChatRule; + HighlightRule* senderKeywordNickCaseWordChatRule; - HighlightRule* senderKeywordNickMUCRule; + HighlightRule* senderKeywordNickMUCRule; }; CPPUNIT_TEST_SUITE_REGISTRATION(HighlightRuleTest); diff --git a/Swift/Controllers/UnitTest/MockChatWindow.h b/Swift/Controllers/UnitTest/MockChatWindow.h index 20c51bc..b4588e7 100644 --- a/Swift/Controllers/UnitTest/MockChatWindow.h +++ b/Swift/Controllers/UnitTest/MockChatWindow.h @@ -13,103 +13,103 @@ #include namespace Swift { - class MockChatWindow : public ChatWindow { - public: - MockChatWindow() : labelsEnabled_(false), impromptuMUCSupported_(false) {} - virtual ~MockChatWindow(); - - virtual std::string addMessage(const ChatMessage& message, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) { - lastMessageBody_ = bodyFromMessage(message); - return "id"; - } - - virtual std::string addAction(const ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {return "id";} - - virtual std::string addSystemMessage(const ChatMessage& message, Direction /*direction*/) { - lastAddedSystemMessage_ = message; - return "id"; - } - - virtual void addPresenceMessage(const ChatMessage& message, Direction /*direction*/) { - lastAddedPresence_ = message; - } - - virtual void addErrorMessage(const ChatMessage& /*message*/) {} - virtual void replaceMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {} - virtual void replaceWithAction(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {} - virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour /*timestampBehaviour*/) { - lastReplacedMessage_ = message; - } - virtual void replaceSystemMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const TimestampBehaviour /*timestampBehaviour*/) {} - - // File transfer related stuff - virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/,const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/) { return 0; } - virtual void setFileTransferProgress(std::string /*id*/, const int /*alreadyTransferedBytes*/) { } - virtual void setFileTransferStatus(std::string /*id*/, const FileTransferState /*state*/, const std::string& /*msg*/) { } - - virtual void setMessageReceiptState(const std::string &/* id */, ReceiptState /* state */) { } - - virtual void setContactChatState(ChatState::ChatStateType /*state*/) {} - virtual void setName(const std::string& name) {name_ = name;} - virtual void show() {} - virtual bool isVisible() const { return true; } - virtual void activate() {} - virtual void setAvailableSecurityLabels(const std::vector& labels) {labels_ = labels;} - virtual void setSecurityLabelsEnabled(bool enabled) {labelsEnabled_ = enabled;} - virtual void setUnreadMessageCount(int /*count*/) {} - virtual void convertToMUC(MUCType /*mucType*/) {} - virtual void setSecurityLabelsError() {} - virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() {return label_;} - virtual void setOnline(bool /*online*/) {} - virtual void setRosterModel(Roster* roster) { roster_ = roster; } - Roster* getRosterModel() { return roster_; } - virtual void setTabComplete(TabComplete*) {} - - void setAckState(const std::string& /*id*/, AckState /*state*/) {} - virtual void flash() {} - virtual AlertID addAlert(const std::string& /*alertText*/) { return 0; } - virtual void removeAlert(const AlertID /*id*/) {} - virtual void setCorrectionEnabled(Tristate /*enabled*/) {} - virtual void setFileTransferEnabled(Tristate /*enabled*/) {} - void setAvailableOccupantActions(const std::vector&/* actions*/) {} - void setSubject(const std::string& /*subject*/) {} - virtual void showRoomConfigurationForm(Form::ref) {} - virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool = true, bool = false, bool = false) {} - - virtual std::string addWhiteboardRequest(bool) {return "";} - virtual void setWhiteboardSessionStatus(std::string, const ChatWindow::WhiteboardSessionState){} - - virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector&) {} - virtual void setAvailableRoomActions(const std::vector &) {} - - virtual void setBlockingState(BlockingState) {} - virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) { - impromptuMUCSupported_ = supportsImpromptu; - } - - virtual void showBookmarkWindow(const MUCBookmark& /*bookmark*/) {} - virtual void setBookmarkState(RoomBookmarkState) {} - - static std::string bodyFromMessage(const ChatMessage& message) { - boost::shared_ptr text; - foreach (boost::shared_ptr part, message.getParts()) { - if ((text = boost::dynamic_pointer_cast(part))) { - return text->text; - } - } - return ""; - } - - std::string name_; - std::string lastMessageBody_; - ChatMessage lastAddedPresence_; - ChatMessage lastReplacedMessage_; - ChatMessage lastAddedSystemMessage_; - std::vector labels_; - bool labelsEnabled_; - bool impromptuMUCSupported_; - SecurityLabelsCatalog::Item label_; - Roster* roster_; - }; + class MockChatWindow : public ChatWindow { + public: + MockChatWindow() : labelsEnabled_(false), impromptuMUCSupported_(false) {} + virtual ~MockChatWindow(); + + virtual std::string addMessage(const ChatMessage& message, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) { + lastMessageBody_ = bodyFromMessage(message); + return "id"; + } + + virtual std::string addAction(const ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/) {return "id";} + + virtual std::string addSystemMessage(const ChatMessage& message, Direction /*direction*/) { + lastAddedSystemMessage_ = message; + return "id"; + } + + virtual void addPresenceMessage(const ChatMessage& message, Direction /*direction*/) { + lastAddedPresence_ = message; + } + + virtual void addErrorMessage(const ChatMessage& /*message*/) {} + virtual void replaceMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {} + virtual void replaceWithAction(const ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/) {} + virtual void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour /*timestampBehaviour*/) { + lastReplacedMessage_ = message; + } + virtual void replaceSystemMessage(const ChatMessage& /*message*/, const std::string& /*id*/, const TimestampBehaviour /*timestampBehaviour*/) {} + + // File transfer related stuff + virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/,const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/) { return 0; } + virtual void setFileTransferProgress(std::string /*id*/, const int /*alreadyTransferedBytes*/) { } + virtual void setFileTransferStatus(std::string /*id*/, const FileTransferState /*state*/, const std::string& /*msg*/) { } + + virtual void setMessageReceiptState(const std::string &/* id */, ReceiptState /* state */) { } + + virtual void setContactChatState(ChatState::ChatStateType /*state*/) {} + virtual void setName(const std::string& name) {name_ = name;} + virtual void show() {} + virtual bool isVisible() const { return true; } + virtual void activate() {} + virtual void setAvailableSecurityLabels(const std::vector& labels) {labels_ = labels;} + virtual void setSecurityLabelsEnabled(bool enabled) {labelsEnabled_ = enabled;} + virtual void setUnreadMessageCount(int /*count*/) {} + virtual void convertToMUC(MUCType /*mucType*/) {} + virtual void setSecurityLabelsError() {} + virtual SecurityLabelsCatalog::Item getSelectedSecurityLabel() {return label_;} + virtual void setOnline(bool /*online*/) {} + virtual void setRosterModel(Roster* roster) { roster_ = roster; } + Roster* getRosterModel() { return roster_; } + virtual void setTabComplete(TabComplete*) {} + + void setAckState(const std::string& /*id*/, AckState /*state*/) {} + virtual void flash() {} + virtual AlertID addAlert(const std::string& /*alertText*/) { return 0; } + virtual void removeAlert(const AlertID /*id*/) {} + virtual void setCorrectionEnabled(Tristate /*enabled*/) {} + virtual void setFileTransferEnabled(Tristate /*enabled*/) {} + void setAvailableOccupantActions(const std::vector&/* actions*/) {} + void setSubject(const std::string& /*subject*/) {} + virtual void showRoomConfigurationForm(Form::ref) {} + virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool = true, bool = false, bool = false) {} + + virtual std::string addWhiteboardRequest(bool) {return "";} + virtual void setWhiteboardSessionStatus(std::string, const ChatWindow::WhiteboardSessionState){} + + virtual void setAffiliations(MUCOccupant::Affiliation, const std::vector&) {} + virtual void setAvailableRoomActions(const std::vector &) {} + + virtual void setBlockingState(BlockingState) {} + virtual void setCanInitiateImpromptuChats(bool supportsImpromptu) { + impromptuMUCSupported_ = supportsImpromptu; + } + + virtual void showBookmarkWindow(const MUCBookmark& /*bookmark*/) {} + virtual void setBookmarkState(RoomBookmarkState) {} + + static std::string bodyFromMessage(const ChatMessage& message) { + boost::shared_ptr text; + foreach (boost::shared_ptr part, message.getParts()) { + if ((text = boost::dynamic_pointer_cast(part))) { + return text->text; + } + } + return ""; + } + + std::string name_; + std::string lastMessageBody_; + ChatMessage lastAddedPresence_; + ChatMessage lastReplacedMessage_; + ChatMessage lastAddedSystemMessage_; + std::vector labels_; + bool labelsEnabled_; + bool impromptuMUCSupported_; + SecurityLabelsCatalog::Item label_; + Roster* roster_; + }; } diff --git a/Swift/Controllers/UnitTest/MockMainWindow.h b/Swift/Controllers/UnitTest/MockMainWindow.h index af4267f..9177bdc 100644 --- a/Swift/Controllers/UnitTest/MockMainWindow.h +++ b/Swift/Controllers/UnitTest/MockMainWindow.h @@ -9,24 +9,24 @@ #include namespace Swift { - class Roster; - class MockMainWindow : public MainWindow { - public: - MockMainWindow() : roster(NULL) {} - virtual ~MockMainWindow() {} - virtual void setRosterModel(Roster* roster) {this->roster = roster;} - virtual void setMyNick(const std::string& /*name*/) {} - virtual void setMyJID(const JID& /*jid*/) {} - virtual void setMyAvatarPath(const std::string& /*path*/) {} - virtual void setMyStatusText(const std::string& /*status*/) {} - virtual void setMyStatusType(StatusShow::Type /*type*/) {} - virtual void setMyContactRosterItem(boost::shared_ptr /*contact*/) {} - virtual void setAvailableAdHocCommands(const std::vector& /*commands*/) {} - virtual void setConnecting() {} - virtual void setStreamEncryptionStatus(bool /*tlsInPlaceAndValid*/) {} - virtual void openCertificateDialog(const std::vector& /*chain*/) {} - virtual void setBlockingCommandAvailable(bool /*isAvailable*/) {} - Roster* roster; + class Roster; + class MockMainWindow : public MainWindow { + public: + MockMainWindow() : roster(NULL) {} + virtual ~MockMainWindow() {} + virtual void setRosterModel(Roster* roster) {this->roster = roster;} + virtual void setMyNick(const std::string& /*name*/) {} + virtual void setMyJID(const JID& /*jid*/) {} + virtual void setMyAvatarPath(const std::string& /*path*/) {} + virtual void setMyStatusText(const std::string& /*status*/) {} + virtual void setMyStatusType(StatusShow::Type /*type*/) {} + virtual void setMyContactRosterItem(boost::shared_ptr /*contact*/) {} + virtual void setAvailableAdHocCommands(const std::vector& /*commands*/) {} + virtual void setConnecting() {} + virtual void setStreamEncryptionStatus(bool /*tlsInPlaceAndValid*/) {} + virtual void openCertificateDialog(const std::vector& /*chain*/) {} + virtual void setBlockingCommandAvailable(bool /*isAvailable*/) {} + Roster* roster; - }; + }; } diff --git a/Swift/Controllers/UnitTest/MockMainWindowFactory.h b/Swift/Controllers/UnitTest/MockMainWindowFactory.h index 0298bf2..4af0c79 100644 --- a/Swift/Controllers/UnitTest/MockMainWindowFactory.h +++ b/Swift/Controllers/UnitTest/MockMainWindowFactory.h @@ -11,18 +11,18 @@ namespace Swift { - class MockMainWindowFactory : public MainWindowFactory { - public: - MockMainWindowFactory() : last(NULL) {} - - virtual ~MockMainWindowFactory() {} - - /** - * Transfers ownership of result. - */ - virtual MainWindow* createMainWindow(UIEventStream*) {last = new MockMainWindow();return last;} - MockMainWindow* last; - }; + class MockMainWindowFactory : public MainWindowFactory { + public: + MockMainWindowFactory() : last(NULL) {} + + virtual ~MockMainWindowFactory() {} + + /** + * Transfers ownership of result. + */ + virtual MainWindow* createMainWindow(UIEventStream*) {last = new MockMainWindow();return last;} + MockMainWindow* last; + }; } diff --git a/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp b/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp index 40530dc..e1284fd 100644 --- a/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp +++ b/Swift/Controllers/UnitTest/PresenceNotifierTest.cpp @@ -26,297 +26,297 @@ using namespace Swift; class PresenceNotifierTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(PresenceNotifierTest); - CPPUNIT_TEST(testReceiveFirstPresenceCreatesAvailableNotification); - CPPUNIT_TEST(testReceiveSecondPresenceCreatesStatusChangeNotification); - CPPUNIT_TEST(testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification); - CPPUNIT_TEST(testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification); - CPPUNIT_TEST(testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification); - CPPUNIT_TEST(testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification); - CPPUNIT_TEST(testReceiveAvailablePresenceFromMUCDoesNotCreateNotification); - CPPUNIT_TEST(testNotificationSubjectContainsNameForJIDInRoster); - CPPUNIT_TEST(testNotificationSubjectContainsJIDForJIDNotInRoster); - CPPUNIT_TEST(testNotificationSubjectContainsStatus); - CPPUNIT_TEST(testNotificationMessageContainsStatusMessage); - CPPUNIT_TEST(testNotificationPicture); - CPPUNIT_TEST(testNotificationActivationEmitsSignal); - CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotNotify); - CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod); - CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodDoesNotNotify); - CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodResetsTimer); - CPPUNIT_TEST(testReceivePresenceAfterQuietPeriodNotifies); - CPPUNIT_TEST(testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - stanzaChannel = new DummyStanzaChannel(); - notifier = new LoggingNotifier(); - mucRegistry = new MUCRegistry(); - user1 = JID("user1@bar.com/bla"); - user2 = JID("user2@foo.com/baz"); - avatarManager = new DummyAvatarManager(); - roster = new XMPPRosterImpl(); - nickResolver = new NickResolver(JID("foo@bar.com"), roster, NULL, mucRegistry); - presenceOracle = new PresenceOracle(stanzaChannel, roster); - timerFactory = new DummyTimerFactory(); - } - - void tearDown() { - delete timerFactory; - delete presenceOracle; - delete nickResolver; - delete roster; - delete avatarManager; - delete mucRegistry; - delete notifier; - delete stanzaChannel; - } - - void testReceiveFirstPresenceCreatesAvailableNotification() { - boost::shared_ptr testling = createNotifier(); - - sendPresence(user1, StatusShow::Online); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type); - } - - void testReceiveSecondPresenceCreatesStatusChangeNotification() { - boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Away); - notifier->notifications.clear(); - - sendPresence(user1, StatusShow::Online); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - CPPUNIT_ASSERT_EQUAL(Notifier::ContactStatusChange, notifier->notifications[0].type); - } - - void testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification() { - boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Away); - notifier->notifications.clear(); - - sendUnavailablePresence(user1); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - CPPUNIT_ASSERT_EQUAL(Notifier::ContactUnavailable, notifier->notifications[0].type); - } - - void testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification() { - boost::shared_ptr testling = createNotifier(); - - sendUnavailablePresence(user1); - - CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); - } - - void testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification() { - boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Away); - sendUnavailablePresence(user1); - notifier->notifications.clear(); - - sendPresence(user1, StatusShow::Away); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type); - } - - void testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification() { - boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Away); - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - notifier->notifications.clear(); - - sendPresence(user1, StatusShow::Away); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type); - } + CPPUNIT_TEST_SUITE(PresenceNotifierTest); + CPPUNIT_TEST(testReceiveFirstPresenceCreatesAvailableNotification); + CPPUNIT_TEST(testReceiveSecondPresenceCreatesStatusChangeNotification); + CPPUNIT_TEST(testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification); + CPPUNIT_TEST(testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification); + CPPUNIT_TEST(testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification); + CPPUNIT_TEST(testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification); + CPPUNIT_TEST(testReceiveAvailablePresenceFromMUCDoesNotCreateNotification); + CPPUNIT_TEST(testNotificationSubjectContainsNameForJIDInRoster); + CPPUNIT_TEST(testNotificationSubjectContainsJIDForJIDNotInRoster); + CPPUNIT_TEST(testNotificationSubjectContainsStatus); + CPPUNIT_TEST(testNotificationMessageContainsStatusMessage); + CPPUNIT_TEST(testNotificationPicture); + CPPUNIT_TEST(testNotificationActivationEmitsSignal); + CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotNotify); + CPPUNIT_TEST(testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod); + CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodDoesNotNotify); + CPPUNIT_TEST(testReceivePresenceDuringQuietPeriodResetsTimer); + CPPUNIT_TEST(testReceivePresenceAfterQuietPeriodNotifies); + CPPUNIT_TEST(testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify); + CPPUNIT_TEST_SUITE_END(); + + public: + void setUp() { + stanzaChannel = new DummyStanzaChannel(); + notifier = new LoggingNotifier(); + mucRegistry = new MUCRegistry(); + user1 = JID("user1@bar.com/bla"); + user2 = JID("user2@foo.com/baz"); + avatarManager = new DummyAvatarManager(); + roster = new XMPPRosterImpl(); + nickResolver = new NickResolver(JID("foo@bar.com"), roster, NULL, mucRegistry); + presenceOracle = new PresenceOracle(stanzaChannel, roster); + timerFactory = new DummyTimerFactory(); + } + + void tearDown() { + delete timerFactory; + delete presenceOracle; + delete nickResolver; + delete roster; + delete avatarManager; + delete mucRegistry; + delete notifier; + delete stanzaChannel; + } + + void testReceiveFirstPresenceCreatesAvailableNotification() { + boost::shared_ptr testling = createNotifier(); + + sendPresence(user1, StatusShow::Online); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type); + } + + void testReceiveSecondPresenceCreatesStatusChangeNotification() { + boost::shared_ptr testling = createNotifier(); + sendPresence(user1, StatusShow::Away); + notifier->notifications.clear(); + + sendPresence(user1, StatusShow::Online); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + CPPUNIT_ASSERT_EQUAL(Notifier::ContactStatusChange, notifier->notifications[0].type); + } + + void testReceiveUnavailablePresenceAfterAvailablePresenceCreatesUnavailableNotification() { + boost::shared_ptr testling = createNotifier(); + sendPresence(user1, StatusShow::Away); + notifier->notifications.clear(); + + sendUnavailablePresence(user1); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + CPPUNIT_ASSERT_EQUAL(Notifier::ContactUnavailable, notifier->notifications[0].type); + } + + void testReceiveUnavailablePresenceWithoutAvailableDoesNotCreateNotification() { + boost::shared_ptr testling = createNotifier(); + + sendUnavailablePresence(user1); + + CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); + } + + void testReceiveAvailablePresenceAfterUnavailableCreatesAvailableNotification() { + boost::shared_ptr testling = createNotifier(); + sendPresence(user1, StatusShow::Away); + sendUnavailablePresence(user1); + notifier->notifications.clear(); + + sendPresence(user1, StatusShow::Away); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type); + } + + void testReceiveAvailablePresenceAfterReconnectCreatesAvailableNotification() { + boost::shared_ptr testling = createNotifier(); + sendPresence(user1, StatusShow::Away); + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + notifier->notifications.clear(); + + sendPresence(user1, StatusShow::Away); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + CPPUNIT_ASSERT_EQUAL(Notifier::ContactAvailable, notifier->notifications[0].type); + } - void testReceiveAvailablePresenceFromMUCDoesNotCreateNotification() { - boost::shared_ptr testling = createNotifier(); - mucRegistry->addMUC(JID("teaparty@wonderland.lit")); + void testReceiveAvailablePresenceFromMUCDoesNotCreateNotification() { + boost::shared_ptr testling = createNotifier(); + mucRegistry->addMUC(JID("teaparty@wonderland.lit")); - sendPresence(JID("teaparty@wonderland.lit/Alice"), StatusShow::Away); + sendPresence(JID("teaparty@wonderland.lit/Alice"), StatusShow::Away); - CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); - } + CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); + } - void testNotificationPicture() { - boost::shared_ptr testling = createNotifier(); - avatarManager->avatars[user1] = createByteArray("abcdef"); + void testNotificationPicture() { + boost::shared_ptr testling = createNotifier(); + avatarManager->avatars[user1] = createByteArray("abcdef"); - sendPresence(user1, StatusShow::Online); + sendPresence(user1, StatusShow::Online); - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - CPPUNIT_ASSERT_EQUAL(boost::filesystem::path("/avatars/user1@bar.com/bla"), notifier->notifications[0].picture); - } + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + CPPUNIT_ASSERT_EQUAL(boost::filesystem::path("/avatars/user1@bar.com/bla"), notifier->notifications[0].picture); + } - void testNotificationActivationEmitsSignal() { - boost::shared_ptr testling = createNotifier(); + void testNotificationActivationEmitsSignal() { + boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Online); - CPPUNIT_ASSERT(notifier->notifications[0].callback); - notifier->notifications[0].callback(); + sendPresence(user1, StatusShow::Online); + CPPUNIT_ASSERT(notifier->notifications[0].callback); + notifier->notifications[0].callback(); - CPPUNIT_ASSERT_EQUAL(1, static_cast(activatedNotifications.size())); - CPPUNIT_ASSERT_EQUAL(user1, activatedNotifications[0]); - } + CPPUNIT_ASSERT_EQUAL(1, static_cast(activatedNotifications.size())); + CPPUNIT_ASSERT_EQUAL(user1, activatedNotifications[0]); + } - void testNotificationSubjectContainsNameForJIDInRoster() { - boost::shared_ptr testling = createNotifier(); - roster->addContact(user1.toBare(), "User 1", std::vector(), RosterItemPayload::Both); + void testNotificationSubjectContainsNameForJIDInRoster() { + boost::shared_ptr testling = createNotifier(); + roster->addContact(user1.toBare(), "User 1", std::vector(), RosterItemPayload::Both); - sendPresence(user1, StatusShow::Online); + sendPresence(user1, StatusShow::Online); - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - std::string subject = notifier->notifications[0].subject; - CPPUNIT_ASSERT(subject.find("User 1") != std::string::npos); - } + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + std::string subject = notifier->notifications[0].subject; + CPPUNIT_ASSERT(subject.find("User 1") != std::string::npos); + } - void testNotificationSubjectContainsJIDForJIDNotInRoster() { - boost::shared_ptr testling = createNotifier(); + void testNotificationSubjectContainsJIDForJIDNotInRoster() { + boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Online); + sendPresence(user1, StatusShow::Online); - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - std::string subject = notifier->notifications[0].subject; - CPPUNIT_ASSERT(subject.find(user1.toBare().toString()) != std::string::npos); - } + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + std::string subject = notifier->notifications[0].subject; + CPPUNIT_ASSERT(subject.find(user1.toBare().toString()) != std::string::npos); + } - void testNotificationSubjectContainsStatus() { - boost::shared_ptr testling = createNotifier(); + void testNotificationSubjectContainsStatus() { + boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Away); + sendPresence(user1, StatusShow::Away); - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - std::string subject = notifier->notifications[0].subject; - CPPUNIT_ASSERT(subject.find("Away") != std::string::npos); - } + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + std::string subject = notifier->notifications[0].subject; + CPPUNIT_ASSERT(subject.find("Away") != std::string::npos); + } - void testNotificationMessageContainsStatusMessage() { - boost::shared_ptr testling = createNotifier(); + void testNotificationMessageContainsStatusMessage() { + boost::shared_ptr testling = createNotifier(); - sendPresence(user1, StatusShow::Away); + sendPresence(user1, StatusShow::Away); - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - CPPUNIT_ASSERT(notifier->notifications[0].description.find("Status Message") != std::string::npos); - } + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + CPPUNIT_ASSERT(notifier->notifications[0].description.find("Status Message") != std::string::npos); + } - void testReceiveFirstPresenceWithQuietPeriodDoesNotNotify() { - boost::shared_ptr testling = createNotifier(); - testling->setInitialQuietPeriodMS(10); + void testReceiveFirstPresenceWithQuietPeriodDoesNotNotify() { + boost::shared_ptr testling = createNotifier(); + testling->setInitialQuietPeriodMS(10); - sendPresence(user1, StatusShow::Online); + sendPresence(user1, StatusShow::Online); - CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); - } + CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); + } - void testReceivePresenceDuringQuietPeriodDoesNotNotify() { - boost::shared_ptr testling = createNotifier(); - testling->setInitialQuietPeriodMS(10); + void testReceivePresenceDuringQuietPeriodDoesNotNotify() { + boost::shared_ptr testling = createNotifier(); + testling->setInitialQuietPeriodMS(10); - sendPresence(user1, StatusShow::Online); - timerFactory->setTime(1); - sendPresence(user2, StatusShow::Away); + sendPresence(user1, StatusShow::Online); + timerFactory->setTime(1); + sendPresence(user2, StatusShow::Away); - CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); - } + CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); + } - void testReceivePresenceDuringQuietPeriodResetsTimer() { - boost::shared_ptr testling = createNotifier(); - testling->setInitialQuietPeriodMS(10); + void testReceivePresenceDuringQuietPeriodResetsTimer() { + boost::shared_ptr testling = createNotifier(); + testling->setInitialQuietPeriodMS(10); - sendPresence(user1, StatusShow::Online); - timerFactory->setTime(9); - sendPresence(user2, StatusShow::Away); - timerFactory->setTime(18); - sendPresence(user1, StatusShow::Away); + sendPresence(user1, StatusShow::Online); + timerFactory->setTime(9); + sendPresence(user2, StatusShow::Away); + timerFactory->setTime(18); + sendPresence(user1, StatusShow::Away); - CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); - } + CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); + } - void testReceivePresenceAfterQuietPeriodNotifies() { - boost::shared_ptr testling = createNotifier(); - testling->setInitialQuietPeriodMS(10); - - sendPresence(user1, StatusShow::Online); - timerFactory->setTime(11); - sendPresence(user2, StatusShow::Away); - - CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); - } - - void testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod() { - boost::shared_ptr testling = createNotifier(); - testling->setInitialQuietPeriodMS(10); - - timerFactory->setTime(11); - sendPresence(user1, StatusShow::Away); - - CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); - } - - void testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify() { - boost::shared_ptr testling = createNotifier(); - testling->setInitialQuietPeriodMS(10); - sendPresence(user1, StatusShow::Online); - timerFactory->setTime(15); - notifier->notifications.clear(); - - stanzaChannel->setAvailable(false); - stanzaChannel->setAvailable(true); - sendPresence(user1, StatusShow::Online); - timerFactory->setTime(21); - sendPresence(user2, StatusShow::Online); - - CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); - } - - - private: - boost::shared_ptr createNotifier() { - boost::shared_ptr result(new PresenceNotifier(stanzaChannel, notifier, mucRegistry, avatarManager, nickResolver, presenceOracle, timerFactory)); - result->onNotificationActivated.connect(boost::bind(&PresenceNotifierTest::handleNotificationActivated, this, _1)); - result->setInitialQuietPeriodMS(0); - return result; - } - - void sendPresence(const JID& jid, StatusShow::Type type) { - boost::shared_ptr presence(new Presence()); - presence->setFrom(jid); - presence->setShow(type); - presence->setStatus("Status Message"); - stanzaChannel->onPresenceReceived(presence); - } - - void sendUnavailablePresence(const JID& jid) { - boost::shared_ptr presence(new Presence()); - presence->setType(Presence::Unavailable); - presence->setFrom(jid); - stanzaChannel->onPresenceReceived(presence); - } - - void handleNotificationActivated(const JID& j) { - activatedNotifications.push_back(j); - } - - private: - DummyStanzaChannel* stanzaChannel; - LoggingNotifier* notifier; - MUCRegistry* mucRegistry; - DummyAvatarManager* avatarManager; - XMPPRosterImpl* roster; - NickResolver* nickResolver; - PresenceOracle* presenceOracle; - DummyTimerFactory* timerFactory; - JID user1; - JID user2; - std::vector activatedNotifications; + void testReceivePresenceAfterQuietPeriodNotifies() { + boost::shared_ptr testling = createNotifier(); + testling->setInitialQuietPeriodMS(10); + + sendPresence(user1, StatusShow::Online); + timerFactory->setTime(11); + sendPresence(user2, StatusShow::Away); + + CPPUNIT_ASSERT_EQUAL(1, static_cast(notifier->notifications.size())); + } + + void testReceiveFirstPresenceWithQuietPeriodDoesNotCountAsQuietPeriod() { + boost::shared_ptr testling = createNotifier(); + testling->setInitialQuietPeriodMS(10); + + timerFactory->setTime(11); + sendPresence(user1, StatusShow::Away); + + CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); + } + + void testReceiveFirstPresenceAfterReconnectWithQuietPeriodDoesNotNotify() { + boost::shared_ptr testling = createNotifier(); + testling->setInitialQuietPeriodMS(10); + sendPresence(user1, StatusShow::Online); + timerFactory->setTime(15); + notifier->notifications.clear(); + + stanzaChannel->setAvailable(false); + stanzaChannel->setAvailable(true); + sendPresence(user1, StatusShow::Online); + timerFactory->setTime(21); + sendPresence(user2, StatusShow::Online); + + CPPUNIT_ASSERT_EQUAL(0, static_cast(notifier->notifications.size())); + } + + + private: + boost::shared_ptr createNotifier() { + boost::shared_ptr result(new PresenceNotifier(stanzaChannel, notifier, mucRegistry, avatarManager, nickResolver, presenceOracle, timerFactory)); + result->onNotificationActivated.connect(boost::bind(&PresenceNotifierTest::handleNotificationActivated, this, _1)); + result->setInitialQuietPeriodMS(0); + return result; + } + + void sendPresence(const JID& jid, StatusShow::Type type) { + boost::shared_ptr presence(new Presence()); + presence->setFrom(jid); + presence->setShow(type); + presence->setStatus("Status Message"); + stanzaChannel->onPresenceReceived(presence); + } + + void sendUnavailablePresence(const JID& jid) { + boost::shared_ptr presence(new Presence()); + presence->setType(Presence::Unavailable); + presence->setFrom(jid); + stanzaChannel->onPresenceReceived(presence); + } + + void handleNotificationActivated(const JID& j) { + activatedNotifications.push_back(j); + } + + private: + DummyStanzaChannel* stanzaChannel; + LoggingNotifier* notifier; + MUCRegistry* mucRegistry; + DummyAvatarManager* avatarManager; + XMPPRosterImpl* roster; + NickResolver* nickResolver; + PresenceOracle* presenceOracle; + DummyTimerFactory* timerFactory; + JID user1; + JID user2; + std::vector activatedNotifications; }; CPPUNIT_TEST_SUITE_REGISTRATION(PresenceNotifierTest); diff --git a/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp b/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp index 266cd64..be35468 100644 --- a/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp +++ b/Swift/Controllers/UnitTest/PreviousStatusStoreTest.cpp @@ -12,33 +12,33 @@ using namespace Swift; class PreviousStatusStoreTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(PreviousStatusStoreTest); - CPPUNIT_TEST(testGetAll); - //CPPUNIT_TEST(testGetAllLimited); - //CPPUNIT_TEST(testGetSuggestionsInexact); - //CPPUNIT_TEST(testGetSuggestionsExact); - CPPUNIT_TEST_SUITE_END(); + CPPUNIT_TEST_SUITE(PreviousStatusStoreTest); + CPPUNIT_TEST(testGetAll); + //CPPUNIT_TEST(testGetAllLimited); + //CPPUNIT_TEST(testGetSuggestionsInexact); + //CPPUNIT_TEST(testGetSuggestionsExact); + CPPUNIT_TEST_SUITE_END(); public: - void setUp() { - store_ = new PreviousStatusStore(); - store_->addStatus(StatusShow::Online, "At home in the study"); - store_->addStatus(StatusShow::DND, "In a meeting"); - store_->addStatus(StatusShow::DND, "With a client"); - store_->addStatus(StatusShow::Away, "Walking the elephant"); - store_->addStatus(StatusShow::Online, "In the office, at my desk"); - } + void setUp() { + store_ = new PreviousStatusStore(); + store_->addStatus(StatusShow::Online, "At home in the study"); + store_->addStatus(StatusShow::DND, "In a meeting"); + store_->addStatus(StatusShow::DND, "With a client"); + store_->addStatus(StatusShow::Away, "Walking the elephant"); + store_->addStatus(StatusShow::Online, "In the office, at my desk"); + } - void tearDown() { - delete store_; - } + void tearDown() { + delete store_; + } - void testGetAll() { + void testGetAll() { - } + } private: - PreviousStatusStore* store_; + PreviousStatusStore* store_; }; CPPUNIT_TEST_SUITE_REGISTRATION(PreviousStatusStoreTest); diff --git a/Swift/Controllers/WhiteboardManager.cpp b/Swift/Controllers/WhiteboardManager.cpp index f62a94a..91f01c8 100644 --- a/Swift/Controllers/WhiteboardManager.cpp +++ b/Swift/Controllers/WhiteboardManager.cpp @@ -25,121 +25,121 @@ #include namespace Swift { - typedef std::pair JIDWhiteboardWindowPair; + typedef std::pair JIDWhiteboardWindowPair; - WhiteboardManager::WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager) : whiteboardWindowFactory_(whiteboardWindowFactory), uiEventStream_(uiEventStream), nickResolver_(nickResolver), whiteboardSessionManager_(whiteboardSessionManager) { + WhiteboardManager::WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager) : whiteboardWindowFactory_(whiteboardWindowFactory), uiEventStream_(uiEventStream), nickResolver_(nickResolver), whiteboardSessionManager_(whiteboardSessionManager) { #ifdef SWIFT_EXPERIMENTAL_WB - whiteboardSessionManager_->onSessionRequest.connect(boost::bind(&WhiteboardManager::handleIncomingSession, this, _1)); + whiteboardSessionManager_->onSessionRequest.connect(boost::bind(&WhiteboardManager::handleIncomingSession, this, _1)); #endif - uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&WhiteboardManager::handleUIEvent, this, _1)); - } - - WhiteboardManager::~WhiteboardManager() { - foreach (JIDWhiteboardWindowPair whiteboardWindowPair, whiteboardWindows_) { - delete whiteboardWindowPair.second; - } - } - - WhiteboardWindow* WhiteboardManager::createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session) { - WhiteboardWindow *window = whiteboardWindowFactory_->createWhiteboardWindow(session); - window->setName(nickResolver_->jidToNick(contact)); - whiteboardWindows_[contact.toBare()] = window; - return window; - } - - WhiteboardWindow* WhiteboardManager::findWhiteboardWindow(const JID& contact) { - if (whiteboardWindows_.find(contact.toBare()) == whiteboardWindows_.end()) { - return NULL; - } - return whiteboardWindows_[contact.toBare()]; - } - - void WhiteboardManager::handleUIEvent(boost::shared_ptr event) { - boost::shared_ptr requestWhiteboardEvent = boost::dynamic_pointer_cast(event); - if (requestWhiteboardEvent) { - requestSession(requestWhiteboardEvent->getContact()); - } - boost::shared_ptr sessionAcceptEvent = boost::dynamic_pointer_cast(event); - if (sessionAcceptEvent) { - acceptSession(sessionAcceptEvent->getContact()); - } - boost::shared_ptr sessionCancelEvent = boost::dynamic_pointer_cast(event); - if (sessionCancelEvent) { - cancelSession(sessionCancelEvent->getContact()); - } - boost::shared_ptr showWindowEvent = boost::dynamic_pointer_cast(event); - if (showWindowEvent) { - WhiteboardWindow* window = findWhiteboardWindow(showWindowEvent->getContact()); - if (window != NULL) { - window->activateWindow(); - } - } - } - - void WhiteboardManager::acceptSession(const JID& from) { - IncomingWhiteboardSession::ref session = boost::dynamic_pointer_cast(whiteboardSessionManager_->getSession(from)); - WhiteboardWindow* window = findWhiteboardWindow(from); - if (session && window) { - session->accept(); - window->show(); - } - } - - void WhiteboardManager::requestSession(const JID& contact) { - WhiteboardSession::ref session = whiteboardSessionManager_->requestSession(contact); - session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1)); - session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1)); - session->onRequestRejected.connect(boost::bind(&WhiteboardManager::handleRequestReject, this, _1)); - - WhiteboardWindow* window = findWhiteboardWindow(contact); - if (window == NULL) { - createNewWhiteboardWindow(contact, session); - } else { - window->setSession(session); - } - onSessionRequest(session->getTo(), true); - } - - void WhiteboardManager::cancelSession(const JID& from) { - WhiteboardSession::ref session = whiteboardSessionManager_->getSession(from); - if (session) { - session->cancel(); - } - } - - void WhiteboardManager::handleIncomingSession(IncomingWhiteboardSession::ref session) { - session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1)); - session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1)); - - WhiteboardWindow* window = findWhiteboardWindow(session->getTo()); - if (window == NULL) { - createNewWhiteboardWindow(session->getTo(), session); - } else { - window->setSession(session); - } - - onSessionRequest(session->getTo(), false); - } - - void WhiteboardManager::handleSessionTerminate(const JID& contact) { - onSessionTerminate(contact); - } - - void WhiteboardManager::handleSessionCancel(const JID& contact) { - onSessionTerminate(contact); - } - - void WhiteboardManager::handleSessionAccept(const JID& contact) { - WhiteboardWindow* window = findWhiteboardWindow(contact); - if (window != NULL) { - window->show(); - } - onRequestAccepted(contact); - } - - void WhiteboardManager::handleRequestReject(const JID& contact) { - onRequestRejected(contact); - } + uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&WhiteboardManager::handleUIEvent, this, _1)); + } + + WhiteboardManager::~WhiteboardManager() { + foreach (JIDWhiteboardWindowPair whiteboardWindowPair, whiteboardWindows_) { + delete whiteboardWindowPair.second; + } + } + + WhiteboardWindow* WhiteboardManager::createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session) { + WhiteboardWindow *window = whiteboardWindowFactory_->createWhiteboardWindow(session); + window->setName(nickResolver_->jidToNick(contact)); + whiteboardWindows_[contact.toBare()] = window; + return window; + } + + WhiteboardWindow* WhiteboardManager::findWhiteboardWindow(const JID& contact) { + if (whiteboardWindows_.find(contact.toBare()) == whiteboardWindows_.end()) { + return NULL; + } + return whiteboardWindows_[contact.toBare()]; + } + + void WhiteboardManager::handleUIEvent(boost::shared_ptr event) { + boost::shared_ptr requestWhiteboardEvent = boost::dynamic_pointer_cast(event); + if (requestWhiteboardEvent) { + requestSession(requestWhiteboardEvent->getContact()); + } + boost::shared_ptr sessionAcceptEvent = boost::dynamic_pointer_cast(event); + if (sessionAcceptEvent) { + acceptSession(sessionAcceptEvent->getContact()); + } + boost::shared_ptr sessionCancelEvent = boost::dynamic_pointer_cast(event); + if (sessionCancelEvent) { + cancelSession(sessionCancelEvent->getContact()); + } + boost::shared_ptr showWindowEvent = boost::dynamic_pointer_cast(event); + if (showWindowEvent) { + WhiteboardWindow* window = findWhiteboardWindow(showWindowEvent->getContact()); + if (window != NULL) { + window->activateWindow(); + } + } + } + + void WhiteboardManager::acceptSession(const JID& from) { + IncomingWhiteboardSession::ref session = boost::dynamic_pointer_cast(whiteboardSessionManager_->getSession(from)); + WhiteboardWindow* window = findWhiteboardWindow(from); + if (session && window) { + session->accept(); + window->show(); + } + } + + void WhiteboardManager::requestSession(const JID& contact) { + WhiteboardSession::ref session = whiteboardSessionManager_->requestSession(contact); + session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1)); + session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1)); + session->onRequestRejected.connect(boost::bind(&WhiteboardManager::handleRequestReject, this, _1)); + + WhiteboardWindow* window = findWhiteboardWindow(contact); + if (window == NULL) { + createNewWhiteboardWindow(contact, session); + } else { + window->setSession(session); + } + onSessionRequest(session->getTo(), true); + } + + void WhiteboardManager::cancelSession(const JID& from) { + WhiteboardSession::ref session = whiteboardSessionManager_->getSession(from); + if (session) { + session->cancel(); + } + } + + void WhiteboardManager::handleIncomingSession(IncomingWhiteboardSession::ref session) { + session->onSessionTerminated.connect(boost::bind(&WhiteboardManager::handleSessionTerminate, this, _1)); + session->onRequestAccepted.connect(boost::bind(&WhiteboardManager::handleSessionAccept, this, _1)); + + WhiteboardWindow* window = findWhiteboardWindow(session->getTo()); + if (window == NULL) { + createNewWhiteboardWindow(session->getTo(), session); + } else { + window->setSession(session); + } + + onSessionRequest(session->getTo(), false); + } + + void WhiteboardManager::handleSessionTerminate(const JID& contact) { + onSessionTerminate(contact); + } + + void WhiteboardManager::handleSessionCancel(const JID& contact) { + onSessionTerminate(contact); + } + + void WhiteboardManager::handleSessionAccept(const JID& contact) { + WhiteboardWindow* window = findWhiteboardWindow(contact); + if (window != NULL) { + window->show(); + } + onRequestAccepted(contact); + } + + void WhiteboardManager::handleRequestReject(const JID& contact) { + onRequestRejected(contact); + } } diff --git a/Swift/Controllers/WhiteboardManager.h b/Swift/Controllers/WhiteboardManager.h index 863dd60..35ed9bd 100644 --- a/Swift/Controllers/WhiteboardManager.h +++ b/Swift/Controllers/WhiteboardManager.h @@ -26,40 +26,40 @@ #include namespace Swift { - class WhiteboardSessionManager; - class NickResolver; + class WhiteboardSessionManager; + class NickResolver; - class WhiteboardManager { - public: - WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager); - ~WhiteboardManager(); + class WhiteboardManager { + public: + WhiteboardManager(WhiteboardWindowFactory* whiteboardWindowFactory, UIEventStream* uiEventStream, NickResolver* nickResolver, WhiteboardSessionManager* whiteboardSessionManager); + ~WhiteboardManager(); - WhiteboardWindow* createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session); + WhiteboardWindow* createNewWhiteboardWindow(const JID& contact, WhiteboardSession::ref session); - public: - boost::signal< void (const JID&, bool senderIsSelf)> onSessionRequest; - boost::signal< void (const JID&)> onSessionTerminate; - boost::signal< void (const JID&)> onRequestAccepted; - boost::signal< void (const JID&)> onRequestRejected; + public: + boost::signal< void (const JID&, bool senderIsSelf)> onSessionRequest; + boost::signal< void (const JID&)> onSessionTerminate; + boost::signal< void (const JID&)> onRequestAccepted; + boost::signal< void (const JID&)> onRequestRejected; - private: - void handleUIEvent(boost::shared_ptr event); - void handleSessionTerminate(const JID& contact); - void handleSessionCancel(const JID& contact); - void handleSessionAccept(const JID& contact); - void handleRequestReject(const JID& contact); - void handleIncomingSession(IncomingWhiteboardSession::ref session); - void acceptSession(const JID& from); - void requestSession(const JID& contact); - void cancelSession(const JID& from); - WhiteboardWindow* findWhiteboardWindow(const JID& contact); + private: + void handleUIEvent(boost::shared_ptr event); + void handleSessionTerminate(const JID& contact); + void handleSessionCancel(const JID& contact); + void handleSessionAccept(const JID& contact); + void handleRequestReject(const JID& contact); + void handleIncomingSession(IncomingWhiteboardSession::ref session); + void acceptSession(const JID& from); + void requestSession(const JID& contact); + void cancelSession(const JID& from); + WhiteboardWindow* findWhiteboardWindow(const JID& contact); - private: - std::map whiteboardWindows_; - WhiteboardWindowFactory* whiteboardWindowFactory_; - UIEventStream* uiEventStream_; - NickResolver* nickResolver_; - boost::bsignals::scoped_connection uiEventConnection_; - WhiteboardSessionManager* whiteboardSessionManager_; - }; + private: + std::map whiteboardWindows_; + WhiteboardWindowFactory* whiteboardWindowFactory_; + UIEventStream* uiEventStream_; + NickResolver* nickResolver_; + boost::bsignals::scoped_connection uiEventConnection_; + WhiteboardSessionManager* whiteboardSessionManager_; + }; } diff --git a/Swift/Controllers/XMLConsoleController.cpp b/Swift/Controllers/XMLConsoleController.cpp index 22be4f6..175a4eb 100644 --- a/Swift/Controllers/XMLConsoleController.cpp +++ b/Swift/Controllers/XMLConsoleController.cpp @@ -12,34 +12,34 @@ namespace Swift { XMLConsoleController::XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory) : xmlConsoleWidgetFactory(xmlConsoleWidgetFactory), xmlConsoleWidget(NULL) { - uiEventStream->onUIEvent.connect(boost::bind(&XMLConsoleController::handleUIEvent, this, _1)); + uiEventStream->onUIEvent.connect(boost::bind(&XMLConsoleController::handleUIEvent, this, _1)); } XMLConsoleController::~XMLConsoleController() { - delete xmlConsoleWidget; + delete xmlConsoleWidget; } void XMLConsoleController::handleUIEvent(boost::shared_ptr rawEvent) { - boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); - if (event != NULL) { - if (xmlConsoleWidget == NULL) { - xmlConsoleWidget = xmlConsoleWidgetFactory->createXMLConsoleWidget(); - } - xmlConsoleWidget->show(); - xmlConsoleWidget->activate(); - } + boost::shared_ptr event = boost::dynamic_pointer_cast(rawEvent); + if (event != NULL) { + if (xmlConsoleWidget == NULL) { + xmlConsoleWidget = xmlConsoleWidgetFactory->createXMLConsoleWidget(); + } + xmlConsoleWidget->show(); + xmlConsoleWidget->activate(); + } } void XMLConsoleController::handleDataRead(const SafeByteArray& data) { - if (xmlConsoleWidget) { - xmlConsoleWidget->handleDataRead(data); - } + if (xmlConsoleWidget) { + xmlConsoleWidget->handleDataRead(data); + } } void XMLConsoleController::handleDataWritten(const SafeByteArray& data) { - if (xmlConsoleWidget) { - xmlConsoleWidget->handleDataWritten(data); - } + if (xmlConsoleWidget) { + xmlConsoleWidget->handleDataWritten(data); + } } } diff --git a/Swift/Controllers/XMLConsoleController.h b/Swift/Controllers/XMLConsoleController.h index bd4d256..eac27d3 100644 --- a/Swift/Controllers/XMLConsoleController.h +++ b/Swift/Controllers/XMLConsoleController.h @@ -15,24 +15,24 @@ #include namespace Swift { - - class XMLConsoleWidgetFactory; - class XMLConsoleWidget; - - class XMLConsoleController { - public: - XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory); - ~XMLConsoleController(); - - public: - void handleDataRead(const SafeByteArray& data); - void handleDataWritten(const SafeByteArray& data); - - private: - void handleUIEvent(boost::shared_ptr event); - - private: - XMLConsoleWidgetFactory* xmlConsoleWidgetFactory; - XMLConsoleWidget* xmlConsoleWidget; - }; + + class XMLConsoleWidgetFactory; + class XMLConsoleWidget; + + class XMLConsoleController { + public: + XMLConsoleController(UIEventStream* uiEventStream, XMLConsoleWidgetFactory* xmlConsoleWidgetFactory); + ~XMLConsoleController(); + + public: + void handleDataRead(const SafeByteArray& data); + void handleDataWritten(const SafeByteArray& data); + + private: + void handleUIEvent(boost::shared_ptr event); + + private: + XMLConsoleWidgetFactory* xmlConsoleWidgetFactory; + XMLConsoleWidget* xmlConsoleWidget; + }; } diff --git a/Swift/Controllers/XMPPEvents/ErrorEvent.h b/Swift/Controllers/XMPPEvents/ErrorEvent.h index 0b18dfc..959f210 100644 --- a/Swift/Controllers/XMPPEvents/ErrorEvent.h +++ b/Swift/Controllers/XMPPEvents/ErrorEvent.h @@ -17,16 +17,16 @@ #include namespace Swift { - class ErrorEvent : public StanzaEvent { - public: - ErrorEvent(const JID& jid, const std::string& text) : jid_(jid), text_(text){} - virtual ~ErrorEvent(){} - const JID& getJID() const {return jid_;} - const std::string& getText() const {return text_;} - - private: - JID jid_; - std::string text_; - }; + class ErrorEvent : public StanzaEvent { + public: + ErrorEvent(const JID& jid, const std::string& text) : jid_(jid), text_(text){} + virtual ~ErrorEvent(){} + const JID& getJID() const {return jid_;} + const std::string& getText() const {return text_;} + + private: + JID jid_; + std::string text_; + }; } diff --git a/Swift/Controllers/XMPPEvents/EventController.cpp b/Swift/Controllers/XMPPEvents/EventController.cpp index bbe7356..4c6b3bc 100644 --- a/Swift/Controllers/XMPPEvents/EventController.cpp +++ b/Swift/Controllers/XMPPEvents/EventController.cpp @@ -25,56 +25,56 @@ EventController::EventController() { } EventController::~EventController() { - foreach(boost::shared_ptr event, events_) { - event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event)); - } + foreach(boost::shared_ptr event, events_) { + event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event)); + } } void EventController::handleIncomingEvent(boost::shared_ptr sourceEvent) { - boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(sourceEvent); - boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(sourceEvent); - boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(sourceEvent); - boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(sourceEvent); - boost::shared_ptr incomingFileTransferEvent = boost::dynamic_pointer_cast(sourceEvent); + boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(sourceEvent); + boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(sourceEvent); + boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(sourceEvent); + boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(sourceEvent); + boost::shared_ptr incomingFileTransferEvent = boost::dynamic_pointer_cast(sourceEvent); - /* If it's a duplicate subscription request, remove the previous request first */ - if (subscriptionEvent) { - EventList existingEvents(events_); - foreach(boost::shared_ptr existingEvent, existingEvents) { - boost::shared_ptr existingSubscriptionEvent = boost::dynamic_pointer_cast(existingEvent); - if (existingSubscriptionEvent) { - if (existingSubscriptionEvent->getJID() == subscriptionEvent->getJID()) { - existingEvent->conclude(); - } - } - } - } + /* If it's a duplicate subscription request, remove the previous request first */ + if (subscriptionEvent) { + EventList existingEvents(events_); + foreach(boost::shared_ptr existingEvent, existingEvents) { + boost::shared_ptr existingSubscriptionEvent = boost::dynamic_pointer_cast(existingEvent); + if (existingSubscriptionEvent) { + if (existingSubscriptionEvent->getJID() == subscriptionEvent->getJID()) { + existingEvent->conclude(); + } + } + } + } - if ((messageEvent && messageEvent->isReadable()) || subscriptionEvent || errorEvent || mucInviteEvent || incomingFileTransferEvent) { - events_.push_back(sourceEvent); - sourceEvent->onConclusion.connect(boost::bind(&EventController::handleEventConcluded, this, sourceEvent)); - onEventQueueLengthChange(boost::numeric_cast(events_.size())); - onEventQueueEventAdded(sourceEvent); - if (sourceEvent->getConcluded()) { - handleEventConcluded(sourceEvent); - } - } + if ((messageEvent && messageEvent->isReadable()) || subscriptionEvent || errorEvent || mucInviteEvent || incomingFileTransferEvent) { + events_.push_back(sourceEvent); + sourceEvent->onConclusion.connect(boost::bind(&EventController::handleEventConcluded, this, sourceEvent)); + onEventQueueLengthChange(boost::numeric_cast(events_.size())); + onEventQueueEventAdded(sourceEvent); + if (sourceEvent->getConcluded()) { + handleEventConcluded(sourceEvent); + } + } } void EventController::handleEventConcluded(boost::shared_ptr event) { - event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event)); - events_.erase(std::remove(events_.begin(), events_.end(), event), events_.end()); - onEventQueueLengthChange(boost::numeric_cast(events_.size())); + event->onConclusion.disconnect(boost::bind(&EventController::handleEventConcluded, this, event)); + events_.erase(std::remove(events_.begin(), events_.end(), event), events_.end()); + onEventQueueLengthChange(boost::numeric_cast(events_.size())); } void EventController::disconnectAll() { - onEventQueueLengthChange.disconnect_all_slots(); - onEventQueueEventAdded.disconnect_all_slots(); + onEventQueueLengthChange.disconnect_all_slots(); + onEventQueueEventAdded.disconnect_all_slots(); } void EventController::clear() { - events_.clear(); - onEventQueueLengthChange(0); + events_.clear(); + onEventQueueLengthChange(0); } } diff --git a/Swift/Controllers/XMPPEvents/EventController.h b/Swift/Controllers/XMPPEvents/EventController.h index 35938ac..3081449 100644 --- a/Swift/Controllers/XMPPEvents/EventController.h +++ b/Swift/Controllers/XMPPEvents/EventController.h @@ -16,21 +16,21 @@ #include namespace Swift { - typedef std::vector > EventList; - class EventController { - public: - EventController(); - ~EventController(); - - void handleIncomingEvent(boost::shared_ptr sourceEvent); - boost::signal onEventQueueLengthChange; - boost::signal)> onEventQueueEventAdded; - const EventList& getEvents() const {return events_;} - void disconnectAll(); - void clear(); - - private: - void handleEventConcluded(boost::shared_ptr event); - EventList events_; - }; + typedef std::vector > EventList; + class EventController { + public: + EventController(); + ~EventController(); + + void handleIncomingEvent(boost::shared_ptr sourceEvent); + boost::signal onEventQueueLengthChange; + boost::signal)> onEventQueueEventAdded; + const EventList& getEvents() const {return events_;} + void disconnectAll(); + void clear(); + + private: + void handleEventConcluded(boost::shared_ptr event); + EventList events_; + }; } diff --git a/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h b/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h index 24af640..4c128e8 100644 --- a/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h +++ b/Swift/Controllers/XMPPEvents/IncomingFileTransferEvent.h @@ -13,18 +13,18 @@ #include namespace Swift { - class IncomingFileTransferEvent : public StanzaEvent { - public: - typedef boost::shared_ptr ref; + class IncomingFileTransferEvent : public StanzaEvent { + public: + typedef boost::shared_ptr ref; - IncomingFileTransferEvent(const JID& sender) : sender_(sender) {} + IncomingFileTransferEvent(const JID& sender) : sender_(sender) {} - const JID& getSender() const { - return sender_; - } + const JID& getSender() const { + return sender_; + } - private: - JID sender_; - }; + private: + JID sender_; + }; } diff --git a/Swift/Controllers/XMPPEvents/MUCInviteEvent.h b/Swift/Controllers/XMPPEvents/MUCInviteEvent.h index 1ae9891..7d333fb 100644 --- a/Swift/Controllers/XMPPEvents/MUCInviteEvent.h +++ b/Swift/Controllers/XMPPEvents/MUCInviteEvent.h @@ -22,26 +22,26 @@ namespace Swift { - class MUCInviteEvent : public StanzaEvent { - public: - typedef boost::shared_ptr ref; - - public: - MUCInviteEvent(const JID& inviter, const JID& roomJID, const std::string& reason, const std::string& password, bool direct, bool impromptu) : inviter_(inviter), roomJID_(roomJID), reason_(reason), password_(password), direct_(direct), impromptu_(impromptu) {} - - const JID& getInviter() const { return inviter_; } - const JID& getRoomJID() const { return roomJID_; } - const std::string& getReason() const { return reason_; } - const std::string& getPassword() const { return password_; } - bool getDirect() const { return direct_; } - bool getImpromptu() const { return impromptu_; } - - private: - JID inviter_; - JID roomJID_; - std::string reason_; - std::string password_; - bool direct_; - bool impromptu_; - }; + class MUCInviteEvent : public StanzaEvent { + public: + typedef boost::shared_ptr ref; + + public: + MUCInviteEvent(const JID& inviter, const JID& roomJID, const std::string& reason, const std::string& password, bool direct, bool impromptu) : inviter_(inviter), roomJID_(roomJID), reason_(reason), password_(password), direct_(direct), impromptu_(impromptu) {} + + const JID& getInviter() const { return inviter_; } + const JID& getRoomJID() const { return roomJID_; } + const std::string& getReason() const { return reason_; } + const std::string& getPassword() const { return password_; } + bool getDirect() const { return direct_; } + bool getImpromptu() const { return impromptu_; } + + private: + JID inviter_; + JID roomJID_; + std::string reason_; + std::string password_; + bool direct_; + bool impromptu_; + }; } diff --git a/Swift/Controllers/XMPPEvents/MessageEvent.h b/Swift/Controllers/XMPPEvents/MessageEvent.h index b5b1215..4ec0406 100644 --- a/Swift/Controllers/XMPPEvents/MessageEvent.h +++ b/Swift/Controllers/XMPPEvents/MessageEvent.h @@ -4,7 +4,7 @@ * See the COPYING file for more information. */ -#pragma once +#pragma once #include @@ -15,34 +15,34 @@ #include namespace Swift { - class MessageEvent : public StanzaEvent { - public: - typedef boost::shared_ptr ref; + class MessageEvent : public StanzaEvent { + public: + typedef boost::shared_ptr ref; - MessageEvent(boost::shared_ptr stanza) : stanza_(stanza), targetsMe_(true) {} + MessageEvent(boost::shared_ptr stanza) : stanza_(stanza), targetsMe_(true) {} - boost::shared_ptr getStanza() {return stanza_;} + boost::shared_ptr getStanza() {return stanza_;} - bool isReadable() { - return getStanza()->isError() || !getStanza()->getBody().get_value_or("").empty(); - } + bool isReadable() { + return getStanza()->isError() || !getStanza()->getBody().get_value_or("").empty(); + } - void read() { - assert (isReadable()); - conclude(); - } + void read() { + assert (isReadable()); + conclude(); + } - void setTargetsMe(bool targetsMe) { - targetsMe_ = targetsMe; - } + void setTargetsMe(bool targetsMe) { + targetsMe_ = targetsMe; + } - bool targetsMe() const { - return targetsMe_; - } + bool targetsMe() const { + return targetsMe_; + } - private: - boost::shared_ptr stanza_; - bool targetsMe_; - }; + private: + boost::shared_ptr stanza_; + bool targetsMe_; + }; } diff --git a/Swift/Controllers/XMPPEvents/StanzaEvent.h b/Swift/Controllers/XMPPEvents/StanzaEvent.h index e8d5eb9..fe97e23 100644 --- a/Swift/Controllers/XMPPEvents/StanzaEvent.h +++ b/Swift/Controllers/XMPPEvents/StanzaEvent.h @@ -12,18 +12,18 @@ #include namespace Swift { - class StanzaEvent { - public: - StanzaEvent() : time_(boost::posix_time::microsec_clock::universal_time()) {concluded_ = false;} - virtual ~StanzaEvent() {} - void conclude() {concluded_ = true; onConclusion();} - /** Do not call this directly from outside the class. - * If you connect to this signal, you *must* disconnect from it manually. */ - boost::signal onConclusion; - bool getConcluded() {return concluded_;} - boost::posix_time::ptime getTime() {return time_;} - private: - bool concluded_; - boost::posix_time::ptime time_; - }; + class StanzaEvent { + public: + StanzaEvent() : time_(boost::posix_time::microsec_clock::universal_time()) {concluded_ = false;} + virtual ~StanzaEvent() {} + void conclude() {concluded_ = true; onConclusion();} + /** Do not call this directly from outside the class. + * If you connect to this signal, you *must* disconnect from it manually. */ + boost::signal onConclusion; + bool getConcluded() {return concluded_;} + boost::posix_time::ptime getTime() {return time_;} + private: + bool concluded_; + boost::posix_time::ptime time_; + }; } diff --git a/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h b/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h index a22399b..92922e9 100644 --- a/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h +++ b/Swift/Controllers/XMPPEvents/SubscriptionRequestEvent.h @@ -17,31 +17,31 @@ #include namespace Swift { - class SubscriptionRequestEvent : public StanzaEvent { - public: - SubscriptionRequestEvent(const JID& jid, const std::string& reason) : jid_(jid), reason_(reason){} - virtual ~SubscriptionRequestEvent(){} - const JID& getJID() const {return jid_;} - const std::string& getReason() const {return reason_;} - boost::signal onAccept; - boost::signal onDecline; - void accept() { - onAccept(); - conclude(); - } - - void decline() { - onDecline(); - conclude(); - } - - void defer() { - conclude(); - } - - private: - JID jid_; - std::string reason_; - }; + class SubscriptionRequestEvent : public StanzaEvent { + public: + SubscriptionRequestEvent(const JID& jid, const std::string& reason) : jid_(jid), reason_(reason){} + virtual ~SubscriptionRequestEvent(){} + const JID& getJID() const {return jid_;} + const std::string& getReason() const {return reason_;} + boost::signal onAccept; + boost::signal onDecline; + void accept() { + onAccept(); + conclude(); + } + + void decline() { + onDecline(); + conclude(); + } + + void defer() { + conclude(); + } + + private: + JID jid_; + std::string reason_; + }; } diff --git a/Swift/Controllers/XMPPURIController.cpp b/Swift/Controllers/XMPPURIController.cpp index 3deb2d8..57c0ca4 100644 --- a/Swift/Controllers/XMPPURIController.cpp +++ b/Swift/Controllers/XMPPURIController.cpp @@ -19,21 +19,21 @@ using namespace Swift; XMPPURIController::XMPPURIController(URIHandler* uriHandler, UIEventStream* uiEventStream) : uriHandler(uriHandler), uiEventStream(uiEventStream) { - uriHandler->onURI.connect(boost::bind(&XMPPURIController::handleURI, this, _1)); + uriHandler->onURI.connect(boost::bind(&XMPPURIController::handleURI, this, _1)); } XMPPURIController::~XMPPURIController() { - uriHandler->onURI.disconnect(boost::bind(&XMPPURIController::handleURI, this, _1)); + uriHandler->onURI.disconnect(boost::bind(&XMPPURIController::handleURI, this, _1)); } void XMPPURIController::handleURI(const std::string& s) { - XMPPURI uri = XMPPURI::fromString(s); - if (!uri.isNull()) { - if (uri.getQueryType() == "join") { - uiEventStream->send(boost::make_shared(uri.getPath())); - } - else { - uiEventStream->send(boost::make_shared(uri.getPath())); - } - } + XMPPURI uri = XMPPURI::fromString(s); + if (!uri.isNull()) { + if (uri.getQueryType() == "join") { + uiEventStream->send(boost::make_shared(uri.getPath())); + } + else { + uiEventStream->send(boost::make_shared(uri.getPath())); + } + } } diff --git a/Swift/Controllers/XMPPURIController.h b/Swift/Controllers/XMPPURIController.h index 4938ad7..4d2fb5c 100644 --- a/Swift/Controllers/XMPPURIController.h +++ b/Swift/Controllers/XMPPURIController.h @@ -11,23 +11,23 @@ #include namespace Swift { - class URIHandler; - class JID; - class UIEventStream; + class URIHandler; + class JID; + class UIEventStream; - class XMPPURIController { - public: - XMPPURIController(URIHandler* uriHandler, UIEventStream* uiEventStream); - ~XMPPURIController(); + class XMPPURIController { + public: + XMPPURIController(URIHandler* uriHandler, UIEventStream* uiEventStream); + ~XMPPURIController(); - boost::signal onStartChat; - boost::signal onJoinMUC; + boost::signal onStartChat; + boost::signal onJoinMUC; - private: - void handleURI(const std::string&); + private: + void handleURI(const std::string&); - private: - URIHandler* uriHandler; - UIEventStream* uiEventStream; - }; + private: + URIHandler* uriHandler; + UIEventStream* uiEventStream; + }; } diff --git a/Swift/QtUI/ApplicationTest/main.cpp b/Swift/QtUI/ApplicationTest/main.cpp index 489865e..782bbf1 100644 --- a/Swift/QtUI/ApplicationTest/main.cpp +++ b/Swift/QtUI/ApplicationTest/main.cpp @@ -18,31 +18,31 @@ using namespace Swift; class MyWidget : public QWidget { - Q_OBJECT - - public: - MyWidget() : application_("MyApplication") { - QVBoxLayout *layout = new QVBoxLayout(this); - input_ = new QLineEdit(this); - layout->addWidget(input_); - connect(input_, SIGNAL(returnPressed()), SLOT(handleReturnPressed())); - } - - private slots: - void handleReturnPressed() { - application_.getApplicationMessageDisplay()->setMessage(Q2PSTRING(input_->text())); - } - - private: - PlatformApplication application_; - QLineEdit* input_; + Q_OBJECT + + public: + MyWidget() : application_("MyApplication") { + QVBoxLayout *layout = new QVBoxLayout(this); + input_ = new QLineEdit(this); + layout->addWidget(input_); + connect(input_, SIGNAL(returnPressed()), SLOT(handleReturnPressed())); + } + + private slots: + void handleReturnPressed() { + application_.getApplicationMessageDisplay()->setMessage(Q2PSTRING(input_->text())); + } + + private: + PlatformApplication application_; + QLineEdit* input_; }; int main(int argc, char* argv[]) { - QApplication app(argc, argv); - MyWidget widget; - widget.show(); - return app.exec(); + QApplication app(argc, argv); + MyWidget widget; + widget.show(); + return app.exec(); } #include "main.moc" diff --git a/Swift/QtUI/CAPICertificateSelector.cpp b/Swift/QtUI/CAPICertificateSelector.cpp index 953051b..36d8c54 100644 --- a/Swift/QtUI/CAPICertificateSelector.cpp +++ b/Swift/QtUI/CAPICertificateSelector.cpp @@ -23,94 +23,94 @@ namespace Swift { /////Hmm, maybe we should not exlude the "location" column -#define exclude_columns CRYPTUI_SELECT_LOCATION_COLUMN | CRYPTUI_SELECT_INTENDEDUSE_COLUMN +#define exclude_columns CRYPTUI_SELECT_LOCATION_COLUMN | CRYPTUI_SELECT_INTENDEDUSE_COLUMN #define SHA1_HASH_LENGTH 20 static std::string getCertUri(PCCERT_CONTEXT cert, const char * cert_store_name) { - DWORD cbHash = SHA1_HASH_LENGTH; - BYTE aHash[SHA1_HASH_LENGTH]; - std::string result("certstore:"); + DWORD cbHash = SHA1_HASH_LENGTH; + BYTE aHash[SHA1_HASH_LENGTH]; + std::string result("certstore:"); - result += cert_store_name; - result += ":sha1:"; + result += cert_store_name; + result += ":sha1:"; - if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, aHash, &cbHash) == FALSE ) { - return ""; - } + if (CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID, aHash, &cbHash) == FALSE ) { + return ""; + } - ByteArray byteArray = createByteArray((char *)(&aHash[0]), cbHash); - result += Hexify::hexify(byteArray); + ByteArray byteArray = createByteArray((char *)(&aHash[0]), cbHash); + result += Hexify::hexify(byteArray); - return result; + return result; } std::string selectCAPICertificate() { - const char* certStoreName = "MY"; + const char* certStoreName = "MY"; - DWORD storeFlags = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER; + DWORD storeFlags = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER; - HCERTSTORE hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, storeFlags, certStoreName); - if (!hstore) { - return ""; - } + HCERTSTORE hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, storeFlags, certStoreName); + if (!hstore) { + return ""; + } - HWND hwnd = GetForegroundWindow(); - if (!hwnd) { - hwnd = GetActiveWindow(); - } + HWND hwnd = GetForegroundWindow(); + if (!hwnd) { + hwnd = GetActiveWindow(); + } - std::string certificateDialogTitle = QT_TRANSLATE_NOOP("", "TLS Client Certificate Selection"); - std::string certificateDialogPrompt = QT_TRANSLATE_NOOP("", "Select a certificate to use for authentication"); + std::string certificateDialogTitle = QT_TRANSLATE_NOOP("", "TLS Client Certificate Selection"); + std::string certificateDialogPrompt = QT_TRANSLATE_NOOP("", "Select a certificate to use for authentication"); - int titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, NULL, 0); - int promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, NULL, 0); + int titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, NULL, 0); + int promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, NULL, 0); - wchar_t* titleChars = new wchar_t[titleLength]; - wchar_t* promptChars = new wchar_t[promptLength]; + wchar_t* titleChars = new wchar_t[titleLength]; + wchar_t* promptChars = new wchar_t[promptLength]; - //titleChars[titleLength] = '\0'; - //promptChars[promptLength] = '\0'; + //titleChars[titleLength] = '\0'; + //promptChars[promptLength] = '\0'; - titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, titleChars, titleLength); - promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, promptChars, promptLength); + titleLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogTitle.c_str(), -1, titleChars, titleLength); + promptLength = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, certificateDialogPrompt.c_str(), -1, promptChars, promptLength); - if (titleLength == 0 || promptLength == 0) { - int error = GetLastError(); - switch (error) { - case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog" << std::endl;break; - case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog" << std::endl;break; - case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog" << std::endl;break; - case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog" << std::endl;break; - default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode" << std::endl; + if (titleLength == 0 || promptLength == 0) { + int error = GetLastError(); + switch (error) { + case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog" << std::endl;break; + case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog" << std::endl;break; + case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog" << std::endl;break; + case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog" << std::endl;break; + default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode" << std::endl; - } - } + } + } - - /* Call Windows dialog to select a suitable certificate */ - PCCERT_CONTEXT cert = CryptUIDlgSelectCertificateFromStore(hstore, hwnd, titleChars, promptChars, exclude_columns, 0, NULL); - delete[] titleChars; - delete[] promptChars; + /* Call Windows dialog to select a suitable certificate */ + PCCERT_CONTEXT cert = CryptUIDlgSelectCertificateFromStore(hstore, hwnd, titleChars, promptChars, exclude_columns, 0, NULL); - if (hstore) { - CertCloseStore(hstore, 0); - } + delete[] titleChars; + delete[] promptChars; - std::string result; + if (hstore) { + CertCloseStore(hstore, 0); + } - if (cert) { - result = getCertUri(cert, certStoreName); - CertFreeCertificateContext(cert); - } + std::string result; - return result; + if (cert) { + result = getCertUri(cert, certStoreName); + CertFreeCertificateContext(cert); + } + + return result; } bool isCAPIURI(std::string uri) { - return (boost::iequals(uri.substr(0, 10), "certstore:")); + return (boost::iequals(uri.substr(0, 10), "certstore:")); } } diff --git a/Swift/QtUI/CAPICertificateSelector.h b/Swift/QtUI/CAPICertificateSelector.h index 714f1c5..8273c78 100644 --- a/Swift/QtUI/CAPICertificateSelector.h +++ b/Swift/QtUI/CAPICertificateSelector.h @@ -9,6 +9,6 @@ #include namespace Swift { - std::string selectCAPICertificate(); - bool isCAPIURI(std::string uri); + std::string selectCAPICertificate(); + bool isCAPIURI(std::string uri); } diff --git a/Swift/QtUI/ChatList/ChatListDelegate.cpp b/Swift/QtUI/ChatList/ChatListDelegate.cpp index 5fa4e23..29eb29a 100644 --- a/Swift/QtUI/ChatList/ChatListDelegate.cpp +++ b/Swift/QtUI/ChatList/ChatListDelegate.cpp @@ -19,125 +19,125 @@ namespace Swift { ChatListDelegate::ChatListDelegate(bool compact) : compact_(compact) { - groupDelegate_ = new GroupItemDelegate(); + groupDelegate_ = new GroupItemDelegate(); } ChatListDelegate::~ChatListDelegate() { - delete groupDelegate_; + delete groupDelegate_; } void ChatListDelegate::setCompact(bool compact) { - compact_ = compact; - emit sizeHintChanged(QModelIndex()); + compact_ = compact; + emit sizeHintChanged(QModelIndex()); } QSize ChatListDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const { - ChatListItem* item = static_cast(index.internalPointer()); - if (item && dynamic_cast(item)) { - return mucSizeHint(option, index); - } - else if (item && dynamic_cast(item)) { - return common_.contactSizeHint(option, index, compact_); - } - else if (item && dynamic_cast(item)) { - return groupDelegate_->sizeHint(option, index); - } - else if (item && dynamic_cast(item)) { - return common_.contactSizeHint(option, index, compact_); - } - return QStyledItemDelegate::sizeHint(option, index); + ChatListItem* item = static_cast(index.internalPointer()); + if (item && dynamic_cast(item)) { + return mucSizeHint(option, index); + } + else if (item && dynamic_cast(item)) { + return common_.contactSizeHint(option, index, compact_); + } + else if (item && dynamic_cast(item)) { + return groupDelegate_->sizeHint(option, index); + } + else if (item && dynamic_cast(item)) { + return common_.contactSizeHint(option, index, compact_); + } + return QStyledItemDelegate::sizeHint(option, index); } QSize ChatListDelegate::mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const { - QFontMetrics nameMetrics(common_.nameFont); - QFontMetrics statusMetrics(common_.detailFont); - int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height(); - return QSize(150, sizeByText); + QFontMetrics nameMetrics(common_.nameFont); + QFontMetrics statusMetrics(common_.detailFont); + int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height(); + return QSize(150, sizeByText); } QSize ChatListDelegate::recentSizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { - return mucSizeHint(option, index); + return mucSizeHint(option, index); } void ChatListDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { - ChatListItem* item = static_cast(index.internalPointer()); - if (item && dynamic_cast(item)) { - paintMUC(painter, option, dynamic_cast(item)); - } - else if (item && dynamic_cast(item)) { - paintRecent(painter, option, dynamic_cast(item)); - } - else if (item && dynamic_cast(item)) { - ChatListGroupItem* group = dynamic_cast(item); - groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open); - } - else if (item && dynamic_cast(item)) { - paintWhiteboard(painter, option, dynamic_cast(item)); - } - else { - QStyledItemDelegate::paint(painter, option, index); - } + ChatListItem* item = static_cast(index.internalPointer()); + if (item && dynamic_cast(item)) { + paintMUC(painter, option, dynamic_cast(item)); + } + else if (item && dynamic_cast(item)) { + paintRecent(painter, option, dynamic_cast(item)); + } + else if (item && dynamic_cast(item)) { + ChatListGroupItem* group = dynamic_cast(item); + groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open); + } + else if (item && dynamic_cast(item)) { + paintWhiteboard(painter, option, dynamic_cast(item)); + } + else { + QStyledItemDelegate::paint(painter, option, index); + } } void ChatListDelegate::paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const { - painter->save(); - QRect fullRegion(option.rect); - if ( option.state & QStyle::State_Selected ) { - painter->fillRect(fullRegion, option.palette.highlight()); - painter->setPen(option.palette.highlightedText().color()); - } else { - QColor nameColor = item->data(Qt::TextColorRole).value(); - painter->setPen(QPen(nameColor)); - } - - QFontMetrics nameMetrics(common_.nameFont); - painter->setFont(common_.nameFont); - int extraFontWidth = nameMetrics.width("H"); - int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2; - QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0)); - - int nameHeight = nameMetrics.height() + common_.verticalMargin; - QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0)); - - DelegateCommons::drawElidedText(painter, nameRegion, item->data(Qt::DisplayRole).toString()); - - painter->setFont(common_.detailFont); - painter->setPen(QPen(QColor(160,160,160))); - - QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0)); - DelegateCommons::drawElidedText(painter, detailRegion, item->data(ChatListMUCItem::DetailTextRole).toString()); - - painter->restore(); + painter->save(); + QRect fullRegion(option.rect); + if ( option.state & QStyle::State_Selected ) { + painter->fillRect(fullRegion, option.palette.highlight()); + painter->setPen(option.palette.highlightedText().color()); + } else { + QColor nameColor = item->data(Qt::TextColorRole).value(); + painter->setPen(QPen(nameColor)); + } + + QFontMetrics nameMetrics(common_.nameFont); + painter->setFont(common_.nameFont); + int extraFontWidth = nameMetrics.width("H"); + int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2; + QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0)); + + int nameHeight = nameMetrics.height() + common_.verticalMargin; + QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0)); + + DelegateCommons::drawElidedText(painter, nameRegion, item->data(Qt::DisplayRole).toString()); + + painter->setFont(common_.detailFont); + painter->setPen(QPen(QColor(160,160,160))); + + QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0)); + DelegateCommons::drawElidedText(painter, detailRegion, item->data(ChatListMUCItem::DetailTextRole).toString()); + + painter->restore(); } void ChatListDelegate::paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const { - QColor nameColor = item->data(Qt::TextColorRole).value(); - QString avatarPath; - if (item->data(ChatListRecentItem::AvatarRole).isValid() && !item->data(ChatListRecentItem::AvatarRole).value().isNull()) { - avatarPath = item->data(ChatListRecentItem::AvatarRole).value(); - } - QIcon presenceIcon = item->data(ChatListRecentItem::PresenceIconRole).isValid() && !item->data(ChatListRecentItem::PresenceIconRole).value().isNull() - ? item->data(ChatListRecentItem::PresenceIconRole).value() - : QIcon(":/icons/offline.png"); - QString name = item->data(Qt::DisplayRole).toString(); - //qDebug() << "Avatar for " << name << " = " << avatarPath; - QString statusText = item->data(ChatListRecentItem::DetailTextRole).toString(); - common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_); + QColor nameColor = item->data(Qt::TextColorRole).value(); + QString avatarPath; + if (item->data(ChatListRecentItem::AvatarRole).isValid() && !item->data(ChatListRecentItem::AvatarRole).value().isNull()) { + avatarPath = item->data(ChatListRecentItem::AvatarRole).value(); + } + QIcon presenceIcon = item->data(ChatListRecentItem::PresenceIconRole).isValid() && !item->data(ChatListRecentItem::PresenceIconRole).value().isNull() + ? item->data(ChatListRecentItem::PresenceIconRole).value() + : QIcon(":/icons/offline.png"); + QString name = item->data(Qt::DisplayRole).toString(); + //qDebug() << "Avatar for " << name << " = " << avatarPath; + QString statusText = item->data(ChatListRecentItem::DetailTextRole).toString(); + common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_); } void ChatListDelegate::paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const { - QColor nameColor = item->data(Qt::TextColorRole).value(); - QString avatarPath; - if (item->data(ChatListWhiteboardItem::AvatarRole).isValid() && !item->data(ChatListWhiteboardItem::AvatarRole).value().isNull()) { - avatarPath = item->data(ChatListWhiteboardItem::AvatarRole).value(); - } - QIcon presenceIcon;/* = item->data(ChatListWhiteboardItem::PresenceIconRole).isValid() && !item->data(ChatListWhiteboardItem::PresenceIconRole).value().isNull() - ? item->data(ChatListWhiteboardItem::PresenceIconRole).value() - : QIcon(":/icons/offline.png");*/ - QString name = item->data(Qt::DisplayRole).toString(); - //qDebug() << "Avatar for " << name << " = " << avatarPath; - QString statusText = item->data(ChatListWhiteboardItem::DetailTextRole).toString(); - common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_); + QColor nameColor = item->data(Qt::TextColorRole).value(); + QString avatarPath; + if (item->data(ChatListWhiteboardItem::AvatarRole).isValid() && !item->data(ChatListWhiteboardItem::AvatarRole).value().isNull()) { + avatarPath = item->data(ChatListWhiteboardItem::AvatarRole).value(); + } + QIcon presenceIcon;/* = item->data(ChatListWhiteboardItem::PresenceIconRole).isValid() && !item->data(ChatListWhiteboardItem::PresenceIconRole).value().isNull() + ? item->data(ChatListWhiteboardItem::PresenceIconRole).value() + : QIcon(":/icons/offline.png");*/ + QString name = item->data(Qt::DisplayRole).toString(); + //qDebug() << "Avatar for " << name << " = " << avatarPath; + QString statusText = item->data(ChatListWhiteboardItem::DetailTextRole).toString(); + common_.paintContact(painter, option, nameColor, avatarPath, presenceIcon, name, statusText, false, item->getChat().unreadCount, compact_); } diff --git a/Swift/QtUI/ChatList/ChatListDelegate.h b/Swift/QtUI/ChatList/ChatListDelegate.h index 2de209d..44ca947 100644 --- a/Swift/QtUI/ChatList/ChatListDelegate.h +++ b/Swift/QtUI/ChatList/ChatListDelegate.h @@ -11,28 +11,28 @@ #include namespace Swift { - class ChatListMUCItem; - class ChatListRecentItem; - class ChatListWhiteboardItem; - class ChatListDelegate : public QStyledItemDelegate { - public: - ChatListDelegate(bool compact); - ~ChatListDelegate(); - QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; - public slots: - void setCompact(bool compact); - private: - void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const; - void paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const; - void paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const; - QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const; - QSize recentSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const; + class ChatListMUCItem; + class ChatListRecentItem; + class ChatListWhiteboardItem; + class ChatListDelegate : public QStyledItemDelegate { + public: + ChatListDelegate(bool compact); + ~ChatListDelegate(); + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + public slots: + void setCompact(bool compact); + private: + void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, ChatListMUCItem* item) const; + void paintRecent(QPainter* painter, const QStyleOptionViewItem& option, ChatListRecentItem* item) const; + void paintWhiteboard(QPainter* painter, const QStyleOptionViewItem& option, ChatListWhiteboardItem* item) const; + QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const; + QSize recentSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const; - bool compact_; - DelegateCommons common_; - GroupItemDelegate* groupDelegate_; - }; + bool compact_; + DelegateCommons common_; + GroupItemDelegate* groupDelegate_; + }; } diff --git a/Swift/QtUI/ChatList/ChatListGroupItem.h b/Swift/QtUI/ChatList/ChatListGroupItem.h index 9330505..427f00b 100644 --- a/Swift/QtUI/ChatList/ChatListGroupItem.h +++ b/Swift/QtUI/ChatList/ChatListGroupItem.h @@ -13,33 +13,33 @@ #include namespace Swift { - class ChatListGroupItem : public ChatListItem { - public: - ChatListGroupItem(const QString& name, ChatListGroupItem* parent, bool sorted = true) : ChatListItem(parent), name_(name), sorted_(sorted) {} - virtual ~ChatListGroupItem() {clear();} - void addItem(ChatListItem* item) {items_.push_back(item); if (sorted_) {qStableSort(items_.begin(), items_.end(), pointerItemLessThan);}} - void remove(int index) {items_.removeAt(index);} - int rowCount() {return items_.size();} - ChatListItem* item(int i) {return items_[i];} - int row(ChatListItem* item) {return items_.indexOf(item);} - QVariant data(int role) const {return (role == Qt::DisplayRole) ? name_ : QVariant();} - void clear() { - foreach (ChatListItem* item, items_) { - delete item; - } - items_.clear(); - } - - - private: - static bool pointerItemLessThan(const ChatListItem* first, const ChatListItem* second) { - QString myName = first->data(Qt::DisplayRole).toString().toLower(); - QString theirName = second->data(Qt::DisplayRole).toString().toLower(); - return myName < theirName; - } - - QString name_; - QList items_; - bool sorted_; - }; + class ChatListGroupItem : public ChatListItem { + public: + ChatListGroupItem(const QString& name, ChatListGroupItem* parent, bool sorted = true) : ChatListItem(parent), name_(name), sorted_(sorted) {} + virtual ~ChatListGroupItem() {clear();} + void addItem(ChatListItem* item) {items_.push_back(item); if (sorted_) {qStableSort(items_.begin(), items_.end(), pointerItemLessThan);}} + void remove(int index) {items_.removeAt(index);} + int rowCount() {return items_.size();} + ChatListItem* item(int i) {return items_[i];} + int row(ChatListItem* item) {return items_.indexOf(item);} + QVariant data(int role) const {return (role == Qt::DisplayRole) ? name_ : QVariant();} + void clear() { + foreach (ChatListItem* item, items_) { + delete item; + } + items_.clear(); + } + + + private: + static bool pointerItemLessThan(const ChatListItem* first, const ChatListItem* second) { + QString myName = first->data(Qt::DisplayRole).toString().toLower(); + QString theirName = second->data(Qt::DisplayRole).toString().toLower(); + return myName < theirName; + } + + QString name_; + QList items_; + bool sorted_; + }; } diff --git a/Swift/QtUI/ChatList/ChatListItem.h b/Swift/QtUI/ChatList/ChatListItem.h index fa8b18a..c6fd762 100644 --- a/Swift/QtUI/ChatList/ChatListItem.h +++ b/Swift/QtUI/ChatList/ChatListItem.h @@ -11,16 +11,16 @@ #include namespace Swift { - class ChatListGroupItem; - class ChatListItem { - public: - ChatListItem(ChatListGroupItem* parent) {parent_ = parent;} - virtual ~ChatListItem() {} + class ChatListGroupItem; + class ChatListItem { + public: + ChatListItem(ChatListGroupItem* parent) {parent_ = parent;} + virtual ~ChatListItem() {} - ChatListGroupItem* parent() {return parent_;} - virtual QVariant data(int role) const = 0; + ChatListGroupItem* parent() {return parent_;} + virtual QVariant data(int role) const = 0; - private: - ChatListGroupItem* parent_; - }; + private: + ChatListGroupItem* parent_; + }; } diff --git a/Swift/QtUI/ChatList/ChatListMUCItem.cpp b/Swift/QtUI/ChatList/ChatListMUCItem.cpp index 1ad622d..7d072df 100644 --- a/Swift/QtUI/ChatList/ChatListMUCItem.cpp +++ b/Swift/QtUI/ChatList/ChatListMUCItem.cpp @@ -14,21 +14,21 @@ ChatListMUCItem::ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* } const MUCBookmark& ChatListMUCItem::getBookmark() const { - return bookmark_; + return bookmark_; } QVariant ChatListMUCItem::data(int role) const { - switch (role) { - case Qt::DisplayRole: return P2QSTRING(bookmark_.getName()); - case DetailTextRole: return P2QSTRING(bookmark_.getRoom().toString()); - /*case Qt::TextColorRole: return textColor_; - case Qt::BackgroundColorRole: return backgroundColor_; - case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant(); - case StatusTextRole: return statusText_; - case AvatarRole: return avatar_; - case PresenceIconRole: return getPresenceIcon();*/ - default: return QVariant(); - } + switch (role) { + case Qt::DisplayRole: return P2QSTRING(bookmark_.getName()); + case DetailTextRole: return P2QSTRING(bookmark_.getRoom().toString()); + /*case Qt::TextColorRole: return textColor_; + case Qt::BackgroundColorRole: return backgroundColor_; + case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant(); + case StatusTextRole: return statusText_; + case AvatarRole: return avatar_; + case PresenceIconRole: return getPresenceIcon();*/ + default: return QVariant(); + } } } diff --git a/Swift/QtUI/ChatList/ChatListMUCItem.h b/Swift/QtUI/ChatList/ChatListMUCItem.h index fb90b88..4e93600 100644 --- a/Swift/QtUI/ChatList/ChatListMUCItem.h +++ b/Swift/QtUI/ChatList/ChatListMUCItem.h @@ -15,19 +15,19 @@ #include namespace Swift { - class ChatListMUCItem : public ChatListItem { - public: - enum MUCItemRoles { - DetailTextRole = Qt::UserRole/*, - AvatarRole = Qt::UserRole + 1, - PresenceIconRole = Qt::UserRole + 2, - StatusShowTypeRole = Qt::UserRole + 3*/ - }; - ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* parent); - const MUCBookmark& getBookmark() const; - QVariant data(int role) const; - private: - MUCBookmark bookmark_; - QList items_; - }; + class ChatListMUCItem : public ChatListItem { + public: + enum MUCItemRoles { + DetailTextRole = Qt::UserRole/*, + AvatarRole = Qt::UserRole + 1, + PresenceIconRole = Qt::UserRole + 2, + StatusShowTypeRole = Qt::UserRole + 3*/ + }; + ChatListMUCItem(const MUCBookmark& bookmark, ChatListGroupItem* parent); + const MUCBookmark& getBookmark() const; + QVariant data(int role) const; + private: + MUCBookmark bookmark_; + QList items_; + }; } diff --git a/Swift/QtUI/ChatList/ChatListModel.cpp b/Swift/QtUI/ChatList/ChatListModel.cpp index 2447aa1..307cdea 100644 --- a/Swift/QtUI/ChatList/ChatListModel.cpp +++ b/Swift/QtUI/ChatList/ChatListModel.cpp @@ -17,172 +17,172 @@ namespace Swift { ChatListModel::ChatListModel() : whiteboards_(NULL) { - root_ = new ChatListGroupItem("", NULL, false); - mucBookmarks_ = new ChatListGroupItem(tr("Bookmarked Rooms"), root_); - recents_ = new ChatListGroupItem(tr("Recent Chats"), root_, false); + root_ = new ChatListGroupItem("", NULL, false); + mucBookmarks_ = new ChatListGroupItem(tr("Bookmarked Rooms"), root_); + recents_ = new ChatListGroupItem(tr("Recent Chats"), root_, false); #ifdef SWIFT_EXPERIMENTAL_WB - whiteboards_ = new ChatListGroupItem(tr("Opened Whiteboards"), root_, false); - root_->addItem(whiteboards_); + whiteboards_ = new ChatListGroupItem(tr("Opened Whiteboards"), root_, false); + root_->addItem(whiteboards_); #endif - root_->addItem(recents_); - root_->addItem(mucBookmarks_); + root_->addItem(recents_); + root_->addItem(mucBookmarks_); - QModelIndex idx = index(0, 0, QModelIndex()); - while (idx.isValid()) { - if (idx.internalPointer() == mucBookmarks_) { - mucBookmarksIndex_ = idx; - } else if (idx.internalPointer() == recents_) { - recentsIndex_ = idx; - } else if (idx.internalPointer() == whiteboards_) { - whiteboardsIndex_ = idx; - } - idx = index(idx.row() + 1, 0, QModelIndex()); - } + QModelIndex idx = index(0, 0, QModelIndex()); + while (idx.isValid()) { + if (idx.internalPointer() == mucBookmarks_) { + mucBookmarksIndex_ = idx; + } else if (idx.internalPointer() == recents_) { + recentsIndex_ = idx; + } else if (idx.internalPointer() == whiteboards_) { + whiteboardsIndex_ = idx; + } + idx = index(idx.row() + 1, 0, QModelIndex()); + } } Qt::ItemFlags ChatListModel::flags(const QModelIndex& index) const { - Qt::ItemFlags flags = QAbstractItemModel::flags(index); - if (dynamic_cast(getItemForIndex(index))) { - flags |= Qt::ItemIsDragEnabled; - } - return flags; + Qt::ItemFlags flags = QAbstractItemModel::flags(index); + if (dynamic_cast(getItemForIndex(index))) { + flags |= Qt::ItemIsDragEnabled; + } + return flags; } void ChatListModel::clearBookmarks() { - beginRemoveRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount()); - mucBookmarks_->clear(); - endRemoveRows(); + beginRemoveRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount()); + mucBookmarks_->clear(); + endRemoveRows(); } void ChatListModel::addMUCBookmark(const Swift::MUCBookmark& bookmark) { - beginInsertRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount()); - mucBookmarks_->addItem(new ChatListMUCItem(bookmark, mucBookmarks_)); - endInsertRows(); + beginInsertRows(mucBookmarksIndex_, 0, mucBookmarks_->rowCount()); + mucBookmarks_->addItem(new ChatListMUCItem(bookmark, mucBookmarks_)); + endInsertRows(); } void ChatListModel::removeMUCBookmark(const Swift::MUCBookmark& bookmark) { - for (int i = 0; i < mucBookmarks_->rowCount(); i++) { - ChatListMUCItem* item = dynamic_cast(mucBookmarks_->item(i)); - if (item->getBookmark() == bookmark) { - beginRemoveRows(mucBookmarksIndex_, i, i+1); - mucBookmarks_->remove(i); - endRemoveRows(); - break; - } - } + for (int i = 0; i < mucBookmarks_->rowCount(); i++) { + ChatListMUCItem* item = dynamic_cast(mucBookmarks_->item(i)); + if (item->getBookmark() == bookmark) { + beginRemoveRows(mucBookmarksIndex_, i, i+1); + mucBookmarks_->remove(i); + endRemoveRows(); + break; + } + } } void ChatListModel::addWhiteboardSession(const ChatListWindow::Chat& chat) { - beginInsertRows(whiteboardsIndex_, 0, whiteboards_->rowCount()); - whiteboards_->addItem(new ChatListWhiteboardItem(chat, whiteboards_)); - endInsertRows(); + beginInsertRows(whiteboardsIndex_, 0, whiteboards_->rowCount()); + whiteboards_->addItem(new ChatListWhiteboardItem(chat, whiteboards_)); + endInsertRows(); } void ChatListModel::removeWhiteboardSession(const JID& jid) { - for (int i = 0; i < whiteboards_->rowCount(); i++) { - ChatListWhiteboardItem* item = dynamic_cast(whiteboards_->item(i)); - if (item->getChat().jid == jid) { - beginRemoveRows(whiteboardsIndex_, i, i+1); - whiteboards_->remove(i); - endRemoveRows(); - break; - } - } + for (int i = 0; i < whiteboards_->rowCount(); i++) { + ChatListWhiteboardItem* item = dynamic_cast(whiteboards_->item(i)); + if (item->getChat().jid == jid) { + beginRemoveRows(whiteboardsIndex_, i, i+1); + whiteboards_->remove(i); + endRemoveRows(); + break; + } + } } void ChatListModel::setRecents(const std::list& recents) { - beginRemoveRows(recentsIndex_, 0, recents_->rowCount()); - recents_->clear(); - endRemoveRows(); - beginInsertRows(recentsIndex_, 0, recents.size()); - foreach (const ChatListWindow::Chat chat, recents) { - recents_->addItem(new ChatListRecentItem(chat, recents_)); + beginRemoveRows(recentsIndex_, 0, recents_->rowCount()); + recents_->clear(); + endRemoveRows(); + beginInsertRows(recentsIndex_, 0, recents.size()); + foreach (const ChatListWindow::Chat chat, recents) { + recents_->addItem(new ChatListRecentItem(chat, recents_)); //whiteboards_->addItem(new ChatListRecentItem(chat, whiteboards_)); - } - endInsertRows(); + } + endInsertRows(); } QMimeData* ChatListModel::mimeData(const QModelIndexList& indexes) const { - QMimeData* data = QAbstractItemModel::mimeData(indexes); - ChatListRecentItem *item = dynamic_cast(getItemForIndex(indexes.first())); - if (item == NULL) { - return data; - } - - QByteArray itemData; - QDataStream dataStream(&itemData, QIODevice::WriteOnly); - const ChatListWindow::Chat& chat = item->getChat(); - - QString mimeType = "application/vnd.swift.contact-jid-list"; - if (!chat.impromptuJIDs.size()) { - if (chat.isMUC) { - mimeType = "application/vnd.swift.contact-jid-muc"; - } - dataStream << P2QSTRING(chat.jid.toString()); - } else { - typedef std::map JIDMap; - foreach (const JIDMap::value_type& jid, chat.impromptuJIDs) { - dataStream << P2QSTRING(jid.second.toString()); - } - } - - data->setData(mimeType, itemData); - return data; + QMimeData* data = QAbstractItemModel::mimeData(indexes); + ChatListRecentItem *item = dynamic_cast(getItemForIndex(indexes.first())); + if (item == NULL) { + return data; + } + + QByteArray itemData; + QDataStream dataStream(&itemData, QIODevice::WriteOnly); + const ChatListWindow::Chat& chat = item->getChat(); + + QString mimeType = "application/vnd.swift.contact-jid-list"; + if (!chat.impromptuJIDs.size()) { + if (chat.isMUC) { + mimeType = "application/vnd.swift.contact-jid-muc"; + } + dataStream << P2QSTRING(chat.jid.toString()); + } else { + typedef std::map JIDMap; + foreach (const JIDMap::value_type& jid, chat.impromptuJIDs) { + dataStream << P2QSTRING(jid.second.toString()); + } + } + + data->setData(mimeType, itemData); + return data; } const ChatListMUCItem* ChatListModel::getChatListMUCItem(const JID& roomJID) const { - const ChatListMUCItem* mucItem = NULL; - for (int i = 0; i < mucBookmarks_->rowCount(); i++) { - ChatListMUCItem* item = dynamic_cast(mucBookmarks_->item(i)); - if (item->getBookmark().getRoom() == roomJID) { - mucItem = item; - break; - } - } - return mucItem; + const ChatListMUCItem* mucItem = NULL; + for (int i = 0; i < mucBookmarks_->rowCount(); i++) { + ChatListMUCItem* item = dynamic_cast(mucBookmarks_->item(i)); + if (item->getBookmark().getRoom() == roomJID) { + mucItem = item; + break; + } + } + return mucItem; } int ChatListModel::columnCount(const QModelIndex& /*parent*/) const { - return 1; + return 1; } ChatListItem* ChatListModel::getItemForIndex(const QModelIndex& index) const { - return index.isValid() ? static_cast(index.internalPointer()) : NULL; + return index.isValid() ? static_cast(index.internalPointer()) : NULL; } QVariant ChatListModel::data(const QModelIndex& index, int role) const { - ChatListItem* item = getItemForIndex(index); - return item ? item->data(role) : QVariant(); + ChatListItem* item = getItemForIndex(index); + return item ? item->data(role) : QVariant(); } QModelIndex ChatListModel::index(int row, int column, const QModelIndex & parent) const { - if (!hasIndex(row, column, parent)) { - return QModelIndex(); - } + if (!hasIndex(row, column, parent)) { + return QModelIndex(); + } - ChatListGroupItem *parentItem = parent.isValid() ? static_cast(parent.internalPointer()) : root_; + ChatListGroupItem *parentItem = parent.isValid() ? static_cast(parent.internalPointer()) : root_; - return row < parentItem->rowCount() ? createIndex(row, column, parentItem->item(row)) : QModelIndex(); + return row < parentItem->rowCount() ? createIndex(row, column, parentItem->item(row)) : QModelIndex(); } QModelIndex ChatListModel::parent(const QModelIndex& index) const { - if (!index.isValid()) { - return QModelIndex(); - } - ChatListGroupItem* parent = static_cast(index.internalPointer())->parent(); - return (parent == root_) ? QModelIndex() : createIndex(parent->parent()->row(parent), 0, parent); + if (!index.isValid()) { + return QModelIndex(); + } + ChatListGroupItem* parent = static_cast(index.internalPointer())->parent(); + return (parent == root_) ? QModelIndex() : createIndex(parent->parent()->row(parent), 0, parent); } int ChatListModel::rowCount(const QModelIndex& parentIndex) const { - ChatListGroupItem* parent = NULL; - if (parentIndex.isValid()) { - parent = dynamic_cast(static_cast(parentIndex.internalPointer())); - } else { - parent = root_; - } - int count = (parent ? parent->rowCount() : 0); - return count; + ChatListGroupItem* parent = NULL; + if (parentIndex.isValid()) { + parent = dynamic_cast(static_cast(parentIndex.internalPointer())); + } else { + parent = root_; + } + int count = (parent ? parent->rowCount() : 0); + return count; } } diff --git a/Swift/QtUI/ChatList/ChatListModel.h b/Swift/QtUI/ChatList/ChatListModel.h index ea85efb..363b2e6 100644 --- a/Swift/QtUI/ChatList/ChatListModel.h +++ b/Swift/QtUI/ChatList/ChatListModel.h @@ -16,38 +16,38 @@ #include namespace Swift { - class ChatListMUCItem; - - class ChatListModel : public QAbstractItemModel { - Q_OBJECT - public: - ChatListModel(); - Qt::ItemFlags flags(const QModelIndex& index) const; - void addMUCBookmark(const MUCBookmark& bookmark); - void removeMUCBookmark(const MUCBookmark& bookmark); - void addWhiteboardSession(const ChatListWindow::Chat& chat); - void removeWhiteboardSession(const JID& jid); - int columnCount(const QModelIndex& parent = QModelIndex()) const; - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex& index) const; - int rowCount(const QModelIndex& parent = QModelIndex()) const; - ChatListItem* getItemForIndex(const QModelIndex& index) const; - void clearBookmarks(); - void setRecents(const std::list& recents); - QMimeData* mimeData(const QModelIndexList& indexes) const; - - const ChatListMUCItem* getChatListMUCItem(const JID& roomJID) const; - - private: - ChatListGroupItem* mucBookmarks_; - ChatListGroupItem* recents_; - ChatListGroupItem* whiteboards_; - ChatListGroupItem* root_; - - QPersistentModelIndex mucBookmarksIndex_; - QPersistentModelIndex recentsIndex_; - QPersistentModelIndex whiteboardsIndex_; - }; + class ChatListMUCItem; + + class ChatListModel : public QAbstractItemModel { + Q_OBJECT + public: + ChatListModel(); + Qt::ItemFlags flags(const QModelIndex& index) const; + void addMUCBookmark(const MUCBookmark& bookmark); + void removeMUCBookmark(const MUCBookmark& bookmark); + void addWhiteboardSession(const ChatListWindow::Chat& chat); + void removeWhiteboardSession(const JID& jid); + int columnCount(const QModelIndex& parent = QModelIndex()) const; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex& index) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; + ChatListItem* getItemForIndex(const QModelIndex& index) const; + void clearBookmarks(); + void setRecents(const std::list& recents); + QMimeData* mimeData(const QModelIndexList& indexes) const; + + const ChatListMUCItem* getChatListMUCItem(const JID& roomJID) const; + + private: + ChatListGroupItem* mucBookmarks_; + ChatListGroupItem* recents_; + ChatListGroupItem* whiteboards_; + ChatListGroupItem* root_; + + QPersistentModelIndex mucBookmarksIndex_; + QPersistentModelIndex recentsIndex_; + QPersistentModelIndex whiteboardsIndex_; + }; } diff --git a/Swift/QtUI/ChatList/ChatListRecentItem.cpp b/Swift/QtUI/ChatList/ChatListRecentItem.cpp index dc40855..383f312 100644 --- a/Swift/QtUI/ChatList/ChatListRecentItem.cpp +++ b/Swift/QtUI/ChatList/ChatListRecentItem.cpp @@ -17,25 +17,25 @@ ChatListRecentItem::ChatListRecentItem(const ChatListWindow::Chat& chat, ChatLis } const ChatListWindow::Chat& ChatListRecentItem::getChat() const { - return chat_; + return chat_; } QVariant ChatListRecentItem::data(int role) const { - switch (role) { - case Qt::DisplayRole: return chat_.impromptuJIDs.empty() ? P2QSTRING(chat_.chatName) : P2QSTRING(chat_.getImpromptuTitle()); - case DetailTextRole: return P2QSTRING(chat_.activity); - /*case Qt::TextColorRole: return textColor_; - case Qt::BackgroundColorRole: return backgroundColor_; - case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant(); - case StatusTextRole: return statusText_;*/ - case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath))); - case PresenceIconRole: return getPresenceIcon(); - default: return QVariant(); - } + switch (role) { + case Qt::DisplayRole: return chat_.impromptuJIDs.empty() ? P2QSTRING(chat_.chatName) : P2QSTRING(chat_.getImpromptuTitle()); + case DetailTextRole: return P2QSTRING(chat_.activity); + /*case Qt::TextColorRole: return textColor_; + case Qt::BackgroundColorRole: return backgroundColor_; + case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant(); + case StatusTextRole: return statusText_;*/ + case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath))); + case PresenceIconRole: return getPresenceIcon(); + default: return QVariant(); + } } QIcon ChatListRecentItem::getPresenceIcon() const { - return QIcon(statusShowTypeToIconPath(chat_.statusType)); + return QIcon(statusShowTypeToIconPath(chat_.statusType)); } } diff --git a/Swift/QtUI/ChatList/ChatListRecentItem.h b/Swift/QtUI/ChatList/ChatListRecentItem.h index 338bc43..4f0a363 100644 --- a/Swift/QtUI/ChatList/ChatListRecentItem.h +++ b/Swift/QtUI/ChatList/ChatListRecentItem.h @@ -18,20 +18,20 @@ #include namespace Swift { - class ChatListRecentItem : public ChatListItem { - public: - enum RecentItemRoles { - DetailTextRole = Qt::UserRole, - AvatarRole = Qt::UserRole + 1, - PresenceIconRole = Qt::UserRole + 2/*, - StatusShowTypeRole = Qt::UserRole + 3, - IdleRole = Qt::UserRole + 4*/ - }; - ChatListRecentItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent); - const ChatListWindow::Chat& getChat() const; - QVariant data(int role) const; - private: - QIcon getPresenceIcon() const; - ChatListWindow::Chat chat_; - }; + class ChatListRecentItem : public ChatListItem { + public: + enum RecentItemRoles { + DetailTextRole = Qt::UserRole, + AvatarRole = Qt::UserRole + 1, + PresenceIconRole = Qt::UserRole + 2/*, + StatusShowTypeRole = Qt::UserRole + 3, + IdleRole = Qt::UserRole + 4*/ + }; + ChatListRecentItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent); + const ChatListWindow::Chat& getChat() const; + QVariant data(int role) const; + private: + QIcon getPresenceIcon() const; + ChatListWindow::Chat chat_; + }; } diff --git a/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp b/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp index f6ecec1..b6f8951 100644 --- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp +++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.cpp @@ -18,30 +18,30 @@ #include namespace Swift { - ChatListWhiteboardItem::ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent) : ChatListItem(parent), chat_(chat) { - - } - - const ChatListWindow::Chat& ChatListWhiteboardItem::getChat() const { - return chat_; - } - - QVariant ChatListWhiteboardItem::data(int role) const { - switch (role) { - case Qt::DisplayRole: return P2QSTRING(chat_.chatName); - case DetailTextRole: return P2QSTRING(chat_.activity); - /*case Qt::TextColorRole: return textColor_; - case Qt::BackgroundColorRole: return backgroundColor_; - case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant(); - case StatusTextRole: return statusText_;*/ - case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath))); - case PresenceIconRole: return getPresenceIcon(); - default: return QVariant(); - } - } - - QIcon ChatListWhiteboardItem::getPresenceIcon() const { - return QIcon(statusShowTypeToIconPath(chat_.statusType)); - } + ChatListWhiteboardItem::ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent) : ChatListItem(parent), chat_(chat) { + + } + + const ChatListWindow::Chat& ChatListWhiteboardItem::getChat() const { + return chat_; + } + + QVariant ChatListWhiteboardItem::data(int role) const { + switch (role) { + case Qt::DisplayRole: return P2QSTRING(chat_.chatName); + case DetailTextRole: return P2QSTRING(chat_.activity); + /*case Qt::TextColorRole: return textColor_; + case Qt::BackgroundColorRole: return backgroundColor_; + case Qt::ToolTipRole: return isContact() ? toolTipString() : QVariant(); + case StatusTextRole: return statusText_;*/ + case AvatarRole: return QVariant(P2QSTRING(pathToString(chat_.avatarPath))); + case PresenceIconRole: return getPresenceIcon(); + default: return QVariant(); + } + } + + QIcon ChatListWhiteboardItem::getPresenceIcon() const { + return QIcon(statusShowTypeToIconPath(chat_.statusType)); + } } diff --git a/Swift/QtUI/ChatList/ChatListWhiteboardItem.h b/Swift/QtUI/ChatList/ChatListWhiteboardItem.h index fbbe7c5..92acb1c 100644 --- a/Swift/QtUI/ChatList/ChatListWhiteboardItem.h +++ b/Swift/QtUI/ChatList/ChatListWhiteboardItem.h @@ -18,19 +18,19 @@ #include namespace Swift { - class ChatListWhiteboardItem : public ChatListItem { - public: - enum RecentItemRoles { - DetailTextRole = Qt::UserRole, - AvatarRole = Qt::UserRole + 1, - PresenceIconRole = Qt::UserRole + 2/*, - StatusShowTypeRole = Qt::UserRole + 3*/ - }; - ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent); - const ChatListWindow::Chat& getChat() const; - QVariant data(int role) const; - private: - QIcon getPresenceIcon() const; - ChatListWindow::Chat chat_; - }; + class ChatListWhiteboardItem : public ChatListItem { + public: + enum RecentItemRoles { + DetailTextRole = Qt::UserRole, + AvatarRole = Qt::UserRole + 1, + PresenceIconRole = Qt::UserRole + 2/*, + StatusShowTypeRole = Qt::UserRole + 3*/ + }; + ChatListWhiteboardItem(const ChatListWindow::Chat& chat, ChatListGroupItem* parent); + const ChatListWindow::Chat& getChat() const; + QVariant data(int role) const; + private: + QIcon getPresenceIcon() const; + ChatListWindow::Chat chat_; + }; } diff --git a/Swift/QtUI/ChatList/QtChatListWindow.cpp b/Swift/QtUI/ChatList/QtChatListWindow.cpp index b990b84..eddd0cd 100644 --- a/Swift/QtUI/ChatList/QtChatListWindow.cpp +++ b/Swift/QtUI/ChatList/QtChatListWindow.cpp @@ -31,197 +31,197 @@ namespace Swift { QtChatListWindow::QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent) : QTreeView(parent), isOnline_(false) { - eventStream_ = uiEventStream; - settings_ = settings; - bookmarksEnabled_ = false; - model_ = new ChatListModel(); - setModel(model_); - delegate_ = new ChatListDelegate(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); - setItemDelegate(delegate_); - setHeaderHidden(true); + eventStream_ = uiEventStream; + settings_ = settings; + bookmarksEnabled_ = false; + model_ = new ChatListModel(); + setModel(model_); + delegate_ = new ChatListDelegate(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); + setItemDelegate(delegate_); + setHeaderHidden(true); #ifdef SWIFT_PLATFORM_MACOSX - setAlternatingRowColors(true); + setAlternatingRowColors(true); #endif - expandAll(); - setAnimated(true); - setIndentation(0); - setDragEnabled(true); - setRootIsDecorated(true); - setupContextMenus(); - connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&))); - connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&))); + expandAll(); + setAnimated(true); + setIndentation(0); + setDragEnabled(true); + setRootIsDecorated(true); + setupContextMenus(); + connect(this, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&))); + connect(this, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleClicked(const QModelIndex&))); - settings_->onSettingChanged.connect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1)); + settings_->onSettingChanged.connect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1)); } QtChatListWindow::~QtChatListWindow() { - settings_->onSettingChanged.disconnect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1)); - delete model_; - delete delegate_; - delete mucMenu_; - delete emptyMenu_; + settings_->onSettingChanged.disconnect(boost::bind(&QtChatListWindow::handleSettingChanged, this, _1)); + delete model_; + delete delegate_; + delete mucMenu_; + delete emptyMenu_; } void QtChatListWindow::handleSettingChanged(const std::string& setting) { - if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) { - delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); - repaint(); - } + if (setting == QtUISettingConstants::COMPACT_ROSTER.getKey()) { + delegate_->setCompact(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); + repaint(); + } } void QtChatListWindow::handleClearRecentsRequested() { - onClearRecentsRequested(); + onClearRecentsRequested(); } void QtChatListWindow::setBookmarksEnabled(bool enabled) { - bookmarksEnabled_ = enabled; + bookmarksEnabled_ = enabled; } void QtChatListWindow::handleClicked(const QModelIndex& index) { - ChatListGroupItem* item = dynamic_cast(static_cast(index.internalPointer())); - if (item) { - setExpanded(index, !isExpanded(index)); - } + ChatListGroupItem* item = dynamic_cast(static_cast(index.internalPointer())); + if (item) { + setExpanded(index, !isExpanded(index)); + } } void QtChatListWindow::setupContextMenus() { - mucMenu_ = new QMenu(); - onlineOnlyActions_ << mucMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark())); - onlineOnlyActions_ << mucMenu_->addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark())); - onlineOnlyActions_ << mucMenu_->addAction(tr("Remove Bookmark"), this, SLOT(handleRemoveBookmark())); - emptyMenu_ = new QMenu(); - onlineOnlyActions_ << emptyMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark())); + mucMenu_ = new QMenu(); + onlineOnlyActions_ << mucMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark())); + onlineOnlyActions_ << mucMenu_->addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark())); + onlineOnlyActions_ << mucMenu_->addAction(tr("Remove Bookmark"), this, SLOT(handleRemoveBookmark())); + emptyMenu_ = new QMenu(); + onlineOnlyActions_ << emptyMenu_->addAction(tr("Add New Bookmark"), this, SLOT(handleAddBookmark())); } void QtChatListWindow::handleItemActivated(const QModelIndex& index) { - ChatListItem* item = model_->getItemForIndex(index); - if (ChatListMUCItem* mucItem = dynamic_cast(item)) { - onMUCBookmarkActivated(mucItem->getBookmark()); - } - else if (ChatListRecentItem* recentItem = dynamic_cast(item)) { - onRecentActivated(recentItem->getChat()); - } - else if (ChatListWhiteboardItem* whiteboardItem = dynamic_cast(item)) { - if (!whiteboardItem->getChat().isMUC || bookmarksEnabled_) { - eventStream_->send(boost::make_shared(whiteboardItem->getChat().jid)); - } - } + ChatListItem* item = model_->getItemForIndex(index); + if (ChatListMUCItem* mucItem = dynamic_cast(item)) { + onMUCBookmarkActivated(mucItem->getBookmark()); + } + else if (ChatListRecentItem* recentItem = dynamic_cast(item)) { + onRecentActivated(recentItem->getChat()); + } + else if (ChatListWhiteboardItem* whiteboardItem = dynamic_cast(item)) { + if (!whiteboardItem->getChat().isMUC || bookmarksEnabled_) { + eventStream_->send(boost::make_shared(whiteboardItem->getChat().jid)); + } + } } void QtChatListWindow::clearBookmarks() { - model_->clearBookmarks(); + model_->clearBookmarks(); } void QtChatListWindow::addMUCBookmark(const MUCBookmark& bookmark) { - model_->addMUCBookmark(bookmark); + model_->addMUCBookmark(bookmark); } void QtChatListWindow::removeMUCBookmark(const MUCBookmark& bookmark) { - model_->removeMUCBookmark(bookmark); + model_->removeMUCBookmark(bookmark); } void QtChatListWindow::addWhiteboardSession(const ChatListWindow::Chat& chat) { - model_->addWhiteboardSession(chat); + model_->addWhiteboardSession(chat); } void QtChatListWindow::removeWhiteboardSession(const JID& jid) { - model_->removeWhiteboardSession(jid); + model_->removeWhiteboardSession(jid); } void QtChatListWindow::setRecents(const std::list& recents) { - model_->setRecents(recents); + model_->setRecents(recents); } void QtChatListWindow::setUnreadCount(int unread) { - emit onCountUpdated(unread); + emit onCountUpdated(unread); } void QtChatListWindow::setOnline(bool isOnline) { - isOnline_ = isOnline; + isOnline_ = isOnline; } void QtChatListWindow::handleRemoveBookmark() { - const ChatListMUCItem* mucItem = dynamic_cast(contextMenuItem_); - if (!mucItem) return; - eventStream_->send(boost::shared_ptr(new RemoveMUCBookmarkUIEvent(mucItem->getBookmark()))); + const ChatListMUCItem* mucItem = dynamic_cast(contextMenuItem_); + if (!mucItem) return; + eventStream_->send(boost::shared_ptr(new RemoveMUCBookmarkUIEvent(mucItem->getBookmark()))); } void QtChatListWindow::handleAddBookmarkFromRecents() { - const ChatListRecentItem* item = dynamic_cast(contextMenuItem_); - if (item) { - const ChatListWindow::Chat& chat = item->getChat(); - MUCBookmark bookmark(chat.jid, chat.jid.toBare().toString()); - bookmark.setNick(chat.nick); - bookmark.setPassword(chat.password); - eventStream_->send(boost::shared_ptr(new AddMUCBookmarkUIEvent(bookmark))); - } + const ChatListRecentItem* item = dynamic_cast(contextMenuItem_); + if (item) { + const ChatListWindow::Chat& chat = item->getChat(); + MUCBookmark bookmark(chat.jid, chat.jid.toBare().toString()); + bookmark.setNick(chat.nick); + bookmark.setPassword(chat.password); + eventStream_->send(boost::shared_ptr(new AddMUCBookmarkUIEvent(bookmark))); + } } void QtChatListWindow::handleAddBookmark() { - (new QtAddBookmarkWindow(eventStream_))->show(); + (new QtAddBookmarkWindow(eventStream_))->show(); } void QtChatListWindow::handleEditBookmark() { - const ChatListMUCItem* mucItem = dynamic_cast(contextMenuItem_); - if (!mucItem) return; - QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, mucItem->getBookmark()); - window->show(); + const ChatListMUCItem* mucItem = dynamic_cast(contextMenuItem_); + if (!mucItem) return; + QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, mucItem->getBookmark()); + window->show(); } void QtChatListWindow::dragEnterEvent(QDragEnterEvent *event) { - if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) { - event->acceptProposedAction(); - } + if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) { + event->acceptProposedAction(); + } } void QtChatListWindow::contextMenuEvent(QContextMenuEvent* event) { - QModelIndex index = indexAt(event->pos()); - ChatListItem* baseItem = index.isValid() ? static_cast(index.internalPointer()) : NULL; - contextMenuItem_ = baseItem; - - foreach(QAction* action, onlineOnlyActions_) { - action->setEnabled(isOnline_); - } - - if (!baseItem) { - emptyMenu_->exec(QCursor::pos()); - return; - } - - ChatListMUCItem* mucItem = dynamic_cast(baseItem); - if (mucItem) { - if (!bookmarksEnabled_) { - return; - } - mucMenu_->exec(QCursor::pos()); - return; - } - - ChatListRecentItem* recentItem = dynamic_cast(baseItem); - if (recentItem) { - const ChatListWindow::Chat& chat = recentItem->getChat(); - if (chat.isMUC) { - QMenu mucRecentsMenu; - QAction* bookmarkAction = NULL; - const ChatListMUCItem* mucItem = model_->getChatListMUCItem(chat.jid); - if (mucItem) { - contextMenuItem_ = mucItem; - bookmarkAction = mucRecentsMenu.addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark())); - } - else { - bookmarkAction = mucRecentsMenu.addAction(tr("Add to Bookmarks"), this, SLOT(handleAddBookmarkFromRecents())); - } - bookmarkAction->setEnabled(isOnline_); - mucRecentsMenu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested())); - mucRecentsMenu.exec(QCursor::pos()); - return; - } - } - - QMenu menu; - menu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested())); - menu.exec(event->globalPos()); + QModelIndex index = indexAt(event->pos()); + ChatListItem* baseItem = index.isValid() ? static_cast(index.internalPointer()) : NULL; + contextMenuItem_ = baseItem; + + foreach(QAction* action, onlineOnlyActions_) { + action->setEnabled(isOnline_); + } + + if (!baseItem) { + emptyMenu_->exec(QCursor::pos()); + return; + } + + ChatListMUCItem* mucItem = dynamic_cast(baseItem); + if (mucItem) { + if (!bookmarksEnabled_) { + return; + } + mucMenu_->exec(QCursor::pos()); + return; + } + + ChatListRecentItem* recentItem = dynamic_cast(baseItem); + if (recentItem) { + const ChatListWindow::Chat& chat = recentItem->getChat(); + if (chat.isMUC) { + QMenu mucRecentsMenu; + QAction* bookmarkAction = NULL; + const ChatListMUCItem* mucItem = model_->getChatListMUCItem(chat.jid); + if (mucItem) { + contextMenuItem_ = mucItem; + bookmarkAction = mucRecentsMenu.addAction(tr("Edit Bookmark"), this, SLOT(handleEditBookmark())); + } + else { + bookmarkAction = mucRecentsMenu.addAction(tr("Add to Bookmarks"), this, SLOT(handleAddBookmarkFromRecents())); + } + bookmarkAction->setEnabled(isOnline_); + mucRecentsMenu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested())); + mucRecentsMenu.exec(QCursor::pos()); + return; + } + } + + QMenu menu; + menu.addAction(tr("Clear recents"), this, SLOT(handleClearRecentsRequested())); + menu.exec(event->globalPos()); } } diff --git a/Swift/QtUI/ChatList/QtChatListWindow.h b/Swift/QtUI/ChatList/QtChatListWindow.h index 627dcd4..61f8391 100644 --- a/Swift/QtUI/ChatList/QtChatListWindow.h +++ b/Swift/QtUI/ChatList/QtChatListWindow.h @@ -15,50 +15,50 @@ #include namespace Swift { - class SettingsProvider; - class QtChatListWindow : public QTreeView, public ChatListWindow { - Q_OBJECT - public: - QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent = NULL); - virtual ~QtChatListWindow(); - void addMUCBookmark(const MUCBookmark& bookmark); - void removeMUCBookmark(const MUCBookmark& bookmark); - void addWhiteboardSession(const ChatListWindow::Chat& chat); - void removeWhiteboardSession(const JID& jid); - void setBookmarksEnabled(bool enabled); - void setRecents(const std::list& recents); - void setUnreadCount(int unread); - void clearBookmarks(); - virtual void setOnline(bool isOnline); + class SettingsProvider; + class QtChatListWindow : public QTreeView, public ChatListWindow { + Q_OBJECT + public: + QtChatListWindow(UIEventStream *uiEventStream, SettingsProvider* settings, QWidget* parent = NULL); + virtual ~QtChatListWindow(); + void addMUCBookmark(const MUCBookmark& bookmark); + void removeMUCBookmark(const MUCBookmark& bookmark); + void addWhiteboardSession(const ChatListWindow::Chat& chat); + void removeWhiteboardSession(const JID& jid); + void setBookmarksEnabled(bool enabled); + void setRecents(const std::list& recents); + void setUnreadCount(int unread); + void clearBookmarks(); + virtual void setOnline(bool isOnline); - signals: - void onCountUpdated(int count); - private slots: - void handleItemActivated(const QModelIndex&); - void handleAddBookmark(); - void handleEditBookmark(); - void handleRemoveBookmark(); - void handleAddBookmarkFromRecents(); - void handleClicked(const QModelIndex& index); - void handleSettingChanged(const std::string& setting); - void handleClearRecentsRequested(); + signals: + void onCountUpdated(int count); + private slots: + void handleItemActivated(const QModelIndex&); + void handleAddBookmark(); + void handleEditBookmark(); + void handleRemoveBookmark(); + void handleAddBookmarkFromRecents(); + void handleClicked(const QModelIndex& index); + void handleSettingChanged(const std::string& setting); + void handleClearRecentsRequested(); - protected: - void dragEnterEvent(QDragEnterEvent* event); - void contextMenuEvent(QContextMenuEvent* event); + protected: + void dragEnterEvent(QDragEnterEvent* event); + void contextMenuEvent(QContextMenuEvent* event); - private: - void setupContextMenus(); - bool bookmarksEnabled_; - UIEventStream* eventStream_; - ChatListModel* model_; - ChatListDelegate* delegate_; - QMenu* mucMenu_; - QMenu* emptyMenu_; - const ChatListItem* contextMenuItem_; - SettingsProvider* settings_; - QList onlineOnlyActions_; - bool isOnline_; - }; + private: + void setupContextMenus(); + bool bookmarksEnabled_; + UIEventStream* eventStream_; + ChatListModel* model_; + ChatListDelegate* delegate_; + QMenu* mucMenu_; + QMenu* emptyMenu_; + const ChatListItem* contextMenuItem_; + SettingsProvider* settings_; + QList onlineOnlyActions_; + bool isOnline_; + }; } diff --git a/Swift/QtUI/ChatSnippet.cpp b/Swift/QtUI/ChatSnippet.cpp index d8b64c1..14e4674 100644 --- a/Swift/QtUI/ChatSnippet.cpp +++ b/Swift/QtUI/ChatSnippet.cpp @@ -19,79 +19,79 @@ ChatSnippet::~ChatSnippet() { } QString ChatSnippet::timeToEscapedString(const QDateTime& time) { - QDate now(QDate::currentDate()); - QString date = ""; - if (time.date().daysTo(now) > 0) { - date = "ddd "; - } - if (time.date().month() != now.month()) { - date = date + "MMMM "; - } - if (time.date().daysTo(now) > 6) { - date = date + "d "; - } - if (time.date().year() != now.year()) { - date = date + "yy "; - } - date += "h:mm"; - return escape(time.toString(date)); + QDate now(QDate::currentDate()); + QString date = ""; + if (time.date().daysTo(now) > 0) { + date = "ddd "; + } + if (time.date().month() != now.month()) { + date = date + "MMMM "; + } + if (time.date().daysTo(now) > 6) { + date = date + "d "; + } + if (time.date().year() != now.year()) { + date = date + "yy "; + } + date += "h:mm"; + return escape(time.toString(date)); } QString ChatSnippet::wrapResizable(const QString& text) { - return "" + text + ""; + return "" + text + ""; } QString ChatSnippet::directionToCSS(Direction direction) { - return direction == RTL ? QString("rtl") : QString("ltr"); + return direction == RTL ? QString("rtl") : QString("ltr"); } ChatSnippet::Direction ChatSnippet::getDirection(const ChatWindow::ChatMessage& message) { - boost::shared_ptr textPart; - std::string text = ""; - foreach (boost::shared_ptr part, message.getParts()) { - if ((textPart = boost::dynamic_pointer_cast(part))) { - text = textPart->text; - break; - } - } - return getDirection(text); + boost::shared_ptr textPart; + std::string text = ""; + foreach (boost::shared_ptr part, message.getParts()) { + if ((textPart = boost::dynamic_pointer_cast(part))) { + text = textPart->text; + break; + } + } + return getDirection(text); } ChatSnippet::Direction ChatSnippet::getDirection(const std::string& message) { - return getDirection(P2QSTRING(message)); + return getDirection(P2QSTRING(message)); } ChatSnippet::Direction ChatSnippet::getDirection(const QString& message) { - /* - for (int i = 0; i < message.size(); ++i) { - switch (message.at(i).direction()) { - case QChar::DirL: - case QChar::DirLRE: - case QChar::DirLRO: - return ChatSnippet::LTR; - case QChar::DirR: - case QChar::DirAL: - case QChar::DirRLE: - case QChar::DirRLO: - return ChatSnippet::RTL; - case QChar::DirEN: - case QChar::DirES: - case QChar::DirET: - case QChar::DirAN: - case QChar::DirCS: - case QChar::DirB: - case QChar::DirWS: - case QChar::DirON: - case QChar::DirS: - case QChar::DirPDF: - case QChar::DirNSM: - case QChar::DirBN: - break; - } - } - return ChatSnippet::LTR; - */ - return message.isRightToLeft() ? ChatSnippet::RTL : ChatSnippet::LTR; + /* + for (int i = 0; i < message.size(); ++i) { + switch (message.at(i).direction()) { + case QChar::DirL: + case QChar::DirLRE: + case QChar::DirLRO: + return ChatSnippet::LTR; + case QChar::DirR: + case QChar::DirAL: + case QChar::DirRLE: + case QChar::DirRLO: + return ChatSnippet::RTL; + case QChar::DirEN: + case QChar::DirES: + case QChar::DirET: + case QChar::DirAN: + case QChar::DirCS: + case QChar::DirB: + case QChar::DirWS: + case QChar::DirON: + case QChar::DirS: + case QChar::DirPDF: + case QChar::DirNSM: + case QChar::DirBN: + break; + } + } + return ChatSnippet::LTR; + */ + return message.isRightToLeft() ? ChatSnippet::RTL : ChatSnippet::LTR; } diff --git a/Swift/QtUI/ChatSnippet.h b/Swift/QtUI/ChatSnippet.h index 7c99928..bf2d6d2 100644 --- a/Swift/QtUI/ChatSnippet.h +++ b/Swift/QtUI/ChatSnippet.h @@ -18,55 +18,55 @@ #include namespace Swift { - class ChatSnippet { - public: - enum Direction { - RTL, - LTR - }; - - ChatSnippet(bool appendToPrevious); - virtual ~ChatSnippet(); - - virtual const QString& getContent() const = 0; - virtual QString getContinuationElementID() const { return ""; } - - boost::shared_ptr getContinuationFallbackSnippet() const {return continuationFallback_;} - - bool getAppendToPrevious() const { - return appendToPrevious_; - } - - static QString escape(const QString& original) { - QString result(original); - result.replace("%message%", "%message%"); - result.replace("%sender%", "%sender%"); - result.replace("%wrapped_sender%", "%wrapped_sender%"); - result.replace("%time%", "%%time%"); - result.replace("%shortTime%", "%%shortTime%"); - result.replace("%userIconPath%", "%userIconPath%"); - result.replace("%id%", "%id%"); - result.replace("\t", " "); - result.replace(" ", "  "); - return result; - } - - static QString timeToEscapedString(const QDateTime& time); - - static Direction getDirection(const std::string& message); - static Direction getDirection(const ChatWindow::ChatMessage& message); - static Direction getDirection(const QString& message); - - protected: - static QString directionToCSS(Direction direction); - - QString wrapResizable(const QString& text); - void setContinuationFallbackSnippet(boost::shared_ptr continuationFallback) { - continuationFallback_ = continuationFallback; - } - private: - bool appendToPrevious_; - boost::shared_ptr continuationFallback_; - }; + class ChatSnippet { + public: + enum Direction { + RTL, + LTR + }; + + ChatSnippet(bool appendToPrevious); + virtual ~ChatSnippet(); + + virtual const QString& getContent() const = 0; + virtual QString getContinuationElementID() const { return ""; } + + boost::shared_ptr getContinuationFallbackSnippet() const {return continuationFallback_;} + + bool getAppendToPrevious() const { + return appendToPrevious_; + } + + static QString escape(const QString& original) { + QString result(original); + result.replace("%message%", "%message%"); + result.replace("%sender%", "%sender%"); + result.replace("%wrapped_sender%", "%wrapped_sender%"); + result.replace("%time%", "%%time%"); + result.replace("%shortTime%", "%%shortTime%"); + result.replace("%userIconPath%", "%userIconPath%"); + result.replace("%id%", "%id%"); + result.replace("\t", " "); + result.replace(" ", "  "); + return result; + } + + static QString timeToEscapedString(const QDateTime& time); + + static Direction getDirection(const std::string& message); + static Direction getDirection(const ChatWindow::ChatMessage& message); + static Direction getDirection(const QString& message); + + protected: + static QString directionToCSS(Direction direction); + + QString wrapResizable(const QString& text); + void setContinuationFallbackSnippet(boost::shared_ptr continuationFallback) { + continuationFallback_ = continuationFallback; + } + private: + bool appendToPrevious_; + boost::shared_ptr continuationFallback_; + }; } diff --git a/Swift/QtUI/ChatView/main.cpp b/Swift/QtUI/ChatView/main.cpp index 4bde1ef..aa3255e 100644 --- a/Swift/QtUI/ChatView/main.cpp +++ b/Swift/QtUI/ChatView/main.cpp @@ -27,154 +27,154 @@ using namespace Swift; /* class MyNetworkReply : public QNetworkReply { - public: - MyNetworkReply() { - } - - qint64 readData(char*, qint64) { - return 0; - } - - virtual void abort() { - } + public: + MyNetworkReply() { + } + + qint64 readData(char*, qint64) { + return 0; + } + + virtual void abort() { + } }; class MyNetworkAccessManager : public QNetworkAccessManager { - public: - MyNetworkAccessManager() { - } - - QNetworkReply * createRequest (Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) { - assert(op == QNetworkAccessManager::GetOperation); - qDebug() << "Requesting: " << request.url(); - return QNetworkAccessManager::createRequest(op, request, outgoingData); - //return new MyNetworkReply(); - } + public: + MyNetworkAccessManager() { + } + + QNetworkReply * createRequest (Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) { + assert(op == QNetworkAccessManager::GetOperation); + qDebug() << "Requesting: " << request.url(); + return QNetworkAccessManager::createRequest(op, request, outgoingData); + //return new MyNetworkReply(); + } }; - QVBoxLayout* mainLayout = new QVBoxLayout(this); - webView_ = new QWebView(this); - - QFile file(":/themes/Stockholm/Contents/Resources/Incoming/Content.html"); - file.open(QIODevice::ReadOnly); - QString content = QString::fromUtf8(file.readAll()); - - webPage_ = new QWebPage(this); - webPage_->setNetworkAccessManager(new MyNetworkAccessManager()); - webView_->setPage(webPage_); - QString pagehtml = - "" - //"" - "" - "" - "" - "" + content + ""; - qDebug() << pagehtml; - webPage_->mainFrame()->setHtml(pagehtml); + QVBoxLayout* mainLayout = new QVBoxLayout(this); + webView_ = new QWebView(this); + + QFile file(":/themes/Stockholm/Contents/Resources/Incoming/Content.html"); + file.open(QIODevice::ReadOnly); + QString content = QString::fromUtf8(file.readAll()); + + webPage_ = new QWebPage(this); + webPage_->setNetworkAccessManager(new MyNetworkAccessManager()); + webView_->setPage(webPage_); + QString pagehtml = + "" + //"" + "" + "" + "" + "" + content + ""; + qDebug() << pagehtml; + webPage_->mainFrame()->setHtml(pagehtml); */ /* class ChatView : public QWidget { - public: - ChatView(QWidget* parent) : QWidget(parent) { - setFocusPolicy(Qt::NoFocus); - - QVBoxLayout* mainLayout = new QVBoxLayout(this); - mainLayout->setSpacing(0); - mainLayout->setContentsMargins(0,0,0,0); - - webView_ = new QWebView(this); - webView_->setFocusPolicy(Qt::NoFocus); - mainLayout->addWidget(webView_); - - webPage_ = new QWebPage(this); - webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); - webView_->setPage(webPage_); - connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard())); - - QString pageHTML = "
"; - webPage_->mainFrame()->setHtml(pageHTML); - } - - void appendHTML(const QString& html) { - webPage_->mainFrame()->evaluateJavaScript( - "newNode = document.createElement(\"div\");" - "newNode.innerHTML = \"" + html + "\";" - "chatElement = document.getElementById(\"chat\");" - "chatElement.appendChild(newNode);"); - webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)); - } - - private: - QWebView* webView_; - QWebPage* webPage_; + public: + ChatView(QWidget* parent) : QWidget(parent) { + setFocusPolicy(Qt::NoFocus); + + QVBoxLayout* mainLayout = new QVBoxLayout(this); + mainLayout->setSpacing(0); + mainLayout->setContentsMargins(0,0,0,0); + + webView_ = new QWebView(this); + webView_->setFocusPolicy(Qt::NoFocus); + mainLayout->addWidget(webView_); + + webPage_ = new QWebPage(this); + webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); + webView_->setPage(webPage_); + connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard())); + + QString pageHTML = "
"; + webPage_->mainFrame()->setHtml(pageHTML); + } + + void appendHTML(const QString& html) { + webPage_->mainFrame()->evaluateJavaScript( + "newNode = document.createElement(\"div\");" + "newNode.innerHTML = \"" + html + "\";" + "chatElement = document.getElementById(\"chat\");" + "chatElement.appendChild(newNode);"); + webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)); + } + + private: + QWebView* webView_; + QWebPage* webPage_; }; */ class MyWidget : public QWidget { - Q_OBJECT - - public: - MyWidget() : previousWasIncoming_(false), previousWasOutgoing_(false), previousWasSystem_(false) { - QVBoxLayout* mainLayout = new QVBoxLayout(this); - chatView_ = new QtChatView(this); - mainLayout->addWidget(chatView_); - input1_ = new QLineEdit(this); - connect(input1_, SIGNAL(returnPressed()), SLOT(addIncoming())); - mainLayout->addWidget(input1_); - input2_ = new QLineEdit(this); - connect(input2_, SIGNAL(returnPressed()), SLOT(addOutgoing())); - mainLayout->addWidget(input2_); - input3_ = new QLineEdit(this); - connect(input3_, SIGNAL(returnPressed()), SLOT(addSystem())); - mainLayout->addWidget(input3_); - - resize(300,200); - } - - public slots: - void addIncoming() { - chatView_->addMessage(MessageSnippet(input1_->text(), "Me", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", true, previousWasIncoming_)); - previousWasIncoming_ = true; - previousWasOutgoing_ = false; - previousWasSystem_ = false; - input1_->clear(); - } - - void addOutgoing() { - chatView_->addMessage(MessageSnippet(input2_->text(), "You", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", false, previousWasOutgoing_)); - previousWasIncoming_ = false; - previousWasOutgoing_ = true; - previousWasSystem_ = false; - input2_->clear(); - } - - void addSystem() { - chatView_->addMessage(SystemMessageSnippet(input3_->text(), QDateTime::currentDateTime(), previousWasSystem_)); - previousWasIncoming_ = false; - previousWasOutgoing_ = false; - previousWasSystem_ = true; - input3_->clear(); - } - - private: - bool previousWasIncoming_; - bool previousWasOutgoing_; - bool previousWasSystem_; - QtChatView* chatView_; - QLineEdit* input1_; - QLineEdit* input2_; - QLineEdit* input3_; + Q_OBJECT + + public: + MyWidget() : previousWasIncoming_(false), previousWasOutgoing_(false), previousWasSystem_(false) { + QVBoxLayout* mainLayout = new QVBoxLayout(this); + chatView_ = new QtChatView(this); + mainLayout->addWidget(chatView_); + input1_ = new QLineEdit(this); + connect(input1_, SIGNAL(returnPressed()), SLOT(addIncoming())); + mainLayout->addWidget(input1_); + input2_ = new QLineEdit(this); + connect(input2_, SIGNAL(returnPressed()), SLOT(addOutgoing())); + mainLayout->addWidget(input2_); + input3_ = new QLineEdit(this); + connect(input3_, SIGNAL(returnPressed()), SLOT(addSystem())); + mainLayout->addWidget(input3_); + + resize(300,200); + } + + public slots: + void addIncoming() { + chatView_->addMessage(MessageSnippet(input1_->text(), "Me", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", true, previousWasIncoming_)); + previousWasIncoming_ = true; + previousWasOutgoing_ = false; + previousWasSystem_ = false; + input1_->clear(); + } + + void addOutgoing() { + chatView_->addMessage(MessageSnippet(input2_->text(), "You", QDateTime::currentDateTime(), "qrc:/icons/avatar.png", false, previousWasOutgoing_)); + previousWasIncoming_ = false; + previousWasOutgoing_ = true; + previousWasSystem_ = false; + input2_->clear(); + } + + void addSystem() { + chatView_->addMessage(SystemMessageSnippet(input3_->text(), QDateTime::currentDateTime(), previousWasSystem_)); + previousWasIncoming_ = false; + previousWasOutgoing_ = false; + previousWasSystem_ = true; + input3_->clear(); + } + + private: + bool previousWasIncoming_; + bool previousWasOutgoing_; + bool previousWasSystem_; + QtChatView* chatView_; + QLineEdit* input1_; + QLineEdit* input2_; + QLineEdit* input3_; }; - + int main(int argc, char* argv[]) { - QApplication app(argc, argv); - MyWidget w; - w.show(); - return app.exec(); + QApplication app(argc, argv); + MyWidget w; + w.show(); + return app.exec(); } #include "main.moc" diff --git a/Swift/QtUI/CocoaApplicationActivateHelper.h b/Swift/QtUI/CocoaApplicationActivateHelper.h index 2b166e2..c7aa5b3 100644 --- a/Swift/QtUI/CocoaApplicationActivateHelper.h +++ b/Swift/QtUI/CocoaApplicationActivateHelper.h @@ -9,20 +9,20 @@ #include namespace Swift { - /** - * This class is here as a workaround for a bug in Qt. - * See Case #501. - */ - class CocoaApplicationActivateHelper : public QObject { - public: - CocoaApplicationActivateHelper(); - virtual ~CocoaApplicationActivateHelper(); + /** + * This class is here as a workaround for a bug in Qt. + * See Case #501. + */ + class CocoaApplicationActivateHelper : public QObject { + public: + CocoaApplicationActivateHelper(); + virtual ~CocoaApplicationActivateHelper(); - private: - bool eventFilter(QObject* o, QEvent* e); + private: + bool eventFilter(QObject* o, QEvent* e); - private: - struct Private; - Private* p; - }; + private: + struct Private; + Private* p; + }; } diff --git a/Swift/QtUI/CocoaApplicationActivateHelper.mm b/Swift/QtUI/CocoaApplicationActivateHelper.mm index f9c455c..4d4409d 100644 --- a/Swift/QtUI/CocoaApplicationActivateHelper.mm +++ b/Swift/QtUI/CocoaApplicationActivateHelper.mm @@ -19,37 +19,37 @@ @implementation CocoaApplicationActivateHelperDelegate - (void) handleActivate: (NSAppleEventDescriptor*) event withReply: (NSAppleEventDescriptor*) reply { - (void) event; (void) reply; - QApplication::postEvent(qApp, new QEvent(QEvent::ApplicationActivate)); + (void) event; (void) reply; + QApplication::postEvent(qApp, new QEvent(QEvent::ApplicationActivate)); } @end namespace Swift { struct CocoaApplicationActivateHelper::Private { - CocoaApplicationActivateHelperDelegate* delegate; - bool initialized; + CocoaApplicationActivateHelperDelegate* delegate; + bool initialized; }; CocoaApplicationActivateHelper::CocoaApplicationActivateHelper() { - p = new Private(); - p->delegate = [[CocoaApplicationActivateHelperDelegate alloc] init]; - p->initialized = false; - qApp->installEventFilter(this); + p = new Private(); + p->delegate = [[CocoaApplicationActivateHelperDelegate alloc] init]; + p->initialized = false; + qApp->installEventFilter(this); } CocoaApplicationActivateHelper::~CocoaApplicationActivateHelper() { - [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEReopenApplication]; - [p->delegate release]; - delete p; + [[NSAppleEventManager sharedAppleEventManager] removeEventHandlerForEventClass:kCoreEventClass andEventID:kAEReopenApplication]; + [p->delegate release]; + delete p; } bool CocoaApplicationActivateHelper::eventFilter(QObject* object, QEvent* event) { - if (object == qApp && event->type() == QEvent::ApplicationActivate && !p->initialized) { - [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->delegate andSelector:@selector(handleActivate:withReply:) forEventClass:kCoreEventClass andEventID:kAEReopenApplication]; - p->initialized = true; - } - return QObject::eventFilter(object, event); + if (object == qApp && event->type() == QEvent::ApplicationActivate && !p->initialized) { + [[NSAppleEventManager sharedAppleEventManager] setEventHandler:p->delegate andSelector:@selector(handleActivate:withReply:) forEventClass:kCoreEventClass andEventID:kAEReopenApplication]; + p->initialized = true; + } + return QObject::eventFilter(object, event); } diff --git a/Swift/QtUI/CocoaUIHelpers.h b/Swift/QtUI/CocoaUIHelpers.h index f5ec457..58cd539 100644 --- a/Swift/QtUI/CocoaUIHelpers.h +++ b/Swift/QtUI/CocoaUIHelpers.h @@ -20,7 +20,7 @@ namespace Swift { class CocoaUIHelpers { public: - static void displayCertificateChainAsSheet(QWidget* parent, const std::vector& chain); + static void displayCertificateChainAsSheet(QWidget* parent, const std::vector& chain); }; } diff --git a/Swift/QtUI/CocoaUIHelpers.mm b/Swift/QtUI/CocoaUIHelpers.mm index 3cb62f3..16fe2ce 100644 --- a/Swift/QtUI/CocoaUIHelpers.mm +++ b/Swift/QtUI/CocoaUIHelpers.mm @@ -21,23 +21,23 @@ namespace Swift { void CocoaUIHelpers::displayCertificateChainAsSheet(QWidget* parent, const std::vector& chain) { - NSWindow* parentWindow = [((NSView*)parent->winId()) window]; - NSMutableArray* certificates = [[NSMutableArray alloc] init]; - foreach(Certificate::ref cert, chain) { - // convert chain to SecCertificateRef - ByteArray certAsDER = cert->toDER(); - boost::shared_ptr::type> certData(CFDataCreate(NULL, certAsDER.data(), certAsDER.size()), CFRelease); - boost::shared_ptr macCert(SecCertificateCreateWithData(NULL, certData.get()), CFRelease); - - // add to NSMutable array - [certificates addObject: (id)macCert.get()]; - } - - - SFCertificatePanel* panel = [[SFCertificatePanel alloc] init]; - //[panel setPolicies:(id)policies.get()]; - [panel beginSheetForWindow:parentWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL certificates:certificates showGroup:YES]; - [certificates release]; + NSWindow* parentWindow = [((NSView*)parent->winId()) window]; + NSMutableArray* certificates = [[NSMutableArray alloc] init]; + foreach(Certificate::ref cert, chain) { + // convert chain to SecCertificateRef + ByteArray certAsDER = cert->toDER(); + boost::shared_ptr::type> certData(CFDataCreate(NULL, certAsDER.data(), certAsDER.size()), CFRelease); + boost::shared_ptr macCert(SecCertificateCreateWithData(NULL, certData.get()), CFRelease); + + // add to NSMutable array + [certificates addObject: (id)macCert.get()]; + } + + + SFCertificatePanel* panel = [[SFCertificatePanel alloc] init]; + //[panel setPolicies:(id)policies.get()]; + [panel beginSheetForWindow:parentWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL certificates:certificates showGroup:YES]; + [certificates release]; } } diff --git a/Swift/QtUI/EventViewer/EventDelegate.cpp b/Swift/QtUI/EventViewer/EventDelegate.cpp index cd657b8..eff9a7b 100644 --- a/Swift/QtUI/EventViewer/EventDelegate.cpp +++ b/Swift/QtUI/EventViewer/EventDelegate.cpp @@ -17,69 +17,69 @@ namespace Swift { EventDelegate::EventDelegate() : QStyledItemDelegate(), - messageDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false), - subscriptionDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true), - errorDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true), - mucInviteDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false), - incomingFileTransferDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false) { + messageDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false), + subscriptionDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true), + errorDelegate_(QtEvent::SenderRole, Qt::DisplayRole, true), + mucInviteDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false), + incomingFileTransferDelegate_(QtEvent::SenderRole, Qt::DisplayRole, false) { } QSize EventDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const { - QtEvent* item = static_cast(index.internalPointer()); - if (!item) { - return QStyledItemDelegate::sizeHint(option, index); - } - switch (getEventType(item->getEvent())) { - case MessageEventType: return messageDelegate_.sizeHint(option, item); - case SubscriptionEventType: return subscriptionDelegate_.sizeHint(option, item); - case ErrorEventType: return errorDelegate_.sizeHint(option, item); - case MUCInviteEventType: return mucInviteDelegate_.sizeHint(option, item); - case IncomingFileTransferEventType: return incomingFileTransferDelegate_.sizeHint(option, item); - } - assert(false); - return QSize(); + QtEvent* item = static_cast(index.internalPointer()); + if (!item) { + return QStyledItemDelegate::sizeHint(option, index); + } + switch (getEventType(item->getEvent())) { + case MessageEventType: return messageDelegate_.sizeHint(option, item); + case SubscriptionEventType: return subscriptionDelegate_.sizeHint(option, item); + case ErrorEventType: return errorDelegate_.sizeHint(option, item); + case MUCInviteEventType: return mucInviteDelegate_.sizeHint(option, item); + case IncomingFileTransferEventType: return incomingFileTransferDelegate_.sizeHint(option, item); + } + assert(false); + return QSize(); } void EventDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { - QtEvent* item = static_cast(index.internalPointer()); - if (!item) { - QStyledItemDelegate::paint(painter, option, index); - return; - } - switch (getEventType(item->getEvent())) { - case MessageEventType: messageDelegate_.paint(painter, option, item);break; - case SubscriptionEventType: subscriptionDelegate_.paint(painter, option, item);break; - case ErrorEventType: errorDelegate_.paint(painter, option, item);break; - case MUCInviteEventType: mucInviteDelegate_.paint(painter, option, item);break; - case IncomingFileTransferEventType: incomingFileTransferDelegate_.paint(painter, option, item);break; - } + QtEvent* item = static_cast(index.internalPointer()); + if (!item) { + QStyledItemDelegate::paint(painter, option, index); + return; + } + switch (getEventType(item->getEvent())) { + case MessageEventType: messageDelegate_.paint(painter, option, item);break; + case SubscriptionEventType: subscriptionDelegate_.paint(painter, option, item);break; + case ErrorEventType: errorDelegate_.paint(painter, option, item);break; + case MUCInviteEventType: mucInviteDelegate_.paint(painter, option, item);break; + case IncomingFileTransferEventType: incomingFileTransferDelegate_.paint(painter, option, item);break; + } } EventType EventDelegate::getEventType(boost::shared_ptr event) const { - boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event); - if (messageEvent) { - return MessageEventType; - } - boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(event); - if (subscriptionEvent) { - return SubscriptionEventType; - } - boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event); - if (errorEvent) { - return ErrorEventType; - } - boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event); - if (mucInviteEvent) { - return MUCInviteEventType; - } - boost::shared_ptr incomingFileTransferEvent = boost::dynamic_pointer_cast(event); - if (incomingFileTransferEvent) { - return IncomingFileTransferEventType; - } - //I don't know what this is. - assert(false); - return MessageEventType; + boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event); + if (messageEvent) { + return MessageEventType; + } + boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(event); + if (subscriptionEvent) { + return SubscriptionEventType; + } + boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event); + if (errorEvent) { + return ErrorEventType; + } + boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event); + if (mucInviteEvent) { + return MUCInviteEventType; + } + boost::shared_ptr incomingFileTransferEvent = boost::dynamic_pointer_cast(event); + if (incomingFileTransferEvent) { + return IncomingFileTransferEventType; + } + //I don't know what this is. + assert(false); + return MessageEventType; } } diff --git a/Swift/QtUI/EventViewer/EventDelegate.h b/Swift/QtUI/EventViewer/EventDelegate.h index 6ab96e4..0804589 100644 --- a/Swift/QtUI/EventViewer/EventDelegate.h +++ b/Swift/QtUI/EventViewer/EventDelegate.h @@ -12,21 +12,21 @@ #include namespace Swift { - enum EventType {MessageEventType, SubscriptionEventType, ErrorEventType, MUCInviteEventType, IncomingFileTransferEventType}; - class EventDelegate : public QStyledItemDelegate { - Q_OBJECT - public: - EventDelegate(); - QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; - private: - EventType getEventType(boost::shared_ptr event) const; - DelegateCommons common_; - TwoLineDelegate messageDelegate_; - TwoLineDelegate subscriptionDelegate_; - TwoLineDelegate errorDelegate_; - TwoLineDelegate mucInviteDelegate_; - TwoLineDelegate incomingFileTransferDelegate_; - }; + enum EventType {MessageEventType, SubscriptionEventType, ErrorEventType, MUCInviteEventType, IncomingFileTransferEventType}; + class EventDelegate : public QStyledItemDelegate { + Q_OBJECT + public: + EventDelegate(); + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; + private: + EventType getEventType(boost::shared_ptr event) const; + DelegateCommons common_; + TwoLineDelegate messageDelegate_; + TwoLineDelegate subscriptionDelegate_; + TwoLineDelegate errorDelegate_; + TwoLineDelegate mucInviteDelegate_; + TwoLineDelegate incomingFileTransferDelegate_; + }; } diff --git a/Swift/QtUI/EventViewer/EventModel.cpp b/Swift/QtUI/EventViewer/EventModel.cpp index 889bcac..1568ec7 100644 --- a/Swift/QtUI/EventViewer/EventModel.cpp +++ b/Swift/QtUI/EventViewer/EventModel.cpp @@ -11,100 +11,100 @@ namespace Swift { namespace { - const int inactiveEventsLimit = 50; + const int inactiveEventsLimit = 50; } EventModel::EventModel() { - + } EventModel::~EventModel() { - foreach (QtEvent* event, activeEvents_) { - delete event; - } - foreach (QtEvent* event, inactiveEvents_) { - delete event; - } + foreach (QtEvent* event, activeEvents_) { + delete event; + } + foreach (QtEvent* event, inactiveEvents_) { + delete event; + } } QtEvent* EventModel::getItem(int row) const { - QtEvent* event = NULL; - if (row < activeEvents_.size()) { - event = activeEvents_[row]; - } - else { - int inactiveRow = row - activeEvents_.size(); - if (inactiveRow < inactiveEvents_.size()) { - event = inactiveEvents_[inactiveRow]; - } - else { - SWIFT_LOG(error) << "Misbehaving EventModel requests row index outside of range"; - } - } - return event; + QtEvent* event = NULL; + if (row < activeEvents_.size()) { + event = activeEvents_[row]; + } + else { + int inactiveRow = row - activeEvents_.size(); + if (inactiveRow < inactiveEvents_.size()) { + event = inactiveEvents_[inactiveRow]; + } + else { + SWIFT_LOG(error) << "Misbehaving EventModel requests row index outside of range"; + } + } + return event; } int EventModel::getNewEventCount() { - return activeEvents_.size(); + return activeEvents_.size(); } QVariant EventModel::data(const QModelIndex& index, int role) const { - if (!index.isValid()) { - return QVariant(); - } - QtEvent* item = getItem(index.row()); - QVariant result = item ? item->data(role) : QVariant(); - return result; + if (!index.isValid()) { + return QVariant(); + } + QtEvent* item = getItem(index.row()); + QVariant result = item ? item->data(role) : QVariant(); + return result; } /* * We only reimplement this to get the pointers inside the indices. */ QModelIndex EventModel::index(int row, int column, const QModelIndex & parent) const { - if (!hasIndex(row, column, parent) || parent.isValid()) { - return QModelIndex(); - } + if (!hasIndex(row, column, parent) || parent.isValid()) { + return QModelIndex(); + } - return row < rowCount() ? createIndex(row, column, getItem(row)) : QModelIndex(); + return row < rowCount() ? createIndex(row, column, getItem(row)) : QModelIndex(); } int EventModel::rowCount(const QModelIndex& parent) const { - /* Invalid parent = root, valid parent = child, and we're a list not a tree.*/ - int count = parent.isValid() ? 0 : activeEvents_.size() + inactiveEvents_.size(); - return count; + /* Invalid parent = root, valid parent = child, and we're a list not a tree.*/ + int count = parent.isValid() ? 0 : activeEvents_.size() + inactiveEvents_.size(); + return count; } void EventModel::addEvent(boost::shared_ptr event, bool active) { - beginResetModel(); - if (active) { - activeEvents_.push_front(new QtEvent(event, active)); - } else { - inactiveEvents_.push_front(new QtEvent(event, active)); - if (inactiveEvents_.size() > inactiveEventsLimit) { - removeEvent(inactiveEvents_[inactiveEventsLimit]->getEvent()); - } - } - endResetModel(); + beginResetModel(); + if (active) { + activeEvents_.push_front(new QtEvent(event, active)); + } else { + inactiveEvents_.push_front(new QtEvent(event, active)); + if (inactiveEvents_.size() > inactiveEventsLimit) { + removeEvent(inactiveEvents_[inactiveEventsLimit]->getEvent()); + } + } + endResetModel(); } void EventModel::removeEvent(boost::shared_ptr event) { - beginResetModel(); - for (int i = inactiveEvents_.size() - 1; i >= 0; i--) { - if (event == inactiveEvents_[i]->getEvent()) { - inactiveEvents_.removeAt(i); - endResetModel(); - return; - } - } - - for (int i = 0; i < activeEvents_.size(); i++) { - if (event == activeEvents_[i]->getEvent()) { - activeEvents_.removeAt(i); - endResetModel(); - return; - } - } - endResetModel(); + beginResetModel(); + for (int i = inactiveEvents_.size() - 1; i >= 0; i--) { + if (event == inactiveEvents_[i]->getEvent()) { + inactiveEvents_.removeAt(i); + endResetModel(); + return; + } + } + + for (int i = 0; i < activeEvents_.size(); i++) { + if (event == activeEvents_[i]->getEvent()) { + activeEvents_.removeAt(i); + endResetModel(); + return; + } + } + endResetModel(); } } diff --git a/Swift/QtUI/EventViewer/EventModel.h b/Swift/QtUI/EventViewer/EventModel.h index 844e50f..5cd5028 100644 --- a/Swift/QtUI/EventViewer/EventModel.h +++ b/Swift/QtUI/EventViewer/EventModel.h @@ -17,21 +17,21 @@ namespace Swift { class EventModel : public QAbstractListModel { - Q_OBJECT - public: - EventModel(); - virtual ~EventModel(); - void addEvent(boost::shared_ptr event, bool active); - void removeEvent(boost::shared_ptr event); - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - int rowCount(const QModelIndex& parent = QModelIndex()) const; - QtEvent* getItem(int row) const; - int getNewEventCount(); - protected: - QModelIndex index(int row, int column = 0, const QModelIndex & parent = QModelIndex()) const; - private: - QList activeEvents_; - QList inactiveEvents_; + Q_OBJECT + public: + EventModel(); + virtual ~EventModel(); + void addEvent(boost::shared_ptr event, bool active); + void removeEvent(boost::shared_ptr event); + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; + QtEvent* getItem(int row) const; + int getNewEventCount(); + protected: + QModelIndex index(int row, int column = 0, const QModelIndex & parent = QModelIndex()) const; + private: + QList activeEvents_; + QList inactiveEvents_; }; } diff --git a/Swift/QtUI/EventViewer/EventView.cpp b/Swift/QtUI/EventViewer/EventView.cpp index fe299b8..4d56548 100644 --- a/Swift/QtUI/EventViewer/EventView.cpp +++ b/Swift/QtUI/EventViewer/EventView.cpp @@ -8,7 +8,7 @@ namespace Swift { EventView::EventView(QWidget* parent) : QListView(parent) { - + } } diff --git a/Swift/QtUI/EventViewer/EventView.h b/Swift/QtUI/EventViewer/EventView.h index 36c67f3..83898bd 100644 --- a/Swift/QtUI/EventViewer/EventView.h +++ b/Swift/QtUI/EventViewer/EventView.h @@ -9,9 +9,9 @@ #include namespace Swift { - class EventView : public QListView { - Q_OBJECT - public: - EventView(QWidget* parent); - }; + class EventView : public QListView { + Q_OBJECT + public: + EventView(QWidget* parent); + }; } diff --git a/Swift/QtUI/EventViewer/QtEvent.cpp b/Swift/QtUI/EventViewer/QtEvent.cpp index cc52ba6..c287c66 100644 --- a/Swift/QtUI/EventViewer/QtEvent.cpp +++ b/Swift/QtUI/EventViewer/QtEvent.cpp @@ -20,79 +20,79 @@ namespace Swift { QtEvent::QtEvent(boost::shared_ptr event, bool active) : event_(event) { - active_ = active; + active_ = active; } QVariant QtEvent::data(int role) { - switch (role) { - case Qt::ToolTipRole: return QVariant(text()).toString() + "\n" + B2QDATE(event_->getTime()).toString(); - case Qt::DisplayRole: return QVariant(text()); - case Qt::TextColorRole: return QColor(active_ ? Qt::black : Qt::darkGray); - case Qt::BackgroundColorRole: return QColor(active_ ? Qt::white : Qt::lightGray); - case SenderRole: return QVariant(sender()); - /*case StatusTextRole: return statusText_; - case AvatarRole: return avatar_; - case PresenceIconRole: return getPresenceIcon();*/ - default: return QVariant(); - } + switch (role) { + case Qt::ToolTipRole: return QVariant(text()).toString() + "\n" + B2QDATE(event_->getTime()).toString(); + case Qt::DisplayRole: return QVariant(text()); + case Qt::TextColorRole: return QColor(active_ ? Qt::black : Qt::darkGray); + case Qt::BackgroundColorRole: return QColor(active_ ? Qt::white : Qt::lightGray); + case SenderRole: return QVariant(sender()); + /*case StatusTextRole: return statusText_; + case AvatarRole: return avatar_; + case PresenceIconRole: return getPresenceIcon();*/ + default: return QVariant(); + } } QString QtEvent::sender() { - boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event_); - if (messageEvent) { - return P2QSTRING(messageEvent->getStanza()->getFrom().toString()); - } - boost::shared_ptr subscriptionRequestEvent = boost::dynamic_pointer_cast(event_); - if (subscriptionRequestEvent) { - return P2QSTRING(subscriptionRequestEvent->getJID().toBare().toString()); - } - boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event_); - if (errorEvent) { - return P2QSTRING(errorEvent->getJID().toBare().toString()); - } - boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event_); - if (mucInviteEvent) { - return P2QSTRING(mucInviteEvent->getInviter().toString()); - } - boost::shared_ptr incomingFTEvent = boost::dynamic_pointer_cast(event_); - if (incomingFTEvent) { - return P2QSTRING(incomingFTEvent->getSender().toString()); - } - return ""; + boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event_); + if (messageEvent) { + return P2QSTRING(messageEvent->getStanza()->getFrom().toString()); + } + boost::shared_ptr subscriptionRequestEvent = boost::dynamic_pointer_cast(event_); + if (subscriptionRequestEvent) { + return P2QSTRING(subscriptionRequestEvent->getJID().toBare().toString()); + } + boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event_); + if (errorEvent) { + return P2QSTRING(errorEvent->getJID().toBare().toString()); + } + boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event_); + if (mucInviteEvent) { + return P2QSTRING(mucInviteEvent->getInviter().toString()); + } + boost::shared_ptr incomingFTEvent = boost::dynamic_pointer_cast(event_); + if (incomingFTEvent) { + return P2QSTRING(incomingFTEvent->getSender().toString()); + } + return ""; } QString QtEvent::text() { - boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event_); - if (messageEvent) { - return P2QSTRING(messageEvent->getStanza()->getBody().get_value_or("")); - } - boost::shared_ptr subscriptionRequestEvent = boost::dynamic_pointer_cast(event_); - if (subscriptionRequestEvent) { - std::string reason = subscriptionRequestEvent->getReason(); - QString message; - if (reason.empty()) { - message = QString(QObject::tr("%1 would like to add you to their contact list.")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()); - } - else { - message = QString(QObject::tr("%1 would like to add you to their contact list, saying '%2'")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()).arg(reason.c_str()); - } - return message; - } - boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event_); - if (errorEvent) { - return P2QSTRING(errorEvent->getText()); - } - boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event_); - if (mucInviteEvent) { - QString message = QString(QObject::tr("%1 has invited you to enter the %2 room.")).arg(P2QSTRING(mucInviteEvent->getInviter().toBare().toString())).arg(P2QSTRING(mucInviteEvent->getRoomJID().toString())); - return message; - } - boost::shared_ptr incomingFTEvent = boost::dynamic_pointer_cast(event_); - if (incomingFTEvent) { - QString message = QString(QObject::tr("%1 would like to send a file to you.")).arg(P2QSTRING(incomingFTEvent->getSender().toBare().toString())); - return message; - } - return ""; + boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event_); + if (messageEvent) { + return P2QSTRING(messageEvent->getStanza()->getBody().get_value_or("")); + } + boost::shared_ptr subscriptionRequestEvent = boost::dynamic_pointer_cast(event_); + if (subscriptionRequestEvent) { + std::string reason = subscriptionRequestEvent->getReason(); + QString message; + if (reason.empty()) { + message = QString(QObject::tr("%1 would like to add you to their contact list.")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()); + } + else { + message = QString(QObject::tr("%1 would like to add you to their contact list, saying '%2'")).arg(subscriptionRequestEvent->getJID().toBare().toString().c_str()).arg(reason.c_str()); + } + return message; + } + boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event_); + if (errorEvent) { + return P2QSTRING(errorEvent->getText()); + } + boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event_); + if (mucInviteEvent) { + QString message = QString(QObject::tr("%1 has invited you to enter the %2 room.")).arg(P2QSTRING(mucInviteEvent->getInviter().toBare().toString())).arg(P2QSTRING(mucInviteEvent->getRoomJID().toString())); + return message; + } + boost::shared_ptr incomingFTEvent = boost::dynamic_pointer_cast(event_); + if (incomingFTEvent) { + QString message = QString(QObject::tr("%1 would like to send a file to you.")).arg(P2QSTRING(incomingFTEvent->getSender().toBare().toString())); + return message; + } + return ""; } } diff --git a/Swift/QtUI/EventViewer/QtEvent.h b/Swift/QtUI/EventViewer/QtEvent.h index 3be041c..d369255 100644 --- a/Swift/QtUI/EventViewer/QtEvent.h +++ b/Swift/QtUI/EventViewer/QtEvent.h @@ -13,20 +13,20 @@ #include namespace Swift { - class QtEvent { - public: - QtEvent(boost::shared_ptr event, bool active); - QVariant data(int role); - boost::shared_ptr getEvent() { return event_; } - enum EventRoles { - SenderRole = Qt::UserRole + class QtEvent { + public: + QtEvent(boost::shared_ptr event, bool active); + QVariant data(int role); + boost::shared_ptr getEvent() { return event_; } + enum EventRoles { + SenderRole = Qt::UserRole - }; + }; - private: - QString text(); - QString sender(); - boost::shared_ptr event_; - bool active_; - }; + private: + QString text(); + QString sender(); + boost::shared_ptr event_; + bool active_; + }; } diff --git a/Swift/QtUI/EventViewer/QtEventWindow.cpp b/Swift/QtUI/EventViewer/QtEventWindow.cpp index f92cd07..8395a6c 100644 --- a/Swift/QtUI/EventViewer/QtEventWindow.cpp +++ b/Swift/QtUI/EventViewer/QtEventWindow.cpp @@ -26,97 +26,97 @@ namespace Swift { QtEventWindow::QtEventWindow(UIEventStream* eventStream) : EventWindow(false) { - QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this); - layout->setContentsMargins(0,0,0,0); - layout->setSpacing(0); - - view_ = new QTreeView(this); - layout->addWidget(view_); - eventStream_ = eventStream; - model_ = new EventModel(); - view_->setModel(model_); - delegate_ = new EventDelegate(); - view_->setItemDelegate(delegate_); - view_->setHeaderHidden(true); + QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this); + layout->setContentsMargins(0,0,0,0); + layout->setSpacing(0); + + view_ = new QTreeView(this); + layout->addWidget(view_); + eventStream_ = eventStream; + model_ = new EventModel(); + view_->setModel(model_); + delegate_ = new EventDelegate(); + view_->setItemDelegate(delegate_); + view_->setHeaderHidden(true); #ifdef SWIFT_PLATFORM_MACOSX - view_->setAlternatingRowColors(true); + view_->setAlternatingRowColors(true); #endif - view_->setAnimated(true); - view_->setIndentation(0); - view_->setRootIsDecorated(true); - - readButton_ = new QPushButton(tr("Display Notice"), this); - layout->addWidget(readButton_); - readButton_->setEnabled(false); - connect(readButton_, SIGNAL(clicked()), this, SLOT(handleReadClicked())); - connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleItemClicked(const QModelIndex&))); - connect(view_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&))); + view_->setAnimated(true); + view_->setIndentation(0); + view_->setRootIsDecorated(true); + + readButton_ = new QPushButton(tr("Display Notice"), this); + layout->addWidget(readButton_); + readButton_->setEnabled(false); + connect(readButton_, SIGNAL(clicked()), this, SLOT(handleReadClicked())); + connect(view_, SIGNAL(clicked(const QModelIndex&)), this, SLOT(handleItemClicked(const QModelIndex&))); + connect(view_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleItemActivated(const QModelIndex&))); } QtEventWindow::~QtEventWindow() { - delete model_; - delete delegate_; - /* Not view_ because this is the parent */ + delete model_; + delete delegate_; + /* Not view_ because this is the parent */ } void QtEventWindow::handleItemClicked(const QModelIndex&) { - readButton_->setEnabled(true); + readButton_->setEnabled(true); } void QtEventWindow::handleReadClicked() { - QModelIndex index = view_->currentIndex(); - if (!index.isValid()) { - return; - } - handleItemActivated(index); + QModelIndex index = view_->currentIndex(); + if (!index.isValid()) { + return; + } + handleItemActivated(index); } void QtEventWindow::handleItemActivated(const QModelIndex& item) { - QtEvent* event = model_->getItem(item.row()); - boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event->getEvent()); - boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(event->getEvent()); - boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event->getEvent()); - boost::shared_ptr incomingFTEvent = boost::dynamic_pointer_cast(event->getEvent()); - boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event->getEvent()); - - if (messageEvent) { - if (messageEvent->getStanza()->getType() == Message::Groupchat) { - eventStream_->send(boost::shared_ptr(new JoinMUCUIEvent(messageEvent->getStanza()->getFrom().toBare(), messageEvent->getStanza()->getTo().getResource()))); - } else { - eventStream_->send(boost::shared_ptr(new RequestChatUIEvent(messageEvent->getStanza()->getFrom()))); - } - } else if (subscriptionEvent) { - QtSubscriptionRequestWindow* window = QtSubscriptionRequestWindow::getWindow(subscriptionEvent, this); - window->show(); - } else if (mucInviteEvent) { - eventStream_->send(boost::shared_ptr(new RequestChatUIEvent(mucInviteEvent->getInviter()))); - mucInviteEvent->conclude(); - } else if (incomingFTEvent) { - eventStream_->send(boost::shared_ptr(new RequestChatUIEvent(incomingFTEvent->getSender()))); - incomingFTEvent->conclude(); - } else { - if (errorEvent) { - errorEvent->conclude(); - } - QMessageBox msgBox; - msgBox.setText(model_->data(item, Qt::DisplayRole).toString()); - msgBox.exec(); - } + QtEvent* event = model_->getItem(item.row()); + boost::shared_ptr messageEvent = boost::dynamic_pointer_cast(event->getEvent()); + boost::shared_ptr subscriptionEvent = boost::dynamic_pointer_cast(event->getEvent()); + boost::shared_ptr mucInviteEvent = boost::dynamic_pointer_cast(event->getEvent()); + boost::shared_ptr incomingFTEvent = boost::dynamic_pointer_cast(event->getEvent()); + boost::shared_ptr errorEvent = boost::dynamic_pointer_cast(event->getEvent()); + + if (messageEvent) { + if (messageEvent->getStanza()->getType() == Message::Groupchat) { + eventStream_->send(boost::shared_ptr(new JoinMUCUIEvent(messageEvent->getStanza()->getFrom().toBare(), messageEvent->getStanza()->getTo().getResource()))); + } else { + eventStream_->send(boost::shared_ptr(new RequestChatUIEvent(messageEvent->getStanza()->getFrom()))); + } + } else if (subscriptionEvent) { + QtSubscriptionRequestWindow* window = QtSubscriptionRequestWindow::getWindow(subscriptionEvent, this); + window->show(); + } else if (mucInviteEvent) { + eventStream_->send(boost::shared_ptr(new RequestChatUIEvent(mucInviteEvent->getInviter()))); + mucInviteEvent->conclude(); + } else if (incomingFTEvent) { + eventStream_->send(boost::shared_ptr(new RequestChatUIEvent(incomingFTEvent->getSender()))); + incomingFTEvent->conclude(); + } else { + if (errorEvent) { + errorEvent->conclude(); + } + QMessageBox msgBox; + msgBox.setText(model_->data(item, Qt::DisplayRole).toString()); + msgBox.exec(); + } } void QtEventWindow::addEvent(boost::shared_ptr event, bool active) { - view_->clearSelection(); - model_->addEvent(event, active); - emit onNewEventCountUpdated(model_->getNewEventCount()); - readButton_->setEnabled(model_->rowCount() > 0); + view_->clearSelection(); + model_->addEvent(event, active); + emit onNewEventCountUpdated(model_->getNewEventCount()); + readButton_->setEnabled(model_->rowCount() > 0); } void QtEventWindow::removeEvent(boost::shared_ptr event) { - view_->clearSelection(); - model_->removeEvent(event); - emit onNewEventCountUpdated(model_->getNewEventCount()); - readButton_->setEnabled(model_->rowCount() > 0); + view_->clearSelection(); + model_->removeEvent(event); + emit onNewEventCountUpdated(model_->getNewEventCount()); + readButton_->setEnabled(model_->rowCount() > 0); } } diff --git a/Swift/QtUI/EventViewer/QtEventWindow.h b/Swift/QtUI/EventViewer/QtEventWindow.h index 1591c15..92f8de0 100644 --- a/Swift/QtUI/EventViewer/QtEventWindow.h +++ b/Swift/QtUI/EventViewer/QtEventWindow.h @@ -20,26 +20,26 @@ class QPushButton; namespace Swift { - class QtEventWindow : public QWidget, public EventWindow { - Q_OBJECT - public: - QtEventWindow(UIEventStream* eventStream); - ~QtEventWindow(); - void addEvent(boost::shared_ptr event, bool active); - void removeEvent(boost::shared_ptr event); - signals: - void onNewEventCountUpdated(int count); - private slots: - void handleItemActivated(const QModelIndex& item); - void handleItemClicked(const QModelIndex& item); - void handleReadClicked(); - private: - EventModel* model_; - EventDelegate* delegate_; - UIEventStream* eventStream_; - QTreeView* view_; - QPushButton* readButton_; - }; - + class QtEventWindow : public QWidget, public EventWindow { + Q_OBJECT + public: + QtEventWindow(UIEventStream* eventStream); + ~QtEventWindow(); + void addEvent(boost::shared_ptr event, bool active); + void removeEvent(boost::shared_ptr event); + signals: + void onNewEventCountUpdated(int count); + private slots: + void handleItemActivated(const QModelIndex& item); + void handleItemClicked(const QModelIndex& item); + void handleReadClicked(); + private: + EventModel* model_; + EventDelegate* delegate_; + UIEventStream* eventStream_; + QTreeView* view_; + QPushButton* readButton_; + }; + } diff --git a/Swift/QtUI/EventViewer/TwoLineDelegate.cpp b/Swift/QtUI/EventViewer/TwoLineDelegate.cpp index 586de55..b90acca 100644 --- a/Swift/QtUI/EventViewer/TwoLineDelegate.cpp +++ b/Swift/QtUI/EventViewer/TwoLineDelegate.cpp @@ -12,9 +12,9 @@ namespace Swift { TwoLineDelegate::TwoLineDelegate(int firstRole, int secondRole, bool wrap) { - firstRole_ = firstRole; - secondRole_ = secondRole; - wrap_ = wrap; + firstRole_ = firstRole; + secondRole_ = secondRole; + wrap_ = wrap; } TwoLineDelegate::~TwoLineDelegate() { @@ -22,41 +22,41 @@ TwoLineDelegate::~TwoLineDelegate() { } QSize TwoLineDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, QtEvent* /*event*/ ) const { - QFontMetrics nameMetrics(common_.nameFont); - QFontMetrics statusMetrics(common_.detailFont); - int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height(); - return QSize(150, sizeByText); + QFontMetrics nameMetrics(common_.nameFont); + QFontMetrics statusMetrics(common_.detailFont); + int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height(); + return QSize(150, sizeByText); } void TwoLineDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const { - painter->save(); - QRect fullRegion(option.rect); - if ( option.state & QStyle::State_Selected ) { - painter->fillRect(fullRegion, option.palette.highlight()); - painter->setPen(option.palette.highlightedText().color()); - } else { - QColor nameColor = event->data(Qt::TextColorRole).value(); - painter->setPen(QPen(nameColor)); - } - - QFontMetrics nameMetrics(common_.nameFont); - painter->setFont(common_.nameFont); - int extraFontWidth = nameMetrics.width("H"); - int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2; - QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0)); - - int nameHeight = nameMetrics.height() + common_.verticalMargin; - QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0)); - - DelegateCommons::drawElidedText(painter, nameRegion, event->data(firstRole_).toString()); - - painter->setFont(common_.detailFont); - painter->setPen(QPen(QColor(160,160,160))); - - QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0)); - DelegateCommons::drawElidedText(painter, detailRegion, event->data(secondRole_).toString()); - - painter->restore(); + painter->save(); + QRect fullRegion(option.rect); + if ( option.state & QStyle::State_Selected ) { + painter->fillRect(fullRegion, option.palette.highlight()); + painter->setPen(option.palette.highlightedText().color()); + } else { + QColor nameColor = event->data(Qt::TextColorRole).value(); + painter->setPen(QPen(nameColor)); + } + + QFontMetrics nameMetrics(common_.nameFont); + painter->setFont(common_.nameFont); + int extraFontWidth = nameMetrics.width("H"); + int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2; + QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0)); + + int nameHeight = nameMetrics.height() + common_.verticalMargin; + QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0)); + + DelegateCommons::drawElidedText(painter, nameRegion, event->data(firstRole_).toString()); + + painter->setFont(common_.detailFont); + painter->setPen(QPen(QColor(160,160,160))); + + QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0)); + DelegateCommons::drawElidedText(painter, detailRegion, event->data(secondRole_).toString()); + + painter->restore(); } } diff --git a/Swift/QtUI/EventViewer/TwoLineDelegate.h b/Swift/QtUI/EventViewer/TwoLineDelegate.h index 9eebb68..089f97a 100644 --- a/Swift/QtUI/EventViewer/TwoLineDelegate.h +++ b/Swift/QtUI/EventViewer/TwoLineDelegate.h @@ -12,18 +12,18 @@ #include namespace Swift { - class TwoLineDelegate { - public: - TwoLineDelegate(int firstRole, int secondRole, bool wrap); - ~TwoLineDelegate(); - QSize sizeHint(const QStyleOptionViewItem& option, QtEvent* event) const; - void paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const; - private: - DelegateCommons common_; - int firstRole_; - int secondRole_; - bool wrap_; - }; + class TwoLineDelegate { + public: + TwoLineDelegate(int firstRole, int secondRole, bool wrap); + ~TwoLineDelegate(); + QSize sizeHint(const QStyleOptionViewItem& option, QtEvent* event) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, QtEvent* event) const; + private: + DelegateCommons common_; + int firstRole_; + int secondRole_; + bool wrap_; + }; } diff --git a/Swift/QtUI/EventViewer/main.cpp b/Swift/QtUI/EventViewer/main.cpp index ba2ab4b..5eddd90 100644 --- a/Swift/QtUI/EventViewer/main.cpp +++ b/Swift/QtUI/EventViewer/main.cpp @@ -17,17 +17,17 @@ int main(int argc, char *argv[]) { - QApplication app(argc, argv); - Swift::UIEventStream eventStream; - Swift::QtEventWindow* viewer = new Swift::QtEventWindow(&eventStream); - viewer->show(); - boost::shared_ptr message1(new Swift::Message()); - message1->setBody("Oooh, shiny"); - boost::shared_ptr event1(new Swift::MessageEvent(message1)); - viewer->addEvent(boost::dynamic_pointer_cast(event1), true); - for (int i = 0; i < 100; i++) { - viewer->addEvent(boost::dynamic_pointer_cast(event1), false); - } - viewer->addEvent(boost::dynamic_pointer_cast(boost::make_shared(Swift::JID("me@example.com"), "Something bad did happen to you.")), true); - return app.exec(); + QApplication app(argc, argv); + Swift::UIEventStream eventStream; + Swift::QtEventWindow* viewer = new Swift::QtEventWindow(&eventStream); + viewer->show(); + boost::shared_ptr message1(new Swift::Message()); + message1->setBody("Oooh, shiny"); + boost::shared_ptr event1(new Swift::MessageEvent(message1)); + viewer->addEvent(boost::dynamic_pointer_cast(event1), true); + for (int i = 0; i < 100; i++) { + viewer->addEvent(boost::dynamic_pointer_cast(event1), false); + } + viewer->addEvent(boost::dynamic_pointer_cast(boost::make_shared(Swift::JID("me@example.com"), "Something bad did happen to you.")), true); + return app.exec(); } diff --git a/Swift/QtUI/FreeDesktopNotifier.cpp b/Swift/QtUI/FreeDesktopNotifier.cpp index 54e0ccc..16f6a11 100644 --- a/Swift/QtUI/FreeDesktopNotifier.cpp +++ b/Swift/QtUI/FreeDesktopNotifier.cpp @@ -23,37 +23,37 @@ FreeDesktopNotifier::FreeDesktopNotifier(const std::string& name) : applicationN } void FreeDesktopNotifier::showMessage(Type type, const std::string& subject, const std::string& description, const boost::filesystem::path& picture, boost::function) { - QDBusConnection bus = QDBusConnection::sessionBus(); - if (!bus.isConnected()) { - return; - } - std::vector defaultTypes = getDefaultTypes(); - if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) { - return; - } - - QString body = description.c_str(); - body = body.replace("&", "&"); - body = body.replace("<", "<"); - body = body.replace(">", ">"); - - int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS; - - QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "", "Notify"); - - QStringList actions; - QMap hints; - hints["x-canonical-append"] = QString("allowed"); - msg << applicationName.c_str(); - msg << quint32(0); // ID of previous notification to replace - msg << P2QSTRING(pathToString(imageScaler.getScaledImage(picture, 48))); // Icon to display - msg << subject.c_str(); // Summary / Header of the message to display - msg << body; // Body of the message to display - msg << actions; // Actions from which the user may choose - msg << hints; // Hints to the server displaying the message - msg << qint32(timeout*1000); // Timeout in milliseconds - - bus.asyncCall(msg); + QDBusConnection bus = QDBusConnection::sessionBus(); + if (!bus.isConnected()) { + return; + } + std::vector defaultTypes = getDefaultTypes(); + if (std::find(defaultTypes.begin(), defaultTypes.end(), type) == defaultTypes.end()) { + return; + } + + QString body = description.c_str(); + body = body.replace("&", "&"); + body = body.replace("<", "<"); + body = body.replace(">", ">"); + + int timeout = (type == IncomingMessage || type == SystemMessage) ? DEFAULT_MESSAGE_NOTIFICATION_TIMEOUT_SECONDS : DEFAULT_STATUS_NOTIFICATION_TIMEOUT_SECONDS; + + QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "", "Notify"); + + QStringList actions; + QMap hints; + hints["x-canonical-append"] = QString("allowed"); + msg << applicationName.c_str(); + msg << quint32(0); // ID of previous notification to replace + msg << P2QSTRING(pathToString(imageScaler.getScaledImage(picture, 48))); // Icon to display + msg << subject.c_str(); // Summary / Header of the message to display + msg << body; // Body of the message to display + msg << actions; // Actions from which the user may choose + msg << hints; // Hints to the server displaying the message + msg << qint32(timeout*1000); // Timeout in milliseconds + + bus.asyncCall(msg); } } diff --git a/Swift/QtUI/FreeDesktopNotifier.h b/Swift/QtUI/FreeDesktopNotifier.h index 50601a0..dab7e73 100644 --- a/Swift/QtUI/FreeDesktopNotifier.h +++ b/Swift/QtUI/FreeDesktopNotifier.h @@ -11,15 +11,15 @@ #include namespace Swift { - class FreeDesktopNotifier : public Notifier { - public: - FreeDesktopNotifier(const std::string& name); + class FreeDesktopNotifier : public Notifier { + public: + FreeDesktopNotifier(const std::string& name); - 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() {} - private: - std::string applicationName; - QtCachedImageScaler imageScaler; - }; + private: + std::string applicationName; + QtCachedImageScaler imageScaler; + }; } diff --git a/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp b/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp index c5f4685..0163e03 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp +++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.cpp @@ -25,63 +25,63 @@ MUCSearchDelegate::~MUCSearchDelegate() { } // QSize MUCSearchDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index ) const { -// // MUCSearchItem* item = static_cast(index.internalPointer()); -// // if (item && dynamic_cast(item)) { -// // return mucSizeHint(option, index); -// // } else if (item && dynamic_cast(item)) { -// // return groupDelegate_->sizeHint(option, index); -// // } -// return QStyledItemDelegate::sizeHint(option, index); +// // MUCSearchItem* item = static_cast(index.internalPointer()); +// // if (item && dynamic_cast(item)) { +// // return mucSizeHint(option, index); +// // } else if (item && dynamic_cast(item)) { +// // return groupDelegate_->sizeHint(option, index); +// // } +// return QStyledItemDelegate::sizeHint(option, index); // } // QSize MUCSearchDelegate::mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const { -// QFontMetrics nameMetrics(common_.nameFont); -// QFontMetrics statusMetrics(common_.detailFont); -// int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height(); -// return QSize(150, sizeByText); +// QFontMetrics nameMetrics(common_.nameFont); +// QFontMetrics statusMetrics(common_.detailFont); +// int sizeByText = 2 * common_.verticalMargin + nameMetrics.height() + statusMetrics.height(); +// return QSize(150, sizeByText); // } // void MUCSearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { -// MUCSearchItem* item = static_cast(index.internalPointer()); -// if (item && dynamic_cast(item)) { -// paintMUC(painter, option, dynamic_cast(item)); -// } else if (item && dynamic_cast(item)) { -// MUCSearchGroupItem* group = dynamic_cast(item); -// groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open); -// } else { -// QStyledItemDelegate::paint(painter, option, index); -// } +// MUCSearchItem* item = static_cast(index.internalPointer()); +// if (item && dynamic_cast(item)) { +// paintMUC(painter, option, dynamic_cast(item)); +// } else if (item && dynamic_cast(item)) { +// MUCSearchGroupItem* group = dynamic_cast(item); +// groupDelegate_->paint(painter, option, group->data(Qt::DisplayRole).toString(), group->rowCount(), option.state & QStyle::State_Open); +// } else { +// QStyledItemDelegate::paint(painter, option, index); +// } // } // void MUCSearchDelegate::paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const { -// painter->save(); -// QRect fullRegion(option.rect); -// if ( option.state & QStyle::State_Selected ) { -// painter->fillRect(fullRegion, option.palette.highlight()); -// painter->setPen(option.palette.highlightedText().color()); -// } else { -// QColor nameColor = item->data(Qt::TextColorRole).value(); -// painter->setPen(QPen(nameColor)); -// } - -// QFontMetrics nameMetrics(common_.nameFont); -// painter->setFont(common_.nameFont); -// int extraFontWidth = nameMetrics.width("H"); -// int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2; -// QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0)); - -// int nameHeight = nameMetrics.height() + common_.verticalMargin; -// QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0)); - -// painter->drawText(nameRegion, Qt::AlignTop, item->data(Qt::DisplayRole).toString()); - -// painter->setFont(common_.detailFont); -// painter->setPen(QPen(QColor(160,160,160))); - -// QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0)); -// painter->drawText(detailRegion, Qt::AlignTop, item->data(DetailTextRole).toString()); - -// painter->restore(); +// painter->save(); +// QRect fullRegion(option.rect); +// if ( option.state & QStyle::State_Selected ) { +// painter->fillRect(fullRegion, option.palette.highlight()); +// painter->setPen(option.palette.highlightedText().color()); +// } else { +// QColor nameColor = item->data(Qt::TextColorRole).value(); +// painter->setPen(QPen(nameColor)); +// } + +// QFontMetrics nameMetrics(common_.nameFont); +// painter->setFont(common_.nameFont); +// int extraFontWidth = nameMetrics.width("H"); +// int leftOffset = common_.horizontalMargin * 2 + extraFontWidth / 2; +// QRect textRegion(fullRegion.adjusted(leftOffset, 0, 0, 0)); + +// int nameHeight = nameMetrics.height() + common_.verticalMargin; +// QRect nameRegion(textRegion.adjusted(0, common_.verticalMargin, 0, 0)); + +// painter->drawText(nameRegion, Qt::AlignTop, item->data(Qt::DisplayRole).toString()); + +// painter->setFont(common_.detailFont); +// painter->setPen(QPen(QColor(160,160,160))); + +// QRect detailRegion(textRegion.adjusted(0, nameHeight, 0, 0)); +// painter->drawText(detailRegion, Qt::AlignTop, item->data(DetailTextRole).toString()); + +// painter->restore(); // } } diff --git a/Swift/QtUI/MUCSearch/MUCSearchDelegate.h b/Swift/QtUI/MUCSearch/MUCSearchDelegate.h index d521d7b..5bf9646 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchDelegate.h +++ b/Swift/QtUI/MUCSearch/MUCSearchDelegate.h @@ -11,18 +11,18 @@ #include namespace Swift { - class MUCSearchDelegate : public QStyledItemDelegate { - public: - MUCSearchDelegate(); - ~MUCSearchDelegate(); - /* QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; */ - /* void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; */ - private: -// void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const; -// QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const; + class MUCSearchDelegate : public QStyledItemDelegate { + public: + MUCSearchDelegate(); + ~MUCSearchDelegate(); + /* QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; */ + /* void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; */ + private: +// void paintMUC(QPainter* painter, const QStyleOptionViewItem& option, MUCSearchMUCItem* item) const; +// QSize mucSizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/ ) const; - DelegateCommons common_; - }; + DelegateCommons common_; + }; } diff --git a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp index 5ab6391..d95682c 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp +++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.cpp @@ -13,27 +13,27 @@ namespace Swift { MUCSearchEmptyItem::MUCSearchEmptyItem(MUCSearchServiceItem* parent) : parent(parent) { - parent->addRoom(this); + parent->addRoom(this); } MUCSearchServiceItem* MUCSearchEmptyItem::getParent() { - return parent; + return parent; } QVariant MUCSearchEmptyItem::data(int role) { - switch (role) { - case Qt::DisplayRole: - return QVariant(QObject::tr("No rooms found")); - case Qt::FontRole: { - QFont font; - font.setItalic(true); - return font; - } - case Qt::ForegroundRole: - return QColor(Qt::gray); - default: - return QVariant(); - } + switch (role) { + case Qt::DisplayRole: + return QVariant(QObject::tr("No rooms found")); + case Qt::FontRole: { + QFont font; + font.setItalic(true); + return font; + } + case Qt::ForegroundRole: + return QColor(Qt::gray); + default: + return QVariant(); + } } } diff --git a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h index 74e0154..ca4b2b2 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h +++ b/Swift/QtUI/MUCSearch/MUCSearchEmptyItem.h @@ -9,17 +9,17 @@ #include namespace Swift { - class MUCSearchServiceItem; + class MUCSearchServiceItem; - class MUCSearchEmptyItem : public MUCSearchItem { - public: - MUCSearchEmptyItem(MUCSearchServiceItem* parent); + class MUCSearchEmptyItem : public MUCSearchItem { + public: + MUCSearchEmptyItem(MUCSearchServiceItem* parent); - MUCSearchServiceItem* getParent(); + MUCSearchServiceItem* getParent(); - QVariant data(int role); + QVariant data(int role); - private: - MUCSearchServiceItem* parent; - }; + private: + MUCSearchServiceItem* parent; + }; } diff --git a/Swift/QtUI/MUCSearch/MUCSearchItem.h b/Swift/QtUI/MUCSearch/MUCSearchItem.h index d2a2c2d..c378247 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchItem.h +++ b/Swift/QtUI/MUCSearch/MUCSearchItem.h @@ -9,9 +9,9 @@ #include namespace Swift { - class MUCSearchItem { - public: - virtual ~MUCSearchItem() {} - virtual QVariant data(int role) = 0; - }; + class MUCSearchItem { + public: + virtual ~MUCSearchItem() {} + virtual QVariant data(int role) = 0; + }; } diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp index 1a3ccc4..af6f17f 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchModel.cpp +++ b/Swift/QtUI/MUCSearch/MUCSearchModel.cpp @@ -14,78 +14,78 @@ MUCSearchModel::MUCSearchModel() { } void MUCSearchModel::clear() { - emit layoutAboutToBeChanged(); - services_.clear(); - emit layoutChanged(); + emit layoutAboutToBeChanged(); + services_.clear(); + emit layoutChanged(); } void MUCSearchModel::addService(MUCSearchServiceItem* service) { - emit layoutAboutToBeChanged(); - services_.push_back(service); - emit layoutChanged(); + emit layoutAboutToBeChanged(); + services_.push_back(service); + emit layoutChanged(); } int MUCSearchModel::columnCount(const QModelIndex& /*parent*/) const { - return 1; + return 1; } QVariant MUCSearchModel::data(const QModelIndex& index, int role) const { - return index.isValid() ? static_cast(index.internalPointer())->data(role) : QVariant(); + return index.isValid() ? static_cast(index.internalPointer())->data(role) : QVariant(); } QModelIndex MUCSearchModel::index(int row, int column, const QModelIndex & parent) const { - if (!hasIndex(row, column, parent)) { - return QModelIndex(); - } - - if (parent.isValid()) { - MUCSearchServiceItem* parentItem = static_cast(parent.internalPointer()); - return row < parentItem->rowCount() ? createIndex(row, column, parentItem->getItem(row)) : QModelIndex(); - } else { - return row < services_.size() ? createIndex(row, column, services_[row]) : QModelIndex(); - } + if (!hasIndex(row, column, parent)) { + return QModelIndex(); + } + + if (parent.isValid()) { + MUCSearchServiceItem* parentItem = static_cast(parent.internalPointer()); + return row < parentItem->rowCount() ? createIndex(row, column, parentItem->getItem(row)) : QModelIndex(); + } else { + return row < services_.size() ? createIndex(row, column, services_[row]) : QModelIndex(); + } } QModelIndex MUCSearchModel::parent(const QModelIndex& index) const { - if (!index.isValid()) { - return QModelIndex(); - } - MUCSearchItem* item = static_cast(index.internalPointer()); - if (!item) { - return QModelIndex(); - } - else if (dynamic_cast(item)) { - return QModelIndex(); - } - - MUCSearchServiceItem* parent = NULL; - if (MUCSearchRoomItem* roomItem = dynamic_cast(item)) { - parent = roomItem->getParent(); - } - else if (MUCSearchEmptyItem* emptyItem = dynamic_cast(item)) { - parent = emptyItem->getParent(); - } - if (parent) { - int row = services_.indexOf(parent); - return createIndex(row, 1, parent); - } - else { - return QModelIndex(); - } + if (!index.isValid()) { + return QModelIndex(); + } + MUCSearchItem* item = static_cast(index.internalPointer()); + if (!item) { + return QModelIndex(); + } + else if (dynamic_cast(item)) { + return QModelIndex(); + } + + MUCSearchServiceItem* parent = NULL; + if (MUCSearchRoomItem* roomItem = dynamic_cast(item)) { + parent = roomItem->getParent(); + } + else if (MUCSearchEmptyItem* emptyItem = dynamic_cast(item)) { + parent = emptyItem->getParent(); + } + if (parent) { + int row = services_.indexOf(parent); + return createIndex(row, 1, parent); + } + else { + return QModelIndex(); + } } int MUCSearchModel::rowCount(const QModelIndex& parentIndex) const { - if (!parentIndex.isValid()) { - return services_.size(); - } - if (dynamic_cast(static_cast(parentIndex.internalPointer()))) { - return services_[parentIndex.row()]->rowCount(); - } - else { - return 0; - } + if (!parentIndex.isValid()) { + return services_.size(); + } + if (dynamic_cast(static_cast(parentIndex.internalPointer()))) { + return services_[parentIndex.row()]->rowCount(); + } + else { + return 0; + } } } diff --git a/Swift/QtUI/MUCSearch/MUCSearchModel.h b/Swift/QtUI/MUCSearch/MUCSearchModel.h index 4ea811f..d6a24f3 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchModel.h +++ b/Swift/QtUI/MUCSearch/MUCSearchModel.h @@ -14,22 +14,22 @@ #include namespace Swift { - class MUCSearchModel : public QAbstractItemModel { - Q_OBJECT - public: - MUCSearchModel(); - void clear(); - void addService(MUCSearchServiceItem* service); - int columnCount(const QModelIndex& parent = QModelIndex()) const; - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; - QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; - QModelIndex parent(const QModelIndex& index) const; - int rowCount(const QModelIndex& parent = QModelIndex()) const; -// ChatListItem* getItemForIndex(const QModelIndex& index) const; - private: -// ChatListGroupItem* mucBookmarks_; -// ChatListGroupItem* root_; - QList services_; - }; + class MUCSearchModel : public QAbstractItemModel { + Q_OBJECT + public: + MUCSearchModel(); + void clear(); + void addService(MUCSearchServiceItem* service); + int columnCount(const QModelIndex& parent = QModelIndex()) const; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const; + QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const; + QModelIndex parent(const QModelIndex& index) const; + int rowCount(const QModelIndex& parent = QModelIndex()) const; +// ChatListItem* getItemForIndex(const QModelIndex& index) const; + private: +// ChatListGroupItem* mucBookmarks_; +// ChatListGroupItem* root_; + QList services_; + }; } diff --git a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp index 169ab49..cb7ee2d 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp +++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.cpp @@ -10,17 +10,17 @@ namespace Swift { MUCSearchRoomItem::MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent) : parent_(parent), node_(node) { - parent_->addRoom(this); + parent_->addRoom(this); } MUCSearchServiceItem* MUCSearchRoomItem::getParent() { - return parent_; + return parent_; } QVariant MUCSearchRoomItem::data(int role) { - switch (role) { - case Qt::DisplayRole: return QVariant(node_); - default: return QVariant(); - } + switch (role) { + case Qt::DisplayRole: return QVariant(node_); + default: return QVariant(); + } } } diff --git a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h index c853221..d2b88bc 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h +++ b/Swift/QtUI/MUCSearch/MUCSearchRoomItem.h @@ -9,15 +9,15 @@ #include namespace Swift { - class MUCSearchServiceItem; - class MUCSearchRoomItem : public MUCSearchItem { - public: - MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent); - MUCSearchServiceItem* getParent(); - QVariant data(int role); - QString getNode() const {return node_;} - private: - MUCSearchServiceItem* parent_; - QString node_; - }; + class MUCSearchServiceItem; + class MUCSearchRoomItem : public MUCSearchItem { + public: + MUCSearchRoomItem(const QString& node, MUCSearchServiceItem* parent); + MUCSearchServiceItem* getParent(); + QVariant data(int role); + QString getNode() const {return node_;} + private: + MUCSearchServiceItem* parent_; + QString node_; + }; } diff --git a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h index 421ac25..cfde071 100644 --- a/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h +++ b/Swift/QtUI/MUCSearch/MUCSearchServiceItem.h @@ -12,21 +12,21 @@ #include namespace Swift { - class MUCSearchServiceItem : public MUCSearchItem { - public: - MUCSearchServiceItem(const QString& jidString) : jidString_(jidString) {} - void addRoom(MUCSearchItem* room) {rooms_.push_back(room);} - int rowCount() {return rooms_.count();} - MUCSearchItem* getItem(int i) {return rooms_[i];} - QVariant data(int role) { - switch (role) { - case Qt::DisplayRole: return QVariant(jidString_); - default: return QVariant(); - } - } - QString getHost() const {return jidString_;} - private: - QList rooms_; - QString jidString_; - }; + class MUCSearchServiceItem : public MUCSearchItem { + public: + MUCSearchServiceItem(const QString& jidString) : jidString_(jidString) {} + void addRoom(MUCSearchItem* room) {rooms_.push_back(room);} + int rowCount() {return rooms_.count();} + MUCSearchItem* getItem(int i) {return rooms_[i];} + QVariant data(int role) { + switch (role) { + case Qt::DisplayRole: return QVariant(jidString_); + default: return QVariant(); + } + } + QString getHost() const {return jidString_;} + private: + QList rooms_; + QString jidString_; + }; } diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp index e3bd7f3..03fa582 100644 --- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp +++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.cpp @@ -24,37 +24,37 @@ namespace Swift { QtMUCSearchWindow::QtMUCSearchWindow() { - ui_.setupUi(this); + ui_.setupUi(this); #ifndef Q_OS_MAC - setWindowIcon(QIcon(":/logo-icon-16.png")); + setWindowIcon(QIcon(":/logo-icon-16.png")); #endif - setModal(true); - ui_.filter_->hide(); - model_ = new MUCSearchModel(); - delegate_ = new MUCSearchDelegate(); - ui_.results_->setModel(model_); - ui_.results_->setItemDelegate(delegate_); - ui_.results_->setHeaderHidden(true); - ui_.results_->setRootIsDecorated(true); - ui_.results_->setAnimated(true); - ui_.results_->setAlternatingRowColors(true); - connect(ui_.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch())); - connect(ui_.service_, SIGNAL(activated(const QString&)), this, SLOT(handleSearch(const QString&))); - connect(ui_.results_->selectionModel(), SIGNAL(selectionChanged (const QItemSelection&, const QItemSelection&)), this, SLOT(handleSelectionChanged (const QItemSelection&, const QItemSelection&))); - connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&))); - connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&))); - // Not using a button box, because i can't seem to be able to make the ok button non-default (on mac) - connect(ui_.okButton, SIGNAL(clicked()), this, SLOT(accept())); - ui_.okButton->setEnabled(false); - connect(ui_.cancelButton, SIGNAL(clicked()), this, SLOT(reject())); - - throbber_ = new QLabel(tr("Searching"), ui_.results_); - throbber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), throbber_)); - throbber_->setToolTip(tr("Searching")); - - hasHadScrollBars_ = false; - updateThrobberPosition(); - setSearchInProgress(false); + setModal(true); + ui_.filter_->hide(); + model_ = new MUCSearchModel(); + delegate_ = new MUCSearchDelegate(); + ui_.results_->setModel(model_); + ui_.results_->setItemDelegate(delegate_); + ui_.results_->setHeaderHidden(true); + ui_.results_->setRootIsDecorated(true); + ui_.results_->setAnimated(true); + ui_.results_->setAlternatingRowColors(true); + connect(ui_.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch())); + connect(ui_.service_, SIGNAL(activated(const QString&)), this, SLOT(handleSearch(const QString&))); + connect(ui_.results_->selectionModel(), SIGNAL(selectionChanged (const QItemSelection&, const QItemSelection&)), this, SLOT(handleSelectionChanged (const QItemSelection&, const QItemSelection&))); + connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&))); + connect(ui_.results_, SIGNAL(activated(const QModelIndex&)), this, SLOT(handleActivated(const QModelIndex&))); + // Not using a button box, because i can't seem to be able to make the ok button non-default (on mac) + connect(ui_.okButton, SIGNAL(clicked()), this, SLOT(accept())); + ui_.okButton->setEnabled(false); + connect(ui_.cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + + throbber_ = new QLabel(tr("Searching"), ui_.results_); + throbber_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), throbber_)); + throbber_->setToolTip(tr("Searching")); + + hasHadScrollBars_ = false; + updateThrobberPosition(); + setSearchInProgress(false); } QtMUCSearchWindow::~QtMUCSearchWindow() { @@ -62,136 +62,136 @@ QtMUCSearchWindow::~QtMUCSearchWindow() { } void QtMUCSearchWindow::resizeEvent(QResizeEvent* /*event*/) { - updateThrobberPosition(); + updateThrobberPosition(); } void QtMUCSearchWindow::updateThrobberPosition() { - bool isShown = throbber_->isVisible(); - int resultWidth = ui_.results_->width(); - int resultHeight = ui_.results_->height(); - //throbberWidth = throbber_->movie()->scaledSize().width(); - //throbberHeight = throbber_->movie()->scaledSize().height(); - int throbberWidth = 16; /* This is nasty, but the above doesn't work! */ - int throbberHeight = 16; - /* It's difficult (or I spent a while trying) to work out whether the scrollbars are currently shown and their appropriate size, - * because if you listen for the expanded/collapsed signals, you seem to get them before the scrollbars are updated. - * This seems an acceptable workaround. - */ - hasHadScrollBars_ |= ui_.results_->verticalScrollBar()->isVisible(); - int hMargin = hasHadScrollBars_ ? ui_.results_->verticalScrollBar()->width() + 2 : 2; - int vMargin = 2; /* We don't get horizontal scrollbars */ - throbber_->setGeometry(QRect(resultWidth - throbberWidth - hMargin, resultHeight - throbberHeight - vMargin, throbberWidth, throbberHeight)); /* include margins */ - throbber_->setVisible(isShown); + bool isShown = throbber_->isVisible(); + int resultWidth = ui_.results_->width(); + int resultHeight = ui_.results_->height(); + //throbberWidth = throbber_->movie()->scaledSize().width(); + //throbberHeight = throbber_->movie()->scaledSize().height(); + int throbberWidth = 16; /* This is nasty, but the above doesn't work! */ + int throbberHeight = 16; + /* It's difficult (or I spent a while trying) to work out whether the scrollbars are currently shown and their appropriate size, + * because if you listen for the expanded/collapsed signals, you seem to get them before the scrollbars are updated. + * This seems an acceptable workaround. + */ + hasHadScrollBars_ |= ui_.results_->verticalScrollBar()->isVisible(); + int hMargin = hasHadScrollBars_ ? ui_.results_->verticalScrollBar()->width() + 2 : 2; + int vMargin = 2; /* We don't get horizontal scrollbars */ + throbber_->setGeometry(QRect(resultWidth - throbberWidth - hMargin, resultHeight - throbberHeight - vMargin, throbberWidth, throbberHeight)); /* include margins */ + throbber_->setVisible(isShown); } void QtMUCSearchWindow::addSavedServices(const std::list& services) { - ui_.service_->clear(); - foreach (const JID& jid, services) { - ui_.service_->addItem(P2QSTRING(jid.toString())); - } - if (!services.empty()) { - ui_.service_->setEditText(P2QSTRING(services.begin()->toString())); - } - else { - ui_.service_->clearEditText(); - } + ui_.service_->clear(); + foreach (const JID& jid, services) { + ui_.service_->addItem(P2QSTRING(jid.toString())); + } + if (!services.empty()) { + ui_.service_->setEditText(P2QSTRING(services.begin()->toString())); + } + else { + ui_.service_->clearEditText(); + } } void QtMUCSearchWindow::handleActivated(const QModelIndex& index) { - if (!index.isValid()) { - return; - } - if (dynamic_cast(static_cast(index.internalPointer()))) { - accept(); - } + if (!index.isValid()) { + return; + } + if (dynamic_cast(static_cast(index.internalPointer()))) { + accept(); + } } void QtMUCSearchWindow::handleSearch() { - handleSearch(ui_.service_->currentText()); + handleSearch(ui_.service_->currentText()); } void QtMUCSearchWindow::handleSearch(const QString& service) { - if (!service.isEmpty()) { - onSearchService(JID(Q2PSTRING(service))); - } + if (!service.isEmpty()) { + onSearchService(JID(Q2PSTRING(service))); + } } void QtMUCSearchWindow::show() { - QWidget::show(); - QWidget::activateWindow(); + QWidget::show(); + QWidget::activateWindow(); } void QtMUCSearchWindow::clearList() { - model_->clear(); + model_->clear(); } void QtMUCSearchWindow::addService(const MUCService& service) { - updateThrobberPosition(); - MUCSearchServiceItem* serviceItem = new MUCSearchServiceItem(P2QSTRING(service.getJID().toString())); - if (service.getRooms().size() > 0) { - foreach (MUCService::MUCRoom room, service.getRooms()) { - new MUCSearchRoomItem(P2QSTRING(room.getNode()), serviceItem); - } - } - else { - new MUCSearchEmptyItem(serviceItem); - } - model_->addService(serviceItem); - ui_.results_->expandAll(); + updateThrobberPosition(); + MUCSearchServiceItem* serviceItem = new MUCSearchServiceItem(P2QSTRING(service.getJID().toString())); + if (service.getRooms().size() > 0) { + foreach (MUCService::MUCRoom room, service.getRooms()) { + new MUCSearchRoomItem(P2QSTRING(room.getNode()), serviceItem); + } + } + else { + new MUCSearchEmptyItem(serviceItem); + } + model_->addService(serviceItem); + ui_.results_->expandAll(); } void QtMUCSearchWindow::setSearchInProgress(bool searching) { - if (searching) { - throbber_->movie()->start(); - } else { - throbber_->movie()->stop(); - } - throbber_->setVisible(searching); + if (searching) { + throbber_->movie()->start(); + } else { + throbber_->movie()->stop(); + } + throbber_->setVisible(searching); } void QtMUCSearchWindow::accept() { - MUCSearchRoomItem* room = getSelectedRoom(); - if (room) { - onFinished(JID(Q2PSTRING(room->getNode()), Q2PSTRING(room->getParent()->getHost()))); - } - else { - onFinished(boost::optional()); - } - QDialog::accept(); + MUCSearchRoomItem* room = getSelectedRoom(); + if (room) { + onFinished(JID(Q2PSTRING(room->getNode()), Q2PSTRING(room->getParent()->getHost()))); + } + else { + onFinished(boost::optional()); + } + QDialog::accept(); } void QtMUCSearchWindow::reject() { - onFinished(boost::optional()); - QDialog::reject(); + onFinished(boost::optional()); + QDialog::reject(); } void QtMUCSearchWindow::handleSelectionChanged(const QItemSelection&, const QItemSelection&) { - ui_.okButton->setEnabled(getSelectedRoom()); + ui_.okButton->setEnabled(getSelectedRoom()); } MUCSearchRoomItem* QtMUCSearchWindow::getSelectedRoom() const { - // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the - // QModelIndexList destructor. - // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case - // was resolved by linking against the debug libs, ours isn't, and we're not alone) - QItemSelection ranges = ui_.results_->selectionModel()->selection(); - QModelIndexList lstIndex; - for (int i = 0; i < ranges.count(); ++i) { - QModelIndex parent = ranges.at(i).parent(); - int right = ranges.at(i).model()->columnCount(parent) - 1; - if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) { - for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) { - lstIndex.append(ranges.at(i).model()->index(r, 0, parent)); - } - } - } - if (lstIndex.isEmpty()) { - return NULL; - } - else { - return dynamic_cast(static_cast(lstIndex.first().internalPointer())); - } + // Not using selectedIndexes(), because this seems to cause a crash in Qt (4.7.0) in the + // QModelIndexList destructor. + // This is a workaround posted in http://www.qtcentre.org/threads/16933 (although this case + // was resolved by linking against the debug libs, ours isn't, and we're not alone) + QItemSelection ranges = ui_.results_->selectionModel()->selection(); + QModelIndexList lstIndex; + for (int i = 0; i < ranges.count(); ++i) { + QModelIndex parent = ranges.at(i).parent(); + int right = ranges.at(i).model()->columnCount(parent) - 1; + if (ranges.at(i).left() == 0 && ranges.at(i).right() == right) { + for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r) { + lstIndex.append(ranges.at(i).model()->index(r, 0, parent)); + } + } + } + if (lstIndex.isEmpty()) { + return NULL; + } + else { + return dynamic_cast(static_cast(lstIndex.first().internalPointer())); + } } } diff --git a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h index 4ac845a..b115e6f 100644 --- a/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h +++ b/Swift/QtUI/MUCSearch/QtMUCSearchWindow.h @@ -11,41 +11,41 @@ #include namespace Swift { - class MUCSearchModel; - class MUCSearchDelegate; - class MUCSearchRoomItem; - - class QtMUCSearchWindow : public QDialog, public MUCSearchWindow { - Q_OBJECT - public: - QtMUCSearchWindow(); - virtual ~QtMUCSearchWindow(); - - virtual void clearList(); - virtual void addService(const MUCService& service); - virtual void addSavedServices(const std::list& services); - virtual void setSearchInProgress(bool searching); - - virtual void show(); - virtual void accept(); - virtual void reject(); - - protected: - virtual void resizeEvent(QResizeEvent* event); - - private slots: - void handleSearch(); - void handleSearch(const QString&); - void handleActivated(const QModelIndex& index); - void updateThrobberPosition(); - void handleSelectionChanged (const QItemSelection&, const QItemSelection&); - MUCSearchRoomItem* getSelectedRoom() const; - - private: - Ui::QtMUCSearchWindow ui_; - MUCSearchModel* model_; - MUCSearchDelegate* delegate_; - QLabel* throbber_; - bool hasHadScrollBars_; - }; + class MUCSearchModel; + class MUCSearchDelegate; + class MUCSearchRoomItem; + + class QtMUCSearchWindow : public QDialog, public MUCSearchWindow { + Q_OBJECT + public: + QtMUCSearchWindow(); + virtual ~QtMUCSearchWindow(); + + virtual void clearList(); + virtual void addService(const MUCService& service); + virtual void addSavedServices(const std::list& services); + virtual void setSearchInProgress(bool searching); + + virtual void show(); + virtual void accept(); + virtual void reject(); + + protected: + virtual void resizeEvent(QResizeEvent* event); + + private slots: + void handleSearch(); + void handleSearch(const QString&); + void handleActivated(const QModelIndex& index); + void updateThrobberPosition(); + void handleSelectionChanged (const QItemSelection&, const QItemSelection&); + MUCSearchRoomItem* getSelectedRoom() const; + + private: + Ui::QtMUCSearchWindow ui_; + MUCSearchModel* model_; + MUCSearchDelegate* delegate_; + QLabel* throbber_; + bool hasHadScrollBars_; + }; } diff --git a/Swift/QtUI/MessageSnippet.cpp b/Swift/QtUI/MessageSnippet.cpp index c2969cf..85cbdb9 100644 --- a/Swift/QtUI/MessageSnippet.cpp +++ b/Swift/QtUI/MessageSnippet.cpp @@ -11,33 +11,33 @@ namespace Swift { MessageSnippet::MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction) : ChatSnippet(appendToPrevious) { - if (appendToPrevious) { - setContinuationFallbackSnippet(boost::shared_ptr(new MessageSnippet(message, sender, time, iconURI, isIncoming, false, theme, id, direction))); - } - if (isIncoming) { - if (appendToPrevious) { - content_ = theme->getIncomingNextContent(); - } - else { - content_ = theme->getIncomingContent(); - } - } - else { - if (appendToPrevious) { - content_ = theme->getOutgoingNextContent(); - } - else { - content_ = theme->getOutgoingContent(); - } - } - - content_.replace("%direction%", directionToCSS(direction)); - content_.replace("%message%", wrapResizable("" + escape(message) + "")); - content_.replace("%wrapped_sender%", wrapResizable(escape(sender))); - content_.replace("%sender%", escape(sender)); - content_.replace("%time%", wrapResizable("" + timeToEscapedString(time) + "")); - content_.replace("%userIconPath%", escape(iconURI)); - content_.replace("%id%", id); + if (appendToPrevious) { + setContinuationFallbackSnippet(boost::shared_ptr(new MessageSnippet(message, sender, time, iconURI, isIncoming, false, theme, id, direction))); + } + if (isIncoming) { + if (appendToPrevious) { + content_ = theme->getIncomingNextContent(); + } + else { + content_ = theme->getIncomingContent(); + } + } + else { + if (appendToPrevious) { + content_ = theme->getOutgoingNextContent(); + } + else { + content_ = theme->getOutgoingContent(); + } + } + + content_.replace("%direction%", directionToCSS(direction)); + content_.replace("%message%", wrapResizable("" + escape(message) + "")); + content_.replace("%wrapped_sender%", wrapResizable(escape(sender))); + content_.replace("%sender%", escape(sender)); + content_.replace("%time%", wrapResizable("" + timeToEscapedString(time) + "")); + content_.replace("%userIconPath%", escape(iconURI)); + content_.replace("%id%", id); } MessageSnippet::~MessageSnippet() { diff --git a/Swift/QtUI/MessageSnippet.h b/Swift/QtUI/MessageSnippet.h index e6972a1..302785f 100644 --- a/Swift/QtUI/MessageSnippet.h +++ b/Swift/QtUI/MessageSnippet.h @@ -13,19 +13,19 @@ class QDateTime; namespace Swift { - class MessageSnippet : public ChatSnippet { - public: - MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction); - virtual ~MessageSnippet(); - const QString& getContent() const { - return content_; - } + class MessageSnippet : public ChatSnippet { + public: + MessageSnippet(const QString& message, const QString& sender, const QDateTime& time, const QString& iconURI, bool isIncoming, bool appendToPrevious, QtChatTheme* theme, const QString& id, Direction direction); + virtual ~MessageSnippet(); + const QString& getContent() const { + return content_; + } - QString getContinuationElementID() const { - return "insert"; - } + QString getContinuationElementID() const { + return "insert"; + } - private: - QString content_; - }; + private: + QString content_; + }; } diff --git a/Swift/QtUI/NotifierTest/NotifierTest.cpp b/Swift/QtUI/NotifierTest/NotifierTest.cpp index 56f7985..8d2e467 100644 --- a/Swift/QtUI/NotifierTest/NotifierTest.cpp +++ b/Swift/QtUI/NotifierTest/NotifierTest.cpp @@ -17,12 +17,12 @@ using namespace Swift; void notificationClicked(const std::string& message) { - std::cout << "Notification clicked: " << message << std::endl; + std::cout << "Notification clicked: " << message << std::endl; } int main(int argc, char* argv[]) { - QApplication app(argc, argv); - GrowlNotifier notifier("Swift-NotifierTest"); - notifier.showMessage(Notifier::ContactAvailable, "Contact is available", "The contact has become available", ByteArray(), boost::bind(¬ificationClicked, "Message 1")); - return app.exec(); + QApplication app(argc, argv); + GrowlNotifier notifier("Swift-NotifierTest"); + notifier.showMessage(Notifier::ContactAvailable, "Contact is available", "The contact has become available", ByteArray(), boost::bind(¬ificationClicked, "Message 1")); + return app.exec(); } diff --git a/Swift/QtUI/QtAboutWidget.cpp b/Swift/QtUI/QtAboutWidget.cpp index 9fb07ed..b69113f 100644 --- a/Swift/QtUI/QtAboutWidget.cpp +++ b/Swift/QtUI/QtAboutWidget.cpp @@ -22,67 +22,67 @@ namespace Swift { QtAboutWidget::QtAboutWidget() : QDialog() { #ifndef Q_OS_MAC - setWindowTitle(QString(tr("About %1")).arg("Swift")); + setWindowTitle(QString(tr("About %1")).arg("Swift")); #endif - setWindowIcon(QIcon(":/logo-icon-16.png")); + setWindowIcon(QIcon(":/logo-icon-16.png")); - resize(180, 240); - QVBoxLayout *mainLayout = new QVBoxLayout(this); - mainLayout->setAlignment(Qt::AlignHCenter); - setLayout(mainLayout); - - QLabel* iconLabel = new QLabel(this); - iconLabel->setPixmap(QIcon(":/logo-shaded-text.256.png").pixmap(90, 90)); - iconLabel->setAlignment(Qt::AlignHCenter); - mainLayout->addWidget(iconLabel); - - QLabel* appNameLabel = new QLabel("
" + QCoreApplication::applicationName() + "
", this); - mainLayout->addWidget(appNameLabel); - - QLabel* versionLabel = new QLabel((QString("
") + tr("Version %1") + "

" + QString(tr("Built with Qt %2")) + QString("
") + QString(tr("Running with Qt %3")) + "
").arg(QCoreApplication::applicationVersion()).arg(QT_VERSION_STR).arg(qVersion())); - versionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); - mainLayout->addWidget(versionLabel); + resize(180, 240); + QVBoxLayout *mainLayout = new QVBoxLayout(this); + mainLayout->setAlignment(Qt::AlignHCenter); + setLayout(mainLayout); - if (QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR") != "TRANSLATION_AUTHOR") { - mainLayout->addWidget(new QLabel(QString("
") + QString(tr("Using the English translation by\n%1")).arg(QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR")).replace("\n", "
") + "
", this)); - } - QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_LICENSE", "This string contains the license under which this translation is licensed. We ask you to license the translation under the BSD license. Please read http://www.opensource.org/licenses/bsd-license.php, and if you agree to release your translation under this license, use the following (untranslated) text: 'This translation is licensed under the BSD License. See http://www.opensource.org/licenses/bsd-license.php'"); + QLabel* iconLabel = new QLabel(this); + iconLabel->setPixmap(QIcon(":/logo-shaded-text.256.png").pixmap(90, 90)); + iconLabel->setAlignment(Qt::AlignHCenter); + mainLayout->addWidget(iconLabel); + + QLabel* appNameLabel = new QLabel("
" + QCoreApplication::applicationName() + "
", this); + mainLayout->addWidget(appNameLabel); + + QLabel* versionLabel = new QLabel((QString("
") + tr("Version %1") + "

" + QString(tr("Built with Qt %2")) + QString("
") + QString(tr("Running with Qt %3")) + "
").arg(QCoreApplication::applicationVersion()).arg(QT_VERSION_STR).arg(qVersion())); + versionLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); + mainLayout->addWidget(versionLabel); + + if (QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR") != "TRANSLATION_AUTHOR") { + mainLayout->addWidget(new QLabel(QString("
") + QString(tr("Using the English translation by\n%1")).arg(QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_AUTHOR")).replace("\n", "
") + "
", this)); + } + QCoreApplication::translate("TRANSLATION_INFO", "TRANSLATION_LICENSE", "This string contains the license under which this translation is licensed. We ask you to license the translation under the BSD license. Please read http://www.opensource.org/licenses/bsd-license.php, and if you agree to release your translation under this license, use the following (untranslated) text: 'This translation is licensed under the BSD License. See http://www.opensource.org/licenses/bsd-license.php'"); #if defined(SWIFTEN_PLATFORM_WINDOWS) || defined(SWIFTEN_PLATFORM_MACOSX) - QPushButton* licenseButton = new QPushButton(tr("View License"), this); - mainLayout->addWidget(licenseButton); - connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked())); + QPushButton* licenseButton = new QPushButton(tr("View License"), this); + mainLayout->addWidget(licenseButton); + connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked())); #else - // Some Linux desktops have dialog window decorations without close window buttons. - // This code adds a dedicated button to close the about window dialog. - QHBoxLayout* buttonLayout = new QHBoxLayout(); - mainLayout->addLayout(buttonLayout); + // Some Linux desktops have dialog window decorations without close window buttons. + // This code adds a dedicated button to close the about window dialog. + QHBoxLayout* buttonLayout = new QHBoxLayout(); + mainLayout->addLayout(buttonLayout); - QPushButton* licenseButton = new QPushButton(tr("View License"), this); - buttonLayout->addWidget(licenseButton); - connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked())); + QPushButton* licenseButton = new QPushButton(tr("View License"), this); + buttonLayout->addWidget(licenseButton); + connect(licenseButton, SIGNAL(clicked()), this, SLOT(handleLicenseClicked())); - buttonLayout->addItem(new QSpacerItem(20,20)); + buttonLayout->addItem(new QSpacerItem(20,20)); - QPushButton* closeButton = new QPushButton(tr("Close"), this); - buttonLayout->addWidget(closeButton); - connect(closeButton, SIGNAL(clicked()), this, SLOT(accept())); + QPushButton* closeButton = new QPushButton(tr("Close"), this); + buttonLayout->addWidget(closeButton); + connect(closeButton, SIGNAL(clicked()), this, SLOT(accept())); #endif - setFixedSize(minimumSizeHint()); + setFixedSize(minimumSizeHint()); } void QtAboutWidget::handleLicenseClicked() { - QTextEdit* text = new QTextEdit(); - text->setAttribute(Qt::WA_DeleteOnClose); - text->setReadOnly(true); - QFile file(":/COPYING"); - file.open(QIODevice::ReadOnly); - QTextStream in(&file); - in.setCodec("UTF-8"); - text->setPlainText(in.readAll()); - file.close(); - text->resize(500, 600); - text->show(); - text->activateWindow(); + QTextEdit* text = new QTextEdit(); + text->setAttribute(Qt::WA_DeleteOnClose); + text->setReadOnly(true); + QFile file(":/COPYING"); + file.open(QIODevice::ReadOnly); + QTextStream in(&file); + in.setCodec("UTF-8"); + text->setPlainText(in.readAll()); + file.close(); + text->resize(500, 600); + text->show(); + text->activateWindow(); } } diff --git a/Swift/QtUI/QtAboutWidget.h b/Swift/QtUI/QtAboutWidget.h index d09010b..7d0d628 100644 --- a/Swift/QtUI/QtAboutWidget.h +++ b/Swift/QtUI/QtAboutWidget.h @@ -9,13 +9,13 @@ #include namespace Swift { - class QtAboutWidget : public QDialog { - Q_OBJECT + class QtAboutWidget : public QDialog { + Q_OBJECT - public: - QtAboutWidget(); + public: + QtAboutWidget(); - private slots: - void handleLicenseClicked(); - }; + private slots: + void handleLicenseClicked(); + }; } diff --git a/Swift/QtUI/QtAdHocCommandWindow.cpp b/Swift/QtUI/QtAdHocCommandWindow.cpp index ef397f4..87b1585 100644 --- a/Swift/QtUI/QtAdHocCommandWindow.cpp +++ b/Swift/QtUI/QtAdHocCommandWindow.cpp @@ -20,155 +20,155 @@ const int FormLayoutIndex = 1; namespace Swift { QtAdHocCommandWindow::QtAdHocCommandWindow(boost::shared_ptr command) : command_(command) { - formWidget_ = NULL; - - setAttribute(Qt::WA_DeleteOnClose); - command->onNextStageReceived.connect(boost::bind(&QtAdHocCommandWindow::handleNextStageReceived, this, _1)); - command->onError.connect(boost::bind(&QtAdHocCommandWindow::handleError, this, _1)); - command->start(); - - layout_ = new QBoxLayout(QBoxLayout::TopToBottom, this); - layout_->setContentsMargins(0,0,0,0); - layout_->setSpacing(2); - label_ = new QLabel(this); - label_->setTextFormat(Qt::PlainText); - layout_->addWidget(label_); - - errorLabel_ = new QLabel(this); - errorLabel_->setText(QString("%1").arg(tr("Unable to complete the command because you have been disconnected"))); - errorLabel_->setVisible(false); - errorLabel_->setFrameStyle(QFrame::Box|QFrame::Sunken); - layout_->addWidget(errorLabel_); - - dialogButtons_ = new QDialogButtonBox(this); - layout_->addWidget(dialogButtons_); - - dialogButtons_->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); - okButton_ = dialogButtons_->button(QDialogButtonBox::Ok); - connect(okButton_, SIGNAL(clicked()), this, SLOT(close())); - cancelButton_ = dialogButtons_->button(QDialogButtonBox::Cancel); - connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked())); - // Buttons appear next to the Ok button, right of Cancel with YesRole - completeButton_ = dialogButtons_->addButton(tr("Complete"), QDialogButtonBox::YesRole); - connect(completeButton_, SIGNAL(clicked()), this, SLOT(handleCompleteClicked())); - nextButton_ = dialogButtons_->addButton(tr("Next"), QDialogButtonBox::YesRole); - connect(nextButton_, SIGNAL(clicked()), this, SLOT(handleNextClicked())); - backButton_ = dialogButtons_->addButton(tr("Back"), QDialogButtonBox::YesRole); - connect(backButton_, SIGNAL(clicked()), this, SLOT(handlePrevClicked())); - - okButton_->setEnabled(false); - okButton_->hide(); - - nextButton_->setEnabled(false); - backButton_->setEnabled(false); - completeButton_->setEnabled(false); - - actions_[Command::Next] = nextButton_; - actions_[Command::Prev] = backButton_; - actions_[Command::Complete] = completeButton_; - actions_[Command::Cancel] = cancelButton_; + formWidget_ = NULL; + + setAttribute(Qt::WA_DeleteOnClose); + command->onNextStageReceived.connect(boost::bind(&QtAdHocCommandWindow::handleNextStageReceived, this, _1)); + command->onError.connect(boost::bind(&QtAdHocCommandWindow::handleError, this, _1)); + command->start(); + + layout_ = new QBoxLayout(QBoxLayout::TopToBottom, this); + layout_->setContentsMargins(0,0,0,0); + layout_->setSpacing(2); + label_ = new QLabel(this); + label_->setTextFormat(Qt::PlainText); + layout_->addWidget(label_); + + errorLabel_ = new QLabel(this); + errorLabel_->setText(QString("%1").arg(tr("Unable to complete the command because you have been disconnected"))); + errorLabel_->setVisible(false); + errorLabel_->setFrameStyle(QFrame::Box|QFrame::Sunken); + layout_->addWidget(errorLabel_); + + dialogButtons_ = new QDialogButtonBox(this); + layout_->addWidget(dialogButtons_); + + dialogButtons_->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); + okButton_ = dialogButtons_->button(QDialogButtonBox::Ok); + connect(okButton_, SIGNAL(clicked()), this, SLOT(close())); + cancelButton_ = dialogButtons_->button(QDialogButtonBox::Cancel); + connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked())); + // Buttons appear next to the Ok button, right of Cancel with YesRole + completeButton_ = dialogButtons_->addButton(tr("Complete"), QDialogButtonBox::YesRole); + connect(completeButton_, SIGNAL(clicked()), this, SLOT(handleCompleteClicked())); + nextButton_ = dialogButtons_->addButton(tr("Next"), QDialogButtonBox::YesRole); + connect(nextButton_, SIGNAL(clicked()), this, SLOT(handleNextClicked())); + backButton_ = dialogButtons_->addButton(tr("Back"), QDialogButtonBox::YesRole); + connect(backButton_, SIGNAL(clicked()), this, SLOT(handlePrevClicked())); + + okButton_->setEnabled(false); + okButton_->hide(); + + nextButton_->setEnabled(false); + backButton_->setEnabled(false); + completeButton_->setEnabled(false); + + actions_[Command::Next] = nextButton_; + actions_[Command::Prev] = backButton_; + actions_[Command::Complete] = completeButton_; + actions_[Command::Cancel] = cancelButton_; } QtAdHocCommandWindow::~QtAdHocCommandWindow() { } void QtAdHocCommandWindow::setOnline(bool online) { - if (!online) { - nextButton_->setEnabled(false); - backButton_->setEnabled(false); - completeButton_->setEnabled(false); - errorLabel_->setVisible(true); - } + if (!online) { + nextButton_->setEnabled(false); + backButton_->setEnabled(false); + completeButton_->setEnabled(false); + errorLabel_->setVisible(true); + } } void QtAdHocCommandWindow::closeEvent(QCloseEvent*) { - onClosing(); + onClosing(); } void QtAdHocCommandWindow::handleCancelClicked() { - command_->cancel(); - close(); + command_->cancel(); + close(); } void QtAdHocCommandWindow::handlePrevClicked() { - command_->goBack(); + command_->goBack(); } void QtAdHocCommandWindow::handleNextClicked() { - command_->goNext(formWidget_ ? formWidget_->getCompletedForm() : Form::ref()); + command_->goNext(formWidget_ ? formWidget_->getCompletedForm() : Form::ref()); } void QtAdHocCommandWindow::handleCompleteClicked() { - command_->complete(formWidget_ ? formWidget_->getCompletedForm() : Form::ref()); + command_->complete(formWidget_ ? formWidget_->getCompletedForm() : Form::ref()); } void QtAdHocCommandWindow::handleNextStageReceived(Command::ref command) { - QString notes; - foreach (Command::Note note, command->getNotes()) { - if (!notes.isEmpty()) { - notes += "\n"; - } - QString qNote(P2QSTRING(note.note)); - switch (note.type) { - case Command::Note::Error: notes += tr("Error: %1").arg(qNote); break; - case Command::Note::Warn: notes += tr("Warning: %1").arg(qNote); break; - case Command::Note::Info: notes += qNote; break; - } - } - label_->setText(notes); - if (command->getForm()) { - setForm(command->getForm()); - } else { - setNoForm(notes.isEmpty()); - } - setAvailableActions(command); + QString notes; + foreach (Command::Note note, command->getNotes()) { + if (!notes.isEmpty()) { + notes += "\n"; + } + QString qNote(P2QSTRING(note.note)); + switch (note.type) { + case Command::Note::Error: notes += tr("Error: %1").arg(qNote); break; + case Command::Note::Warn: notes += tr("Warning: %1").arg(qNote); break; + case Command::Note::Info: notes += qNote; break; + } + } + label_->setText(notes); + if (command->getForm()) { + setForm(command->getForm()); + } else { + setNoForm(notes.isEmpty()); + } + setAvailableActions(command); } void QtAdHocCommandWindow::handleError(ErrorPayload::ref /*error*/) { - nextButton_->setEnabled(false); - backButton_->setEnabled(false); - completeButton_->setEnabled(false); - label_->setText(tr("Error executing command")); + nextButton_->setEnabled(false); + backButton_->setEnabled(false); + completeButton_->setEnabled(false); + label_->setText(tr("Error executing command")); } void QtAdHocCommandWindow::setForm(Form::ref form) { - form_ = form; - delete formWidget_; - formWidget_ = new QtFormWidget(form, this); - layout_->insertWidget(FormLayoutIndex, formWidget_); - show(); + form_ = form; + delete formWidget_; + formWidget_ = new QtFormWidget(form, this); + layout_->insertWidget(FormLayoutIndex, formWidget_); + show(); } void QtAdHocCommandWindow::setNoForm(bool andHide) { - form_.reset(); - delete formWidget_; - formWidget_ = NULL; - resize(minimumSize()); - setVisible(!andHide); + form_.reset(); + delete formWidget_; + formWidget_ = NULL; + resize(minimumSize()); + setVisible(!andHide); } typedef std::pair ActionButton; void QtAdHocCommandWindow::setAvailableActions(Command::ref /*commandResult*/) { - okButton_->show(); - okButton_->setEnabled(true); - foreach (ActionButton pair, actions_) { - OutgoingAdHocCommandSession::ActionState state = command_->getActionState(pair.first); - if (state & OutgoingAdHocCommandSession::Present) { - okButton_->hide(); - okButton_->setEnabled(false); - pair.second->show(); - } - else { - pair.second->hide(); - } - if (state & OutgoingAdHocCommandSession::Enabled) { - pair.second->setEnabled(true); - } - else { - pair.second->setEnabled(false); - } - } + okButton_->show(); + okButton_->setEnabled(true); + foreach (ActionButton pair, actions_) { + OutgoingAdHocCommandSession::ActionState state = command_->getActionState(pair.first); + if (state & OutgoingAdHocCommandSession::Present) { + okButton_->hide(); + okButton_->setEnabled(false); + pair.second->show(); + } + else { + pair.second->hide(); + } + if (state & OutgoingAdHocCommandSession::Enabled) { + pair.second->setEnabled(true); + } + else { + pair.second->setEnabled(false); + } + } } } diff --git a/Swift/QtUI/QtAdHocCommandWindow.h b/Swift/QtUI/QtAdHocCommandWindow.h index c8d493c..61cd5be 100644 --- a/Swift/QtUI/QtAdHocCommandWindow.h +++ b/Swift/QtUI/QtAdHocCommandWindow.h @@ -18,41 +18,41 @@ class QBoxLayout; namespace Swift { - class QtFormWidget; - class QtAdHocCommandWindow : public QWidget, public AdHocCommandWindow { - Q_OBJECT - public: - QtAdHocCommandWindow(boost::shared_ptr command); - virtual ~QtAdHocCommandWindow(); - virtual void setOnline(bool online); - - private: - void closeEvent(QCloseEvent* event); - void handleNextStageReceived(Command::ref command); - void handleError(ErrorPayload::ref error); - void setForm(Form::ref); - void setNoForm(bool andHide); - void setAvailableActions(Command::ref commandResult); - - private slots: - void handleCancelClicked(); - void handlePrevClicked(); - void handleNextClicked(); - void handleCompleteClicked(); - - private: - boost::shared_ptr command_; - QtFormWidget* formWidget_; - Form::ref form_; - QLabel* label_; - QLabel* errorLabel_; - QPushButton* backButton_; - QPushButton* nextButton_; - QPushButton* completeButton_; - QPushButton* cancelButton_; - QPushButton* okButton_; - std::map actions_; - QDialogButtonBox* dialogButtons_; - QBoxLayout* layout_; - }; + class QtFormWidget; + class QtAdHocCommandWindow : public QWidget, public AdHocCommandWindow { + Q_OBJECT + public: + QtAdHocCommandWindow(boost::shared_ptr command); + virtual ~QtAdHocCommandWindow(); + virtual void setOnline(bool online); + + private: + void closeEvent(QCloseEvent* event); + void handleNextStageReceived(Command::ref command); + void handleError(ErrorPayload::ref error); + void setForm(Form::ref); + void setNoForm(bool andHide); + void setAvailableActions(Command::ref commandResult); + + private slots: + void handleCancelClicked(); + void handlePrevClicked(); + void handleNextClicked(); + void handleCompleteClicked(); + + private: + boost::shared_ptr command_; + QtFormWidget* formWidget_; + Form::ref form_; + QLabel* label_; + QLabel* errorLabel_; + QPushButton* backButton_; + QPushButton* nextButton_; + QPushButton* completeButton_; + QPushButton* cancelButton_; + QPushButton* okButton_; + std::map actions_; + QDialogButtonBox* dialogButtons_; + QBoxLayout* layout_; + }; } diff --git a/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp b/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp index ac2a603..69e1d68 100644 --- a/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp +++ b/Swift/QtUI/QtAdHocCommandWithJIDWindow.cpp @@ -23,42 +23,42 @@ namespace Swift { QtAdHocCommandWithJIDWindow::QtAdHocCommandWithJIDWindow(UIEventStream* uiEventStream) : uiEventStream_(uiEventStream) { - QVBoxLayout* hlayout = new QVBoxLayout(this); + QVBoxLayout* hlayout = new QVBoxLayout(this); - QLabel* jidLabel = new QLabel("JID:", this); - hlayout->addWidget(jidLabel); - jid_ = new QLineEdit(this); - hlayout->addWidget(jid_); + QLabel* jidLabel = new QLabel("JID:", this); + hlayout->addWidget(jidLabel); + jid_ = new QLineEdit(this); + hlayout->addWidget(jid_); - QLabel* commandLabel = new QLabel("Command:", this); - hlayout->addWidget(commandLabel); - node_ = new QLineEdit(this); - hlayout->addWidget(node_); + QLabel* commandLabel = new QLabel("Command:", this); + hlayout->addWidget(commandLabel); + node_ = new QLineEdit(this); + hlayout->addWidget(node_); - QDialogButtonBox* buttonBox = new QDialogButtonBox(this); - QPushButton* rejectButton = buttonBox->addButton("Cancel", QDialogButtonBox::RejectRole); - connect(rejectButton, SIGNAL(clicked()), this, SLOT(handleRejectClick())); - QPushButton* acceptButton = buttonBox->addButton("Complete", QDialogButtonBox::AcceptRole); - connect(acceptButton, SIGNAL(clicked()), this, SLOT(handleAcceptClick())); - hlayout->addWidget(buttonBox); + QDialogButtonBox* buttonBox = new QDialogButtonBox(this); + QPushButton* rejectButton = buttonBox->addButton("Cancel", QDialogButtonBox::RejectRole); + connect(rejectButton, SIGNAL(clicked()), this, SLOT(handleRejectClick())); + QPushButton* acceptButton = buttonBox->addButton("Complete", QDialogButtonBox::AcceptRole); + connect(acceptButton, SIGNAL(clicked()), this, SLOT(handleAcceptClick())); + hlayout->addWidget(buttonBox); - setLayout(hlayout); - show(); + setLayout(hlayout); + show(); } QtAdHocCommandWithJIDWindow::~QtAdHocCommandWithJIDWindow() { } void QtAdHocCommandWithJIDWindow::handleAcceptClick() { - const JID jid = JID(Q2PSTRING(jid_->text())); - const std::string node = Q2PSTRING(node_->text()); - boost::shared_ptr event(new RequestAdHocWithJIDUIEvent(jid, node)); - uiEventStream_->send(event); - accept(); + const JID jid = JID(Q2PSTRING(jid_->text())); + const std::string node = Q2PSTRING(node_->text()); + boost::shared_ptr event(new RequestAdHocWithJIDUIEvent(jid, node)); + uiEventStream_->send(event); + accept(); } void QtAdHocCommandWithJIDWindow::handleRejectClick() { - reject(); + reject(); } } diff --git a/Swift/QtUI/QtAdHocCommandWithJIDWindow.h b/Swift/QtUI/QtAdHocCommandWithJIDWindow.h index e1f7a9c..0e83555 100644 --- a/Swift/QtUI/QtAdHocCommandWithJIDWindow.h +++ b/Swift/QtUI/QtAdHocCommandWithJIDWindow.h @@ -14,19 +14,19 @@ class QBoxLayout; namespace Swift { - class UIEventStream; - class QtFormWidget; - class QtAdHocCommandWithJIDWindow : public QDialog { - Q_OBJECT - public: - QtAdHocCommandWithJIDWindow(UIEventStream* eventStream); - virtual ~QtAdHocCommandWithJIDWindow(); - public slots: - void handleAcceptClick(); - void handleRejectClick(); - private: - UIEventStream* uiEventStream_; - QLineEdit* jid_; - QLineEdit* node_; - }; + class UIEventStream; + class QtFormWidget; + class QtAdHocCommandWithJIDWindow : public QDialog { + Q_OBJECT + public: + QtAdHocCommandWithJIDWindow(UIEventStream* eventStream); + virtual ~QtAdHocCommandWithJIDWindow(); + public slots: + void handleAcceptClick(); + void handleRejectClick(); + private: + UIEventStream* uiEventStream_; + QLineEdit* jid_; + QLineEdit* node_; + }; } diff --git a/Swift/QtUI/QtAddBookmarkWindow.cpp b/Swift/QtUI/QtAddBookmarkWindow.cpp index 087628d..500b298 100644 --- a/Swift/QtUI/QtAddBookmarkWindow.cpp +++ b/Swift/QtUI/QtAddBookmarkWindow.cpp @@ -8,23 +8,23 @@ namespace Swift { QtAddBookmarkWindow::QtAddBookmarkWindow(UIEventStream* eventStream) : eventStream_(eventStream) { - setWindowTitle(tr("Add Bookmark Details")); + setWindowTitle(tr("Add Bookmark Details")); } QtAddBookmarkWindow::QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark) : eventStream_(eventStream) { - createFormFromBookmark(bookmark); - setWindowTitle(tr("Add Bookmark Details")); + createFormFromBookmark(bookmark); + setWindowTitle(tr("Add Bookmark Details")); } bool QtAddBookmarkWindow::commit() { - boost::optional bookmark = createBookmarkFromForm(); - if (bookmark) { - eventStream_->send(boost::shared_ptr(new AddMUCBookmarkUIEvent(*bookmark))); - return true; - } - else { - return false; - } + boost::optional bookmark = createBookmarkFromForm(); + if (bookmark) { + eventStream_->send(boost::shared_ptr(new AddMUCBookmarkUIEvent(*bookmark))); + return true; + } + else { + return false; + } } } diff --git a/Swift/QtUI/QtAddBookmarkWindow.h b/Swift/QtUI/QtAddBookmarkWindow.h index 7b08b8e..607f647 100644 --- a/Swift/QtUI/QtAddBookmarkWindow.h +++ b/Swift/QtUI/QtAddBookmarkWindow.h @@ -12,13 +12,13 @@ #include namespace Swift { - class QtAddBookmarkWindow : public QtBookmarkDetailWindow { - Q_OBJECT - public: - QtAddBookmarkWindow(UIEventStream* eventStream); - QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark); - bool commit(); - private: - UIEventStream* eventStream_; - }; + class QtAddBookmarkWindow : public QtBookmarkDetailWindow { + Q_OBJECT + public: + QtAddBookmarkWindow(UIEventStream* eventStream); + QtAddBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark); + bool commit(); + private: + UIEventStream* eventStream_; + }; } diff --git a/Swift/QtUI/QtAffiliationEditor.cpp b/Swift/QtUI/QtAffiliationEditor.cpp index d732c4e..980b26a 100644 --- a/Swift/QtUI/QtAffiliationEditor.cpp +++ b/Swift/QtUI/QtAffiliationEditor.cpp @@ -13,66 +13,66 @@ namespace Swift { QtAffiliationEditor::QtAffiliationEditor(QWidget* parent) : QDialog(parent){ - ui_.setupUi(this); - setAttribute(Qt::WA_DeleteOnClose); - connect(ui_.affiliation, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged(int))); - connect(ui_.addJID, SIGNAL(clicked()), this, SLOT(handleAddClicked())); - connect(ui_.removeJID, SIGNAL(clicked()), this, SLOT(handleRemoveClicked())); + ui_.setupUi(this); + setAttribute(Qt::WA_DeleteOnClose); + connect(ui_.affiliation, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentIndexChanged(int))); + connect(ui_.addJID, SIGNAL(clicked()), this, SLOT(handleAddClicked())); + connect(ui_.removeJID, SIGNAL(clicked()), this, SLOT(handleRemoveClicked())); } QtAffiliationEditor::~QtAffiliationEditor() { - + } void QtAffiliationEditor::setAffiliations(MUCOccupant::Affiliation affiliation, const std::vector& jids) { - affiliations_[affiliation] = jids; - if (affiliationFromIndex(ui_.affiliation->currentIndex()) == affiliation) { - handleCurrentIndexChanged(ui_.affiliation->currentIndex()); - } + affiliations_[affiliation] = jids; + if (affiliationFromIndex(ui_.affiliation->currentIndex()) == affiliation) { + handleCurrentIndexChanged(ui_.affiliation->currentIndex()); + } } const std::vector >& QtAffiliationEditor::getChanges() const { - return changes_; + return changes_; } void QtAffiliationEditor::handleCurrentIndexChanged(int index) { - ui_.list->clear(); - foreach (const JID& jid, affiliations_[affiliationFromIndex(index)]) { - ui_.list->addItem(P2QSTRING(jid.toString())); - } + ui_.list->clear(); + foreach (const JID& jid, affiliations_[affiliationFromIndex(index)]) { + ui_.list->addItem(P2QSTRING(jid.toString())); + } } void QtAffiliationEditor::handleAddClicked() { - bool ok = false; - JID jid = JID(Q2PSTRING(QInputDialog::getText(this, tr("Add User"), tr("Added User's Address:"), QLineEdit::Normal, "", &ok))); - if (ok && jid.isValid()) { - //FIXME: validation - MUCOccupant::Affiliation affiliation = affiliationFromIndex(ui_.affiliation->currentIndex()); - changes_.push_back(ChangePair(affiliation, jid)); - ui_.list->addItem(P2QSTRING(jid.toString())); - affiliations_[affiliation].push_back(jid); - } + bool ok = false; + JID jid = JID(Q2PSTRING(QInputDialog::getText(this, tr("Add User"), tr("Added User's Address:"), QLineEdit::Normal, "", &ok))); + if (ok && jid.isValid()) { + //FIXME: validation + MUCOccupant::Affiliation affiliation = affiliationFromIndex(ui_.affiliation->currentIndex()); + changes_.push_back(ChangePair(affiliation, jid)); + ui_.list->addItem(P2QSTRING(jid.toString())); + affiliations_[affiliation].push_back(jid); + } } void QtAffiliationEditor::handleRemoveClicked() { - QListWidgetItem* item = ui_.list->currentItem(); - if (item) { - JID jid(Q2PSTRING(item->text())); - changes_.push_back(ChangePair(MUCOccupant::NoAffiliation, jid)); - std::vector& jids = affiliations_[affiliationFromIndex(ui_.affiliation->currentIndex())]; - jids.erase(std::remove(jids.begin(), jids.end(), jid), jids.end()); - handleCurrentIndexChanged(ui_.affiliation->currentIndex()); - } + QListWidgetItem* item = ui_.list->currentItem(); + if (item) { + JID jid(Q2PSTRING(item->text())); + changes_.push_back(ChangePair(MUCOccupant::NoAffiliation, jid)); + std::vector& jids = affiliations_[affiliationFromIndex(ui_.affiliation->currentIndex())]; + jids.erase(std::remove(jids.begin(), jids.end(), jid), jids.end()); + handleCurrentIndexChanged(ui_.affiliation->currentIndex()); + } } MUCOccupant::Affiliation QtAffiliationEditor::affiliationFromIndex(int affiliation) { - switch (affiliation) { - case 0: return MUCOccupant::Owner; - case 1: return MUCOccupant::Admin; - case 2: return MUCOccupant::Member; - case 3: return MUCOccupant::Outcast; - default: return MUCOccupant::Outcast; - } + switch (affiliation) { + case 0: return MUCOccupant::Owner; + case 1: return MUCOccupant::Admin; + case 2: return MUCOccupant::Member; + case 3: return MUCOccupant::Outcast; + default: return MUCOccupant::Outcast; + } } } diff --git a/Swift/QtUI/QtAffiliationEditor.h b/Swift/QtUI/QtAffiliationEditor.h index d706926..3b7e548 100644 --- a/Swift/QtUI/QtAffiliationEditor.h +++ b/Swift/QtUI/QtAffiliationEditor.h @@ -17,22 +17,22 @@ #include namespace Swift { - class QtAffiliationEditor : public QDialog { - Q_OBJECT - public: - QtAffiliationEditor(QWidget* parent = NULL); - ~QtAffiliationEditor(); - void setAffiliations(MUCOccupant::Affiliation, const std::vector& jids); - const std::vector >& getChanges() const; - private slots: - void handleCurrentIndexChanged(int); - void handleAddClicked(); - void handleRemoveClicked(); - private: - typedef std::pair ChangePair; - MUCOccupant::Affiliation affiliationFromIndex(int affiliation); - Ui::QtAffiliationEditor ui_; - std::map > affiliations_; - std::vector changes_; - }; + class QtAffiliationEditor : public QDialog { + Q_OBJECT + public: + QtAffiliationEditor(QWidget* parent = NULL); + ~QtAffiliationEditor(); + void setAffiliations(MUCOccupant::Affiliation, const std::vector& jids); + const std::vector >& getChanges() const; + private slots: + void handleCurrentIndexChanged(int); + void handleAddClicked(); + void handleRemoveClicked(); + private: + typedef std::pair ChangePair; + MUCOccupant::Affiliation affiliationFromIndex(int affiliation); + Ui::QtAffiliationEditor ui_; + std::map > affiliations_; + std::vector changes_; + }; } diff --git a/Swift/QtUI/QtAvatarWidget.cpp b/Swift/QtUI/QtAvatarWidget.cpp index 2474e80..7f6e275 100644 --- a/Swift/QtUI/QtAvatarWidget.cpp +++ b/Swift/QtUI/QtAvatarWidget.cpp @@ -27,85 +27,85 @@ namespace Swift { QtAvatarWidget::QtAvatarWidget(QWidget* parent) : QWidget(parent), editable(false) { - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0,0,0,0); - - QSizePolicy sp(QSizePolicy::Fixed, QSizePolicy::Fixed); - sp.setHorizontalStretch(0); - sp.setVerticalStretch(0); - setSizePolicy(sp); - setMinimumSize(QSize(96, 96)); - setMaximumSize(QSize(96, 96)); - - label = new QLabel(this); - label->setWordWrap(true); - label->setSizePolicy(sp); - label->setMinimumSize(QSize(96, 96)); - label->setMaximumSize(QSize(96, 96)); - label->setAlignment(Qt::AlignCenter); - layout->addWidget(label); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0,0,0,0); + + QSizePolicy sp(QSizePolicy::Fixed, QSizePolicy::Fixed); + sp.setHorizontalStretch(0); + sp.setVerticalStretch(0); + setSizePolicy(sp); + setMinimumSize(QSize(96, 96)); + setMaximumSize(QSize(96, 96)); + + label = new QLabel(this); + label->setWordWrap(true); + label->setSizePolicy(sp); + label->setMinimumSize(QSize(96, 96)); + label->setMaximumSize(QSize(96, 96)); + label->setAlignment(Qt::AlignCenter); + layout->addWidget(label); } void QtAvatarWidget::setAvatar(const ByteArray& data, const std::string& type) { - this->data = data; - this->type = type; - - QImage image; - if (!data.empty()) { - image.loadFromData(reinterpret_cast(vecptr(data)), data.size()); - } - - if (image.isNull()) { - image = QImage(":/icons/no-avatar.png"); - QPainter painter(&image); - painter.setPen(Qt::gray); - QFont font = painter.font(); - font.setPointSize(14); - painter.setFont(font); - painter.drawText(0, 0, image.height(), image.width(), Qt::AlignHCenter | Qt::AlignVCenter, tr("No picture")); - } - - if (image.height() > label->height() || image.width() > label->width()) { - image = image.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); - } - label->setPixmap(QPixmap::fromImage(image)); + this->data = data; + this->type = type; + + QImage image; + if (!data.empty()) { + image.loadFromData(reinterpret_cast(vecptr(data)), data.size()); + } + + if (image.isNull()) { + image = QImage(":/icons/no-avatar.png"); + QPainter painter(&image); + painter.setPen(Qt::gray); + QFont font = painter.font(); + font.setPointSize(14); + painter.setFont(font); + painter.drawText(0, 0, image.height(), image.width(), Qt::AlignHCenter | Qt::AlignVCenter, tr("No picture")); + } + + if (image.height() > label->height() || image.width() > label->width()) { + image = image.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); + } + label->setPixmap(QPixmap::fromImage(image)); } void QtAvatarWidget::mousePressEvent(QMouseEvent* event) { - if (!editable) { - return; - } - QMenu menu; - - QAction* selectPicture = new QAction(tr("Select picture ..."), this); - menu.addAction(selectPicture); - - QAction* clearPicture = new QAction(tr("Clear picture"), this); - menu.addAction(clearPicture); - - QAction* result = menu.exec(event->globalPos()); - if (result == selectPicture) { - QString fileName = QFileDialog::getOpenFileName(this, tr("Select picture"), "", tr("Image Files (*.png *.jpg *.jpeg *.gif)")); - if (!fileName.isEmpty()) { - ByteArray data; - readByteArrayFromFile(data, stringToPath(Q2PSTRING(fileName))); - - QBuffer buffer; - buffer.setData(reinterpret_cast(vecptr(data)), data.size()); - buffer.open(QIODevice::ReadOnly); - QString type = QImageReader::imageFormat(&buffer).toLower(); - if (!type.isEmpty()) { - type = "image/" + type; - setAvatar(data, Q2PSTRING(type)); - } - else { - QMessageBox::critical(this, tr("Error"), tr("The selected picture is in an unrecognized format")); - } - } - } - else if (result == clearPicture) { - setAvatar(ByteArray(), ""); - } + if (!editable) { + return; + } + QMenu menu; + + QAction* selectPicture = new QAction(tr("Select picture ..."), this); + menu.addAction(selectPicture); + + QAction* clearPicture = new QAction(tr("Clear picture"), this); + menu.addAction(clearPicture); + + QAction* result = menu.exec(event->globalPos()); + if (result == selectPicture) { + QString fileName = QFileDialog::getOpenFileName(this, tr("Select picture"), "", tr("Image Files (*.png *.jpg *.jpeg *.gif)")); + if (!fileName.isEmpty()) { + ByteArray data; + readByteArrayFromFile(data, stringToPath(Q2PSTRING(fileName))); + + QBuffer buffer; + buffer.setData(reinterpret_cast(vecptr(data)), data.size()); + buffer.open(QIODevice::ReadOnly); + QString type = QImageReader::imageFormat(&buffer).toLower(); + if (!type.isEmpty()) { + type = "image/" + type; + setAvatar(data, Q2PSTRING(type)); + } + else { + QMessageBox::critical(this, tr("Error"), tr("The selected picture is in an unrecognized format")); + } + } + } + else if (result == clearPicture) { + setAvatar(ByteArray(), ""); + } } diff --git a/Swift/QtUI/QtAvatarWidget.h b/Swift/QtUI/QtAvatarWidget.h index bcdc7be..612c79b 100644 --- a/Swift/QtUI/QtAvatarWidget.h +++ b/Swift/QtUI/QtAvatarWidget.h @@ -14,36 +14,36 @@ class QLabel; namespace Swift { - class QtAvatarWidget : public QWidget { - Q_OBJECT - Q_PROPERTY(bool editable READ isEditable WRITE setEditable) - public: - QtAvatarWidget(QWidget* parent); - - void setAvatar(const ByteArray& data, const std::string& type); - - const ByteArray& getAvatarData() const { - return data; - } - - const std::string& getAvatarType() const { - return type; - } - - void setEditable(bool b) { - editable = b; - } - - bool isEditable() const { - return editable; - } - - void mousePressEvent(QMouseEvent* event); - - private: - bool editable; - ByteArray data; - std::string type; - QLabel* label; - }; + class QtAvatarWidget : public QWidget { + Q_OBJECT + Q_PROPERTY(bool editable READ isEditable WRITE setEditable) + public: + QtAvatarWidget(QWidget* parent); + + void setAvatar(const ByteArray& data, const std::string& type); + + const ByteArray& getAvatarData() const { + return data; + } + + const std::string& getAvatarType() const { + return type; + } + + void setEditable(bool b) { + editable = b; + } + + bool isEditable() const { + return editable; + } + + void mousePressEvent(QMouseEvent* event); + + private: + bool editable; + ByteArray data; + std::string type; + QLabel* label; + }; } diff --git a/Swift/QtUI/QtBlockListEditorWindow.cpp b/Swift/QtUI/QtBlockListEditorWindow.cpp index 98c9e98..5b04b49 100644 --- a/Swift/QtUI/QtBlockListEditorWindow.cpp +++ b/Swift/QtUI/QtBlockListEditorWindow.cpp @@ -31,197 +31,197 @@ namespace Swift { class QtJIDValidator : public QValidator { - public: - QtJIDValidator(QObject* parent) : QValidator(parent) {} - virtual ~QtJIDValidator() {} - virtual QValidator::State validate(QString& input, int&) const { - return JID(Q2PSTRING(input)).isValid() ? Acceptable : Intermediate; - } + public: + QtJIDValidator(QObject* parent) : QValidator(parent) {} + virtual ~QtJIDValidator() {} + virtual QValidator::State validate(QString& input, int&) const { + return JID(Q2PSTRING(input)).isValid() ? Acceptable : Intermediate; + } }; class QtJIDValidatedItemDelegate : public QItemDelegate { - public: - QtJIDValidatedItemDelegate(QObject* parent) : QItemDelegate(parent) {} - virtual ~QtJIDValidatedItemDelegate() {} - - virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const { - QLineEdit *editor = new QLineEdit(parent); - editor->setValidator(new QtJIDValidator(editor)); - return editor; - } - - void setEditorData(QWidget *editor, const QModelIndex &index) const { - QString value = index.model()->data(index, Qt::EditRole).toString(); - - QLineEdit *lineEdit = static_cast(editor); - lineEdit->setText(value); - } - - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { - QLineEdit *lineEdit = static_cast(editor); - QString currentValue = lineEdit->text(); - int pos = 0; - if (lineEdit->validator()->validate(currentValue, pos) == QValidator::Acceptable) { - model->setData(index, lineEdit->text(), Qt::EditRole); - } else { - model->setData(index, QString(), Qt::EditRole); - } - } - - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { - editor->setGeometry(option.rect); - } + public: + QtJIDValidatedItemDelegate(QObject* parent) : QItemDelegate(parent) {} + virtual ~QtJIDValidatedItemDelegate() {} + + virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex&) const { + QLineEdit *editor = new QLineEdit(parent); + editor->setValidator(new QtJIDValidator(editor)); + return editor; + } + + void setEditorData(QWidget *editor, const QModelIndex &index) const { + QString value = index.model()->data(index, Qt::EditRole).toString(); + + QLineEdit *lineEdit = static_cast(editor); + lineEdit->setText(value); + } + + void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { + QLineEdit *lineEdit = static_cast(editor); + QString currentValue = lineEdit->text(); + int pos = 0; + if (lineEdit->validator()->validate(currentValue, pos) == QValidator::Acceptable) { + model->setData(index, lineEdit->text(), Qt::EditRole); + } else { + model->setData(index, QString(), Qt::EditRole); + } + } + + void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const { + editor->setGeometry(option.rect); + } }; QtBlockListEditorWindow::QtBlockListEditorWindow() : QWidget(), ui(new Ui::QtBlockListEditorWindow), removeItemDelegate(0), editItemDelegate(0) { - ui->setupUi(this); + ui->setupUi(this); - freshBlockListTemplate = tr("Double-click to add contact"); + freshBlockListTemplate = tr("Double-click to add contact"); - new QShortcut(QKeySequence::Close, this, SLOT(close())); - ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this)); + new QShortcut(QKeySequence::Close, this, SLOT(close())); + ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this)); - removeItemDelegate = new QtRemovableItemDelegate(style()); - editItemDelegate = new QtJIDValidatedItemDelegate(this); + removeItemDelegate = new QtRemovableItemDelegate(style()); + editItemDelegate = new QtJIDValidatedItemDelegate(this); - connect(ui->savePushButton, SIGNAL(clicked()), SLOT(applyChanges())); + connect(ui->savePushButton, SIGNAL(clicked()), SLOT(applyChanges())); - ui->blockListTreeWidget->setColumnCount(2); - ui->blockListTreeWidget->header()->setStretchLastSection(false); - ui->blockListTreeWidget->header()->resizeSection(1, removeItemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width()); + ui->blockListTreeWidget->setColumnCount(2); + ui->blockListTreeWidget->header()->setStretchLastSection(false); + ui->blockListTreeWidget->header()->resizeSection(1, removeItemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width()); #if QT_VERSION >= 0x050000 - ui->blockListTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch); + ui->blockListTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch); #else - ui->blockListTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch); + ui->blockListTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch); #endif - ui->blockListTreeWidget->setHeaderHidden(true); - ui->blockListTreeWidget->setRootIsDecorated(false); - ui->blockListTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed); - ui->blockListTreeWidget->setItemDelegateForColumn(0, editItemDelegate); - ui->blockListTreeWidget->setItemDelegateForColumn(1, removeItemDelegate); - connect(ui->blockListTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int))); - ui->blockListTreeWidget->installEventFilter(this); - - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x"); - item->setFlags(item->flags() | Qt::ItemIsEditable); - ui->blockListTreeWidget->addTopLevelItem(item); + ui->blockListTreeWidget->setHeaderHidden(true); + ui->blockListTreeWidget->setRootIsDecorated(false); + ui->blockListTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed); + ui->blockListTreeWidget->setItemDelegateForColumn(0, editItemDelegate); + ui->blockListTreeWidget->setItemDelegateForColumn(1, removeItemDelegate); + connect(ui->blockListTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int))); + ui->blockListTreeWidget->installEventFilter(this); + + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x"); + item->setFlags(item->flags() | Qt::ItemIsEditable); + ui->blockListTreeWidget->addTopLevelItem(item); } QtBlockListEditorWindow::~QtBlockListEditorWindow() { } void QtBlockListEditorWindow::show() { - QWidget::showNormal(); - QWidget::activateWindow(); - QWidget::raise(); + QWidget::showNormal(); + QWidget::activateWindow(); + QWidget::raise(); } void QtBlockListEditorWindow::hide() { - QWidget::hide(); + QWidget::hide(); } void QtBlockListEditorWindow::handleItemChanged(QTreeWidgetItem *item, int) { - // check whether changed item contains a valid JID and make it removable - if (item && item->text(0) != freshBlockListTemplate) { - item->setText(1, ""); - } - - // check for empty rows and add an empty one so the user can add items - bool hasEmptyRow = false; - for( int i = 0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i ) { - QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i); - if (row->text(0) == freshBlockListTemplate) { - hasEmptyRow = true; - } - else if (row->text(0).isEmpty()) { - ui->blockListTreeWidget->removeItemWidget(row, 0); - } - } - - if (!hasEmptyRow) { - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x"); - item->setFlags(item->flags() | Qt::ItemIsEditable); - ui->blockListTreeWidget->addTopLevelItem(item); - } - - if (!item) { - ui->blockListTreeWidget->setCurrentItem(ui->blockListTreeWidget->topLevelItem(0)); - } + // check whether changed item contains a valid JID and make it removable + if (item && item->text(0) != freshBlockListTemplate) { + item->setText(1, ""); + } + + // check for empty rows and add an empty one so the user can add items + bool hasEmptyRow = false; + for( int i = 0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i ) { + QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i); + if (row->text(0) == freshBlockListTemplate) { + hasEmptyRow = true; + } + else if (row->text(0).isEmpty()) { + ui->blockListTreeWidget->removeItemWidget(row, 0); + } + } + + if (!hasEmptyRow) { + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(freshBlockListTemplate) << "x"); + item->setFlags(item->flags() | Qt::ItemIsEditable); + ui->blockListTreeWidget->addTopLevelItem(item); + } + + if (!item) { + ui->blockListTreeWidget->setCurrentItem(ui->blockListTreeWidget->topLevelItem(0)); + } } void QtBlockListEditorWindow::applyChanges() { - onSetNewBlockList(getCurrentBlockList()); + onSetNewBlockList(getCurrentBlockList()); } void QtBlockListEditorWindow::setCurrentBlockList(const std::vector &blockedJIDs) { - ui->blockListTreeWidget->clear(); - - foreach(const JID& jid, blockedJIDs) { - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << ""); - item->setFlags(item->flags() | Qt::ItemIsEditable); - ui->blockListTreeWidget->addTopLevelItem(item); - } - handleItemChanged(0,0); + ui->blockListTreeWidget->clear(); + + foreach(const JID& jid, blockedJIDs) { + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(jid.toString())) << ""); + item->setFlags(item->flags() | Qt::ItemIsEditable); + ui->blockListTreeWidget->addTopLevelItem(item); + } + handleItemChanged(0,0); } void QtBlockListEditorWindow::setBusy(bool isBusy) { - if (isBusy) { - ui->throbberLabel->movie()->start(); - ui->throbberLabel->show(); - ui->blockListTreeWidget->setEnabled(false); - ui->savePushButton->setEnabled(false); - } else { - ui->throbberLabel->movie()->stop(); - ui->throbberLabel->hide(); - ui->blockListTreeWidget->setEnabled(true); - ui->savePushButton->setEnabled(true); - } + if (isBusy) { + ui->throbberLabel->movie()->start(); + ui->throbberLabel->show(); + ui->blockListTreeWidget->setEnabled(false); + ui->savePushButton->setEnabled(false); + } else { + ui->throbberLabel->movie()->stop(); + ui->throbberLabel->hide(); + ui->blockListTreeWidget->setEnabled(true); + ui->savePushButton->setEnabled(true); + } } void QtBlockListEditorWindow::setError(const std::string& error) { - if (!error.empty()) { - ui->errorLabel->setText("" + QtUtilities::htmlEscape(P2QSTRING(error)) + ""); - } - else { - ui->errorLabel->setText(""); - } + if (!error.empty()) { + ui->errorLabel->setText("" + QtUtilities::htmlEscape(P2QSTRING(error)) + ""); + } + else { + ui->errorLabel->setText(""); + } } std::vector Swift::QtBlockListEditorWindow::getCurrentBlockList() const { - std::vector futureBlockedJIDs; - - for(int i=0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i) { - QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i); - JID jid = JID(Q2PSTRING(row->text(0))); - if (!jid.toString().empty() && jid.isValid()) { - futureBlockedJIDs.push_back(jid); - } - } - return futureBlockedJIDs; + std::vector futureBlockedJIDs; + + for(int i=0; i < ui->blockListTreeWidget->topLevelItemCount(); ++i) { + QTreeWidgetItem* row = ui->blockListTreeWidget->topLevelItem(i); + JID jid = JID(Q2PSTRING(row->text(0))); + if (!jid.toString().empty() && jid.isValid()) { + futureBlockedJIDs.push_back(jid); + } + } + return futureBlockedJIDs; } bool QtBlockListEditorWindow::eventFilter(QObject* target, QEvent* event) { - if (target == ui->blockListTreeWidget) { - if (event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); - if (keyEvent->key() == Qt::Key_Backspace) { - // remove currently selected item - QTreeWidgetItem* currentItem = ui->blockListTreeWidget->currentItem(); - if (currentItem->text(0) != freshBlockListTemplate) { - ui->blockListTreeWidget->takeTopLevelItem(ui->blockListTreeWidget->indexOfTopLevelItem(currentItem)); - return true; - } - } - else if (keyEvent->key() == Qt::Key_Return) { - // open editor for return key d - ui->blockListTreeWidget->editItem(ui->blockListTreeWidget->currentItem(), 0); - return true; - } - } - } - return QWidget::eventFilter(target, event); + if (target == ui->blockListTreeWidget) { + if (event->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = static_cast(event); + if (keyEvent->key() == Qt::Key_Backspace) { + // remove currently selected item + QTreeWidgetItem* currentItem = ui->blockListTreeWidget->currentItem(); + if (currentItem->text(0) != freshBlockListTemplate) { + ui->blockListTreeWidget->takeTopLevelItem(ui->blockListTreeWidget->indexOfTopLevelItem(currentItem)); + return true; + } + } + else if (keyEvent->key() == Qt::Key_Return) { + // open editor for return key d + ui->blockListTreeWidget->editItem(ui->blockListTreeWidget->currentItem(), 0); + return true; + } + } + } + return QWidget::eventFilter(target, event); } } diff --git a/Swift/QtUI/QtBlockListEditorWindow.h b/Swift/QtUI/QtBlockListEditorWindow.h index a594210..dc900ab 100644 --- a/Swift/QtUI/QtBlockListEditorWindow.h +++ b/Swift/QtUI/QtBlockListEditorWindow.h @@ -20,7 +20,7 @@ #include namespace Ui { - class QtBlockListEditorWindow; + class QtBlockListEditorWindow; } namespace Swift { @@ -28,29 +28,29 @@ namespace Swift { class QtJIDValidatedItemDelegate; class QtBlockListEditorWindow : public QWidget, public BlockListEditorWidget { - Q_OBJECT - - public: - QtBlockListEditorWindow(); - virtual ~QtBlockListEditorWindow(); - - virtual void show(); - virtual void hide(); - virtual void setCurrentBlockList(const std::vector& blockedJIDs); - virtual void setBusy(bool isBusy); - virtual void setError(const std::string& error); - virtual std::vector getCurrentBlockList() const; - virtual bool eventFilter(QObject* target, QEvent* event); - - private slots: - void handleItemChanged(QTreeWidgetItem*, int); - void applyChanges(); - - private: - Ui::QtBlockListEditorWindow* ui; - QtRemovableItemDelegate* removeItemDelegate; - QtJIDValidatedItemDelegate* editItemDelegate; - QString freshBlockListTemplate; + Q_OBJECT + + public: + QtBlockListEditorWindow(); + virtual ~QtBlockListEditorWindow(); + + virtual void show(); + virtual void hide(); + virtual void setCurrentBlockList(const std::vector& blockedJIDs); + virtual void setBusy(bool isBusy); + virtual void setError(const std::string& error); + virtual std::vector getCurrentBlockList() const; + virtual bool eventFilter(QObject* target, QEvent* event); + + private slots: + void handleItemChanged(QTreeWidgetItem*, int); + void applyChanges(); + + private: + Ui::QtBlockListEditorWindow* ui; + QtRemovableItemDelegate* removeItemDelegate; + QtJIDValidatedItemDelegate* editItemDelegate; + QString freshBlockListTemplate; }; } diff --git a/Swift/QtUI/QtBookmarkDetailWindow.cpp b/Swift/QtUI/QtBookmarkDetailWindow.cpp index ea5b217..920e94e 100644 --- a/Swift/QtUI/QtBookmarkDetailWindow.cpp +++ b/Swift/QtUI/QtBookmarkDetailWindow.cpp @@ -13,67 +13,67 @@ namespace Swift { QtBookmarkDetailWindow::QtBookmarkDetailWindow(QWidget* parent) : QDialog(parent) { - setupUi(this); - setAttribute(Qt::WA_DeleteOnClose, true); - //connect(buttons_, SIGNAL(accepted()), SLOT(accept())); - //connect(buttons_, SIGNAL(rejected()), SLOT(reject())); - setFixedHeight(sizeHint().height()); + setupUi(this); + setAttribute(Qt::WA_DeleteOnClose, true); + //connect(buttons_, SIGNAL(accepted()), SLOT(accept())); + //connect(buttons_, SIGNAL(rejected()), SLOT(reject())); + setFixedHeight(sizeHint().height()); } void QtBookmarkDetailWindow::accept() { - if (commit()) { - QDialog::accept(); - } + if (commit()) { + QDialog::accept(); + } } boost::optional QtBookmarkDetailWindow::createBookmarkFromForm() { - //check room - //check bookmarkName - JID room(Q2PSTRING(room_->text())); - if (!room.isValid() || room.getNode().empty() || !room.getResource().empty()) { - QMessageBox::warning(this, tr("Bookmark not valid"), tr("You must specify a valid room address (e.g. someroom@rooms.example.com).")); - return boost::optional(); - } - std::string name(Q2PSTRING(name_->text())); - if (name.empty()) { - name = room.toString(); - } + //check room + //check bookmarkName + JID room(Q2PSTRING(room_->text())); + if (!room.isValid() || room.getNode().empty() || !room.getResource().empty()) { + QMessageBox::warning(this, tr("Bookmark not valid"), tr("You must specify a valid room address (e.g. someroom@rooms.example.com).")); + return boost::optional(); + } + std::string name(Q2PSTRING(name_->text())); + if (name.empty()) { + name = room.toString(); + } - MUCBookmark bookmark(room, name); - std::string nick(Q2PSTRING(nick_->text())); - std::string password(Q2PSTRING(password_->text())); - bookmark.setAutojoin(autojoin_->isChecked()); - if (!nick.empty()) { - bookmark.setNick(nick); - } - if (!password.empty()) { - bookmark.setPassword(password); - } - return bookmark; + MUCBookmark bookmark(room, name); + std::string nick(Q2PSTRING(nick_->text())); + std::string password(Q2PSTRING(password_->text())); + bookmark.setAutojoin(autojoin_->isChecked()); + if (!nick.empty()) { + bookmark.setNick(nick); + } + if (!password.empty()) { + bookmark.setPassword(password); + } + return bookmark; } void QtBookmarkDetailWindow::createFormFromBookmark(const MUCBookmark& bookmark) { - if (bookmark.getRoom().isValid()) { - room_->setText(P2QSTRING(bookmark.getRoom().toString())); - } + if (bookmark.getRoom().isValid()) { + room_->setText(P2QSTRING(bookmark.getRoom().toString())); + } - if (!bookmark.getName().empty()) { - name_->setText(P2QSTRING(bookmark.getName())); - } + if (!bookmark.getName().empty()) { + name_->setText(P2QSTRING(bookmark.getName())); + } - if (bookmark.getNick()) { - nick_->setText(P2QSTRING((*bookmark.getNick()))); - } + if (bookmark.getNick()) { + nick_->setText(P2QSTRING((*bookmark.getNick()))); + } - if (bookmark.getPassword()) { - password_->setText(P2QSTRING((*bookmark.getPassword()))); - } + if (bookmark.getPassword()) { + password_->setText(P2QSTRING((*bookmark.getPassword()))); + } - if (bookmark.getAutojoin()) { - autojoin_->setCheckState(Qt::Checked); - } else { - autojoin_->setCheckState(Qt::Unchecked); - } + if (bookmark.getAutojoin()) { + autojoin_->setCheckState(Qt::Checked); + } else { + autojoin_->setCheckState(Qt::Unchecked); + } } } diff --git a/Swift/QtUI/QtBookmarkDetailWindow.h b/Swift/QtUI/QtBookmarkDetailWindow.h index 427614a..19c6462 100644 --- a/Swift/QtUI/QtBookmarkDetailWindow.h +++ b/Swift/QtUI/QtBookmarkDetailWindow.h @@ -15,18 +15,18 @@ #include namespace Swift { - class QtBookmarkDetailWindow : public QDialog, protected Ui::QtBookmarkDetailWindow { - Q_OBJECT - public: - QtBookmarkDetailWindow(QWidget* parent = NULL); - virtual bool commit() = 0; - boost::optional createBookmarkFromForm(); - - protected: - void createFormFromBookmark(const MUCBookmark& bookmark); - - public slots: - void accept(); - }; + class QtBookmarkDetailWindow : public QDialog, protected Ui::QtBookmarkDetailWindow { + Q_OBJECT + public: + QtBookmarkDetailWindow(QWidget* parent = NULL); + virtual bool commit() = 0; + boost::optional createBookmarkFromForm(); + + protected: + void createFormFromBookmark(const MUCBookmark& bookmark); + + public slots: + void accept(); + }; } diff --git a/Swift/QtUI/QtCachedImageScaler.cpp b/Swift/QtUI/QtCachedImageScaler.cpp index 0e10062..e1f540b 100644 --- a/Swift/QtUI/QtCachedImageScaler.cpp +++ b/Swift/QtUI/QtCachedImageScaler.cpp @@ -20,25 +20,25 @@ QtCachedImageScaler::QtCachedImageScaler() { } boost::filesystem::path QtCachedImageScaler::getScaledImage(const boost::filesystem::path& imagePath, int size) { - boost::filesystem::path scaledImagePath(imagePath); - std::string suffix = "." + boost::lexical_cast(size); - scaledImagePath = stringToPath(pathToString(scaledImagePath) + suffix); - if (!boost::filesystem::exists(scaledImagePath)) { - QImage image(P2QSTRING(pathToString(imagePath))); - if (!image.isNull()) { - if (image.width() > size || image.height() > size) { - QImage scaledImage = image.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation); - scaledImage.save(P2QSTRING(pathToString(scaledImagePath)), "PNG"); - } - else { - image.save(P2QSTRING(pathToString(scaledImagePath)), "PNG"); - } - } - else { - return imagePath; - } - } - return scaledImagePath; + boost::filesystem::path scaledImagePath(imagePath); + std::string suffix = "." + boost::lexical_cast(size); + scaledImagePath = stringToPath(pathToString(scaledImagePath) + suffix); + if (!boost::filesystem::exists(scaledImagePath)) { + QImage image(P2QSTRING(pathToString(imagePath))); + if (!image.isNull()) { + if (image.width() > size || image.height() > size) { + QImage scaledImage = image.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation); + scaledImage.save(P2QSTRING(pathToString(scaledImagePath)), "PNG"); + } + else { + image.save(P2QSTRING(pathToString(scaledImagePath)), "PNG"); + } + } + else { + return imagePath; + } + } + return scaledImagePath; } diff --git a/Swift/QtUI/QtCachedImageScaler.h b/Swift/QtUI/QtCachedImageScaler.h index fcc2a2d..15d868e 100644 --- a/Swift/QtUI/QtCachedImageScaler.h +++ b/Swift/QtUI/QtCachedImageScaler.h @@ -9,11 +9,11 @@ #include namespace Swift { - class QtCachedImageScaler { - public: - QtCachedImageScaler(); + class QtCachedImageScaler { + public: + QtCachedImageScaler(); - boost::filesystem::path getScaledImage(const boost::filesystem::path& image, int size); - }; + boost::filesystem::path getScaledImage(const boost::filesystem::path& image, int size); + }; } diff --git a/Swift/QtUI/QtCertificateViewerDialog.cpp b/Swift/QtUI/QtCertificateViewerDialog.cpp index 4b8b0cb..a99c29a 100644 --- a/Swift/QtUI/QtCertificateViewerDialog.cpp +++ b/Swift/QtUI/QtCertificateViewerDialog.cpp @@ -25,126 +25,126 @@ namespace Swift { QtCertificateViewerDialog::QtCertificateViewerDialog(QWidget* parent) : QDialog(parent), ui(new Ui::QtCertificateViewerDialog) { - ui->setupUi(this); - connect(ui->certChainTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*))); + ui->setupUi(this); + connect(ui->certChainTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*))); - setAttribute(Qt::WA_DeleteOnClose); + setAttribute(Qt::WA_DeleteOnClose); } QtCertificateViewerDialog::~QtCertificateViewerDialog() { - delete ui; + delete ui; } void QtCertificateViewerDialog::setCertificateChain(const std::vector& chain) { - // clean widgets - ui->certChainTreeWidget->clear(); - - if (chain.empty()) return; - - // convert Swift certificate chain to qt certificate chain (root goes first) - currentChain.clear(); - foreach(Certificate::ref cert, chain) { - ByteArray certAsDer = cert->toDER(); - QByteArray dataArray(reinterpret_cast(certAsDer.data()), certAsDer.size()); - currentChain.push_front(QSslCertificate(dataArray, QSsl::Der)); - } - - // fill treeWidget - QTreeWidgetItem* root = new QTreeWidgetItem(ui->certChainTreeWidget, QStringList(currentChain.at(0).subjectInfo(QSslCertificate::CommonName))); - root->setData(0, Qt::UserRole, QVariant(0)); - root->setExpanded(true); - ui->certChainTreeWidget->addTopLevelItem(root); - if (currentChain.size() > 1) { - QTreeWidgetItem* parent = root; - for (int n = 1; n < currentChain.size(); n++) { - QTreeWidgetItem* link = new QTreeWidgetItem(parent, QStringList(QString("↳ ") + (QStringList(currentChain.at(n).subjectInfo(QSslCertificate::CommonName)).join(", ")))); - link->setExpanded(true); - link->setData(0, Qt::UserRole, QVariant(n)); - parent = link; - } - ui->certChainTreeWidget->setCurrentItem(parent); - } else { - ui->certChainTreeWidget->setCurrentItem(root); - } + // clean widgets + ui->certChainTreeWidget->clear(); + + if (chain.empty()) return; + + // convert Swift certificate chain to qt certificate chain (root goes first) + currentChain.clear(); + foreach(Certificate::ref cert, chain) { + ByteArray certAsDer = cert->toDER(); + QByteArray dataArray(reinterpret_cast(certAsDer.data()), certAsDer.size()); + currentChain.push_front(QSslCertificate(dataArray, QSsl::Der)); + } + + // fill treeWidget + QTreeWidgetItem* root = new QTreeWidgetItem(ui->certChainTreeWidget, QStringList(currentChain.at(0).subjectInfo(QSslCertificate::CommonName))); + root->setData(0, Qt::UserRole, QVariant(0)); + root->setExpanded(true); + ui->certChainTreeWidget->addTopLevelItem(root); + if (currentChain.size() > 1) { + QTreeWidgetItem* parent = root; + for (int n = 1; n < currentChain.size(); n++) { + QTreeWidgetItem* link = new QTreeWidgetItem(parent, QStringList(QString("↳ ") + (QStringList(currentChain.at(n).subjectInfo(QSslCertificate::CommonName)).join(", ")))); + link->setExpanded(true); + link->setData(0, Qt::UserRole, QVariant(n)); + parent = link; + } + ui->certChainTreeWidget->setCurrentItem(parent); + } else { + ui->certChainTreeWidget->setCurrentItem(root); + } } void QtCertificateViewerDialog::displayCertificateChainAsSheet(QWidget* parent, const std::vector& chain) { - QtCertificateViewerDialog* dialog = new QtCertificateViewerDialog(parent); - dialog->setCertificateChain(chain); - dialog->show(); + QtCertificateViewerDialog* dialog = new QtCertificateViewerDialog(parent); + dialog->setCertificateChain(chain); + dialog->show(); } void QtCertificateViewerDialog::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem*) { - setCertificateDetails(currentChain.at(current->data(0, Qt::UserRole).toInt())); + setCertificateDetails(currentChain.at(current->data(0, Qt::UserRole).toInt())); } #define ADD_SECTION( TITLE ) \ - ui->certGridLayout->addWidget(new QLabel("" + TITLE + ""), rowCount++, 0, 1, 2); + ui->certGridLayout->addWidget(new QLabel("" + TITLE + ""), rowCount++, 0, 1, 2); #define ADD_FIELD( TITLE, VALUE) \ - ui->certGridLayout->addWidget(new QLabel(TITLE), rowCount, 0, 1, 1, Qt::AlignRight); \ - valueLabel = new QLabel(); \ - valueLabel->setText(QStringList(VALUE).join(", ")); \ - valueLabel->setTextFormat(Qt::PlainText); \ - valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); \ - ui->certGridLayout->addWidget(valueLabel, rowCount++, 1, 1, 1, Qt::AlignLeft); + ui->certGridLayout->addWidget(new QLabel(TITLE), rowCount, 0, 1, 1, Qt::AlignRight); \ + valueLabel = new QLabel(); \ + valueLabel->setText(QStringList(VALUE).join(", ")); \ + valueLabel->setTextFormat(Qt::PlainText); \ + valueLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); \ + ui->certGridLayout->addWidget(valueLabel, rowCount++, 1, 1, 1, Qt::AlignLeft); void QtCertificateViewerDialog::setCertificateDetails(const QSslCertificate& cert) { - QLayoutItem* item; - while ((item = ui->certGridLayout->takeAt(0)) != NULL ) { - delete item->widget(); - delete item; - } + QLayoutItem* item; + while ((item = ui->certGridLayout->takeAt(0)) != NULL ) { + delete item->widget(); + delete item; + } - int rowCount = 0; + int rowCount = 0; - ui->certGridLayout->setColumnStretch(2, 1); + ui->certGridLayout->setColumnStretch(2, 1); - QLabel* valueLabel = 0; + QLabel* valueLabel = 0; - ADD_SECTION(tr("General")); - ADD_FIELD(tr("Valid From"), cert.effectiveDate().toString(Qt::TextDate)); - ADD_FIELD(tr("Valid To"), cert.expiryDate().toString(Qt::TextDate)); - ADD_FIELD(tr("Serial Number"), QString(cert.serialNumber().toHex())); - ADD_FIELD(tr("Version"), QString(cert.version())); + ADD_SECTION(tr("General")); + ADD_FIELD(tr("Valid From"), cert.effectiveDate().toString(Qt::TextDate)); + ADD_FIELD(tr("Valid To"), cert.expiryDate().toString(Qt::TextDate)); + ADD_FIELD(tr("Serial Number"), QString(cert.serialNumber().toHex())); + ADD_FIELD(tr("Version"), QString(cert.version())); - ADD_SECTION(tr("Subject")); - ADD_FIELD(tr("Organization"), cert.subjectInfo(QSslCertificate::Organization)); - ADD_FIELD(tr("Common Name"), cert.subjectInfo(QSslCertificate::CommonName)); - ADD_FIELD(tr("Locality"), cert.subjectInfo(QSslCertificate::LocalityName)); - ADD_FIELD(tr("Organizational Unit"), cert.subjectInfo(QSslCertificate::OrganizationalUnitName)); - ADD_FIELD(tr("Country"), cert.subjectInfo(QSslCertificate::CountryName)); - ADD_FIELD(tr("State"), cert.subjectInfo(QSslCertificate::StateOrProvinceName)); + ADD_SECTION(tr("Subject")); + ADD_FIELD(tr("Organization"), cert.subjectInfo(QSslCertificate::Organization)); + ADD_FIELD(tr("Common Name"), cert.subjectInfo(QSslCertificate::CommonName)); + ADD_FIELD(tr("Locality"), cert.subjectInfo(QSslCertificate::LocalityName)); + ADD_FIELD(tr("Organizational Unit"), cert.subjectInfo(QSslCertificate::OrganizationalUnitName)); + ADD_FIELD(tr("Country"), cert.subjectInfo(QSslCertificate::CountryName)); + ADD_FIELD(tr("State"), cert.subjectInfo(QSslCertificate::StateOrProvinceName)); #if QT_VERSION < 0x050000 - QMultiMap altNames = cert.alternateSubjectNames(); + QMultiMap altNames = cert.alternateSubjectNames(); #define SANTYPE QSsl::AlternateNameEntryType #else - QMultiMap altNames = cert.subjectAlternativeNames(); + QMultiMap altNames = cert.subjectAlternativeNames(); #define SANTYPE QSsl::AlternativeNameEntryType #endif - if (!altNames.empty()) { - ADD_SECTION(tr("Alternate Subject Names")); - foreach (const SANTYPE &type, altNames.uniqueKeys()) { - foreach (QString name, altNames.values(type)) { - if (type == QSsl::EmailEntry) { - ADD_FIELD(tr("E-mail Address"), name); - } else { - ADD_FIELD(tr("DNS Name"), name); - } - } - } - } - - ADD_SECTION(tr("Issuer")); - ADD_FIELD(tr("Organization"), cert.issuerInfo(QSslCertificate::Organization)); - ADD_FIELD(tr("Common Name"), cert.issuerInfo(QSslCertificate::CommonName)); - ADD_FIELD(tr("Locality"), cert.issuerInfo(QSslCertificate::LocalityName)); - ADD_FIELD(tr("Organizational Unit"), cert.issuerInfo(QSslCertificate::OrganizationalUnitName)); - ADD_FIELD(tr("Country"), cert.issuerInfo(QSslCertificate::CountryName)); - ADD_FIELD(tr("State"), cert.issuerInfo(QSslCertificate::StateOrProvinceName)); - - ui->certGridLayout->setRowStretch(rowCount + 1, 1); + if (!altNames.empty()) { + ADD_SECTION(tr("Alternate Subject Names")); + foreach (const SANTYPE &type, altNames.uniqueKeys()) { + foreach (QString name, altNames.values(type)) { + if (type == QSsl::EmailEntry) { + ADD_FIELD(tr("E-mail Address"), name); + } else { + ADD_FIELD(tr("DNS Name"), name); + } + } + } + } + + ADD_SECTION(tr("Issuer")); + ADD_FIELD(tr("Organization"), cert.issuerInfo(QSslCertificate::Organization)); + ADD_FIELD(tr("Common Name"), cert.issuerInfo(QSslCertificate::CommonName)); + ADD_FIELD(tr("Locality"), cert.issuerInfo(QSslCertificate::LocalityName)); + ADD_FIELD(tr("Organizational Unit"), cert.issuerInfo(QSslCertificate::OrganizationalUnitName)); + ADD_FIELD(tr("Country"), cert.issuerInfo(QSslCertificate::CountryName)); + ADD_FIELD(tr("State"), cert.issuerInfo(QSslCertificate::StateOrProvinceName)); + + ui->certGridLayout->setRowStretch(rowCount + 1, 1); } } diff --git a/Swift/QtUI/QtCertificateViewerDialog.h b/Swift/QtUI/QtCertificateViewerDialog.h index 9475a83..7b72f1d 100644 --- a/Swift/QtUI/QtCertificateViewerDialog.h +++ b/Swift/QtUI/QtCertificateViewerDialog.h @@ -20,25 +20,25 @@ class QtCertificateViewerDialog; namespace Swift { class QtCertificateViewerDialog : public QDialog { - Q_OBJECT - - public: - explicit QtCertificateViewerDialog(QWidget* parent = 0); - ~QtCertificateViewerDialog(); + Q_OBJECT - void setCertificateChain(const std::vector& chain); + public: + explicit QtCertificateViewerDialog(QWidget* parent = 0); + ~QtCertificateViewerDialog(); - static void displayCertificateChainAsSheet(QWidget* parent, const std::vector& chain); + void setCertificateChain(const std::vector& chain); - private slots: - void currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*); + static void displayCertificateChainAsSheet(QWidget* parent, const std::vector& chain); - private: - void setCertificateDetails(const QSslCertificate& cert); + private slots: + void currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*); - private: - Ui::QtCertificateViewerDialog *ui; - QList currentChain; + private: + void setCertificateDetails(const QSslCertificate& cert); + + private: + Ui::QtCertificateViewerDialog *ui; + QList currentChain; }; } diff --git a/Swift/QtUI/QtChatTabs.cpp b/Swift/QtUI/QtChatTabs.cpp index f22d869..4a77ffd 100644 --- a/Swift/QtUI/QtChatTabs.cpp +++ b/Swift/QtUI/QtChatTabs.cpp @@ -35,389 +35,389 @@ namespace Swift { QtChatTabs::QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode) : QWidget(), singleWindow_(singleWindow), settingsProvider_(settingsProvider), trellisMode_(trellisMode), dynamicGrid_(NULL), gridSelectionDialog_(NULL) { #ifndef Q_OS_MAC - setWindowIcon(QIcon(":/logo-chat-16.png")); + setWindowIcon(QIcon(":/logo-chat-16.png")); #else - setAttribute(Qt::WA_ShowWithoutActivating); + setAttribute(Qt::WA_ShowWithoutActivating); #endif - dynamicGrid_ = new QtDynamicGridLayout(this, trellisMode); - connect(dynamicGrid_, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int))); - connect(dynamicGrid_, SIGNAL(onCurrentIndexChanged(int)), this, SLOT(handleCurrentTabIndexChanged(int))); - - QVBoxLayout *layout = new QVBoxLayout; - layout->setSpacing(0); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(dynamicGrid_); - setLayout(layout); - - if (trellisMode) { - // restore size - std::string gridSizeString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_SIZE); - if (!gridSizeString.empty()) { - QByteArray gridSizeData = QByteArray::fromBase64(P2QSTRING(gridSizeString).toUtf8()); - QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite); - QSize gridSize(1,1); - dataStreamGridSize >> gridSize; - dynamicGrid_->setDimensions(gridSize); - } - - // restore positions - std::string tabPositionsString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_POSITIONS); - if (!tabPositionsString.empty()) { - QByteArray tabPositionsData = QByteArray::fromBase64(P2QSTRING(tabPositionsString).toUtf8()); - QDataStream inTabPositions(&tabPositionsData, QIODevice::ReadWrite); - QHash tabPositions; - inTabPositions >> tabPositions; - dynamicGrid_->setTabPositions(tabPositions); - } - } - - gridSelectionDialog_ = new QtGridSelectionDialog(); - - // setup shortcuts - shortcuts_ << new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), window(), SLOT(handleCloseTabShortcut())); - shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), window(), SLOT(handleRequestedPreviousTab())); - shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), window(), SLOT(handleRequestedNextTab())); - shortcuts_ << new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), window(), SLOT(handleRequestedActiveTab())); + dynamicGrid_ = new QtDynamicGridLayout(this, trellisMode); + connect(dynamicGrid_, SIGNAL(tabCloseRequested(int)), this, SLOT(handleTabCloseRequested(int))); + connect(dynamicGrid_, SIGNAL(onCurrentIndexChanged(int)), this, SLOT(handleCurrentTabIndexChanged(int))); + + QVBoxLayout *layout = new QVBoxLayout; + layout->setSpacing(0); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(dynamicGrid_); + setLayout(layout); + + if (trellisMode) { + // restore size + std::string gridSizeString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_SIZE); + if (!gridSizeString.empty()) { + QByteArray gridSizeData = QByteArray::fromBase64(P2QSTRING(gridSizeString).toUtf8()); + QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite); + QSize gridSize(1,1); + dataStreamGridSize >> gridSize; + dynamicGrid_->setDimensions(gridSize); + } + + // restore positions + std::string tabPositionsString = settingsProvider->getSetting(SettingConstants::TRELLIS_GRID_POSITIONS); + if (!tabPositionsString.empty()) { + QByteArray tabPositionsData = QByteArray::fromBase64(P2QSTRING(tabPositionsString).toUtf8()); + QDataStream inTabPositions(&tabPositionsData, QIODevice::ReadWrite); + QHash tabPositions; + inTabPositions >> tabPositions; + dynamicGrid_->setTabPositions(tabPositions); + } + } + + gridSelectionDialog_ = new QtGridSelectionDialog(); + + // setup shortcuts + shortcuts_ << new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), window(), SLOT(handleCloseTabShortcut())); + shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), window(), SLOT(handleRequestedPreviousTab())); + shortcuts_ << new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), window(), SLOT(handleRequestedNextTab())); + shortcuts_ << new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), window(), SLOT(handleRequestedActiveTab())); } QtChatTabs::~QtChatTabs() { - foreach (QShortcut* shortcut, shortcuts_) { - delete shortcut; - } - - if (trellisMode_) { - storeTabPositions(); - } - delete gridSelectionDialog_; + foreach (QShortcut* shortcut, shortcuts_) { + delete shortcut; + } + + if (trellisMode_) { + storeTabPositions(); + } + delete gridSelectionDialog_; } void QtChatTabs::closeEvent(QCloseEvent* event) { - //Hide first to prevent flickering as each tab is removed. - hide(); - if (trellisMode_) { - storeTabPositions(); - } - - for (int i = dynamicGrid_->count() - 1; i >= 0; i--) { - dynamicGrid_->widget(i)->close(); - } - event->accept(); + //Hide first to prevent flickering as each tab is removed. + hide(); + if (trellisMode_) { + storeTabPositions(); + } + + for (int i = dynamicGrid_->count() - 1; i >= 0; i--) { + dynamicGrid_->widget(i)->close(); + } + event->accept(); } QtTabbable* QtChatTabs::getCurrentTab() { - return qobject_cast(dynamicGrid_->currentWidget()); + return qobject_cast(dynamicGrid_->currentWidget()); } void QtChatTabs::setViewMenu(QMenu* viewMenu) { - if (trellisMode_) { - viewMenu->addSeparator(); - QAction* action = new QAction(tr("Change &layout"), this); - action->setShortcutContext(Qt::ApplicationShortcut); - action->setShortcut(QKeySequence(tr("Ctrl+Alt+L"))); - connect(action, SIGNAL(triggered()), this, SLOT(handleOpenLayoutChangeDialog())); - viewMenu->addAction(action); - - action = new QAction(tr("Move Tab right"), this); - action->setShortcutContext(Qt::ApplicationShortcut); - action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgDown"))); - connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabRight())); - viewMenu->addAction(action); - - action = new QAction(tr("Move Tab left"), this); - action->setShortcutContext(Qt::ApplicationShortcut); - action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgUp"))); - connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabLeft())); - viewMenu->addAction(action); - - action = new QAction(tr("Move Tab to next group"), this); - action->setShortcutContext(Qt::ApplicationShortcut); - action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgDown"))); - connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToNextGroup())); - viewMenu->addAction(action); - - action = new QAction(tr("Move Tab to previous group"), this); - action->setShortcutContext(Qt::ApplicationShortcut); - action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgUp"))); - connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToPreviousGroup())); - viewMenu->addAction(action); - } + if (trellisMode_) { + viewMenu->addSeparator(); + QAction* action = new QAction(tr("Change &layout"), this); + action->setShortcutContext(Qt::ApplicationShortcut); + action->setShortcut(QKeySequence(tr("Ctrl+Alt+L"))); + connect(action, SIGNAL(triggered()), this, SLOT(handleOpenLayoutChangeDialog())); + viewMenu->addAction(action); + + action = new QAction(tr("Move Tab right"), this); + action->setShortcutContext(Qt::ApplicationShortcut); + action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgDown"))); + connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabRight())); + viewMenu->addAction(action); + + action = new QAction(tr("Move Tab left"), this); + action->setShortcutContext(Qt::ApplicationShortcut); + action->setShortcut(QKeySequence(tr("Ctrl+Shift+PgUp"))); + connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabLeft())); + viewMenu->addAction(action); + + action = new QAction(tr("Move Tab to next group"), this); + action->setShortcutContext(Qt::ApplicationShortcut); + action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgDown"))); + connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToNextGroup())); + viewMenu->addAction(action); + + action = new QAction(tr("Move Tab to previous group"), this); + action->setShortcutContext(Qt::ApplicationShortcut); + action->setShortcut(QKeySequence(tr("Ctrl+Alt+PgUp"))); + connect(action, SIGNAL(triggered()), dynamicGrid_, SLOT(moveCurrentTabToPreviousGroup())); + viewMenu->addAction(action); + } } void QtChatTabs::addTab(QtTabbable* tab) { - QSizePolicy policy = sizePolicy(); - /* Chat windows like to grow - don't let them */ - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - dynamicGrid_->addTab(tab, tab->windowTitle()); - connect(tab, SIGNAL(titleUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection); - connect(tab, SIGNAL(countUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection); - connect(tab, SIGNAL(windowClosing()), this, SLOT(handleTabClosing()), Qt::UniqueConnection); - connect(tab, SIGNAL(windowOpening()), this, SLOT(handleWidgetShown()), Qt::UniqueConnection); - connect(tab, SIGNAL(wantsToActivate()), this, SLOT(handleWantsToActivate()), Qt::UniqueConnection); - connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection); - connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection); - connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection); - connect(tab, SIGNAL(requestFlash()), this, SLOT(flash()), Qt::UniqueConnection); - setSizePolicy(policy); + QSizePolicy policy = sizePolicy(); + /* Chat windows like to grow - don't let them */ + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + dynamicGrid_->addTab(tab, tab->windowTitle()); + connect(tab, SIGNAL(titleUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection); + connect(tab, SIGNAL(countUpdated()), this, SLOT(handleTabTitleUpdated()), Qt::UniqueConnection); + connect(tab, SIGNAL(windowClosing()), this, SLOT(handleTabClosing()), Qt::UniqueConnection); + connect(tab, SIGNAL(windowOpening()), this, SLOT(handleWidgetShown()), Qt::UniqueConnection); + connect(tab, SIGNAL(wantsToActivate()), this, SLOT(handleWantsToActivate()), Qt::UniqueConnection); + connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection); + connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection); + connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection); + connect(tab, SIGNAL(requestFlash()), this, SLOT(flash()), Qt::UniqueConnection); + setSizePolicy(policy); } void QtChatTabs::handleWidgetShown() { - QtTabbable* widget = qobject_cast(sender()); - if (!widget) { - return; - } - checkForFirstShow(); - if (dynamicGrid_->indexOf(widget) >= 0) { - handleTabTitleUpdated(widget); - return; - } - widget->blockSignals(true); - addTab(widget); - widget->blockSignals(false); - show(); + QtTabbable* widget = qobject_cast(sender()); + if (!widget) { + return; + } + checkForFirstShow(); + if (dynamicGrid_->indexOf(widget) >= 0) { + handleTabTitleUpdated(widget); + return; + } + widget->blockSignals(true); + addTab(widget); + widget->blockSignals(false); + show(); } void QtChatTabs::handleCurrentTabIndexChanged(int newIndex) { - handleTabTitleUpdated(dynamicGrid_->widget(newIndex)); + handleTabTitleUpdated(dynamicGrid_->widget(newIndex)); } void QtChatTabs::handleWantsToActivate() { - QtTabbable* widget = qobject_cast(sender()); - Q_ASSERT(widget); - //Un-minimize and bring to front. - setWindowState(windowState() & ~Qt::WindowMinimized); - setWindowState(windowState() | Qt::WindowActive); - show(); - widget->show(); - dynamicGrid_->setCurrentWidget(widget); - handleTabTitleUpdated(widget); - widget->setFocus(); - raise(); - activateWindow(); + QtTabbable* widget = qobject_cast(sender()); + Q_ASSERT(widget); + //Un-minimize and bring to front. + setWindowState(windowState() & ~Qt::WindowMinimized); + setWindowState(windowState() | Qt::WindowActive); + show(); + widget->show(); + dynamicGrid_->setCurrentWidget(widget); + handleTabTitleUpdated(widget); + widget->setFocus(); + raise(); + activateWindow(); } void QtChatTabs::handleTabClosing() { - QWidget* widget = qobject_cast(sender()); - int index; - if (widget && ((index = dynamicGrid_->indexOf(widget)) >= 0)) { - dynamicGrid_->removeTab(index); - if (dynamicGrid_->count() == 0) { - if (!singleWindow_) { - hide(); - } - else { - setWindowTitle(""); - onTitleChanged(""); - } - } - else { - handleTabTitleUpdated(dynamicGrid_->currentWidget()); - } - } + QWidget* widget = qobject_cast(sender()); + int index; + if (widget && ((index = dynamicGrid_->indexOf(widget)) >= 0)) { + dynamicGrid_->removeTab(index); + if (dynamicGrid_->count() == 0) { + if (!singleWindow_) { + hide(); + } + else { + setWindowTitle(""); + onTitleChanged(""); + } + } + else { + handleTabTitleUpdated(dynamicGrid_->currentWidget()); + } + } } void QtChatTabs::handleRequestedPreviousTab() { - int newIndex = dynamicGrid_->currentIndex() - 1; - dynamicGrid_->setCurrentIndex(newIndex >= 0 ? newIndex : dynamicGrid_->count() - 1); + int newIndex = dynamicGrid_->currentIndex() - 1; + dynamicGrid_->setCurrentIndex(newIndex >= 0 ? newIndex : dynamicGrid_->count() - 1); } void QtChatTabs::handleRequestedNextTab() { - int newIndex = dynamicGrid_->currentIndex() + 1; - dynamicGrid_->setCurrentIndex(newIndex < dynamicGrid_->count() ? newIndex : 0); + int newIndex = dynamicGrid_->currentIndex() + 1; + dynamicGrid_->setCurrentIndex(newIndex < dynamicGrid_->count() ? newIndex : 0); } void QtChatTabs::handleRequestedActiveTab() { - QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity}; - bool finished = false; - for (int j = 0; j < 2; j++) { - bool looped = false; - for (int i = dynamicGrid_->currentIndex() + 1; !finished && i != dynamicGrid_->currentIndex(); i++) { - if (i >= dynamicGrid_->count()) { - if (looped) { - break; - } - looped = true; - i = 0; - } - if (qobject_cast(dynamicGrid_->widget(i))->getWidgetAlertState() == types[j]) { - dynamicGrid_->setCurrentIndex(i); - finished = true; - break; - } - } - } + QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity}; + bool finished = false; + for (int j = 0; j < 2; j++) { + bool looped = false; + for (int i = dynamicGrid_->currentIndex() + 1; !finished && i != dynamicGrid_->currentIndex(); i++) { + if (i >= dynamicGrid_->count()) { + if (looped) { + break; + } + looped = true; + i = 0; + } + if (qobject_cast(dynamicGrid_->widget(i))->getWidgetAlertState() == types[j]) { + dynamicGrid_->setCurrentIndex(i); + finished = true; + break; + } + } + } } void QtChatTabs::handleCloseTabShortcut() { - QWidget* currentWidget = dynamicGrid_->currentWidget(); - if (currentWidget) { - currentWidget->close(); - } + QWidget* currentWidget = dynamicGrid_->currentWidget(); + if (currentWidget) { + currentWidget->close(); + } } void QtChatTabs::handleTabCloseRequested(int index) { - if (trellisMode_) { - storeTabPositions(); - } - - assert(index < dynamicGrid_->count()); - QWidget* widget = dynamicGrid_->widget(index); - assert(widget); - widget->close(); + if (trellisMode_) { + storeTabPositions(); + } + + assert(index < dynamicGrid_->count()); + QWidget* widget = dynamicGrid_->widget(index); + assert(widget); + widget->close(); } void QtChatTabs::handleTabTitleUpdated() { - QWidget* widget = qobject_cast(sender()); - handleTabTitleUpdated(widget); + QWidget* widget = qobject_cast(sender()); + handleTabTitleUpdated(widget); } void QtChatTabs::handleTabTitleUpdated(QWidget* widget) { - if (!widget) { - return; - } - QtTabbable* tabbable = qobject_cast(widget); - int index = dynamicGrid_->indexOf(widget); - if (index < 0) { - return; - } - - QString tabText = tabbable->windowTitle().simplified(); - // look for spectrum-generated and other long JID localparts, and - // try to abbreviate the resulting long tab texts - QRegExp hasTrailingGarbage("^(.[-\\w\\s,&]+)([^\\s\\,w].*)$"); - if (hasTrailingGarbage.exactMatch(tabText) && - hasTrailingGarbage.cap(1).simplified().length() >= 2 && - hasTrailingGarbage.cap(2).length() >= 7) { - // there may be some trailing garbage, and it's long - // enough to be worth removing, and we'd leave at - // least a couple of characters. - tabText = hasTrailingGarbage.cap(1).simplified(); - } - // QTabBar interprets &, so escape that - tabText.replace("&", "&&"); - // see which alt[a-z] keys other tabs use - bool accelsTaken[26]; - int i = 0; - while (i < 26) { - accelsTaken[i] = (i == 0); //A is used for 'switch to active tab' - i++; - } - - int other = dynamicGrid_->count(); - while (other >= 0) { - other--; - if (other != index) { - int tabIndex = -1; - QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(other, tabIndex); - QString t = tabWidget->tabBar()->tabText(tabIndex).toLower(); - int r = t.indexOf('&'); - if (r >= 0 && t[r+1] >= 'a' && t[r+1] <= 'z') { - accelsTaken[t[r+1].unicode()-'a'] = true; - } - } - } - // then look to see which letters in tabText may be used - i = 0; - int accelPos = -1; - while (i < tabText.length() && accelPos < 0) { - if (tabText[i] >= 'A' && tabText[i] <= 'Z' && - !accelsTaken[tabText[i].unicode()-'A']) { - accelPos = i; - } - if (tabText[i] >= 'a' && tabText[i] <= 'z' && - !accelsTaken[tabText[i].unicode()-'a']) { - accelPos = i; - } - ++i; - } - if (accelPos >= 0) { - tabText = tabText.mid(0, accelPos) + "&" + tabText.mid(accelPos); - } - // this could be improved on some european keyboards, such as - // the German one (where alt-Sz-Ligature is available) and basically - // doesn't work on Arabic/Indic keyboards (where Latin letters - // aren't available), but I don't care to deal with those. - - int tabIndex = -1; - QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(index, tabIndex); - tabWidget->setTabText(tabIndex, tabbable->getCount() > 0 ? QString("(%1) %2").arg(tabbable->getCount()).arg(tabText) : tabText); - QColor tabTextColor; - switch (tabbable->getWidgetAlertState()) { - case QtTabbable::WaitingActivity : tabTextColor = QColor(217, 20, 43); break; - case QtTabbable::ImpendingActivity : tabTextColor = QColor(27, 171, 32); break; - case QtTabbable::NoActivity : tabTextColor = QColor(); break; - } - tabWidget->tabBar()->setTabTextColor(tabIndex, tabTextColor); - - std::vector > unreads; - for (int i = 0; i < dynamicGrid_->count(); i++) { - QtTabbable* tab = qobject_cast(dynamicGrid_->widget(i)); - if (tab) { - unreads.push_back(std::pair(Q2PSTRING(tab->windowTitle()), tab->getCount())); - } - } - - std::string current(Q2PSTRING(qobject_cast(dynamicGrid_->currentWidget())->windowTitle())); - ChatMessageSummarizer summary; - QString title = summary.getSummary(current, unreads).c_str(); - setWindowTitle(title); - emit onTitleChanged(title); + if (!widget) { + return; + } + QtTabbable* tabbable = qobject_cast(widget); + int index = dynamicGrid_->indexOf(widget); + if (index < 0) { + return; + } + + QString tabText = tabbable->windowTitle().simplified(); + // look for spectrum-generated and other long JID localparts, and + // try to abbreviate the resulting long tab texts + QRegExp hasTrailingGarbage("^(.[-\\w\\s,&]+)([^\\s\\,w].*)$"); + if (hasTrailingGarbage.exactMatch(tabText) && + hasTrailingGarbage.cap(1).simplified().length() >= 2 && + hasTrailingGarbage.cap(2).length() >= 7) { + // there may be some trailing garbage, and it's long + // enough to be worth removing, and we'd leave at + // least a couple of characters. + tabText = hasTrailingGarbage.cap(1).simplified(); + } + // QTabBar interprets &, so escape that + tabText.replace("&", "&&"); + // see which alt[a-z] keys other tabs use + bool accelsTaken[26]; + int i = 0; + while (i < 26) { + accelsTaken[i] = (i == 0); //A is used for 'switch to active tab' + i++; + } + + int other = dynamicGrid_->count(); + while (other >= 0) { + other--; + if (other != index) { + int tabIndex = -1; + QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(other, tabIndex); + QString t = tabWidget->tabBar()->tabText(tabIndex).toLower(); + int r = t.indexOf('&'); + if (r >= 0 && t[r+1] >= 'a' && t[r+1] <= 'z') { + accelsTaken[t[r+1].unicode()-'a'] = true; + } + } + } + // then look to see which letters in tabText may be used + i = 0; + int accelPos = -1; + while (i < tabText.length() && accelPos < 0) { + if (tabText[i] >= 'A' && tabText[i] <= 'Z' && + !accelsTaken[tabText[i].unicode()-'A']) { + accelPos = i; + } + if (tabText[i] >= 'a' && tabText[i] <= 'z' && + !accelsTaken[tabText[i].unicode()-'a']) { + accelPos = i; + } + ++i; + } + if (accelPos >= 0) { + tabText = tabText.mid(0, accelPos) + "&" + tabText.mid(accelPos); + } + // this could be improved on some european keyboards, such as + // the German one (where alt-Sz-Ligature is available) and basically + // doesn't work on Arabic/Indic keyboards (where Latin letters + // aren't available), but I don't care to deal with those. + + int tabIndex = -1; + QtTabWidget* tabWidget = dynamicGrid_->indexToTabWidget(index, tabIndex); + tabWidget->setTabText(tabIndex, tabbable->getCount() > 0 ? QString("(%1) %2").arg(tabbable->getCount()).arg(tabText) : tabText); + QColor tabTextColor; + switch (tabbable->getWidgetAlertState()) { + case QtTabbable::WaitingActivity : tabTextColor = QColor(217, 20, 43); break; + case QtTabbable::ImpendingActivity : tabTextColor = QColor(27, 171, 32); break; + case QtTabbable::NoActivity : tabTextColor = QColor(); break; + } + tabWidget->tabBar()->setTabTextColor(tabIndex, tabTextColor); + + std::vector > unreads; + for (int i = 0; i < dynamicGrid_->count(); i++) { + QtTabbable* tab = qobject_cast(dynamicGrid_->widget(i)); + if (tab) { + unreads.push_back(std::pair(Q2PSTRING(tab->windowTitle()), tab->getCount())); + } + } + + std::string current(Q2PSTRING(qobject_cast(dynamicGrid_->currentWidget())->windowTitle())); + ChatMessageSummarizer summary; + QString title = summary.getSummary(current, unreads).c_str(); + setWindowTitle(title); + emit onTitleChanged(title); } void QtChatTabs::flash() { #ifndef SWIFTEN_PLATFORM_MACOSX - QApplication::alert(this, 0); + QApplication::alert(this, 0); #endif } void QtChatTabs::handleOpenLayoutChangeDialog() { - disconnect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize))); - gridSelectionDialog_->setCurrentGridSize(dynamicGrid_->getDimension()); - gridSelectionDialog_->move(QCursor::pos()); - connect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize))); - gridSelectionDialog_->show(); + disconnect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize))); + gridSelectionDialog_->setCurrentGridSize(dynamicGrid_->getDimension()); + gridSelectionDialog_->move(QCursor::pos()); + connect(gridSelectionDialog_, SIGNAL(currentGridSizeChanged(QSize)), dynamicGrid_, SLOT(setDimensions(QSize))); + gridSelectionDialog_->show(); } void QtChatTabs::storeTabPositions() { - // save size - QByteArray gridSizeData; - QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite); - dataStreamGridSize << dynamicGrid_->getDimension(); - settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_SIZE, Q2PSTRING(QString(gridSizeData.toBase64()))); - - // save positions - QByteArray tabPositionsData; - QDataStream dataStreamTabPositions(&tabPositionsData, QIODevice::ReadWrite); - dynamicGrid_->updateTabPositions(); - dataStreamTabPositions << dynamicGrid_->getTabPositions(); - settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_POSITIONS, Q2PSTRING(QString(tabPositionsData.toBase64()))); + // save size + QByteArray gridSizeData; + QDataStream dataStreamGridSize(&gridSizeData, QIODevice::ReadWrite); + dataStreamGridSize << dynamicGrid_->getDimension(); + settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_SIZE, Q2PSTRING(QString(gridSizeData.toBase64()))); + + // save positions + QByteArray tabPositionsData; + QDataStream dataStreamTabPositions(&tabPositionsData, QIODevice::ReadWrite); + dynamicGrid_->updateTabPositions(); + dataStreamTabPositions << dynamicGrid_->getTabPositions(); + settingsProvider_->storeSetting(SettingConstants::TRELLIS_GRID_POSITIONS, Q2PSTRING(QString(tabPositionsData.toBase64()))); } void QtChatTabs::resizeEvent(QResizeEvent*) { - emit geometryChanged(); + emit geometryChanged(); } void QtChatTabs::moveEvent(QMoveEvent*) { - emit geometryChanged(); + emit geometryChanged(); } void QtChatTabs::checkForFirstShow() { - if (!isVisible()) { + if (!isVisible()) { #ifndef Q_OS_MAC - showMinimized(); + showMinimized(); #else - /* https://bugreports.qt-project.org/browse/QTBUG-19194 - * ^ When the above is fixed we can swap the below for just show(); - * WA_ShowWithoutActivating seems to helpfully not work, so... */ - - QWidget* currentWindow = QApplication::activeWindow(); /* Remember who had focus if we're the current application*/ - show(); - QCoreApplication::processEvents(); /* Run through the eventloop to clear the show() */ - if (currentWindow) { - currentWindow->activateWindow(); /* Set focus back */ - } + /* https://bugreports.qt-project.org/browse/QTBUG-19194 + * ^ When the above is fixed we can swap the below for just show(); + * WA_ShowWithoutActivating seems to helpfully not work, so... */ + + QWidget* currentWindow = QApplication::activeWindow(); /* Remember who had focus if we're the current application*/ + show(); + QCoreApplication::processEvents(); /* Run through the eventloop to clear the show() */ + if (currentWindow) { + currentWindow->activateWindow(); /* Set focus back */ + } #endif - } + } } } diff --git a/Swift/QtUI/QtChatTabs.h b/Swift/QtUI/QtChatTabs.h index 8fcbf4a..0c12d96 100644 --- a/Swift/QtUI/QtChatTabs.h +++ b/Swift/QtUI/QtChatTabs.h @@ -16,62 +16,62 @@ class QTabWidget; class QMenu; namespace Swift { - class SettingsProvider; - - class QtTabbable; - class QtTabWidget; - class QtDynamicGridLayout; - class QtGridSelectionDialog; - - class QtChatTabs : public QWidget, public QtChatTabsBase { - Q_OBJECT - public: - QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode); - virtual ~QtChatTabs(); - - virtual void addTab(QtTabbable* tab); - void minimise(); - QtTabbable* getCurrentTab(); - void setViewMenu(QMenu* viewMenu); - - signals: - void geometryChanged(); - void onTitleChanged(const QString& title); - - protected slots: - void closeEvent(QCloseEvent* event); - void resizeEvent(QResizeEvent* event); - void moveEvent(QMoveEvent* event); - - private slots: - void handleCurrentTabIndexChanged(int newIndex); - void handleTabClosing(); - void handleTabTitleUpdated(); - void handleTabTitleUpdated(QWidget* widget); - void handleTabCloseRequested(int index); - void handleWidgetShown(); - void handleWantsToActivate(); - void handleRequestedPreviousTab(); - void handleRequestedNextTab(); - void handleRequestedActiveTab(); - void flash(); - - void handleOpenLayoutChangeDialog(); - - void handleCloseTabShortcut(); - - private: - void storeTabPositions(); - void checkForFirstShow(); - - private: - bool singleWindow_; - SettingsProvider* settingsProvider_; - bool trellisMode_; - QtDynamicGridLayout* dynamicGrid_; - QtGridSelectionDialog* gridSelectionDialog_; - - QList shortcuts_; - }; + class SettingsProvider; + + class QtTabbable; + class QtTabWidget; + class QtDynamicGridLayout; + class QtGridSelectionDialog; + + class QtChatTabs : public QWidget, public QtChatTabsBase { + Q_OBJECT + public: + QtChatTabs(bool singleWindow, SettingsProvider* settingsProvider, bool trellisMode); + virtual ~QtChatTabs(); + + virtual void addTab(QtTabbable* tab); + void minimise(); + QtTabbable* getCurrentTab(); + void setViewMenu(QMenu* viewMenu); + + signals: + void geometryChanged(); + void onTitleChanged(const QString& title); + + protected slots: + void closeEvent(QCloseEvent* event); + void resizeEvent(QResizeEvent* event); + void moveEvent(QMoveEvent* event); + + private slots: + void handleCurrentTabIndexChanged(int newIndex); + void handleTabClosing(); + void handleTabTitleUpdated(); + void handleTabTitleUpdated(QWidget* widget); + void handleTabCloseRequested(int index); + void handleWidgetShown(); + void handleWantsToActivate(); + void handleRequestedPreviousTab(); + void handleRequestedNextTab(); + void handleRequestedActiveTab(); + void flash(); + + void handleOpenLayoutChangeDialog(); + + void handleCloseTabShortcut(); + + private: + void storeTabPositions(); + void checkForFirstShow(); + + private: + bool singleWindow_; + SettingsProvider* settingsProvider_; + bool trellisMode_; + QtDynamicGridLayout* dynamicGrid_; + QtGridSelectionDialog* gridSelectionDialog_; + + QList shortcuts_; + }; } diff --git a/Swift/QtUI/QtChatTabsBase.h b/Swift/QtUI/QtChatTabsBase.h index 753b706..b49bb10 100644 --- a/Swift/QtUI/QtChatTabsBase.h +++ b/Swift/QtUI/QtChatTabsBase.h @@ -11,11 +11,11 @@ namespace Swift { class QtTabbable; class QtChatTabsBase { - public: - QtChatTabsBase(); - virtual ~QtChatTabsBase(); + public: + QtChatTabsBase(); + virtual ~QtChatTabsBase(); - virtual void addTab(QtTabbable* tab) = 0; + virtual void addTab(QtTabbable* tab) = 0; }; } diff --git a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp index 7f44177..2c064f8 100644 --- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp +++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.cpp @@ -27,82 +27,82 @@ QtChatTabsShortcutOnlySubstitute::~QtChatTabsShortcutOnlySubstitute() { } void QtChatTabsShortcutOnlySubstitute::addTab(QtTabbable* tab) { - connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection); - connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection); - connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection); - - connect(new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), tab), SIGNAL(activated()), this, SLOT(handleCloseTabShortcut())); - connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), tab), SIGNAL(activated()), tab, SIGNAL(requestPreviousTab())); - connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), tab), SIGNAL(activated()), tab, SIGNAL(requestNextTab())); - connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), tab), SIGNAL(activated()), tab, SIGNAL(requestActiveTab())); + connect(tab, SIGNAL(requestNextTab()), this, SLOT(handleRequestedNextTab()), Qt::UniqueConnection); + connect(tab, SIGNAL(requestActiveTab()), this, SLOT(handleRequestedActiveTab()), Qt::UniqueConnection); + connect(tab, SIGNAL(requestPreviousTab()), this, SLOT(handleRequestedPreviousTab()), Qt::UniqueConnection); + + connect(new QShortcut(QKeySequence(tr("CTRL+W", "Close chat tab.")), tab), SIGNAL(activated()), this, SLOT(handleCloseTabShortcut())); + connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageUp), tab), SIGNAL(activated()), tab, SIGNAL(requestPreviousTab())); + connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_PageDown), tab), SIGNAL(activated()), tab, SIGNAL(requestNextTab())); + connect(new QShortcut(QKeySequence(Qt::ALT + Qt::Key_A), tab), SIGNAL(activated()), tab, SIGNAL(requestActiveTab())); } void QtChatTabsShortcutOnlySubstitute::handleCloseTabShortcut() { - QtTabbable* senderTab = dynamic_cast(sender()->parent()); - SWIFT_LOG_ASSERT(senderTab, debug) << "No window to close." << std::endl; - if (senderTab) { - senderTab->close(); - } + QtTabbable* senderTab = dynamic_cast(sender()->parent()); + SWIFT_LOG_ASSERT(senderTab, debug) << "No window to close." << std::endl; + if (senderTab) { + senderTab->close(); + } } void QtChatTabsShortcutOnlySubstitute::handleRequestedNextTab() { - QtTabbable* senderTab = dynamic_cast(sender()); + QtTabbable* senderTab = dynamic_cast(sender()); - QList tabs = tabbableWindows(); + QList tabs = tabbableWindows(); - int currentIndex = tabs.indexOf(senderTab); - assert(currentIndex >= 0); + int currentIndex = tabs.indexOf(senderTab); + assert(currentIndex >= 0); - QtTabbable* nextTab = tabs.at((currentIndex + 1) % tabs.size()); - nextTab->activateWindow(); + QtTabbable* nextTab = tabs.at((currentIndex + 1) % tabs.size()); + nextTab->activateWindow(); } void QtChatTabsShortcutOnlySubstitute::handleRequestedActiveTab() { - QtTabbable* senderTab = dynamic_cast(sender()); + QtTabbable* senderTab = dynamic_cast(sender()); - QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity}; + QtTabbable::AlertType types[] = {QtTabbable::WaitingActivity, QtTabbable::ImpendingActivity}; - QList tabs = tabbableWindows(); + QList tabs = tabbableWindows(); - for (int j = 0; j < 2; j++) { - int startIndex = tabs.indexOf(senderTab); - int currentIndex = startIndex; + for (int j = 0; j < 2; j++) { + int startIndex = tabs.indexOf(senderTab); + int currentIndex = startIndex; - do { - currentIndex = (currentIndex + 1) % tabs.size(); - QtTabbable* currentTab = tabs.at(currentIndex); - if (currentTab->getWidgetAlertState() == types[j]) { - currentTab->activateWindow(); - return; - } - } while (startIndex != currentIndex); - } + do { + currentIndex = (currentIndex + 1) % tabs.size(); + QtTabbable* currentTab = tabs.at(currentIndex); + if (currentTab->getWidgetAlertState() == types[j]) { + currentTab->activateWindow(); + return; + } + } while (startIndex != currentIndex); + } } void QtChatTabsShortcutOnlySubstitute::handleRequestedPreviousTab() { - QtTabbable* senderTab = dynamic_cast(sender()); + QtTabbable* senderTab = dynamic_cast(sender()); - QList tabs = tabbableWindows(); + QList tabs = tabbableWindows(); - int currentIndex = tabs.indexOf(senderTab); - assert(currentIndex >= 0); + int currentIndex = tabs.indexOf(senderTab); + assert(currentIndex >= 0); - QtTabbable* previousTab = tabs.at((currentIndex + tabs.size() - 1) % tabs.size()); - previousTab->activateWindow(); + QtTabbable* previousTab = tabs.at((currentIndex + tabs.size() - 1) % tabs.size()); + previousTab->activateWindow(); } QList QtChatTabsShortcutOnlySubstitute::tabbableWindows() const { - QList windows = qApp->topLevelWidgets(); + QList windows = qApp->topLevelWidgets(); - QList tabbables; - foreach(QWidget* topLevelWidget, windows) { - QtTabbable* tabbable = dynamic_cast(topLevelWidget); - if (tabbable) { - tabbables << tabbable; - } - } + QList tabbables; + foreach(QWidget* topLevelWidget, windows) { + QtTabbable* tabbable = dynamic_cast(topLevelWidget); + if (tabbable) { + tabbables << tabbable; + } + } - return tabbables; + return tabbables; } } diff --git a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h index 80af008..b330fe7 100644 --- a/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h +++ b/Swift/QtUI/QtChatTabsShortcutOnlySubstitute.h @@ -16,25 +16,25 @@ class QShortcut; namespace Swift { class QtChatTabsShortcutOnlySubstitute : public QWidget, public QtChatTabsBase { - Q_OBJECT + Q_OBJECT - public: - QtChatTabsShortcutOnlySubstitute(); - virtual ~QtChatTabsShortcutOnlySubstitute(); + public: + QtChatTabsShortcutOnlySubstitute(); + virtual ~QtChatTabsShortcutOnlySubstitute(); - virtual void addTab(QtTabbable* tab); + virtual void addTab(QtTabbable* tab); - private slots: - void handleCloseTabShortcut(); - void handleRequestedNextTab(); - void handleRequestedActiveTab(); - void handleRequestedPreviousTab(); + private slots: + void handleCloseTabShortcut(); + void handleRequestedNextTab(); + void handleRequestedActiveTab(); + void handleRequestedPreviousTab(); - private: - QList tabbableWindows() const; + private: + QList tabbableWindows() const; - private: - QList shortcuts_; + private: + QList shortcuts_; }; } diff --git a/Swift/QtUI/QtChatTheme.cpp b/Swift/QtUI/QtChatTheme.cpp index a7628d9..e73f8ac 100644 --- a/Swift/QtUI/QtChatTheme.cpp +++ b/Swift/QtUI/QtChatTheme.cpp @@ -14,58 +14,58 @@ namespace Swift { * Load Adium themes, as http://trac.adium.im/wiki/CreatingMessageStyles */ QtChatTheme::QtChatTheme(const QString& themePath) : qrc_(themePath[0] == ':'), themePath_(qrc_ ? themePath : themePath + "/Contents/Resources/") { - QString fileNames[EndMarker]; - fileNames[Header] = "Header.html"; - fileNames[Footer] = "Footer.html"; - fileNames[Content] = "Content.html"; - fileNames[Status] = "Status.html"; - fileNames[Topic] = "Topic.html"; - fileNames[FileTransferRequest] = "FileTransferRequest.html"; - fileNames[IncomingContent] = "Incoming/Content.html"; - fileNames[IncomingNextContent] = "Incoming/NextContent.html"; - fileNames[IncomingContext] = "Incoming/Context.html"; - fileNames[IncomingNextContext] = "Incoming/NextContext.html"; - fileNames[OutgoingContent] = "Outgoing/Content.html"; - fileNames[OutgoingNextContent] = "Outgoing/NextContent.html"; - fileNames[OutgoingContext] = "Outgoing/Context.html"; - fileNames[OutgoingNextContext] = "Outgoing/NextContext.html"; - fileNames[Template] = "Template.html"; - fileNames[MainCSS] = "main.css"; - fileNames[Unread] = "Unread.html"; - fileNames[TemplateDefault] = ":/themes/Template.html"; - for (int i = 0; i < EndMarker; i++) { - QString source; - QFile sourceFile((i != TemplateDefault ? themePath_ : "") + fileNames[i]); - if (sourceFile.exists() && sourceFile.open(QIODevice::ReadOnly)) { - source = sourceFile.readAll(); - sourceFile.close(); - } else { - //qWarning() << "Couldn't load file " << sourceFile.fileName(); - } - fileContents_.append(source); - } + QString fileNames[EndMarker]; + fileNames[Header] = "Header.html"; + fileNames[Footer] = "Footer.html"; + fileNames[Content] = "Content.html"; + fileNames[Status] = "Status.html"; + fileNames[Topic] = "Topic.html"; + fileNames[FileTransferRequest] = "FileTransferRequest.html"; + fileNames[IncomingContent] = "Incoming/Content.html"; + fileNames[IncomingNextContent] = "Incoming/NextContent.html"; + fileNames[IncomingContext] = "Incoming/Context.html"; + fileNames[IncomingNextContext] = "Incoming/NextContext.html"; + fileNames[OutgoingContent] = "Outgoing/Content.html"; + fileNames[OutgoingNextContent] = "Outgoing/NextContent.html"; + fileNames[OutgoingContext] = "Outgoing/Context.html"; + fileNames[OutgoingNextContext] = "Outgoing/NextContext.html"; + fileNames[Template] = "Template.html"; + fileNames[MainCSS] = "main.css"; + fileNames[Unread] = "Unread.html"; + fileNames[TemplateDefault] = ":/themes/Template.html"; + for (int i = 0; i < EndMarker; i++) { + QString source; + QFile sourceFile((i != TemplateDefault ? themePath_ : "") + fileNames[i]); + if (sourceFile.exists() && sourceFile.open(QIODevice::ReadOnly)) { + source = sourceFile.readAll(); + sourceFile.close(); + } else { + //qWarning() << "Couldn't load file " << sourceFile.fileName(); + } + fileContents_.append(source); + } - /* Fallbacks */ - if (fileContents_[Template].isEmpty()) fileContents_[Template] = fileContents_[TemplateDefault]; - if (fileContents_[Status].isEmpty()) fileContents_[Status] = fileContents_[Content]; - if (fileContents_[IncomingContent].isEmpty()) fileContents_[IncomingContent] = fileContents_[Content]; - if (fileContents_[IncomingNextContent].isEmpty()) fileContents_[IncomingNextContent] = fileContents_[IncomingContent]; - if (fileContents_[FileTransferRequest].isEmpty()) fileContents_[FileTransferRequest] = fileContents_[Status]; - if (fileContents_[IncomingContext].isEmpty()) fileContents_[IncomingContext] = fileContents_[IncomingContent]; - if (fileContents_[IncomingNextContext].isEmpty()) fileContents_[IncomingNextContext] = fileContents_[IncomingNextContent]; - if (fileContents_[OutgoingContent].isEmpty()) fileContents_[OutgoingContent] = fileContents_[IncomingContent]; - if (fileContents_[OutgoingContext].isEmpty()) fileContents_[OutgoingContext] = fileContents_[OutgoingContent]; - if (fileContents_[OutgoingNextContent].isEmpty()) fileContents_[OutgoingNextContent] = fileContents_[OutgoingContent]; - if (fileContents_[OutgoingNextContext].isEmpty()) fileContents_[OutgoingNextContext] = fileContents_[OutgoingNextContent]; + /* Fallbacks */ + if (fileContents_[Template].isEmpty()) fileContents_[Template] = fileContents_[TemplateDefault]; + if (fileContents_[Status].isEmpty()) fileContents_[Status] = fileContents_[Content]; + if (fileContents_[IncomingContent].isEmpty()) fileContents_[IncomingContent] = fileContents_[Content]; + if (fileContents_[IncomingNextContent].isEmpty()) fileContents_[IncomingNextContent] = fileContents_[IncomingContent]; + if (fileContents_[FileTransferRequest].isEmpty()) fileContents_[FileTransferRequest] = fileContents_[Status]; + if (fileContents_[IncomingContext].isEmpty()) fileContents_[IncomingContext] = fileContents_[IncomingContent]; + if (fileContents_[IncomingNextContext].isEmpty()) fileContents_[IncomingNextContext] = fileContents_[IncomingNextContent]; + if (fileContents_[OutgoingContent].isEmpty()) fileContents_[OutgoingContent] = fileContents_[IncomingContent]; + if (fileContents_[OutgoingContext].isEmpty()) fileContents_[OutgoingContext] = fileContents_[OutgoingContent]; + if (fileContents_[OutgoingNextContent].isEmpty()) fileContents_[OutgoingNextContent] = fileContents_[OutgoingContent]; + if (fileContents_[OutgoingNextContext].isEmpty()) fileContents_[OutgoingNextContext] = fileContents_[OutgoingNextContent]; } QString QtChatTheme::getBase() const { - return qrc_ ? "qrc" + themePath_ : "file://" + themePath_; + return qrc_ ? "qrc" + themePath_ : "file://" + themePath_; } QString QtChatTheme::getUnread() const { - return fileContents_[Unread].isEmpty() ? "
" : fileContents_[Unread]; + return fileContents_[Unread].isEmpty() ? "
" : fileContents_[Unread]; } } diff --git a/Swift/QtUI/QtChatTheme.h b/Swift/QtUI/QtChatTheme.h index 2997de0..8db662f 100644 --- a/Swift/QtUI/QtChatTheme.h +++ b/Swift/QtUI/QtChatTheme.h @@ -10,32 +10,32 @@ #include namespace Swift { - class QtChatTheme { - public: - QtChatTheme(const QString& themePath); - QString getHeader() const {return fileContents_[Header];} - QString getFooter() const {return fileContents_[Footer];} - QString getContent() const {return fileContents_[Content];} - QString getStatus() const {return fileContents_[Status];} - QString getTopic() const {return fileContents_[Topic];} - QString getFileTransferRequest() const {return fileContents_[FileTransferRequest];} - QString getIncomingContent() const {return fileContents_[IncomingContent];} - QString getIncomingNextContent() const {return fileContents_[IncomingNextContent];} - QString getIncomingContext() const {return fileContents_[IncomingContext];} - QString getIncomingNextContext() const {return fileContents_[IncomingNextContext];} - QString getOutgoingContent() const {return fileContents_[OutgoingContent];} - QString getOutgoingNextContent() const {return fileContents_[OutgoingNextContent];} - QString getOutgoingContext() const {return fileContents_[OutgoingContext];} - QString getOutgoingNextContext() const {return fileContents_[OutgoingNextContext];} - QString getTemplate() const {return fileContents_[Template];} - QString getMainCSS() const {return fileContents_[MainCSS];} - QString getBase() const; - QString getUnread() const; + class QtChatTheme { + public: + QtChatTheme(const QString& themePath); + QString getHeader() const {return fileContents_[Header];} + QString getFooter() const {return fileContents_[Footer];} + QString getContent() const {return fileContents_[Content];} + QString getStatus() const {return fileContents_[Status];} + QString getTopic() const {return fileContents_[Topic];} + QString getFileTransferRequest() const {return fileContents_[FileTransferRequest];} + QString getIncomingContent() const {return fileContents_[IncomingContent];} + QString getIncomingNextContent() const {return fileContents_[IncomingNextContent];} + QString getIncomingContext() const {return fileContents_[IncomingContext];} + QString getIncomingNextContext() const {return fileContents_[IncomingNextContext];} + QString getOutgoingContent() const {return fileContents_[OutgoingContent];} + QString getOutgoingNextContent() const {return fileContents_[OutgoingNextContent];} + QString getOutgoingContext() const {return fileContents_[OutgoingContext];} + QString getOutgoingNextContext() const {return fileContents_[OutgoingNextContext];} + QString getTemplate() const {return fileContents_[Template];} + QString getMainCSS() const {return fileContents_[MainCSS];} + QString getBase() const; + QString getUnread() const; - private: - enum files {Header = 0, Footer, Content, Status, Topic, FileTransferRequest, IncomingContent, IncomingNextContent, IncomingContext, IncomingNextContext, OutgoingContent, OutgoingNextContent, OutgoingContext, OutgoingNextContext, Template, MainCSS, TemplateDefault, Unread, /*Must be last!*/EndMarker}; - bool qrc_; - QList fileContents_; - QString themePath_; - }; + private: + enum files {Header = 0, Footer, Content, Status, Topic, FileTransferRequest, IncomingContent, IncomingNextContent, IncomingContext, IncomingNextContext, OutgoingContent, OutgoingNextContent, OutgoingContext, OutgoingNextContext, Template, MainCSS, TemplateDefault, Unread, /*Must be last!*/EndMarker}; + bool qrc_; + QList fileContents_; + QString themePath_; + }; } diff --git a/Swift/QtUI/QtChatView.cpp b/Swift/QtUI/QtChatView.cpp index 05366c1..6d9a17d 100644 --- a/Swift/QtUI/QtChatView.cpp +++ b/Swift/QtUI/QtChatView.cpp @@ -13,7 +13,7 @@ QtChatView::QtChatView(QWidget* parent) : QWidget(parent) { } QtChatView::~QtChatView() { - + } } diff --git a/Swift/QtUI/QtChatView.h b/Swift/QtUI/QtChatView.h index 9f0df44..cca3bdf 100644 --- a/Swift/QtUI/QtChatView.h +++ b/Swift/QtUI/QtChatView.h @@ -16,49 +16,49 @@ #include namespace Swift { - class HighlightAction; - class SecurityLabel; + class HighlightAction; + class SecurityLabel; - class QtChatView : public QWidget { - Q_OBJECT - public: - QtChatView(QWidget* parent); - virtual ~QtChatView(); + class QtChatView : public QWidget { + Q_OBJECT + public: + QtChatView(QWidget* parent); + virtual ~QtChatView(); - /** Add message to window. - * @return id of added message (for acks). - */ - virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; - /** Adds action to window. - * @return id of added message (for acks); - */ - virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; + /** Add message to window. + * @return id of added message (for acks). + */ + virtual std::string addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; + /** Adds action to window. + * @return id of added message (for acks); + */ + virtual std::string addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) = 0; - virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0; - virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0; + virtual std::string addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0; + virtual void addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction direction) = 0; - virtual void addErrorMessage(const ChatWindow::ChatMessage& message) = 0; - virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; - virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0; - virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; - virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0; - virtual void setAckState(const std::string& id, ChatWindow::AckState state) = 0; - - virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0; - virtual void setFileTransferProgress(std::string, const int percentageDone) = 0; - virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") = 0; - virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) = 0; - virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) = 0; - virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) = 0; - virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0; + virtual void addErrorMessage(const ChatWindow::ChatMessage& message) = 0; + virtual void replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; + virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0; + virtual void replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) = 0; + virtual void replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) = 0; + virtual void setAckState(const std::string& id, ChatWindow::AckState state) = 0; - virtual void showEmoticons(bool show) = 0; - virtual void addLastSeenLine() = 0; + virtual std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) = 0; + virtual void setFileTransferProgress(std::string, const int percentageDone) = 0; + virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState state, const std::string& msg = "") = 0; + virtual void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) = 0; + virtual std::string addWhiteboardRequest(const QString& contact, bool senderIsSelf) = 0; + virtual void setWhiteboardSessionStatus(const std::string& id, const ChatWindow::WhiteboardSessionState state) = 0; + virtual void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) = 0; - public slots: - virtual void resizeFont(int fontSizeSteps) = 0; - virtual void scrollToBottom() = 0; - virtual void handleKeyPressEvent(QKeyEvent* event) = 0; + virtual void showEmoticons(bool show) = 0; + virtual void addLastSeenLine() = 0; - }; + public slots: + virtual void resizeFont(int fontSizeSteps) = 0; + virtual void scrollToBottom() = 0; + virtual void handleKeyPressEvent(QKeyEvent* event) = 0; + + }; } diff --git a/Swift/QtUI/QtChatWindow.cpp b/Swift/QtUI/QtChatWindow.cpp index 7649256..95d643c 100644 --- a/Swift/QtUI/QtChatWindow.cpp +++ b/Swift/QtUI/QtChatWindow.cpp @@ -62,883 +62,883 @@ namespace Swift { QtChatWindow::QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map& emoticons) : QtTabbable(), id_(Q2PSTRING(contact)), contact_(contact), nextAlertId_(0), eventStream_(eventStream), blockingState_(BlockingUnsupported), isMUC_(false), supportsImpromptuChat_(false), roomBookmarkState_(RoomNotBookmarked) { - settings_ = settings; - unreadCount_ = 0; - isOnline_ = true; - completer_ = NULL; - affiliationEditor_ = NULL; - theme_ = theme; - isCorrection_ = false; - labelModel_ = NULL; - correctionEnabled_ = Maybe; - fileTransferEnabled_ = Maybe; - updateTitleWithUnreadCount(); - assert(settings); - setAcceptDrops(true); - - alertStyleSheet_ = ".QWidget, QTextEdit { background: rgb(255, 255, 153); color: black }"; - - QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, this); - layout->setContentsMargins(0,0,0,0); - layout->setSpacing(2); - - alertLayout_ = new QVBoxLayout(); - layout->addLayout(alertLayout_); - - subjectLayout_ = new QBoxLayout(QBoxLayout::LeftToRight); - subject_ = new QLineEdit(this); - subjectLayout_->addWidget(subject_); - setSubject(""); - subject_->setReadOnly(true); - - QPushButton* actionButton_ = new QPushButton(this); - actionButton_->setIcon(QIcon(":/icons/actions.png")); - connect(actionButton_, SIGNAL(clicked()), this, SLOT(handleActionButtonClicked())); - subject_->hide(); - - layout->addLayout(subjectLayout_); - - logRosterSplitter_ = new QSplitter(this); - logRosterSplitter_->setAutoFillBackground(true); - layout->addWidget(logRosterSplitter_); - if (settings_->getSetting(QtUISettingConstants::USE_PLAIN_CHATS) || settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) { - messageLog_ = new QtPlainChatView(this, eventStream_); - } - else { - messageLog_ = new QtWebKitChatView(this, eventStream_, theme, this); // I accept that passing the ChatWindow in so that the view can call the signals is somewhat inelegant, but it saves a lot of boilerplate. This patch is unpleasant enough already. So let's fix this soon (it at least needs fixing by the time history is sorted), but not now. - } - logRosterSplitter_->addWidget(messageLog_); - - treeWidget_ = new QtOccupantListWidget(eventStream_, settings_, QtTreeWidget::MessageDefaultJID, this); - treeWidget_->hide(); - logRosterSplitter_->addWidget(treeWidget_); - logRosterSplitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - connect(logRosterSplitter_, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int))); - - midBar_ = new QWidget(this); - //layout->addWidget(midBar); - midBar_->setAutoFillBackground(true); - QHBoxLayout *midBarLayout = new QHBoxLayout(midBar_); - midBarLayout->setContentsMargins(0,0,0,0); - midBarLayout->setSpacing(2); - //midBarLayout->addStretch(); - - labelsWidget_ = new QComboBox(this); - labelsWidget_->setFocusPolicy(Qt::NoFocus); - labelsWidget_->hide(); - labelsWidget_->setSizeAdjustPolicy(QComboBox::AdjustToContents); - midBarLayout->addWidget(labelsWidget_,0); - connect(labelsWidget_, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentLabelChanged(int))); - defaultLabelsPalette_ = labelsWidget_->palette(); - - QHBoxLayout* inputBarLayout = new QHBoxLayout(); - inputBarLayout->setContentsMargins(0,0,0,0); - inputBarLayout->setSpacing(2); - input_ = new QtTextEdit(settings_, this); - input_->setAcceptRichText(false); - inputBarLayout->addWidget(midBar_); - inputBarLayout->addWidget(input_); - correctingLabel_ = new QLabel(tr("Correcting"), this); - inputBarLayout->addWidget(correctingLabel_); - correctingLabel_->hide(); - - connect(input_, SIGNAL(receivedFocus()), this, SLOT(handleTextInputReceivedFocus())); - connect(input_, SIGNAL(lostFocus()), this, SLOT(handleTextInputLostFocus())); - QPushButton* emoticonsButton_ = new QPushButton(this); - emoticonsButton_->setIcon(QIcon(":/emoticons/smile.png")); - connect(emoticonsButton_, SIGNAL(clicked()), this, SLOT(handleEmoticonsButtonClicked())); - - emoticonsMenu_ = new QMenu(this); - QtEmoticonsGrid* emoticonsGrid = new QtEmoticonsGrid(emoticons, emoticonsMenu_); - connect(emoticonsGrid, SIGNAL(emoticonClicked(QString)), this, SLOT(handleEmoticonClicked(QString))); - - // using an extra layout to work around Qt margin glitches on OS X - QHBoxLayout* actionLayout = new QHBoxLayout(); - actionLayout->addWidget(emoticonsButton_); - actionLayout->addWidget(actionButton_); - - inputBarLayout->addLayout(actionLayout); - layout->addLayout(inputBarLayout); - - inputClearing_ = false; - contactIsTyping_ = false; - tabCompletion_ = false; - - connect(input_, SIGNAL(unhandledKeyPressEvent(QKeyEvent*)), this, SLOT(handleKeyPressEvent(QKeyEvent*))); - connect(input_, SIGNAL(returnPressed()), this, SLOT(returnPressed())); - connect(input_, SIGNAL(textChanged()), this, SLOT(handleInputChanged())); - connect(input_, SIGNAL(cursorPositionChanged()), this, SLOT(handleCursorPositionChanged())); - setFocusProxy(input_); - logRosterSplitter_->setFocusProxy(input_); - midBar_->setFocusProxy(input_); - messageLog_->setFocusProxy(input_); - connect(messageLog_, SIGNAL(gotFocus()), input_, SLOT(setFocus())); - resize(400,300); - connect(messageLog_, SIGNAL(fontResized(int)), this, SIGNAL(fontResized(int))); - connect(messageLog_, SIGNAL(logCleared()), this, SLOT(handleLogCleared())); - - treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtChatWindow::handleOccupantSelectionChanged, this, _1)); - treeWidget_->onOccupantActionSelected.connect(boost::bind(boost::ref(onOccupantActionSelected), _1, _2)); - - settings_->onSettingChanged.connect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1)); - messageLog_->showEmoticons(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); - setMinimumSize(100, 100); + settings_ = settings; + unreadCount_ = 0; + isOnline_ = true; + completer_ = NULL; + affiliationEditor_ = NULL; + theme_ = theme; + isCorrection_ = false; + labelModel_ = NULL; + correctionEnabled_ = Maybe; + fileTransferEnabled_ = Maybe; + updateTitleWithUnreadCount(); + assert(settings); + setAcceptDrops(true); + + alertStyleSheet_ = ".QWidget, QTextEdit { background: rgb(255, 255, 153); color: black }"; + + QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, this); + layout->setContentsMargins(0,0,0,0); + layout->setSpacing(2); + + alertLayout_ = new QVBoxLayout(); + layout->addLayout(alertLayout_); + + subjectLayout_ = new QBoxLayout(QBoxLayout::LeftToRight); + subject_ = new QLineEdit(this); + subjectLayout_->addWidget(subject_); + setSubject(""); + subject_->setReadOnly(true); + + QPushButton* actionButton_ = new QPushButton(this); + actionButton_->setIcon(QIcon(":/icons/actions.png")); + connect(actionButton_, SIGNAL(clicked()), this, SLOT(handleActionButtonClicked())); + subject_->hide(); + + layout->addLayout(subjectLayout_); + + logRosterSplitter_ = new QSplitter(this); + logRosterSplitter_->setAutoFillBackground(true); + layout->addWidget(logRosterSplitter_); + if (settings_->getSetting(QtUISettingConstants::USE_PLAIN_CHATS) || settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) { + messageLog_ = new QtPlainChatView(this, eventStream_); + } + else { + messageLog_ = new QtWebKitChatView(this, eventStream_, theme, this); // I accept that passing the ChatWindow in so that the view can call the signals is somewhat inelegant, but it saves a lot of boilerplate. This patch is unpleasant enough already. So let's fix this soon (it at least needs fixing by the time history is sorted), but not now. + } + logRosterSplitter_->addWidget(messageLog_); + + treeWidget_ = new QtOccupantListWidget(eventStream_, settings_, QtTreeWidget::MessageDefaultJID, this); + treeWidget_->hide(); + logRosterSplitter_->addWidget(treeWidget_); + logRosterSplitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + connect(logRosterSplitter_, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int))); + + midBar_ = new QWidget(this); + //layout->addWidget(midBar); + midBar_->setAutoFillBackground(true); + QHBoxLayout *midBarLayout = new QHBoxLayout(midBar_); + midBarLayout->setContentsMargins(0,0,0,0); + midBarLayout->setSpacing(2); + //midBarLayout->addStretch(); + + labelsWidget_ = new QComboBox(this); + labelsWidget_->setFocusPolicy(Qt::NoFocus); + labelsWidget_->hide(); + labelsWidget_->setSizeAdjustPolicy(QComboBox::AdjustToContents); + midBarLayout->addWidget(labelsWidget_,0); + connect(labelsWidget_, SIGNAL(currentIndexChanged(int)), this, SLOT(handleCurrentLabelChanged(int))); + defaultLabelsPalette_ = labelsWidget_->palette(); + + QHBoxLayout* inputBarLayout = new QHBoxLayout(); + inputBarLayout->setContentsMargins(0,0,0,0); + inputBarLayout->setSpacing(2); + input_ = new QtTextEdit(settings_, this); + input_->setAcceptRichText(false); + inputBarLayout->addWidget(midBar_); + inputBarLayout->addWidget(input_); + correctingLabel_ = new QLabel(tr("Correcting"), this); + inputBarLayout->addWidget(correctingLabel_); + correctingLabel_->hide(); + + connect(input_, SIGNAL(receivedFocus()), this, SLOT(handleTextInputReceivedFocus())); + connect(input_, SIGNAL(lostFocus()), this, SLOT(handleTextInputLostFocus())); + QPushButton* emoticonsButton_ = new QPushButton(this); + emoticonsButton_->setIcon(QIcon(":/emoticons/smile.png")); + connect(emoticonsButton_, SIGNAL(clicked()), this, SLOT(handleEmoticonsButtonClicked())); + + emoticonsMenu_ = new QMenu(this); + QtEmoticonsGrid* emoticonsGrid = new QtEmoticonsGrid(emoticons, emoticonsMenu_); + connect(emoticonsGrid, SIGNAL(emoticonClicked(QString)), this, SLOT(handleEmoticonClicked(QString))); + + // using an extra layout to work around Qt margin glitches on OS X + QHBoxLayout* actionLayout = new QHBoxLayout(); + actionLayout->addWidget(emoticonsButton_); + actionLayout->addWidget(actionButton_); + + inputBarLayout->addLayout(actionLayout); + layout->addLayout(inputBarLayout); + + inputClearing_ = false; + contactIsTyping_ = false; + tabCompletion_ = false; + + connect(input_, SIGNAL(unhandledKeyPressEvent(QKeyEvent*)), this, SLOT(handleKeyPressEvent(QKeyEvent*))); + connect(input_, SIGNAL(returnPressed()), this, SLOT(returnPressed())); + connect(input_, SIGNAL(textChanged()), this, SLOT(handleInputChanged())); + connect(input_, SIGNAL(cursorPositionChanged()), this, SLOT(handleCursorPositionChanged())); + setFocusProxy(input_); + logRosterSplitter_->setFocusProxy(input_); + midBar_->setFocusProxy(input_); + messageLog_->setFocusProxy(input_); + connect(messageLog_, SIGNAL(gotFocus()), input_, SLOT(setFocus())); + resize(400,300); + connect(messageLog_, SIGNAL(fontResized(int)), this, SIGNAL(fontResized(int))); + connect(messageLog_, SIGNAL(logCleared()), this, SLOT(handleLogCleared())); + + treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtChatWindow::handleOccupantSelectionChanged, this, _1)); + treeWidget_->onOccupantActionSelected.connect(boost::bind(boost::ref(onOccupantActionSelected), _1, _2)); + + settings_->onSettingChanged.connect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1)); + messageLog_->showEmoticons(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); + setMinimumSize(100, 100); } QtChatWindow::~QtChatWindow() { - settings_->onSettingChanged.disconnect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1)); - if (mucConfigurationWindow_) { - delete mucConfigurationWindow_.data(); - } + settings_->onSettingChanged.disconnect(boost::bind(&QtChatWindow::handleSettingChanged, this, _1)); + if (mucConfigurationWindow_) { + delete mucConfigurationWindow_.data(); + } } void QtChatWindow::handleSettingChanged(const std::string& setting) { - if (setting == QtUISettingConstants::SHOW_EMOTICONS.getKey()) { - bool showEmoticons = settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS); - messageLog_->showEmoticons(showEmoticons); - } + if (setting == QtUISettingConstants::SHOW_EMOTICONS.getKey()) { + bool showEmoticons = settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS); + messageLog_->showEmoticons(showEmoticons); + } } void QtChatWindow::handleLogCleared() { - onLogCleared(); + onLogCleared(); } void QtChatWindow::handleOccupantSelectionChanged(RosterItem* item) { - onOccupantSelectionChanged(dynamic_cast(item)); + onOccupantSelectionChanged(dynamic_cast(item)); } void QtChatWindow::handleFontResized(int fontSizeSteps) { - messageLog_->resizeFont(fontSizeSteps); + messageLog_->resizeFont(fontSizeSteps); } void QtChatWindow::handleAlertButtonClicked() { - const QObject* alertWidget = QObject::sender()->parent(); - std::map::const_iterator i = alertWidgets_.begin(); - for ( ; i != alertWidgets_.end(); ++i) { - if (i->second == alertWidget) { - removeAlert(i->first); - break; - } - } + const QObject* alertWidget = QObject::sender()->parent(); + std::map::const_iterator i = alertWidgets_.begin(); + for ( ; i != alertWidgets_.end(); ++i) { + if (i->second == alertWidget) { + removeAlert(i->first); + break; + } + } } QtChatWindow::AlertID QtChatWindow::addAlert(const std::string& alertText) { - QWidget* alertWidget = new QWidget(this); - QHBoxLayout* alertLayout = new QHBoxLayout(alertWidget); - alertLayout_->addWidget(alertWidget); - QLabel* alertLabel = new QLabel(this); - alertLabel->setText(alertText.c_str()); - alertLayout->addWidget(alertLabel); - - QToolButton* closeButton = new QToolButton(alertWidget); - closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); - closeButton->setIconSize(QSize(16,16)); - closeButton->setCursor(Qt::ArrowCursor); - closeButton->setStyleSheet("QToolButton { border: none; padding: 0px; }"); - connect (closeButton, SIGNAL(clicked()), this, SLOT(handleAlertButtonClicked())); - - alertLayout->addWidget(closeButton); - QPalette palette = alertWidget->palette(); - palette.setColor(QPalette::Window, QColor(Qt::yellow)); - palette.setColor(QPalette::WindowText, QColor(Qt::black)); - alertWidget->setStyleSheet(alertStyleSheet_); - alertLabel->setStyleSheet(alertStyleSheet_); - - AlertID id = nextAlertId_++; - alertWidgets_[id] = alertWidget; - return id; + QWidget* alertWidget = new QWidget(this); + QHBoxLayout* alertLayout = new QHBoxLayout(alertWidget); + alertLayout_->addWidget(alertWidget); + QLabel* alertLabel = new QLabel(this); + alertLabel->setText(alertText.c_str()); + alertLayout->addWidget(alertLabel); + + QToolButton* closeButton = new QToolButton(alertWidget); + closeButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); + closeButton->setIconSize(QSize(16,16)); + closeButton->setCursor(Qt::ArrowCursor); + closeButton->setStyleSheet("QToolButton { border: none; padding: 0px; }"); + connect (closeButton, SIGNAL(clicked()), this, SLOT(handleAlertButtonClicked())); + + alertLayout->addWidget(closeButton); + QPalette palette = alertWidget->palette(); + palette.setColor(QPalette::Window, QColor(Qt::yellow)); + palette.setColor(QPalette::WindowText, QColor(Qt::black)); + alertWidget->setStyleSheet(alertStyleSheet_); + alertLabel->setStyleSheet(alertStyleSheet_); + + AlertID id = nextAlertId_++; + alertWidgets_[id] = alertWidget; + return id; } void QtChatWindow::removeAlert(const AlertID id) { - std::map::iterator i = alertWidgets_.find(id); - if (i != alertWidgets_.end()) { - alertLayout_->removeWidget(i->second); - delete i->second; - alertWidgets_.erase(i); - } + std::map::iterator i = alertWidgets_.find(id); + if (i != alertWidgets_.end()) { + alertLayout_->removeWidget(i->second); + delete i->second; + alertWidgets_.erase(i); + } } void QtChatWindow::setTabComplete(TabComplete* completer) { - completer_ = completer; + completer_ = completer; } void QtChatWindow::handleKeyPressEvent(QKeyEvent* event) { - event->ignore(); - if (event->isAccepted()) { - return; - } - event->accept(); - - int key = event->key(); - if (key == Qt::Key_Tab) { - tabComplete(); - } - else if ((key == Qt::Key_Up) && input_->toPlainText().isEmpty() && !(lastSentMessage_.isEmpty())) { - beginCorrection(); - } - else if (key == Qt::Key_Down && isCorrection_ && input_->textCursor().atBlockEnd()) { - cancelCorrection(); - } - else if (key == Qt::Key_Down || key == Qt::Key_Up) { - event->ignore(); - } - else { - messageLog_->handleKeyPressEvent(event); - } + event->ignore(); + if (event->isAccepted()) { + return; + } + event->accept(); + + int key = event->key(); + if (key == Qt::Key_Tab) { + tabComplete(); + } + else if ((key == Qt::Key_Up) && input_->toPlainText().isEmpty() && !(lastSentMessage_.isEmpty())) { + beginCorrection(); + } + else if (key == Qt::Key_Down && isCorrection_ && input_->textCursor().atBlockEnd()) { + cancelCorrection(); + } + else if (key == Qt::Key_Down || key == Qt::Key_Up) { + event->ignore(); + } + else { + messageLog_->handleKeyPressEvent(event); + } } void QtChatWindow::beginCorrection() { - boost::optional newCorrectingAlert; - if (correctionEnabled_ == Maybe) { - newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat may not support message correction. If you send a correction anyway, it may appear as a duplicate message"))); - } - else if (correctionEnabled_ == No) { - newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat does not support message correction. If you send a correction anyway, it will appear as a duplicate message"))); - } - - if (newCorrectingAlert) { - if (correctingAlert_) { - removeAlert(*correctingAlert_); - } - correctingAlert_ = newCorrectingAlert; - } - - QTextCursor cursor = input_->textCursor(); - cursor.select(QTextCursor::Document); - cursor.beginEditBlock(); - cursor.insertText(QString(lastSentMessage_)); - cursor.endEditBlock(); - isCorrection_ = true; - correctingLabel_->show(); - input_->setStyleSheet(alertStyleSheet_); - labelsWidget_->setEnabled(false); + boost::optional newCorrectingAlert; + if (correctionEnabled_ == Maybe) { + newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat may not support message correction. If you send a correction anyway, it may appear as a duplicate message"))); + } + else if (correctionEnabled_ == No) { + newCorrectingAlert = addAlert(Q2PSTRING(tr("This chat does not support message correction. If you send a correction anyway, it will appear as a duplicate message"))); + } + + if (newCorrectingAlert) { + if (correctingAlert_) { + removeAlert(*correctingAlert_); + } + correctingAlert_ = newCorrectingAlert; + } + + QTextCursor cursor = input_->textCursor(); + cursor.select(QTextCursor::Document); + cursor.beginEditBlock(); + cursor.insertText(QString(lastSentMessage_)); + cursor.endEditBlock(); + isCorrection_ = true; + correctingLabel_->show(); + input_->setStyleSheet(alertStyleSheet_); + labelsWidget_->setEnabled(false); } void QtChatWindow::cancelCorrection() { - if (correctingAlert_) { - removeAlert(*correctingAlert_); - correctingAlert_.reset(); - } - QTextCursor cursor = input_->textCursor(); - cursor.select(QTextCursor::Document); - cursor.removeSelectedText(); - isCorrection_ = false; - correctingLabel_->hide(); - input_->setStyleSheet(qApp->styleSheet()); - labelsWidget_->setEnabled(true); + if (correctingAlert_) { + removeAlert(*correctingAlert_); + correctingAlert_.reset(); + } + QTextCursor cursor = input_->textCursor(); + cursor.select(QTextCursor::Document); + cursor.removeSelectedText(); + isCorrection_ = false; + correctingLabel_->hide(); + input_->setStyleSheet(qApp->styleSheet()); + labelsWidget_->setEnabled(true); } QByteArray QtChatWindow::getSplitterState() { - return logRosterSplitter_->saveState(); + return logRosterSplitter_->saveState(); } void QtChatWindow::handleChangeSplitterState(QByteArray state) { - logRosterSplitter_->restoreState(state); + logRosterSplitter_->restoreState(state); } void QtChatWindow::handleSplitterMoved(int, int) { - emit splitterMoved(); + emit splitterMoved(); } void QtChatWindow::tabComplete() { - if (!completer_) { - return; - } - - QTextCursor cursor; - if (tabCompleteCursor_.hasSelection()) { - cursor = tabCompleteCursor_; - } - else { - cursor = input_->textCursor(); - while(cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor) && cursor.document()->characterAt(cursor.position() - 1) != ' ') { } - } - QString root = cursor.selectedText(); - if (root.isEmpty()) { - return; - } - QString suggestion = P2QSTRING(completer_->completeWord(Q2PSTRING(root))); - if (root == suggestion) { - return; - } - tabCompletion_ = true; - cursor.beginEditBlock(); - cursor.removeSelectedText(); - int oldPosition = cursor.position(); - - cursor.insertText(suggestion); - tabCompleteCursor_ = cursor; - tabCompleteCursor_.setPosition(oldPosition, QTextCursor::KeepAnchor); - - cursor.endEditBlock(); - tabCompletion_ = false; + if (!completer_) { + return; + } + + QTextCursor cursor; + if (tabCompleteCursor_.hasSelection()) { + cursor = tabCompleteCursor_; + } + else { + cursor = input_->textCursor(); + while(cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor) && cursor.document()->characterAt(cursor.position() - 1) != ' ') { } + } + QString root = cursor.selectedText(); + if (root.isEmpty()) { + return; + } + QString suggestion = P2QSTRING(completer_->completeWord(Q2PSTRING(root))); + if (root == suggestion) { + return; + } + tabCompletion_ = true; + cursor.beginEditBlock(); + cursor.removeSelectedText(); + int oldPosition = cursor.position(); + + cursor.insertText(suggestion); + tabCompleteCursor_ = cursor; + tabCompleteCursor_.setPosition(oldPosition, QTextCursor::KeepAnchor); + + cursor.endEditBlock(); + tabCompletion_ = false; } void QtChatWindow::setRosterModel(Roster* roster) { - treeWidget_->setRosterModel(roster); + treeWidget_->setRosterModel(roster); } void QtChatWindow::setAvailableSecurityLabels(const std::vector& labels) { - delete labelModel_; - labelModel_ = new LabelModel(); - labelModel_->availableLabels_ = labels; - int i = 0; - int defaultIndex = 0; - labelsWidget_->setModel(labelModel_); - foreach (SecurityLabelsCatalog::Item label, labels) { - if (label.getIsDefault()) { - defaultIndex = i; - break; - } - i++; - } - labelsWidget_->setCurrentIndex(defaultIndex); + delete labelModel_; + labelModel_ = new LabelModel(); + labelModel_->availableLabels_ = labels; + int i = 0; + int defaultIndex = 0; + labelsWidget_->setModel(labelModel_); + foreach (SecurityLabelsCatalog::Item label, labels) { + if (label.getIsDefault()) { + defaultIndex = i; + break; + } + i++; + } + labelsWidget_->setCurrentIndex(defaultIndex); } void QtChatWindow::handleCurrentLabelChanged(int index) { - if (static_cast(index) >= labelModel_->availableLabels_.size()) { - SWIFT_LOG(debug) << "User selected a label that doesn't exist"; - return; - } - const SecurityLabelsCatalog::Item& label = labelModel_->availableLabels_[index]; - if (label.getLabel()) { - QPalette palette = labelsWidget_->palette(); - //palette.setColor(QPalette::Base, P2QSTRING(label.getLabel()->getBackgroundColor())); - palette.setColor(labelsWidget_->backgroundRole(), P2QSTRING(label.getLabel()->getBackgroundColor())); - palette.setColor(labelsWidget_->foregroundRole(), P2QSTRING(label.getLabel()->getForegroundColor())); - labelsWidget_->setPalette(palette); - midBar_->setPalette(palette); - labelsWidget_->setAutoFillBackground(true); - } - else { - labelsWidget_->setAutoFillBackground(false); - labelsWidget_->setPalette(defaultLabelsPalette_); - midBar_->setPalette(defaultLabelsPalette_); - } + if (static_cast(index) >= labelModel_->availableLabels_.size()) { + SWIFT_LOG(debug) << "User selected a label that doesn't exist"; + return; + } + const SecurityLabelsCatalog::Item& label = labelModel_->availableLabels_[index]; + if (label.getLabel()) { + QPalette palette = labelsWidget_->palette(); + //palette.setColor(QPalette::Base, P2QSTRING(label.getLabel()->getBackgroundColor())); + palette.setColor(labelsWidget_->backgroundRole(), P2QSTRING(label.getLabel()->getBackgroundColor())); + palette.setColor(labelsWidget_->foregroundRole(), P2QSTRING(label.getLabel()->getForegroundColor())); + labelsWidget_->setPalette(palette); + midBar_->setPalette(palette); + labelsWidget_->setAutoFillBackground(true); + } + else { + labelsWidget_->setAutoFillBackground(false); + labelsWidget_->setPalette(defaultLabelsPalette_); + midBar_->setPalette(defaultLabelsPalette_); + } } void QtChatWindow::setSecurityLabelsError() { - labelsWidget_->setEnabled(false); + labelsWidget_->setEnabled(false); } void QtChatWindow::setSecurityLabelsEnabled(bool enabled) { - if (enabled) { - labelsWidget_->setEnabled(true); - labelsWidget_->show(); - } - else { - labelsWidget_->hide(); - } + if (enabled) { + labelsWidget_->setEnabled(true); + labelsWidget_->show(); + } + else { + labelsWidget_->hide(); + } } void QtChatWindow::setCorrectionEnabled(Tristate enabled) { - correctionEnabled_ = enabled; + correctionEnabled_ = enabled; } void QtChatWindow::setFileTransferEnabled(Tristate enabled) { - fileTransferEnabled_ = enabled; + fileTransferEnabled_ = enabled; } SecurityLabelsCatalog::Item QtChatWindow::getSelectedSecurityLabel() { - assert(labelsWidget_->isEnabled()); - assert(labelsWidget_->currentIndex() >= 0 && static_cast(labelsWidget_->currentIndex()) < labelModel_->availableLabels_.size()); - return labelModel_->availableLabels_[labelsWidget_->currentIndex()]; + assert(labelsWidget_->isEnabled()); + assert(labelsWidget_->currentIndex() >= 0 && static_cast(labelsWidget_->currentIndex()) < labelModel_->availableLabels_.size()); + return labelModel_->availableLabels_[labelsWidget_->currentIndex()]; } void QtChatWindow::closeEvent(QCloseEvent* event) { - event->accept(); - emit windowClosing(); - onClosed(); + event->accept(); + emit windowClosing(); + onClosed(); } void QtChatWindow::convertToMUC(MUCType mucType) { - impromptu_ = (mucType == ImpromptuMUC); - treeWidget_->setMessageTarget(impromptu_ ? QtTreeWidget::MessageDisplayJID : QtTreeWidget::MessageDefaultJID); - isMUC_ = true; - treeWidget_->show(); - subject_->setVisible(!impromptu_); + impromptu_ = (mucType == ImpromptuMUC); + treeWidget_->setMessageTarget(impromptu_ ? QtTreeWidget::MessageDisplayJID : QtTreeWidget::MessageDefaultJID); + isMUC_ = true; + treeWidget_->show(); + subject_->setVisible(!impromptu_); } void QtChatWindow::setOnline(bool online) { - isOnline_ = online; - if (!online) { - if (mucConfigurationWindow_) { - delete mucConfigurationWindow_.data(); - } - if (affiliationEditor_) { - delete affiliationEditor_.data(); - } - } + isOnline_ = online; + if (!online) { + if (mucConfigurationWindow_) { + delete mucConfigurationWindow_.data(); + } + if (affiliationEditor_) { + delete affiliationEditor_.data(); + } + } } void QtChatWindow::showEvent(QShowEvent* event) { - emit windowOpening(); - QWidget::showEvent(event); + emit windowOpening(); + QWidget::showEvent(event); } void QtChatWindow::setUnreadMessageCount(int count) { - if (unreadCount_ != count) { - unreadCount_ = count; - updateTitleWithUnreadCount(); - emit countUpdated(); - } + if (unreadCount_ != count) { + unreadCount_ = count; + updateTitleWithUnreadCount(); + emit countUpdated(); + } } void QtChatWindow::setContactChatState(ChatState::ChatStateType state) { - contactIsTyping_ = (state == ChatState::Composing); - emit titleUpdated(); + contactIsTyping_ = (state == ChatState::Composing); + emit titleUpdated(); } QtTabbable::AlertType QtChatWindow::getWidgetAlertState() { - if (contactIsTyping_) { - return ImpendingActivity; - } - if (unreadCount_ > 0) { - return WaitingActivity; - } - return NoActivity; + if (contactIsTyping_) { + return ImpendingActivity; + } + if (unreadCount_ > 0) { + return WaitingActivity; + } + return NoActivity; } void QtChatWindow::setName(const std::string& name) { - contact_ = P2QSTRING(name); - updateTitleWithUnreadCount(); + contact_ = P2QSTRING(name); + updateTitleWithUnreadCount(); } void QtChatWindow::updateTitleWithUnreadCount() { - if (isWindow()) { - setWindowTitle(unreadCount_ > 0 ? QString("(%1) %2").arg(unreadCount_).arg(contact_) : contact_); - } - else { - setWindowTitle(contact_); - } - emit titleUpdated(); + if (isWindow()) { + setWindowTitle(unreadCount_ > 0 ? QString("(%1) %2").arg(unreadCount_).arg(contact_) : contact_); + } + else { + setWindowTitle(contact_); + } + emit titleUpdated(); } void QtChatWindow::flash() { - emit requestFlash(); + emit requestFlash(); } int QtChatWindow::getCount() { - return unreadCount_; + return unreadCount_; } void QtChatWindow::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour timestampBehaviour) { - messageLog_->replaceSystemMessage(message, id, timestampBehaviour); + messageLog_->replaceSystemMessage(message, id, timestampBehaviour); } void QtChatWindow::returnPressed() { - if (!isOnline_ || (blockingState_ == IsBlocked)) { - return; - } - messageLog_->scrollToBottom(); - lastSentMessage_ = QString(input_->toPlainText()); - onSendMessageRequest(Q2PSTRING(input_->toPlainText()), isCorrection_); - inputClearing_ = true; - input_->clear(); - cancelCorrection(); - inputClearing_ = false; + if (!isOnline_ || (blockingState_ == IsBlocked)) { + return; + } + messageLog_->scrollToBottom(); + lastSentMessage_ = QString(input_->toPlainText()); + onSendMessageRequest(Q2PSTRING(input_->toPlainText()), isCorrection_); + inputClearing_ = true; + input_->clear(); + cancelCorrection(); + inputClearing_ = false; } void QtChatWindow::handleInputChanged() { - if (inputClearing_) { - return; - } - if (input_->toPlainText().isEmpty()) { - onUserCancelsTyping(); - } - else { - onUserTyping(); - } + if (inputClearing_) { + return; + } + if (input_->toPlainText().isEmpty()) { + onUserCancelsTyping(); + } + else { + onUserTyping(); + } } void QtChatWindow::handleCursorPositionChanged() { - if (tabCompletion_) { - return; - } - tabCompleteCursor_.clearSelection(); + if (tabCompletion_) { + return; + } + tabCompleteCursor_.clearSelection(); } void QtChatWindow::show() { - if (parentWidget() == NULL) { - QWidget::show(); - } - emit windowOpening(); + if (parentWidget() == NULL) { + QWidget::show(); + } + emit windowOpening(); } bool QtChatWindow::isVisible() const { - return QWidget::isVisible(); + return QWidget::isVisible(); } void QtChatWindow::activate() { - if (isWindow()) { - QWidget::show(); - } - emit wantsToActivate(); - input_->setFocus(); + if (isWindow()) { + QWidget::show(); + } + emit wantsToActivate(); + input_->setFocus(); } void QtChatWindow::resizeEvent(QResizeEvent*) { - emit geometryChanged(); + emit geometryChanged(); } void QtChatWindow::moveEvent(QMoveEvent*) { - emit geometryChanged(); + emit geometryChanged(); } void QtChatWindow::dragEnterEvent(QDragEnterEvent *event) { - if (isOnline_ && (blockingState_ != IsBlocked)) { - if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) { - if (!isMUC_ && fileTransferEnabled_ == Yes) { - event->acceptProposedAction(); - } - } - else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) { - if (isMUC_ || supportsImpromptuChat_) { - // Prevent invitations or impromptu initializations for contacts that you are already chatting to. - std::vector droppedJIDs =jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list")); - std::set conversationJIDs; - if (isMUC_) { - conversationJIDs = treeWidget_->getRoster()->getJIDs(); - } - - for (std::vector::iterator i = droppedJIDs.begin(); i != droppedJIDs.end(); ) { - const JID& droppedJID = *i; - if (conversationJIDs.find(droppedJID) != conversationJIDs.end()) { - i = droppedJIDs.erase(i); - } - else { - ++i; - } - } - - if (droppedJIDs.empty()) { - event->ignore(); - } - else { - event->acceptProposedAction(); - } - } - } - } + if (isOnline_ && (blockingState_ != IsBlocked)) { + if (event->mimeData()->hasUrls() && event->mimeData()->urls().size() == 1) { + if (!isMUC_ && fileTransferEnabled_ == Yes) { + event->acceptProposedAction(); + } + } + else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) { + if (isMUC_ || supportsImpromptuChat_) { + // Prevent invitations or impromptu initializations for contacts that you are already chatting to. + std::vector droppedJIDs =jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list")); + std::set conversationJIDs; + if (isMUC_) { + conversationJIDs = treeWidget_->getRoster()->getJIDs(); + } + + for (std::vector::iterator i = droppedJIDs.begin(); i != droppedJIDs.end(); ) { + const JID& droppedJID = *i; + if (conversationJIDs.find(droppedJID) != conversationJIDs.end()) { + i = droppedJIDs.erase(i); + } + else { + ++i; + } + } + + if (droppedJIDs.empty()) { + event->ignore(); + } + else { + event->acceptProposedAction(); + } + } + } + } } void QtChatWindow::dropEvent(QDropEvent *event) { - if (fileTransferEnabled_ == Yes && event->mimeData()->hasUrls()) { - if (event->mimeData()->urls().size() == 1) { - onSendFileRequest(Q2PSTRING(event->mimeData()->urls().at(0).toLocalFile())); - } - else { - std::string messageText(Q2PSTRING(tr("Sending of multiple files at once isn't supported at this time."))); - ChatMessage message; - message.append(boost::make_shared(messageText)); - addSystemMessage(message, DefaultDirection); - } - } - else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) { - std::vector invites = jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list")); - onInviteToChat(invites); - } + if (fileTransferEnabled_ == Yes && event->mimeData()->hasUrls()) { + if (event->mimeData()->urls().size() == 1) { + onSendFileRequest(Q2PSTRING(event->mimeData()->urls().at(0).toLocalFile())); + } + else { + std::string messageText(Q2PSTRING(tr("Sending of multiple files at once isn't supported at this time."))); + ChatMessage message; + message.append(boost::make_shared(messageText)); + addSystemMessage(message, DefaultDirection); + } + } + else if (event->mimeData()->hasFormat("application/vnd.swift.contact-jid-list")) { + std::vector invites = jidListFromQByteArray(event->mimeData()->data("application/vnd.swift.contact-jid-list")); + onInviteToChat(invites); + } } std::vector QtChatWindow::jidListFromQByteArray(const QByteArray& dataBytes) { - QDataStream dataStream(dataBytes); - std::vector invites; - while (!dataStream.atEnd()) { - QString jidString; - dataStream >> jidString; - invites.push_back(Q2PSTRING(jidString)); - } - return invites; + QDataStream dataStream(dataBytes); + std::vector invites; + while (!dataStream.atEnd()) { + QString jidString; + dataStream >> jidString; + invites.push_back(Q2PSTRING(jidString)); + } + return invites; } void QtChatWindow::setAvailableOccupantActions(const std::vector& actions) { - treeWidget_->setAvailableOccupantActions(actions); + treeWidget_->setAvailableOccupantActions(actions); } void QtChatWindow::setSubject(const std::string& subject) { - //subject_->setVisible(!subject.empty()); - subject_->setText(P2QSTRING(subject)); - subject_->setToolTip(P2QSTRING(subject)); - subject_->setCursorPosition(0); + //subject_->setVisible(!subject.empty()); + subject_->setText(P2QSTRING(subject)); + subject_->setToolTip(P2QSTRING(subject)); + subject_->setCursorPosition(0); } void QtChatWindow::handleEmoticonsButtonClicked() { - emoticonsMenu_->adjustSize(); - QSize menuSize = emoticonsMenu_->size(); - emoticonsMenu_->exec(QPoint(QCursor::pos().x() - menuSize.width(), QCursor::pos().y() - menuSize.height())); + emoticonsMenu_->adjustSize(); + QSize menuSize = emoticonsMenu_->size(); + emoticonsMenu_->exec(QPoint(QCursor::pos().x() - menuSize.width(), QCursor::pos().y() - menuSize.height())); } void QtChatWindow::handleEmoticonClicked(QString emoticonAsText) { - input_->textCursor().insertText(emoticonAsText); - input_->setFocus(); + input_->textCursor().insertText(emoticonAsText); + input_->setFocus(); } void QtChatWindow::handleTextInputReceivedFocus() { - lastLineTracker_.setHasFocus(true); - input_->setFocus(); - onAllMessagesRead(); + lastLineTracker_.setHasFocus(true); + input_->setFocus(); + onAllMessagesRead(); } void QtChatWindow::handleTextInputLostFocus() { - lastLineTracker_.setHasFocus(false); + lastLineTracker_.setHasFocus(false); } void QtChatWindow::handleActionButtonClicked() { - QMenu contextMenu; - QAction* changeSubject = NULL; - QAction* configure = NULL; - QAction* affiliations = NULL; - QAction* destroy = NULL; - QAction* invite = NULL; - - QAction* block = NULL; - QAction* unblock = NULL; - - if (availableRoomActions_.empty()) { - if (blockingState_ == IsBlocked) { - unblock = contextMenu.addAction(tr("Unblock")); - unblock->setEnabled(isOnline_); - } - else if (!isMUC_ && blockingState_ == IsUnblocked) { - block = contextMenu.addAction(tr("Block")); - block->setEnabled(isOnline_); - } - - if (supportsImpromptuChat_) { - invite = contextMenu.addAction(tr("Invite person to this chat…")); - invite->setEnabled(isOnline_ && (blockingState_ != IsBlocked)); - } - - } - else { - foreach(ChatWindow::RoomAction availableAction, availableRoomActions_) - { - if (impromptu_) { - // hide options we don't need in impromptu chats - if (availableAction == ChatWindow::ChangeSubject || - availableAction == ChatWindow::Configure || - availableAction == ChatWindow::Affiliations || - availableAction == ChatWindow::Destroy) { - continue; - } - } - switch(availableAction) - { - case ChatWindow::ChangeSubject: - changeSubject = contextMenu.addAction(tr("Change subject…")); - changeSubject->setEnabled(isOnline_); - break; - case ChatWindow::Configure: - configure = contextMenu.addAction(tr("Configure room…")); - configure->setEnabled(isOnline_); - break; - case ChatWindow::Affiliations: - affiliations = contextMenu.addAction(tr("Edit affiliations…")); - affiliations->setEnabled(isOnline_); - break; - case ChatWindow::Destroy: - destroy = contextMenu.addAction(tr("Destroy room")); - destroy->setEnabled(isOnline_); - break; - case ChatWindow::Invite: - invite = contextMenu.addAction(tr("Invite person to this room…")); - invite->setEnabled(isOnline_); - break; - } - } - } - - QAction* bookmark = NULL; - if (isMUC_) { - if (roomBookmarkState_ == RoomNotBookmarked) { - bookmark = contextMenu.addAction(tr("Bookmark this room...")); - } - else { - bookmark = contextMenu.addAction(tr("Edit bookmark...")); - } - bookmark->setEnabled(isOnline_); - } - - QAction* result = contextMenu.exec(QCursor::pos()); - if (result == NULL) { - /* Skip processing. Note that otherwise, because the actions could be null they could match */ - } - else if (result == changeSubject) { - bool ok; - QString subject = QInputDialog::getText(this, tr("Change room subject"), tr("New subject:"), QLineEdit::Normal, subject_->text(), &ok); - if (ok) { - onChangeSubjectRequest(Q2PSTRING(subject)); - } - } - else if (result == configure) { - onConfigureRequest(Form::ref()); - } - else if (result == affiliations) { - if (!affiliationEditor_) { - onGetAffiliationsRequest(); - affiliationEditor_ = new QtAffiliationEditor(this); - connect(affiliationEditor_, SIGNAL(accepted()), this, SLOT(handleAffiliationEditorAccepted())); - } - affiliationEditor_->show(); - } - else if (result == destroy) { - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Confirm room destruction")); - msgBox.setText(tr("Are you sure you want to destroy the room?")); - msgBox.setInformativeText(tr("This will destroy the room.")); - msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); - msgBox.setDefaultButton(QMessageBox::No); - if (msgBox.exec() == QMessageBox::Yes) { - onDestroyRequest(); - } - } - else if (result == invite) { - onInviteToChat(std::vector()); - } - else if (result == block) { - onBlockUserRequest(); - } - else if (result == unblock) { - onUnblockUserRequest(); - } - else if (result == bookmark) { - onBookmarkRequest(); - } + QMenu contextMenu; + QAction* changeSubject = NULL; + QAction* configure = NULL; + QAction* affiliations = NULL; + QAction* destroy = NULL; + QAction* invite = NULL; + + QAction* block = NULL; + QAction* unblock = NULL; + + if (availableRoomActions_.empty()) { + if (blockingState_ == IsBlocked) { + unblock = contextMenu.addAction(tr("Unblock")); + unblock->setEnabled(isOnline_); + } + else if (!isMUC_ && blockingState_ == IsUnblocked) { + block = contextMenu.addAction(tr("Block")); + block->setEnabled(isOnline_); + } + + if (supportsImpromptuChat_) { + invite = contextMenu.addAction(tr("Invite person to this chat…")); + invite->setEnabled(isOnline_ && (blockingState_ != IsBlocked)); + } + + } + else { + foreach(ChatWindow::RoomAction availableAction, availableRoomActions_) + { + if (impromptu_) { + // hide options we don't need in impromptu chats + if (availableAction == ChatWindow::ChangeSubject || + availableAction == ChatWindow::Configure || + availableAction == ChatWindow::Affiliations || + availableAction == ChatWindow::Destroy) { + continue; + } + } + switch(availableAction) + { + case ChatWindow::ChangeSubject: + changeSubject = contextMenu.addAction(tr("Change subject…")); + changeSubject->setEnabled(isOnline_); + break; + case ChatWindow::Configure: + configure = contextMenu.addAction(tr("Configure room…")); + configure->setEnabled(isOnline_); + break; + case ChatWindow::Affiliations: + affiliations = contextMenu.addAction(tr("Edit affiliations…")); + affiliations->setEnabled(isOnline_); + break; + case ChatWindow::Destroy: + destroy = contextMenu.addAction(tr("Destroy room")); + destroy->setEnabled(isOnline_); + break; + case ChatWindow::Invite: + invite = contextMenu.addAction(tr("Invite person to this room…")); + invite->setEnabled(isOnline_); + break; + } + } + } + + QAction* bookmark = NULL; + if (isMUC_) { + if (roomBookmarkState_ == RoomNotBookmarked) { + bookmark = contextMenu.addAction(tr("Bookmark this room...")); + } + else { + bookmark = contextMenu.addAction(tr("Edit bookmark...")); + } + bookmark->setEnabled(isOnline_); + } + + QAction* result = contextMenu.exec(QCursor::pos()); + if (result == NULL) { + /* Skip processing. Note that otherwise, because the actions could be null they could match */ + } + else if (result == changeSubject) { + bool ok; + QString subject = QInputDialog::getText(this, tr("Change room subject"), tr("New subject:"), QLineEdit::Normal, subject_->text(), &ok); + if (ok) { + onChangeSubjectRequest(Q2PSTRING(subject)); + } + } + else if (result == configure) { + onConfigureRequest(Form::ref()); + } + else if (result == affiliations) { + if (!affiliationEditor_) { + onGetAffiliationsRequest(); + affiliationEditor_ = new QtAffiliationEditor(this); + connect(affiliationEditor_, SIGNAL(accepted()), this, SLOT(handleAffiliationEditorAccepted())); + } + affiliationEditor_->show(); + } + else if (result == destroy) { + QMessageBox msgBox; + msgBox.setWindowTitle(tr("Confirm room destruction")); + msgBox.setText(tr("Are you sure you want to destroy the room?")); + msgBox.setInformativeText(tr("This will destroy the room.")); + msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); + msgBox.setDefaultButton(QMessageBox::No); + if (msgBox.exec() == QMessageBox::Yes) { + onDestroyRequest(); + } + } + else if (result == invite) { + onInviteToChat(std::vector()); + } + else if (result == block) { + onBlockUserRequest(); + } + else if (result == unblock) { + onUnblockUserRequest(); + } + else if (result == bookmark) { + onBookmarkRequest(); + } } void QtChatWindow::handleAffiliationEditorAccepted() { - onChangeAffiliationsRequest(affiliationEditor_->getChanges()); + onChangeAffiliationsRequest(affiliationEditor_->getChanges()); } void QtChatWindow::setAffiliations(MUCOccupant::Affiliation affiliation, const std::vector& jids) { - if (!affiliationEditor_) return; - affiliationEditor_->setAffiliations(affiliation, jids); + if (!affiliationEditor_) return; + affiliationEditor_->setAffiliations(affiliation, jids); } void QtChatWindow::setAvailableRoomActions(const std::vector& actions) { - availableRoomActions_ = actions; + availableRoomActions_ = actions; } void QtChatWindow::setBlockingState(BlockingState state) { - blockingState_ = state; + blockingState_ = state; } void QtChatWindow::setCanInitiateImpromptuChats(bool supportsImpromptu) { - supportsImpromptuChat_ = supportsImpromptu; + supportsImpromptuChat_ = supportsImpromptu; } void QtChatWindow::showBookmarkWindow(const MUCBookmark& bookmark) { - if (roomBookmarkState_ == RoomNotBookmarked) { - QtAddBookmarkWindow* window = new QtAddBookmarkWindow(eventStream_, bookmark); - window->show(); - } - else { - QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, bookmark); - window->show(); - } + if (roomBookmarkState_ == RoomNotBookmarked) { + QtAddBookmarkWindow* window = new QtAddBookmarkWindow(eventStream_, bookmark); + window->show(); + } + else { + QtEditBookmarkWindow* window = new QtEditBookmarkWindow(eventStream_, bookmark); + window->show(); + } } std::string QtChatWindow::getID() const { - return id_; + return id_; } void QtChatWindow::showRoomConfigurationForm(Form::ref form) { - if (mucConfigurationWindow_) { - delete mucConfigurationWindow_.data(); - } - mucConfigurationWindow_ = new QtMUCConfigurationWindow(form); - mucConfigurationWindow_->onFormComplete.connect(boost::bind(boost::ref(onConfigureRequest), _1)); - mucConfigurationWindow_->onFormCancelled.connect(boost::bind(boost::ref(onConfigurationFormCancelled))); + if (mucConfigurationWindow_) { + delete mucConfigurationWindow_.data(); + } + mucConfigurationWindow_ = new QtMUCConfigurationWindow(form); + mucConfigurationWindow_->onFormComplete.connect(boost::bind(boost::ref(onConfigureRequest), _1)); + mucConfigurationWindow_->onFormCancelled.connect(boost::bind(boost::ref(onConfigurationFormCancelled))); } void QtChatWindow::handleAppendedToLog() { - if (lastLineTracker_.getShouldMoveLastLine()) { - /* should this be queued? */ - messageLog_->addLastSeenLine(); - } - if (isWidgetSelected()) { - onAllMessagesRead(); - } + if (lastLineTracker_.getShouldMoveLastLine()) { + /* should this be queued? */ + messageLog_->addLastSeenLine(); + } + if (isWidgetSelected()) { + onAllMessagesRead(); + } } void QtChatWindow::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct, bool isImpromptu, bool isContinuation) { - handleAppendedToLog(); - messageLog_->addMUCInvitation(senderName, jid, reason, password, direct, isImpromptu, isContinuation); + handleAppendedToLog(); + messageLog_->addMUCInvitation(senderName, jid, reason, password, direct, isImpromptu, isContinuation); } std::string QtChatWindow::addMessage(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) { - handleAppendedToLog(); - return messageLog_->addMessage(message, senderName, senderIsSelf, label, avatarPath, time); + handleAppendedToLog(); + return messageLog_->addMessage(message, senderName, senderIsSelf, label, avatarPath, time); } std::string QtChatWindow::addAction(const ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time) { - handleAppendedToLog(); - return messageLog_->addAction(message, senderName, senderIsSelf, label, avatarPath, time); + handleAppendedToLog(); + return messageLog_->addAction(message, senderName, senderIsSelf, label, avatarPath, time); } std::string QtChatWindow::addSystemMessage(const ChatMessage& message, Direction direction) { - handleAppendedToLog(); - return messageLog_->addSystemMessage(message, direction); + handleAppendedToLog(); + return messageLog_->addSystemMessage(message, direction); } void QtChatWindow::addPresenceMessage(const ChatMessage& message, Direction direction) { - handleAppendedToLog(); - messageLog_->addPresenceMessage(message, direction); + handleAppendedToLog(); + messageLog_->addPresenceMessage(message, direction); } void QtChatWindow::addErrorMessage(const ChatMessage& message) { - handleAppendedToLog(); - messageLog_->addErrorMessage(message); + handleAppendedToLog(); + messageLog_->addErrorMessage(message); } void QtChatWindow::replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) { - handleAppendedToLog(); - messageLog_->replaceMessage(message, id, time); + handleAppendedToLog(); + messageLog_->replaceMessage(message, id, time); } void QtChatWindow::replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) { - handleAppendedToLog(); - messageLog_->replaceWithAction(message, id, time); + handleAppendedToLog(); + messageLog_->replaceWithAction(message, id, time); } std::string QtChatWindow::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) { - handleAppendedToLog(); - return messageLog_->addFileTransfer(senderName, senderIsSelf, filename, sizeInBytes, description); + handleAppendedToLog(); + return messageLog_->addFileTransfer(senderName, senderIsSelf, filename, sizeInBytes, description); } void QtChatWindow::setFileTransferProgress(std::string id, const int percentageDone) { - messageLog_->setFileTransferProgress(id, percentageDone); + messageLog_->setFileTransferProgress(id, percentageDone); } void QtChatWindow::setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg) { - messageLog_->setFileTransferStatus(id, state, msg); + messageLog_->setFileTransferStatus(id, state, msg); } std::string QtChatWindow::addWhiteboardRequest(bool senderIsSelf) { - handleAppendedToLog(); - return messageLog_->addWhiteboardRequest(contact_, senderIsSelf); + handleAppendedToLog(); + return messageLog_->addWhiteboardRequest(contact_, senderIsSelf); } void QtChatWindow::setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state) { - messageLog_->setWhiteboardSessionStatus(id, state); + messageLog_->setWhiteboardSessionStatus(id, state); } void QtChatWindow::replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour) { - messageLog_->replaceLastMessage(message, timestampBehaviour); + messageLog_->replaceLastMessage(message, timestampBehaviour); } void QtChatWindow::setAckState(const std::string& id, AckState state) { - messageLog_->setAckState(id, state); + messageLog_->setAckState(id, state); } void QtChatWindow::setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state) { - messageLog_->setMessageReceiptState(id, state); + messageLog_->setMessageReceiptState(id, state); } void QtChatWindow::setBookmarkState(RoomBookmarkState bookmarkState) { - roomBookmarkState_ = bookmarkState; + roomBookmarkState_ = bookmarkState; } } diff --git a/Swift/QtUI/QtChatWindow.h b/Swift/QtUI/QtChatWindow.h index 8acb10c..2a23f5f 100644 --- a/Swift/QtUI/QtChatWindow.h +++ b/Swift/QtUI/QtChatWindow.h @@ -32,203 +32,203 @@ class QSplitter; class QPushButton; namespace Swift { - class QtChatView; - class QtOccupantListWidget; - class QtChatTheme; - class TreeWidget; - class QtTextEdit; - class UIEventStream; - class QtChatWindowJSBridge; - class SettingsProvider; - class QtEmoticonsGrid; - - class LabelModel : public QAbstractListModel { - Q_OBJECT - public: - LabelModel(QObject* parent = NULL) : QAbstractListModel(parent) {} - - virtual int rowCount(const QModelIndex& /*index*/) const { - return static_cast(availableLabels_.size()); - } - - virtual QVariant data(const QModelIndex& index, int role) const { - if (!index.isValid()) { - return QVariant(); - } - boost::shared_ptr label = availableLabels_[index.row()].getLabel(); - if (label && role == Qt::TextColorRole) { - return P2QSTRING(label->getForegroundColor()); - } - if (label && role == Qt::TextColorRole) { - return P2QSTRING(label->getBackgroundColor()); - } - if (role == Qt::DisplayRole) { - std::string selector = availableLabels_[index.row()].getSelector(); - std::string displayMarking = label ? label->getDisplayMarking() : ""; - QString labelName = selector.empty() ? displayMarking.c_str() : selector.c_str(); - return labelName; - } - return QVariant(); - } - - std::vector availableLabels_; - }; - - class QtChatWindow : public QtTabbable, public ChatWindow { - Q_OBJECT - - public: - QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map& emoticons); - virtual ~QtChatWindow(); - std::string addMessage(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time); - std::string addAction(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time); - - std::string addSystemMessage(const ChatMessage& message, Direction direction); - void addPresenceMessage(const ChatMessage& message, Direction direction); - void addErrorMessage(const ChatMessage& message); - - void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time); - void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time); - // File transfer related stuff - std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description); - void setFileTransferProgress(std::string id, const int percentageDone); - void setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg); - - std::string addWhiteboardRequest(bool senderIsSelf); - void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state); - - void show(); - bool isVisible() const; - void activate(); - void setUnreadMessageCount(int count); - void convertToMUC(MUCType mucType); -// TreeWidget *getTreeWidget(); - void setAvailableSecurityLabels(const std::vector& labels); - void setSecurityLabelsEnabled(bool enabled); - void setSecurityLabelsError(); - SecurityLabelsCatalog::Item getSelectedSecurityLabel(); - void setName(const std::string& name); - void setOnline(bool online); - QtTabbable::AlertType getWidgetAlertState(); - void setContactChatState(ChatState::ChatStateType state); - void setRosterModel(Roster* roster); - void setTabComplete(TabComplete* completer); - int getCount(); - virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour); - void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour); - void setAckState(const std::string& id, AckState state); - - // message receipts - void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state); - - void flash(); - QByteArray getSplitterState(); - virtual void setAvailableOccupantActions(const std::vector& actions); - void setSubject(const std::string& subject); - void showRoomConfigurationForm(Form::ref); - void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false); - void setAffiliations(MUCOccupant::Affiliation, const std::vector&); - void setAvailableRoomActions(const std::vector& actions); - void setBlockingState(BlockingState state); - virtual void setCanInitiateImpromptuChats(bool supportsImpromptu); - virtual void showBookmarkWindow(const MUCBookmark& bookmark); - virtual void setBookmarkState(RoomBookmarkState bookmarkState); - virtual std::string getID() const; - - public slots: - void handleChangeSplitterState(QByteArray state); - void handleFontResized(int fontSizeSteps); - AlertID addAlert(const std::string& alertText); - void removeAlert(const AlertID id); - void setCorrectionEnabled(Tristate enabled); - void setFileTransferEnabled(Tristate enabled); - - signals: - void geometryChanged(); - void splitterMoved(); - void fontResized(int); - - protected slots: - void closeEvent(QCloseEvent* event); - void resizeEvent(QResizeEvent* event); - void moveEvent(QMoveEvent* event); - - void dragEnterEvent(QDragEnterEvent *event); - void dropEvent(QDropEvent *event); - - protected: - void showEvent(QShowEvent* event); - - private slots: - void handleLogCleared(); - void returnPressed(); - void handleInputChanged(); - void handleCursorPositionChanged(); - void handleKeyPressEvent(QKeyEvent* event); - void handleSplitterMoved(int pos, int index); - void handleAlertButtonClicked(); - void handleActionButtonClicked(); - void handleAffiliationEditorAccepted(); - void handleCurrentLabelChanged(int); - void handleEmoticonsButtonClicked(); - void handleEmoticonClicked(QString emoticonAsText); - void handleTextInputReceivedFocus(); - void handleTextInputLostFocus(); - - private: - void updateTitleWithUnreadCount(); - void tabComplete(); - void beginCorrection(); - void cancelCorrection(); - void handleSettingChanged(const std::string& setting); - - void handleOccupantSelectionChanged(RosterItem* item); - void handleAppendedToLog(); - - static std::vector jidListFromQByteArray(const QByteArray& dataBytes); - - private: - int unreadCount_; - bool contactIsTyping_; - LastLineTracker lastLineTracker_; - std::string id_; - QString contact_; - QString lastSentMessage_; - QTextCursor tabCompleteCursor_; - QtChatView* messageLog_; - QtChatTheme* theme_; - QtTextEdit* input_; - QWidget* midBar_; - QBoxLayout* subjectLayout_; - QComboBox* labelsWidget_; - QtOccupantListWidget* treeWidget_; - QLabel* correctingLabel_; - boost::optional correctingAlert_; - QVBoxLayout* alertLayout_; - std::map alertWidgets_; - AlertID nextAlertId_; - TabComplete* completer_; - QLineEdit* subject_; - bool isCorrection_; - bool inputClearing_; - bool tabCompletion_; - UIEventStream* eventStream_; - bool isOnline_; - QSplitter *logRosterSplitter_; - Tristate correctionEnabled_; - Tristate fileTransferEnabled_; - QString alertStyleSheet_; - QPointer mucConfigurationWindow_; - QPointer affiliationEditor_; - SettingsProvider* settings_; - std::vector availableRoomActions_; - QPalette defaultLabelsPalette_; - LabelModel* labelModel_; - BlockingState blockingState_; - bool impromptu_; - bool isMUC_; - bool supportsImpromptuChat_; - RoomBookmarkState roomBookmarkState_; - QMenu* emoticonsMenu_; - }; + class QtChatView; + class QtOccupantListWidget; + class QtChatTheme; + class TreeWidget; + class QtTextEdit; + class UIEventStream; + class QtChatWindowJSBridge; + class SettingsProvider; + class QtEmoticonsGrid; + + class LabelModel : public QAbstractListModel { + Q_OBJECT + public: + LabelModel(QObject* parent = NULL) : QAbstractListModel(parent) {} + + virtual int rowCount(const QModelIndex& /*index*/) const { + return static_cast(availableLabels_.size()); + } + + virtual QVariant data(const QModelIndex& index, int role) const { + if (!index.isValid()) { + return QVariant(); + } + boost::shared_ptr label = availableLabels_[index.row()].getLabel(); + if (label && role == Qt::TextColorRole) { + return P2QSTRING(label->getForegroundColor()); + } + if (label && role == Qt::TextColorRole) { + return P2QSTRING(label->getBackgroundColor()); + } + if (role == Qt::DisplayRole) { + std::string selector = availableLabels_[index.row()].getSelector(); + std::string displayMarking = label ? label->getDisplayMarking() : ""; + QString labelName = selector.empty() ? displayMarking.c_str() : selector.c_str(); + return labelName; + } + return QVariant(); + } + + std::vector availableLabels_; + }; + + class QtChatWindow : public QtTabbable, public ChatWindow { + Q_OBJECT + + public: + QtChatWindow(const QString& contact, QtChatTheme* theme, UIEventStream* eventStream, SettingsProvider* settings, const std::map& emoticons); + virtual ~QtChatWindow(); + std::string addMessage(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time); + std::string addAction(const ChatMessage& message, const std::string &senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& avatarPath, const boost::posix_time::ptime& time); + + std::string addSystemMessage(const ChatMessage& message, Direction direction); + void addPresenceMessage(const ChatMessage& message, Direction direction); + void addErrorMessage(const ChatMessage& message); + + void replaceMessage(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time); + void replaceWithAction(const ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time); + // File transfer related stuff + std::string addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description); + void setFileTransferProgress(std::string id, const int percentageDone); + void setFileTransferStatus(std::string id, const FileTransferState state, const std::string& msg); + + std::string addWhiteboardRequest(bool senderIsSelf); + void setWhiteboardSessionStatus(std::string id, const ChatWindow::WhiteboardSessionState state); + + void show(); + bool isVisible() const; + void activate(); + void setUnreadMessageCount(int count); + void convertToMUC(MUCType mucType); +// TreeWidget *getTreeWidget(); + void setAvailableSecurityLabels(const std::vector& labels); + void setSecurityLabelsEnabled(bool enabled); + void setSecurityLabelsError(); + SecurityLabelsCatalog::Item getSelectedSecurityLabel(); + void setName(const std::string& name); + void setOnline(bool online); + QtTabbable::AlertType getWidgetAlertState(); + void setContactChatState(ChatState::ChatStateType state); + void setRosterModel(Roster* roster); + void setTabComplete(TabComplete* completer); + int getCount(); + virtual void replaceSystemMessage(const ChatMessage& message, const std::string& id, const TimestampBehaviour timestampBehaviour); + void replaceLastMessage(const ChatMessage& message, const TimestampBehaviour timestampBehaviour); + void setAckState(const std::string& id, AckState state); + + // message receipts + void setMessageReceiptState(const std::string& id, ChatWindow::ReceiptState state); + + void flash(); + QByteArray getSplitterState(); + virtual void setAvailableOccupantActions(const std::vector& actions); + void setSubject(const std::string& subject); + void showRoomConfigurationForm(Form::ref); + void addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& reason, const std::string& password, bool direct = true, bool isImpromptu = false, bool isContinuation = false); + void setAffiliations(MUCOccupant::Affiliation, const std::vector&); + void setAvailableRoomActions(const std::vector& actions); + void setBlockingState(BlockingState state); + virtual void setCanInitiateImpromptuChats(bool supportsImpromptu); + virtual void showBookmarkWindow(const MUCBookmark& bookmark); + virtual void setBookmarkState(RoomBookmarkState bookmarkState); + virtual std::string getID() const; + + public slots: + void handleChangeSplitterState(QByteArray state); + void handleFontResized(int fontSizeSteps); + AlertID addAlert(const std::string& alertText); + void removeAlert(const AlertID id); + void setCorrectionEnabled(Tristate enabled); + void setFileTransferEnabled(Tristate enabled); + + signals: + void geometryChanged(); + void splitterMoved(); + void fontResized(int); + + protected slots: + void closeEvent(QCloseEvent* event); + void resizeEvent(QResizeEvent* event); + void moveEvent(QMoveEvent* event); + + void dragEnterEvent(QDragEnterEvent *event); + void dropEvent(QDropEvent *event); + + protected: + void showEvent(QShowEvent* event); + + private slots: + void handleLogCleared(); + void returnPressed(); + void handleInputChanged(); + void handleCursorPositionChanged(); + void handleKeyPressEvent(QKeyEvent* event); + void handleSplitterMoved(int pos, int index); + void handleAlertButtonClicked(); + void handleActionButtonClicked(); + void handleAffiliationEditorAccepted(); + void handleCurrentLabelChanged(int); + void handleEmoticonsButtonClicked(); + void handleEmoticonClicked(QString emoticonAsText); + void handleTextInputReceivedFocus(); + void handleTextInputLostFocus(); + + private: + void updateTitleWithUnreadCount(); + void tabComplete(); + void beginCorrection(); + void cancelCorrection(); + void handleSettingChanged(const std::string& setting); + + void handleOccupantSelectionChanged(RosterItem* item); + void handleAppendedToLog(); + + static std::vector jidListFromQByteArray(const QByteArray& dataBytes); + + private: + int unreadCount_; + bool contactIsTyping_; + LastLineTracker lastLineTracker_; + std::string id_; + QString contact_; + QString lastSentMessage_; + QTextCursor tabCompleteCursor_; + QtChatView* messageLog_; + QtChatTheme* theme_; + QtTextEdit* input_; + QWidget* midBar_; + QBoxLayout* subjectLayout_; + QComboBox* labelsWidget_; + QtOccupantListWidget* treeWidget_; + QLabel* correctingLabel_; + boost::optional correctingAlert_; + QVBoxLayout* alertLayout_; + std::map alertWidgets_; + AlertID nextAlertId_; + TabComplete* completer_; + QLineEdit* subject_; + bool isCorrection_; + bool inputClearing_; + bool tabCompletion_; + UIEventStream* eventStream_; + bool isOnline_; + QSplitter *logRosterSplitter_; + Tristate correctionEnabled_; + Tristate fileTransferEnabled_; + QString alertStyleSheet_; + QPointer mucConfigurationWindow_; + QPointer affiliationEditor_; + SettingsProvider* settings_; + std::vector availableRoomActions_; + QPalette defaultLabelsPalette_; + LabelModel* labelModel_; + BlockingState blockingState_; + bool impromptu_; + bool isMUC_; + bool supportsImpromptuChat_; + RoomBookmarkState roomBookmarkState_; + QMenu* emoticonsMenu_; + }; } diff --git a/Swift/QtUI/QtChatWindowFactory.cpp b/Swift/QtUI/QtChatWindowFactory.cpp index 019eb21..a97fd7c 100644 --- a/Swift/QtUI/QtChatWindowFactory.cpp +++ b/Swift/QtUI/QtChatWindowFactory.cpp @@ -23,65 +23,65 @@ static const QString SPLITTER_STATE = "mucSplitterState"; static const QString CHAT_TABS_GEOMETRY = "chatTabsGeometry"; QtChatWindowFactory::QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map& emoticons) : themePath_(themePath), emoticons_(emoticons) { - qtOnlySettings_ = qtSettings; - settings_ = settings; - tabs_ = tabs; - theme_ = NULL; - QtChatTabs* fullTabs = dynamic_cast(tabs_); - if (splitter) { - assert(fullTabs && "Netbook mode and no-tabs interface is not supported!"); - splitter->addWidget(fullTabs); - } else if (fullTabs) { - QVariant chatTabsGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY); - if (chatTabsGeometryVariant.isValid()) { - fullTabs->restoreGeometry(chatTabsGeometryVariant.toByteArray()); - } - connect(fullTabs, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged())); - } + qtOnlySettings_ = qtSettings; + settings_ = settings; + tabs_ = tabs; + theme_ = NULL; + QtChatTabs* fullTabs = dynamic_cast(tabs_); + if (splitter) { + assert(fullTabs && "Netbook mode and no-tabs interface is not supported!"); + splitter->addWidget(fullTabs); + } else if (fullTabs) { + QVariant chatTabsGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY); + if (chatTabsGeometryVariant.isValid()) { + fullTabs->restoreGeometry(chatTabsGeometryVariant.toByteArray()); + } + connect(fullTabs, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged())); + } } QtChatWindowFactory::~QtChatWindowFactory() { - delete theme_; + delete theme_; } ChatWindow* QtChatWindowFactory::createChatWindow(const JID &contact,UIEventStream* eventStream) { - if (!theme_) { - theme_ = new QtChatTheme(themePath_); - if (theme_->getIncomingContent().isEmpty()) { - delete theme_; - theme_ = new QtChatTheme(":/themes/Default/"); /* Use the inbuilt theme */ - } - } + if (!theme_) { + theme_ = new QtChatTheme(themePath_); + if (theme_->getIncomingContent().isEmpty()) { + delete theme_; + theme_ = new QtChatTheme(":/themes/Default/"); /* Use the inbuilt theme */ + } + } - QtChatWindow* chatWindow = new QtChatWindow(P2QSTRING(contact.toString()), theme_, eventStream, settings_, emoticons_); - connect(chatWindow, SIGNAL(splitterMoved()), this, SLOT(handleSplitterMoved())); - connect(this, SIGNAL(changeSplitterState(QByteArray)), chatWindow, SLOT(handleChangeSplitterState(QByteArray))); + QtChatWindow* chatWindow = new QtChatWindow(P2QSTRING(contact.toString()), theme_, eventStream, settings_, emoticons_); + connect(chatWindow, SIGNAL(splitterMoved()), this, SLOT(handleSplitterMoved())); + connect(this, SIGNAL(changeSplitterState(QByteArray)), chatWindow, SLOT(handleChangeSplitterState(QByteArray))); - QVariant splitterState = qtOnlySettings_->getQSettings()->value(SPLITTER_STATE); - if(splitterState.isValid()) { - chatWindow->handleChangeSplitterState(splitterState.toByteArray()); - } + QVariant splitterState = qtOnlySettings_->getQSettings()->value(SPLITTER_STATE); + if(splitterState.isValid()) { + chatWindow->handleChangeSplitterState(splitterState.toByteArray()); + } - if (tabs_) { - tabs_->addTab(chatWindow); - } else { - QVariant chatGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY); - if (chatGeometryVariant.isValid()) { - chatWindow->restoreGeometry(chatGeometryVariant.toByteArray()); - } - connect(chatWindow, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged())); - } - return chatWindow; + if (tabs_) { + tabs_->addTab(chatWindow); + } else { + QVariant chatGeometryVariant = qtOnlySettings_->getQSettings()->value(CHAT_TABS_GEOMETRY); + if (chatGeometryVariant.isValid()) { + chatWindow->restoreGeometry(chatGeometryVariant.toByteArray()); + } + connect(chatWindow, SIGNAL(geometryChanged()), this, SLOT(handleWindowGeometryChanged())); + } + return chatWindow; } void QtChatWindowFactory::handleWindowGeometryChanged() { - qtOnlySettings_->getQSettings()->setValue(CHAT_TABS_GEOMETRY, qobject_cast(sender())->saveGeometry()); + qtOnlySettings_->getQSettings()->setValue(CHAT_TABS_GEOMETRY, qobject_cast(sender())->saveGeometry()); } void QtChatWindowFactory::handleSplitterMoved() { - QByteArray splitterState = qobject_cast(sender())->getSplitterState(); - qtOnlySettings_->getQSettings()->setValue(SPLITTER_STATE, QVariant(splitterState)); - emit changeSplitterState(splitterState); + QByteArray splitterState = qobject_cast(sender())->getSplitterState(); + qtOnlySettings_->getQSettings()->setValue(SPLITTER_STATE, QVariant(splitterState)); + emit changeSplitterState(splitterState); } } diff --git a/Swift/QtUI/QtChatWindowFactory.h b/Swift/QtUI/QtChatWindowFactory.h index 6b1f0a1..29bc5bc 100644 --- a/Swift/QtUI/QtChatWindowFactory.h +++ b/Swift/QtUI/QtChatWindowFactory.h @@ -19,29 +19,29 @@ #include namespace Swift { - class QtChatTabsBase; - class QtChatTheme; - class UIEventStream; - class QtUIPreferences; - class QtSingleWindow; - class QtChatWindowFactory : public QObject, public ChatWindowFactory { - Q_OBJECT - public: - QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map& emoticons); - ~QtChatWindowFactory(); - ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream); - signals: - void changeSplitterState(QByteArray); - private slots: - void handleWindowGeometryChanged(); - void handleSplitterMoved(); - private: - QString themePath_; - SettingsProvider* settings_; - QtSettingsProvider* qtOnlySettings_; - QtChatTabsBase* tabs_; - QtChatTheme* theme_; - std::map emoticons_; - }; + class QtChatTabsBase; + class QtChatTheme; + class UIEventStream; + class QtUIPreferences; + class QtSingleWindow; + class QtChatWindowFactory : public QObject, public ChatWindowFactory { + Q_OBJECT + public: + QtChatWindowFactory(QtSingleWindow* splitter, SettingsProvider* settings, QtSettingsProvider* qtSettings, QtChatTabsBase* tabs, const QString& themePath, const std::map& emoticons); + ~QtChatWindowFactory(); + ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream); + signals: + void changeSplitterState(QByteArray); + private slots: + void handleWindowGeometryChanged(); + void handleSplitterMoved(); + private: + QString themePath_; + SettingsProvider* settings_; + QtSettingsProvider* qtOnlySettings_; + QtChatTabsBase* tabs_; + QtChatTheme* theme_; + std::map emoticons_; + }; } diff --git a/Swift/QtUI/QtChatWindowJSBridge.cpp b/Swift/QtUI/QtChatWindowJSBridge.cpp index fa6f906..3030689 100644 --- a/Swift/QtUI/QtChatWindowJSBridge.cpp +++ b/Swift/QtUI/QtChatWindowJSBridge.cpp @@ -15,11 +15,11 @@ namespace Swift { QtChatWindowJSBridge::QtChatWindowJSBridge() { - + } QtChatWindowJSBridge::~QtChatWindowJSBridge() { - + } } diff --git a/Swift/QtUI/QtChatWindowJSBridge.h b/Swift/QtUI/QtChatWindowJSBridge.h index db01abb..bedf6a4 100644 --- a/Swift/QtUI/QtChatWindowJSBridge.h +++ b/Swift/QtUI/QtChatWindowJSBridge.h @@ -21,12 +21,12 @@ namespace Swift { class FileTransferController; class QtChatWindowJSBridge : public QObject { - Q_OBJECT + Q_OBJECT public: - QtChatWindowJSBridge(); - virtual ~QtChatWindowJSBridge(); + QtChatWindowJSBridge(); + virtual ~QtChatWindowJSBridge(); signals: - void buttonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5); + void buttonClicked(QString id, QString arg1, QString arg2, QString arg3, QString arg4, QString arg5); }; } diff --git a/Swift/QtUI/QtClickableLabel.cpp b/Swift/QtUI/QtClickableLabel.cpp index 3749cfe..7ce3325 100644 --- a/Swift/QtUI/QtClickableLabel.cpp +++ b/Swift/QtUI/QtClickableLabel.cpp @@ -12,7 +12,7 @@ QtClickableLabel::QtClickableLabel(QWidget* parent) : QLabel(parent) { } void QtClickableLabel::mousePressEvent(QMouseEvent*) { - emit clicked(); + emit clicked(); } } diff --git a/Swift/QtUI/QtClickableLabel.h b/Swift/QtUI/QtClickableLabel.h index deaf646..83ed3f1 100644 --- a/Swift/QtUI/QtClickableLabel.h +++ b/Swift/QtUI/QtClickableLabel.h @@ -9,14 +9,14 @@ #include namespace Swift { - class QtClickableLabel : public QLabel { - Q_OBJECT - public: - QtClickableLabel(QWidget* parent); + class QtClickableLabel : public QLabel { + Q_OBJECT + public: + QtClickableLabel(QWidget* parent); - void mousePressEvent(QMouseEvent* event); + void mousePressEvent(QMouseEvent* event); - signals: - void clicked(); - }; + signals: + void clicked(); + }; } diff --git a/Swift/QtUI/QtClosableLineEdit.cpp b/Swift/QtUI/QtClosableLineEdit.cpp index 414463a..033db78 100644 --- a/Swift/QtUI/QtClosableLineEdit.cpp +++ b/Swift/QtUI/QtClosableLineEdit.cpp @@ -27,40 +27,40 @@ namespace Swift { const int QtClosableLineEdit::clearButtonPadding = 2; QtClosableLineEdit::QtClosableLineEdit(QWidget *parent) : QLineEdit(parent) { - clearButton = new QToolButton(this); - clearButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); - clearButton->setIconSize(QSize(16,16)); - clearButton->setCursor(Qt::ArrowCursor); - clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }"); - clearButton->hide(); - connect(clearButton, SIGNAL(clicked()), this, SLOT(handleCloseButtonClicked())); - connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&))); - int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); - setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1)); - QSize minimumSize = minimumSizeHint(); - setMinimumSize(qMax(minimumSize.width(), clearButton->sizeHint().width() + frameWidth * 2 + clearButtonPadding), - qMax(minimumSize.height(), clearButton->sizeHint().height() + frameWidth * 2 + clearButtonPadding)); + clearButton = new QToolButton(this); + clearButton->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); + clearButton->setIconSize(QSize(16,16)); + clearButton->setCursor(Qt::ArrowCursor); + clearButton->setStyleSheet("QToolButton { border: none; padding: 0px; }"); + clearButton->hide(); + connect(clearButton, SIGNAL(clicked()), this, SLOT(handleCloseButtonClicked())); + connect(this, SIGNAL(textChanged(const QString&)), this, SLOT(updateCloseButton(const QString&))); + int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); + setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1)); + QSize minimumSize = minimumSizeHint(); + setMinimumSize(qMax(minimumSize.width(), clearButton->sizeHint().width() + frameWidth * 2 + clearButtonPadding), + qMax(minimumSize.height(), clearButton->sizeHint().height() + frameWidth * 2 + clearButtonPadding)); } void QtClosableLineEdit::resizeEvent(QResizeEvent *) { - QSize size = clearButton->sizeHint(); - int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); - int verticalAdjustment = 1; + QSize size = clearButton->sizeHint(); + int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth); + int verticalAdjustment = 1; #if defined(Q_OS_WIN32) - // This vertical adjustment is required on Windows so the close button is vertically centered in the line edit. - verticalAdjustment += 2; -#endif - clearButton->move(rect().right() - frameWidth - size.width(), (rect().bottom() + verticalAdjustment - size.height())/2); + // This vertical adjustment is required on Windows so the close button is vertically centered in the line edit. + verticalAdjustment += 2; +#endif + clearButton->move(rect().right() - frameWidth - size.width(), (rect().bottom() + verticalAdjustment - size.height())/2); } void QtClosableLineEdit::updateCloseButton(const QString& text) { - clearButton->setVisible(!text.isEmpty()); + clearButton->setVisible(!text.isEmpty()); } void QtClosableLineEdit::handleCloseButtonClicked() { - clear(); - QApplication::postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier)); - QApplication::postEvent(this, new QKeyEvent(QEvent::KeyRelease, Qt::Key_Escape, Qt::NoModifier)); + clear(); + QApplication::postEvent(this, new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier)); + QApplication::postEvent(this, new QKeyEvent(QEvent::KeyRelease, Qt::Key_Escape, Qt::NoModifier)); } } diff --git a/Swift/QtUI/QtClosableLineEdit.h b/Swift/QtUI/QtClosableLineEdit.h index da9f5a8..206851b 100644 --- a/Swift/QtUI/QtClosableLineEdit.h +++ b/Swift/QtUI/QtClosableLineEdit.h @@ -24,20 +24,20 @@ namespace Swift { class QtClosableLineEdit : public QLineEdit { - Q_OBJECT - public: - QtClosableLineEdit(QWidget *parent = 0); + Q_OBJECT + public: + QtClosableLineEdit(QWidget *parent = 0); - protected: - void resizeEvent(QResizeEvent *); + protected: + void resizeEvent(QResizeEvent *); - private slots: - void updateCloseButton(const QString &text); - void handleCloseButtonClicked(); + private slots: + void updateCloseButton(const QString &text); + void handleCloseButtonClicked(); - private: - static const int clearButtonPadding; - QToolButton *clearButton; + private: + static const int clearButtonPadding; + QToolButton *clearButton; }; } diff --git a/Swift/QtUI/QtColorToolButton.cpp b/Swift/QtUI/QtColorToolButton.cpp index a91fe0e..b349a47 100644 --- a/Swift/QtUI/QtColorToolButton.cpp +++ b/Swift/QtUI/QtColorToolButton.cpp @@ -18,34 +18,34 @@ namespace Swift { QtColorToolButton::QtColorToolButton(QWidget* parent) : - QToolButton(parent) + QToolButton(parent) { - connect(this, SIGNAL(clicked()), SLOT(onClicked())); - setColorIcon(Qt::transparent); + connect(this, SIGNAL(clicked()), SLOT(onClicked())); + setColorIcon(Qt::transparent); } void QtColorToolButton::setColor(const QColor& color) { - if (color.isValid() != color_.isValid() || (color.isValid() && color != color_)) { - color_ = color; - setColorIcon(color_); - emit colorChanged(color_); - } + if (color.isValid() != color_.isValid() || (color.isValid() && color != color_)) { + color_ = color; + setColorIcon(color_); + emit colorChanged(color_); + } } void QtColorToolButton::onClicked() { - QColor c = QColorDialog::getColor(color_, this); - if (c.isValid()) { - setColor(c); - } + QColor c = QColorDialog::getColor(color_, this); + if (c.isValid()) { + setColor(c); + } } void QtColorToolButton::setColorIcon(const QColor& color) { - QPixmap pix(iconSize()); - pix.fill(color.isValid() ? color : Qt::transparent); - setIcon(pix); + QPixmap pix(iconSize()); + pix.fill(color.isValid() ? color : Qt::transparent); + setIcon(pix); } } diff --git a/Swift/QtUI/QtColorToolButton.h b/Swift/QtUI/QtColorToolButton.h index 33d195d..5260048 100644 --- a/Swift/QtUI/QtColorToolButton.h +++ b/Swift/QtUI/QtColorToolButton.h @@ -10,23 +10,23 @@ namespace Swift { - class QtColorToolButton : public QToolButton { - Q_OBJECT - Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged) - public: - explicit QtColorToolButton(QWidget* parent = NULL); - void setColor(const QColor& color); - const QColor& getColor() const { return color_; } - - signals: - void colorChanged(const QColor&); - - private slots: - void onClicked(); - - private: - void setColorIcon(const QColor& color); - QColor color_; - }; + class QtColorToolButton : public QToolButton { + Q_OBJECT + Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChanged) + public: + explicit QtColorToolButton(QWidget* parent = NULL); + void setColor(const QColor& color); + const QColor& getColor() const { return color_; } + + signals: + void colorChanged(const QColor&); + + private slots: + void onClicked(); + + private: + void setColorIcon(const QColor& color); + QColor color_; + }; } diff --git a/Swift/QtUI/QtConnectionSettingsWindow.cpp b/Swift/QtUI/QtConnectionSettingsWindow.cpp index 940625b..a58bc5c 100644 --- a/Swift/QtUI/QtConnectionSettingsWindow.cpp +++ b/Swift/QtUI/QtConnectionSettingsWindow.cpp @@ -25,147 +25,147 @@ namespace Swift { QtConnectionSettingsWindow::QtConnectionSettingsWindow(const ClientOptions& options) : QDialog() { - ui.setupUi(this); - - connect(ui.connectionMethod, SIGNAL(currentIndexChanged(int)), ui.stackedWidget, SLOT(setCurrentIndex(int))); - - connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostNameLabel, SLOT(setEnabled(bool))); - connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostName, SLOT(setEnabled(bool))); - connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPortLabel, SLOT(setEnabled(bool))); - connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPort, SLOT(setEnabled(bool))); - - connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHostLabel, SLOT(setEnabled(bool))); - connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHost, SLOT(setEnabled(bool))); - connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPortLabel, SLOT(setEnabled(bool))); - connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPort, SLOT(setEnabled(bool))); - - connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHostLabel, SLOT(setEnabled(bool))); - connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHost, SLOT(setEnabled(bool))); - connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPortLabel, SLOT(setEnabled(bool))); - connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPort, SLOT(setEnabled(bool))); - - connect(ui.manual_proxyType, SIGNAL(currentIndexChanged(int)), SLOT(handleProxyTypeChanged(int))); - - connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(handleAcceptRequested())); - - QtURLValidator* urlValidator = new QtURLValidator(this); - ui.bosh_uri->setValidator(urlValidator); - - ui.manual_useTLS->setCurrentIndex(2); - - ui.manual_proxyType->setCurrentIndex(0); - - ClientOptions defaults; - if (options.boshURL.isEmpty()) { - bool isDefault = options.useStreamCompression == defaults.useStreamCompression; - isDefault &= options.useTLS == defaults.useTLS; - isDefault &= options.allowPLAINWithoutTLS == defaults.allowPLAINWithoutTLS; - isDefault &= options.useStreamCompression == defaults.useStreamCompression; - isDefault &= options.useAcks == defaults.useAcks; - isDefault &= options.manualHostname == defaults.manualHostname; - isDefault &= options.manualPort == defaults.manualPort; - isDefault &= options.proxyType == defaults.proxyType; - isDefault &= options.manualProxyHostname == defaults.manualProxyHostname; - isDefault &= options.manualProxyPort == defaults.manualProxyPort; - isDefault &= options.tlsOptions.schannelTLS1_0Workaround == defaults.tlsOptions.schannelTLS1_0Workaround; - if (isDefault) { - ui.connectionMethod->setCurrentIndex(0); - } - else { - ui.connectionMethod->setCurrentIndex(1); - ui.manual_useTLS->setCurrentIndex(options.useTLS); - ui.manual_allowPLAINWithoutTLS->setChecked(options.allowPLAINWithoutTLS); - ui.manual_allowCompression->setChecked(options.useStreamCompression); - if (!options.manualHostname.empty()) { - ui.manual_manualHost->setChecked(true); - ui.manual_manualHostName->setText(P2QSTRING(options.manualHostname)); - if (options.manualPort >=0) { - ui.manual_manualHostPort->setText(P2QSTRING(boost::lexical_cast(options.manualPort))); - } - } - ui.manual_proxyType->setCurrentIndex(options.proxyType); - if (!options.manualProxyHostname.empty()) { - ui.manual_manualProxy->setChecked(true); - ui.manual_manualProxyHost->setText(P2QSTRING(options.manualProxyHostname)); - ui.manual_manualProxyPort->setText(P2QSTRING(boost::lexical_cast(options.manualProxyPort))); - } - ui.manual_forceTLS1_0->setChecked(options.tlsOptions.schannelTLS1_0Workaround); - } - } else { - ui.connectionMethod->setCurrentIndex(2); - ui.bosh_uri->setText(P2QSTRING(options.boshURL.toString())); - if (!options.boshHTTPConnectProxyURL.isEmpty()) { - ui.bosh_manualProxy->setChecked(true); - ui.bosh_manualProxyHost->setText(P2QSTRING(options.boshHTTPConnectProxyURL.getHost())); - if (options.boshHTTPConnectProxyURL.getPort()) { - ui.bosh_manualProxyPort->setText(P2QSTRING(boost::lexical_cast(*options.boshHTTPConnectProxyURL.getPort()))); - } - } - } + ui.setupUi(this); + + connect(ui.connectionMethod, SIGNAL(currentIndexChanged(int)), ui.stackedWidget, SLOT(setCurrentIndex(int))); + + connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostNameLabel, SLOT(setEnabled(bool))); + connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostName, SLOT(setEnabled(bool))); + connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPortLabel, SLOT(setEnabled(bool))); + connect(ui.manual_manualHost, SIGNAL(toggled(bool)), ui.manual_manualHostPort, SLOT(setEnabled(bool))); + + connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHostLabel, SLOT(setEnabled(bool))); + connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyHost, SLOT(setEnabled(bool))); + connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPortLabel, SLOT(setEnabled(bool))); + connect(ui.manual_manualProxy, SIGNAL(toggled(bool)), ui.manual_manualProxyPort, SLOT(setEnabled(bool))); + + connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHostLabel, SLOT(setEnabled(bool))); + connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyHost, SLOT(setEnabled(bool))); + connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPortLabel, SLOT(setEnabled(bool))); + connect(ui.bosh_manualProxy, SIGNAL(toggled(bool)), ui.bosh_manualProxyPort, SLOT(setEnabled(bool))); + + connect(ui.manual_proxyType, SIGNAL(currentIndexChanged(int)), SLOT(handleProxyTypeChanged(int))); + + connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(handleAcceptRequested())); + + QtURLValidator* urlValidator = new QtURLValidator(this); + ui.bosh_uri->setValidator(urlValidator); + + ui.manual_useTLS->setCurrentIndex(2); + + ui.manual_proxyType->setCurrentIndex(0); + + ClientOptions defaults; + if (options.boshURL.isEmpty()) { + bool isDefault = options.useStreamCompression == defaults.useStreamCompression; + isDefault &= options.useTLS == defaults.useTLS; + isDefault &= options.allowPLAINWithoutTLS == defaults.allowPLAINWithoutTLS; + isDefault &= options.useStreamCompression == defaults.useStreamCompression; + isDefault &= options.useAcks == defaults.useAcks; + isDefault &= options.manualHostname == defaults.manualHostname; + isDefault &= options.manualPort == defaults.manualPort; + isDefault &= options.proxyType == defaults.proxyType; + isDefault &= options.manualProxyHostname == defaults.manualProxyHostname; + isDefault &= options.manualProxyPort == defaults.manualProxyPort; + isDefault &= options.tlsOptions.schannelTLS1_0Workaround == defaults.tlsOptions.schannelTLS1_0Workaround; + if (isDefault) { + ui.connectionMethod->setCurrentIndex(0); + } + else { + ui.connectionMethod->setCurrentIndex(1); + ui.manual_useTLS->setCurrentIndex(options.useTLS); + ui.manual_allowPLAINWithoutTLS->setChecked(options.allowPLAINWithoutTLS); + ui.manual_allowCompression->setChecked(options.useStreamCompression); + if (!options.manualHostname.empty()) { + ui.manual_manualHost->setChecked(true); + ui.manual_manualHostName->setText(P2QSTRING(options.manualHostname)); + if (options.manualPort >=0) { + ui.manual_manualHostPort->setText(P2QSTRING(boost::lexical_cast(options.manualPort))); + } + } + ui.manual_proxyType->setCurrentIndex(options.proxyType); + if (!options.manualProxyHostname.empty()) { + ui.manual_manualProxy->setChecked(true); + ui.manual_manualProxyHost->setText(P2QSTRING(options.manualProxyHostname)); + ui.manual_manualProxyPort->setText(P2QSTRING(boost::lexical_cast(options.manualProxyPort))); + } + ui.manual_forceTLS1_0->setChecked(options.tlsOptions.schannelTLS1_0Workaround); + } + } else { + ui.connectionMethod->setCurrentIndex(2); + ui.bosh_uri->setText(P2QSTRING(options.boshURL.toString())); + if (!options.boshHTTPConnectProxyURL.isEmpty()) { + ui.bosh_manualProxy->setChecked(true); + ui.bosh_manualProxyHost->setText(P2QSTRING(options.boshHTTPConnectProxyURL.getHost())); + if (options.boshHTTPConnectProxyURL.getPort()) { + ui.bosh_manualProxyPort->setText(P2QSTRING(boost::lexical_cast(*options.boshHTTPConnectProxyURL.getPort()))); + } + } + } #ifndef HAVE_SCHANNEL - ui.manual_forceTLS1_0->hide(); + ui.manual_forceTLS1_0->hide(); #endif } void QtConnectionSettingsWindow::handleProxyTypeChanged(int index) { - bool proxySettingsVisible = index != NoProxy && index != SystemProxy; - ui.manual_manualProxy->setVisible(proxySettingsVisible); - ui.manual_manualProxyHostLabel->setVisible(proxySettingsVisible); - ui.manual_manualProxyHost->setVisible(proxySettingsVisible); - ui.manual_manualProxyPortLabel->setVisible(proxySettingsVisible); - ui.manual_manualProxyPort->setVisible(proxySettingsVisible); + bool proxySettingsVisible = index != NoProxy && index != SystemProxy; + ui.manual_manualProxy->setVisible(proxySettingsVisible); + ui.manual_manualProxyHostLabel->setVisible(proxySettingsVisible); + ui.manual_manualProxyHost->setVisible(proxySettingsVisible); + ui.manual_manualProxyPortLabel->setVisible(proxySettingsVisible); + ui.manual_manualProxyPort->setVisible(proxySettingsVisible); } void QtConnectionSettingsWindow::handleAcceptRequested() { - if (ui.connectionMethod->currentIndex() != 2 || ui.bosh_uri->hasAcceptableInput()) { - accept(); - } - else { - QMessageBox::critical(this, tr("Configuration invalid"), tr("The provided BOSH URL is not valid.")); - } + if (ui.connectionMethod->currentIndex() != 2 || ui.bosh_uri->hasAcceptableInput()) { + accept(); + } + else { + QMessageBox::critical(this, tr("Configuration invalid"), tr("The provided BOSH URL is not valid.")); + } } ClientOptions QtConnectionSettingsWindow::getOptions() { - ClientOptions options; - if (ui.connectionMethod->currentIndex() > 0) { - /* Not automatic */ - if (ui.connectionMethod->currentIndex() == 1) { - /* Manual */ - options.useTLS = static_cast(ui.manual_useTLS->currentIndex()); - options.useStreamCompression = ui.manual_allowCompression->isChecked(); - options.allowPLAINWithoutTLS = ui.manual_allowPLAINWithoutTLS->isChecked(); - options.tlsOptions.schannelTLS1_0Workaround = ui.manual_forceTLS1_0->isChecked(); - if (ui.manual_manualHost->isChecked()) { - options.manualHostname = Q2PSTRING(ui.manual_manualHostName->text()); - try { - options.manualPort = boost::lexical_cast(Q2PSTRING(ui.manual_manualHostPort->text())); - } catch (const boost::bad_lexical_cast&) { - options.manualPort = -1; - } - } - options.proxyType = static_cast(ui.manual_proxyType->currentIndex()); - if (ui.manual_manualProxy->isChecked()) { - options.manualProxyHostname = Q2PSTRING(ui.manual_manualProxyHost->text()); - try { - options.manualProxyPort = boost::lexical_cast(Q2PSTRING(ui.manual_manualProxyPort->text())); - } catch (const boost::bad_lexical_cast&) {} - } - } - else { - /* BOSH */ - options.boshURL = URL::fromString(Q2PSTRING(ui.bosh_uri->text())); - if (ui.bosh_manualProxy->isChecked()) { - std::string host = Q2PSTRING(ui.bosh_manualProxyHost->text()); - try { - int port = boost::lexical_cast(Q2PSTRING(ui.bosh_manualProxyPort->text())); - options.boshHTTPConnectProxyURL = URL("http", host, port, ""); - } catch (const boost::bad_lexical_cast&) { - options.boshHTTPConnectProxyURL = URL("http", host, ""); - } - } - } - } - return options; + ClientOptions options; + if (ui.connectionMethod->currentIndex() > 0) { + /* Not automatic */ + if (ui.connectionMethod->currentIndex() == 1) { + /* Manual */ + options.useTLS = static_cast(ui.manual_useTLS->currentIndex()); + options.useStreamCompression = ui.manual_allowCompression->isChecked(); + options.allowPLAINWithoutTLS = ui.manual_allowPLAINWithoutTLS->isChecked(); + options.tlsOptions.schannelTLS1_0Workaround = ui.manual_forceTLS1_0->isChecked(); + if (ui.manual_manualHost->isChecked()) { + options.manualHostname = Q2PSTRING(ui.manual_manualHostName->text()); + try { + options.manualPort = boost::lexical_cast(Q2PSTRING(ui.manual_manualHostPort->text())); + } catch (const boost::bad_lexical_cast&) { + options.manualPort = -1; + } + } + options.proxyType = static_cast(ui.manual_proxyType->currentIndex()); + if (ui.manual_manualProxy->isChecked()) { + options.manualProxyHostname = Q2PSTRING(ui.manual_manualProxyHost->text()); + try { + options.manualProxyPort = boost::lexical_cast(Q2PSTRING(ui.manual_manualProxyPort->text())); + } catch (const boost::bad_lexical_cast&) {} + } + } + else { + /* BOSH */ + options.boshURL = URL::fromString(Q2PSTRING(ui.bosh_uri->text())); + if (ui.bosh_manualProxy->isChecked()) { + std::string host = Q2PSTRING(ui.bosh_manualProxyHost->text()); + try { + int port = boost::lexical_cast(Q2PSTRING(ui.bosh_manualProxyPort->text())); + options.boshHTTPConnectProxyURL = URL("http", host, port, ""); + } catch (const boost::bad_lexical_cast&) { + options.boshHTTPConnectProxyURL = URL("http", host, ""); + } + } + } + } + return options; } } diff --git a/Swift/QtUI/QtConnectionSettingsWindow.h b/Swift/QtUI/QtConnectionSettingsWindow.h index a1d4739..f9fad84 100644 --- a/Swift/QtUI/QtConnectionSettingsWindow.h +++ b/Swift/QtUI/QtConnectionSettingsWindow.h @@ -13,25 +13,25 @@ #include namespace Swift { - class QtConnectionSettingsWindow : public QDialog { - Q_OBJECT - - public: - QtConnectionSettingsWindow(const ClientOptions& options); - - ClientOptions getOptions(); - - private slots: - void handleProxyTypeChanged(int); - void handleAcceptRequested(); - - private: - enum { - NoProxy = 0, - SystemProxy = 1, - SOCKS5Proxy = 2, - HTTPProxy = 3 - }; - Ui::QtConnectionSettings ui; - }; + class QtConnectionSettingsWindow : public QDialog { + Q_OBJECT + + public: + QtConnectionSettingsWindow(const ClientOptions& options); + + ClientOptions getOptions(); + + private slots: + void handleProxyTypeChanged(int); + void handleAcceptRequested(); + + private: + enum { + NoProxy = 0, + SystemProxy = 1, + SOCKS5Proxy = 2, + HTTPProxy = 3 + }; + Ui::QtConnectionSettings ui; + }; } diff --git a/Swift/QtUI/QtContactEditWidget.cpp b/Swift/QtUI/QtContactEditWidget.cpp index ad02bf9..ced9157 100644 --- a/Swift/QtUI/QtContactEditWidget.cpp +++ b/Swift/QtUI/QtContactEditWidget.cpp @@ -21,155 +21,155 @@ namespace Swift { QtContactEditWidget::QtContactEditWidget(const std::set& allGroups, QWidget* parent) : QWidget(parent), nameRadioButton_(NULL), groups_(NULL) { - QBoxLayout* layout = new QVBoxLayout(this); - setContentsMargins(0,0,0,0); - layout->setContentsMargins(0,0,0,0); - - nameLayout_ = new QHBoxLayout(); - suggestionsLayout_ = new QHBoxLayout(); - nameLayout_->addLayout(suggestionsLayout_); - - name_ = new QLineEdit(this); - nameLayout_->addWidget(name_); - - throbberLabel_ = new QLabel(this); - throbberLabel_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this)); - throbberLabel_->movie()->start(); - nameLayout_->addWidget(throbberLabel_); - - layout->addLayout(nameLayout_); - - layout->addWidget(new QLabel(tr("Groups:"), this)); - - QScrollArea* groupsArea = new QScrollArea(this); - layout->addWidget(groupsArea); - groupsArea->setWidgetResizable(true); - groupsArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - groupsArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - - QWidget* groups = new QWidget(groupsArea); - groupsArea->setWidget(groups); - QVBoxLayout* scrollLayout = new QVBoxLayout(groups); - - foreach (std::string group, allGroups) { - QString groupName = doubleAmpersand(group); - QCheckBox* check = new QCheckBox(groups); - check->setText(groupName); - check->setCheckState(Qt::Unchecked); - checkBoxes_[group] = check; - scrollLayout->addWidget(check); - } - - QHBoxLayout* newGroupLayout = new QHBoxLayout(); - newGroup_ = new QCheckBox(groups); - newGroup_->setText(tr("New Group:")); - newGroup_->setCheckState(Qt::Unchecked); - newGroupLayout->addWidget(newGroup_); - newGroupName_ = new QLineEdit(groups); - newGroupLayout->addWidget(newGroupName_); - scrollLayout->addLayout(newGroupLayout); - - scrollLayout->addItem(new QSpacerItem(20, 73, QSizePolicy::Minimum, QSizePolicy::Expanding)); + QBoxLayout* layout = new QVBoxLayout(this); + setContentsMargins(0,0,0,0); + layout->setContentsMargins(0,0,0,0); + + nameLayout_ = new QHBoxLayout(); + suggestionsLayout_ = new QHBoxLayout(); + nameLayout_->addLayout(suggestionsLayout_); + + name_ = new QLineEdit(this); + nameLayout_->addWidget(name_); + + throbberLabel_ = new QLabel(this); + throbberLabel_->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this)); + throbberLabel_->movie()->start(); + nameLayout_->addWidget(throbberLabel_); + + layout->addLayout(nameLayout_); + + layout->addWidget(new QLabel(tr("Groups:"), this)); + + QScrollArea* groupsArea = new QScrollArea(this); + layout->addWidget(groupsArea); + groupsArea->setWidgetResizable(true); + groupsArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + groupsArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + + QWidget* groups = new QWidget(groupsArea); + groupsArea->setWidget(groups); + QVBoxLayout* scrollLayout = new QVBoxLayout(groups); + + foreach (std::string group, allGroups) { + QString groupName = doubleAmpersand(group); + QCheckBox* check = new QCheckBox(groups); + check->setText(groupName); + check->setCheckState(Qt::Unchecked); + checkBoxes_[group] = check; + scrollLayout->addWidget(check); + } + + QHBoxLayout* newGroupLayout = new QHBoxLayout(); + newGroup_ = new QCheckBox(groups); + newGroup_->setText(tr("New Group:")); + newGroup_->setCheckState(Qt::Unchecked); + newGroupLayout->addWidget(newGroup_); + newGroupName_ = new QLineEdit(groups); + newGroupLayout->addWidget(newGroupName_); + scrollLayout->addLayout(newGroupLayout); + + scrollLayout->addItem(new QSpacerItem(20, 73, QSizePolicy::Minimum, QSizePolicy::Expanding)); } void QtContactEditWidget::setName(const std::string& name) { - name_->setText(P2QSTRING(name)); + name_->setText(P2QSTRING(name)); } std::string QtContactEditWidget::getName() const { - std::string name = Q2PSTRING(name_->text()); - QList buttons = findChildren(); - foreach(const QRadioButton* button, buttons) { - if (button->isChecked()) { - if (button == nameRadioButton_) { - name = Q2PSTRING(name_->text()); - } else { - name = singleAmpersand(button->text()); - } - break; - } - } - return name; + std::string name = Q2PSTRING(name_->text()); + QList buttons = findChildren(); + foreach(const QRadioButton* button, buttons) { + if (button->isChecked()) { + if (button == nameRadioButton_) { + name = Q2PSTRING(name_->text()); + } else { + name = singleAmpersand(button->text()); + } + break; + } + } + return name; } void QtContactEditWidget::setSelectedGroups(const std::vector& groups) { - foreach (std::string group, groups) { - checkBoxes_[group]->setCheckState(Qt::Checked); - } + foreach (std::string group, groups) { + checkBoxes_[group]->setCheckState(Qt::Checked); + } } std::set QtContactEditWidget::getSelectedGroups() const { - std::set groups; - foreach(const CheckBoxMap::value_type& group, checkBoxes_) { - if (group.second->checkState() == Qt::Checked) { - groups.insert(group.first); - } - } - if (newGroup_->checkState() == Qt::Checked && !newGroupName_->text().isEmpty()) { - groups.insert(Q2PSTRING(newGroupName_->text())); - } - return groups; + std::set groups; + foreach(const CheckBoxMap::value_type& group, checkBoxes_) { + if (group.second->checkState() == Qt::Checked) { + groups.insert(group.first); + } + } + if (newGroup_->checkState() == Qt::Checked && !newGroupName_->text().isEmpty()) { + groups.insert(Q2PSTRING(newGroupName_->text())); + } + return groups; } void QtContactEditWidget::setNameSuggestions(const std::vector& suggestions) { - throbberLabel_->movie()->stop(); - throbberLabel_->hide(); - - // remove old suggestions except for the user input text field - QLayoutItem* suggestionItem = NULL; - while ((suggestionItem = suggestionsLayout_->itemAt(0)) && suggestionItem->widget() != name_) { - QWidget* suggestionWidget = suggestionItem->widget(); - suggestionsLayout_->removeWidget(suggestionWidget); - delete suggestionWidget; - } - - // populate new suggestions - foreach(const std::string& name, suggestions) { - suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this)); - } - - nameRadioButton_ = new QRadioButton(tr("Name:"), this); - suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_); - - QRadioButton* suggestedRadioButton = 0; - QList radioButtons = findChildren(); - foreach (QRadioButton* candidate, radioButtons) { - if (candidate->text() == name_->text()) { - suggestedRadioButton = candidate; - break; - } - } - if (suggestedRadioButton) { - suggestedRadioButton->setChecked(true); - } else { - nameRadioButton_->setChecked(true); - } + throbberLabel_->movie()->stop(); + throbberLabel_->hide(); + + // remove old suggestions except for the user input text field + QLayoutItem* suggestionItem = NULL; + while ((suggestionItem = suggestionsLayout_->itemAt(0)) && suggestionItem->widget() != name_) { + QWidget* suggestionWidget = suggestionItem->widget(); + suggestionsLayout_->removeWidget(suggestionWidget); + delete suggestionWidget; + } + + // populate new suggestions + foreach(const std::string& name, suggestions) { + suggestionsLayout_->insertWidget(nameLayout_->count() - 2, new QRadioButton(doubleAmpersand(name), this)); + } + + nameRadioButton_ = new QRadioButton(tr("Name:"), this); + suggestionsLayout_->insertWidget(nameLayout_->count(), nameRadioButton_); + + QRadioButton* suggestedRadioButton = 0; + QList radioButtons = findChildren(); + foreach (QRadioButton* candidate, radioButtons) { + if (candidate->text() == name_->text()) { + suggestedRadioButton = candidate; + break; + } + } + if (suggestedRadioButton) { + suggestedRadioButton->setChecked(true); + } else { + nameRadioButton_->setChecked(true); + } } QString QtContactEditWidget::doubleAmpersand(const std::string& name) const { - return P2QSTRING(name).replace("&", "&&"); + return P2QSTRING(name).replace("&", "&&"); } std::string QtContactEditWidget::singleAmpersand(const QString& name) const { - return Q2PSTRING(QString(name).replace("&&", "&")); + return Q2PSTRING(QString(name).replace("&&", "&")); } void QtContactEditWidget::clear() { - name_->clear(); - setSelectedGroups(std::vector()); - newGroup_->setChecked(false); - newGroupName_->clear(); - throbberLabel_->movie()->start(); - throbberLabel_->show(); - - // clear suggestions - while(suggestionsLayout_->count() != 0) { - QLayoutItem *layoutItem = suggestionsLayout_->takeAt(0); - delete layoutItem->widget(); - delete layoutItem; - } - nameRadioButton_ = NULL; + name_->clear(); + setSelectedGroups(std::vector()); + newGroup_->setChecked(false); + newGroupName_->clear(); + throbberLabel_->movie()->start(); + throbberLabel_->show(); + + // clear suggestions + while(suggestionsLayout_->count() != 0) { + QLayoutItem *layoutItem = suggestionsLayout_->takeAt(0); + delete layoutItem->widget(); + delete layoutItem; + } + nameRadioButton_ = NULL; } } diff --git a/Swift/QtUI/QtContactEditWidget.h b/Swift/QtUI/QtContactEditWidget.h index a9f1305..5c081e9 100644 --- a/Swift/QtUI/QtContactEditWidget.h +++ b/Swift/QtUI/QtContactEditWidget.h @@ -22,37 +22,37 @@ class QHBoxLayout; class QRadioButton; namespace Swift { - class QtContactEditWidget : public QWidget { - Q_OBJECT - - public: - QtContactEditWidget(const std::set& allGroups, QWidget* parent); - - void setName(const std::string&); - std::string getName() const; - - void setSelectedGroups(const std::vector& groups); - std::set getSelectedGroups() const; - - void setNameSuggestions(const std::vector& suggestions); - - void clear(); - - - private: - QString doubleAmpersand(const std::string& name) const; - std::string singleAmpersand(const QString& name) const; - private: - typedef std::map CheckBoxMap; - CheckBoxMap checkBoxes_; - QHBoxLayout* nameLayout_; - QHBoxLayout* suggestionsLayout_; - QRadioButton* nameRadioButton_; - QLineEdit* name_; - QWidget* groups_; - QCheckBox* newGroup_; - QLineEdit* newGroupName_; - QLabel* throbberLabel_; - }; + class QtContactEditWidget : public QWidget { + Q_OBJECT + + public: + QtContactEditWidget(const std::set& allGroups, QWidget* parent); + + void setName(const std::string&); + std::string getName() const; + + void setSelectedGroups(const std::vector& groups); + std::set getSelectedGroups() const; + + void setNameSuggestions(const std::vector& suggestions); + + void clear(); + + + private: + QString doubleAmpersand(const std::string& name) const; + std::string singleAmpersand(const QString& name) const; + private: + typedef std::map CheckBoxMap; + CheckBoxMap checkBoxes_; + QHBoxLayout* nameLayout_; + QHBoxLayout* suggestionsLayout_; + QRadioButton* nameRadioButton_; + QLineEdit* name_; + QWidget* groups_; + QCheckBox* newGroup_; + QLineEdit* newGroupName_; + QLabel* throbberLabel_; + }; } diff --git a/Swift/QtUI/QtContactEditWindow.cpp b/Swift/QtUI/QtContactEditWindow.cpp index abd247a..214f256 100644 --- a/Swift/QtUI/QtContactEditWindow.cpp +++ b/Swift/QtUI/QtContactEditWindow.cpp @@ -24,84 +24,84 @@ namespace Swift { QtContactEditWindow::QtContactEditWindow() : contactEditWidget_(NULL) { - resize(400,300); - setWindowTitle(tr("Edit contact")); - setContentsMargins(0,0,0,0); - - QBoxLayout* layout = new QVBoxLayout(this); - - jidLabel_ = new QLabel(this); - jidLabel_->setAlignment(Qt::AlignHCenter); - layout->addWidget(jidLabel_); - - groupsLayout_ = new QVBoxLayout(); - groupsLayout_->setContentsMargins(0,0,0,0); - layout->addLayout(groupsLayout_); - - QHBoxLayout* buttonLayout = new QHBoxLayout(); - layout->addLayout(buttonLayout); - QPushButton* removeButton = new QPushButton(tr("Remove contact"), this); - connect(removeButton, SIGNAL(clicked()), this, SLOT(handleRemoveContact())); - buttonLayout->addWidget(removeButton); - QPushButton* okButton = new QPushButton(tr("OK"), this); - okButton->setDefault( true ); - connect(okButton, SIGNAL(clicked()), this, SLOT(handleUpdateContact())); - buttonLayout->addStretch(); - buttonLayout->addWidget(okButton); + resize(400,300); + setWindowTitle(tr("Edit contact")); + setContentsMargins(0,0,0,0); + + QBoxLayout* layout = new QVBoxLayout(this); + + jidLabel_ = new QLabel(this); + jidLabel_->setAlignment(Qt::AlignHCenter); + layout->addWidget(jidLabel_); + + groupsLayout_ = new QVBoxLayout(); + groupsLayout_->setContentsMargins(0,0,0,0); + layout->addLayout(groupsLayout_); + + QHBoxLayout* buttonLayout = new QHBoxLayout(); + layout->addLayout(buttonLayout); + QPushButton* removeButton = new QPushButton(tr("Remove contact"), this); + connect(removeButton, SIGNAL(clicked()), this, SLOT(handleRemoveContact())); + buttonLayout->addWidget(removeButton); + QPushButton* okButton = new QPushButton(tr("OK"), this); + okButton->setDefault( true ); + connect(okButton, SIGNAL(clicked()), this, SLOT(handleUpdateContact())); + buttonLayout->addStretch(); + buttonLayout->addWidget(okButton); } QtContactEditWindow::~QtContactEditWindow() { } void QtContactEditWindow::setNameSuggestions(const std::vector& nameSuggestions) { - if (contactEditWidget_) { - contactEditWidget_->setNameSuggestions(nameSuggestions); - } + if (contactEditWidget_) { + contactEditWidget_->setNameSuggestions(nameSuggestions); + } } void QtContactEditWindow::setContact(const JID& jid, const std::string& name, const std::vector& groups, const std::set& allGroups) { - delete contactEditWidget_; - jid_ = jid; - jidLabel_->setText("" + P2QSTRING(jid.toString()) + ""); - - contactEditWidget_ = new QtContactEditWidget(allGroups, this); - groupsLayout_->addWidget(contactEditWidget_); - contactEditWidget_->setName(name); - contactEditWidget_->setSelectedGroups(groups); + delete contactEditWidget_; + jid_ = jid; + jidLabel_->setText("" + P2QSTRING(jid.toString()) + ""); + + contactEditWidget_ = new QtContactEditWidget(allGroups, this); + groupsLayout_->addWidget(contactEditWidget_); + contactEditWidget_->setName(name); + contactEditWidget_->setSelectedGroups(groups); } void QtContactEditWindow::setEnabled(bool b) { - QWidget::setEnabled(b); + QWidget::setEnabled(b); } void QtContactEditWindow::show() { - QWidget::showNormal(); - QWidget::activateWindow(); - QWidget::raise(); + QWidget::showNormal(); + QWidget::activateWindow(); + QWidget::raise(); } void QtContactEditWindow::hide() { - QWidget::hide(); + QWidget::hide(); } void QtContactEditWindow::handleRemoveContact() { - if (confirmContactDeletion(jid_)) { - onRemoveContactRequest(); - } + if (confirmContactDeletion(jid_)) { + onRemoveContactRequest(); + } } bool QtContactEditWindow::confirmContactDeletion(const JID& jid) { - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Confirm contact deletion")); - msgBox.setText(tr("Are you sure you want to delete this contact?")); - msgBox.setInformativeText(QString(tr("This will remove the contact '%1' from all groups they may be in.")).arg(P2QSTRING(jid.toString()))); - msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); - msgBox.setDefaultButton(QMessageBox::Yes); - return msgBox.exec() == QMessageBox::Yes; + QMessageBox msgBox; + msgBox.setWindowTitle(tr("Confirm contact deletion")); + msgBox.setText(tr("Are you sure you want to delete this contact?")); + msgBox.setInformativeText(QString(tr("This will remove the contact '%1' from all groups they may be in.")).arg(P2QSTRING(jid.toString()))); + msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); + msgBox.setDefaultButton(QMessageBox::Yes); + return msgBox.exec() == QMessageBox::Yes; } void QtContactEditWindow::handleUpdateContact() { - onChangeContactRequest(contactEditWidget_->getName(), contactEditWidget_->getSelectedGroups()); + onChangeContactRequest(contactEditWidget_->getName(), contactEditWidget_->getSelectedGroups()); } } diff --git a/Swift/QtUI/QtContactEditWindow.h b/Swift/QtUI/QtContactEditWindow.h index a6c73b9..655fbb4 100644 --- a/Swift/QtUI/QtContactEditWindow.h +++ b/Swift/QtUI/QtContactEditWindow.h @@ -19,33 +19,33 @@ class QLabel; class QVBoxLayout; namespace Swift { - class QtContactEditWidget; + class QtContactEditWidget; - class QtContactEditWindow : public QWidget, public ContactEditWindow { - Q_OBJECT + class QtContactEditWindow : public QWidget, public ContactEditWindow { + Q_OBJECT - public: - QtContactEditWindow(); - virtual ~QtContactEditWindow(); + public: + QtContactEditWindow(); + virtual ~QtContactEditWindow(); - virtual void setNameSuggestions(const std::vector& nameSuggestions); - virtual void setContact(const JID& jid, const std::string& name, const std::vector& groups, const std::set& allGroups); + virtual void setNameSuggestions(const std::vector& nameSuggestions); + virtual void setContact(const JID& jid, const std::string& name, const std::vector& groups, const std::set& allGroups); - void setEnabled(bool); - void show(); - void hide(); + void setEnabled(bool); + void show(); + void hide(); - static bool confirmContactDeletion(const JID& jid); + static bool confirmContactDeletion(const JID& jid); - private slots: - void handleRemoveContact(); - void handleUpdateContact(); + private slots: + void handleRemoveContact(); + void handleUpdateContact(); - private: - JID jid_; - QVBoxLayout* groupsLayout_; - QLabel* jidLabel_; - QtContactEditWidget* contactEditWidget_; - }; + private: + JID jid_; + QVBoxLayout* groupsLayout_; + QLabel* jidLabel_; + QtContactEditWidget* contactEditWidget_; + }; } diff --git a/Swift/QtUI/QtDBUSURIHandler.cpp b/Swift/QtUI/QtDBUSURIHandler.cpp index 71a7016..c873676 100644 --- a/Swift/QtUI/QtDBUSURIHandler.cpp +++ b/Swift/QtUI/QtDBUSURIHandler.cpp @@ -14,28 +14,28 @@ using namespace Swift; namespace { - class DBUSAdaptor: public QDBusAbstractAdaptor { - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "im.swift.Swift.URIHandler"); - public: - DBUSAdaptor(QtDBUSURIHandler* uriHandler) : QDBusAbstractAdaptor(uriHandler), uriHandler(uriHandler) { - } - - public slots: - void openURI(const QString& uri) { - uriHandler->onURI(Q2PSTRING(uri)); - } - - private: - QtDBUSURIHandler* uriHandler; - }; + class DBUSAdaptor: public QDBusAbstractAdaptor { + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "im.swift.Swift.URIHandler"); + public: + DBUSAdaptor(QtDBUSURIHandler* uriHandler) : QDBusAbstractAdaptor(uriHandler), uriHandler(uriHandler) { + } + + public slots: + void openURI(const QString& uri) { + uriHandler->onURI(Q2PSTRING(uri)); + } + + private: + QtDBUSURIHandler* uriHandler; + }; } QtDBUSURIHandler::QtDBUSURIHandler() { - new DBUSAdaptor(this); - QDBusConnection connection = QDBusConnection::sessionBus(); - connection.registerService("im.swift.Swift.URIHandler"); - connection.registerObject("/", this); + new DBUSAdaptor(this); + QDBusConnection connection = QDBusConnection::sessionBus(); + connection.registerService("im.swift.Swift.URIHandler"); + connection.registerObject("/", this); } #include "QtDBUSURIHandler.moc" diff --git a/Swift/QtUI/QtDBUSURIHandler.h b/Swift/QtUI/QtDBUSURIHandler.h index cb16892..3cd12f7 100644 --- a/Swift/QtUI/QtDBUSURIHandler.h +++ b/Swift/QtUI/QtDBUSURIHandler.h @@ -11,8 +11,8 @@ #include namespace Swift { - class QtDBUSURIHandler : public QObject, public URIHandler { - public: - QtDBUSURIHandler(); - }; + class QtDBUSURIHandler : public QObject, public URIHandler { + public: + QtDBUSURIHandler(); + }; } diff --git a/Swift/QtUI/QtEditBookmarkWindow.cpp b/Swift/QtUI/QtEditBookmarkWindow.cpp index 756e377..a17b1aa 100644 --- a/Swift/QtUI/QtEditBookmarkWindow.cpp +++ b/Swift/QtUI/QtEditBookmarkWindow.cpp @@ -10,20 +10,20 @@ namespace Swift { QtEditBookmarkWindow::QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark) : eventStream_(eventStream), bookmark_(bookmark) { - name_->setText(P2QSTRING(bookmark.getName())); - room_->setText(P2QSTRING(bookmark.getRoom().toString())); - autojoin_->setChecked(bookmark.getAutojoin()); - nick_->setText(bookmark.getNick() ? P2QSTRING(bookmark.getNick().get()) : ""); - password_->setText(bookmark.getPassword() ? P2QSTRING(bookmark.getPassword().get()) : ""); + name_->setText(P2QSTRING(bookmark.getName())); + room_->setText(P2QSTRING(bookmark.getRoom().toString())); + autojoin_->setChecked(bookmark.getAutojoin()); + nick_->setText(bookmark.getNick() ? P2QSTRING(bookmark.getNick().get()) : ""); + password_->setText(bookmark.getPassword() ? P2QSTRING(bookmark.getPassword().get()) : ""); } bool QtEditBookmarkWindow::commit() { - boost::optional bookmark = createBookmarkFromForm(); - if (!bookmark) { - return false; - } - eventStream_->send(boost::shared_ptr(new EditMUCBookmarkUIEvent(bookmark_, *bookmark))); - return true; + boost::optional bookmark = createBookmarkFromForm(); + if (!bookmark) { + return false; + } + eventStream_->send(boost::shared_ptr(new EditMUCBookmarkUIEvent(bookmark_, *bookmark))); + return true; } } diff --git a/Swift/QtUI/QtEditBookmarkWindow.h b/Swift/QtUI/QtEditBookmarkWindow.h index 1d7d08b..337ba1f 100644 --- a/Swift/QtUI/QtEditBookmarkWindow.h +++ b/Swift/QtUI/QtEditBookmarkWindow.h @@ -12,14 +12,14 @@ #include namespace Swift { - class QtEditBookmarkWindow : public QtBookmarkDetailWindow { - Q_OBJECT - public: - QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark); - bool commit(); - - private: - UIEventStream* eventStream_; - MUCBookmark bookmark_; - }; + class QtEditBookmarkWindow : public QtBookmarkDetailWindow { + Q_OBJECT + public: + QtEditBookmarkWindow(UIEventStream* eventStream, const MUCBookmark& bookmark); + bool commit(); + + private: + UIEventStream* eventStream_; + MUCBookmark bookmark_; + }; } diff --git a/Swift/QtUI/QtElidingLabel.cpp b/Swift/QtUI/QtElidingLabel.cpp index f5a39f0..4707f9f 100644 --- a/Swift/QtUI/QtElidingLabel.cpp +++ b/Swift/QtUI/QtElidingLabel.cpp @@ -8,17 +8,17 @@ namespace Swift { QtElidingLabel::QtElidingLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f) { - fullText_ = ""; - dirty_ = true; - setSizes(); - setTextFormat(Qt::PlainText); + fullText_ = ""; + dirty_ = true; + setSizes(); + setTextFormat(Qt::PlainText); } QtElidingLabel::QtElidingLabel(const QString& text, QWidget* parent, Qt::WindowFlags f) : QLabel(text, parent, f) { - fullText_ = text; - dirty_ = true; - setSizes(); - setTextFormat(Qt::PlainText); + fullText_ = text; + dirty_ = true; + setSizes(); + setTextFormat(Qt::PlainText); } QtElidingLabel::~QtElidingLabel() { @@ -26,35 +26,35 @@ QtElidingLabel::~QtElidingLabel() { } QSize QtElidingLabel::sizeHint() const { - return sizeHint_; + return sizeHint_; } void QtElidingLabel::setSizes() { - setMinimumSize(1, minimumHeight()); + setMinimumSize(1, minimumHeight()); } void QtElidingLabel::setText(const QString& text) { - fullText_ = text; - QLabel::setText(text); - sizeHint_ = QLabel::sizeHint(); - dirty_ = true; + fullText_ = text; + QLabel::setText(text); + sizeHint_ = QLabel::sizeHint(); + dirty_ = true; } void QtElidingLabel::paintEvent(QPaintEvent* event) { - QRect rect = contentsRect(); - dirty_ = dirty_ || rect != lastRect_; - if (dirty_) { - lastRect_ = rect; - int fontWidth = fontMetrics().width(fullText_); - if (fontWidth > rect.width()) { - QString elidedText(fontMetrics().elidedText(fullText_, Qt::ElideRight, rect.width(), Qt::TextShowMnemonic)); - QLabel::setText(elidedText); - } else { - QLabel::setText(fullText_); - } - dirty_ = false; - } - QLabel::paintEvent(event); + QRect rect = contentsRect(); + dirty_ = dirty_ || rect != lastRect_; + if (dirty_) { + lastRect_ = rect; + int fontWidth = fontMetrics().width(fullText_); + if (fontWidth > rect.width()) { + QString elidedText(fontMetrics().elidedText(fullText_, Qt::ElideRight, rect.width(), Qt::TextShowMnemonic)); + QLabel::setText(elidedText); + } else { + QLabel::setText(fullText_); + } + dirty_ = false; + } + QLabel::paintEvent(event); } } diff --git a/Swift/QtUI/QtElidingLabel.h b/Swift/QtUI/QtElidingLabel.h index 84fa00f..9f590a8 100644 --- a/Swift/QtUI/QtElidingLabel.h +++ b/Swift/QtUI/QtElidingLabel.h @@ -9,23 +9,23 @@ #include namespace Swift { - class QtElidingLabel : public QLabel { - Q_OBJECT - public: - QtElidingLabel(QWidget* parent = NULL, Qt::WindowFlags f = 0); - QtElidingLabel(const QString &text, QWidget* parent = NULL, Qt::WindowFlags f = 0); - void setText(const QString& text); - virtual ~QtElidingLabel(); - - virtual QSize sizeHint() const; + class QtElidingLabel : public QLabel { + Q_OBJECT + public: + QtElidingLabel(QWidget* parent = NULL, Qt::WindowFlags f = 0); + QtElidingLabel(const QString &text, QWidget* parent = NULL, Qt::WindowFlags f = 0); + void setText(const QString& text); + virtual ~QtElidingLabel(); - virtual void paintEvent(QPaintEvent* event); + virtual QSize sizeHint() const; - private: - void setSizes(); - bool dirty_; - QString fullText_; - QRect lastRect_; - QSize sizeHint_; - }; + virtual void paintEvent(QPaintEvent* event); + + private: + void setSizes(); + bool dirty_; + QString fullText_; + QRect lastRect_; + QSize sizeHint_; + }; } diff --git a/Swift/QtUI/QtEmoticonCell.cpp b/Swift/QtUI/QtEmoticonCell.cpp index a781876..fe580aa 100644 --- a/Swift/QtUI/QtEmoticonCell.cpp +++ b/Swift/QtUI/QtEmoticonCell.cpp @@ -15,11 +15,11 @@ namespace Swift { QtEmoticonCell::QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent) : QLabel(parent), emoticonAsText_(emoticonAsText) { - if (filePath.startsWith("qrc:/")) { - filePath.remove(0, 3); - } - setPixmap(QPixmap(filePath)); - setToolTip(emoticonAsText_); + if (filePath.startsWith("qrc:/")) { + filePath.remove(0, 3); + } + setPixmap(QPixmap(filePath)); + setToolTip(emoticonAsText_); } QtEmoticonCell::~QtEmoticonCell() { @@ -27,8 +27,8 @@ QtEmoticonCell::~QtEmoticonCell() { } void QtEmoticonCell::mousePressEvent (QMouseEvent* event) { - emit emoticonClicked(emoticonAsText_); - QLabel::mousePressEvent(event); + emit emoticonClicked(emoticonAsText_); + QLabel::mousePressEvent(event); } } diff --git a/Swift/QtUI/QtEmoticonCell.h b/Swift/QtUI/QtEmoticonCell.h index 379f5d6..e408a83 100644 --- a/Swift/QtUI/QtEmoticonCell.h +++ b/Swift/QtUI/QtEmoticonCell.h @@ -18,17 +18,17 @@ class QMouseEvent; namespace Swift { - class QtEmoticonCell : public QLabel { - Q_OBJECT - public: - QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent = 0); - ~QtEmoticonCell(); - virtual void mousePressEvent(QMouseEvent* event); - - signals: - void emoticonClicked(QString emoticonAsText); - - private: - QString emoticonAsText_; - }; + class QtEmoticonCell : public QLabel { + Q_OBJECT + public: + QtEmoticonCell(const QString emoticonAsText, QString filePath, QWidget* parent = 0); + ~QtEmoticonCell(); + virtual void mousePressEvent(QMouseEvent* event); + + signals: + void emoticonClicked(QString emoticonAsText); + + private: + QString emoticonAsText_; + }; } diff --git a/Swift/QtUI/QtEmoticonsGrid.cpp b/Swift/QtUI/QtEmoticonsGrid.cpp index 82fb7e8..a81f516 100644 --- a/Swift/QtUI/QtEmoticonsGrid.cpp +++ b/Swift/QtUI/QtEmoticonsGrid.cpp @@ -25,23 +25,23 @@ namespace Swift { typedef std::map EmoticonsMap; // Without this typedef compiler complains when using foreach QtEmoticonsGrid::QtEmoticonsGrid(const std::map& emoticons, QWidget* parent) : QGridLayout(parent) { - makeUniqueEmoticonsMap(emoticons); - - // Create grid: 3 columns, [uniqueEmoticons_.size()/3] rows - int row = 0; - int column = 0; - - foreach(EmoticonsMap::value_type emoticon, uniqueEmoticons_) { - QtEmoticonCell* newCell = new QtEmoticonCell(P2QSTRING(emoticon.first), P2QSTRING(emoticon.second)); - addWidget(newCell, row, column); - connect(newCell, SIGNAL(emoticonClicked(QString)), this, SLOT(emoticonClickedSlot(QString))); - - column++; - if (column >= 3) { - column = 0; - row++; - } - } + makeUniqueEmoticonsMap(emoticons); + + // Create grid: 3 columns, [uniqueEmoticons_.size()/3] rows + int row = 0; + int column = 0; + + foreach(EmoticonsMap::value_type emoticon, uniqueEmoticons_) { + QtEmoticonCell* newCell = new QtEmoticonCell(P2QSTRING(emoticon.first), P2QSTRING(emoticon.second)); + addWidget(newCell, row, column); + connect(newCell, SIGNAL(emoticonClicked(QString)), this, SLOT(emoticonClickedSlot(QString))); + + column++; + if (column >= 3) { + column = 0; + row++; + } + } } QtEmoticonsGrid::~QtEmoticonsGrid() { @@ -49,17 +49,17 @@ QtEmoticonsGrid::~QtEmoticonsGrid() { } void QtEmoticonsGrid::makeUniqueEmoticonsMap(const std::map& emoticons) { - std::set paths; - reverse_foreach(EmoticonsMap::value_type emoticon, emoticons) { - if (paths.find(emoticon.second) == paths.end()) { - uniqueEmoticons_.insert(emoticon); - paths.insert(emoticon.second); - } - } + std::set paths; + reverse_foreach(EmoticonsMap::value_type emoticon, emoticons) { + if (paths.find(emoticon.second) == paths.end()) { + uniqueEmoticons_.insert(emoticon); + paths.insert(emoticon.second); + } + } } void QtEmoticonsGrid::emoticonClickedSlot(QString emoticonAsText) { - emit emoticonClicked(emoticonAsText); + emit emoticonClicked(emoticonAsText); } } diff --git a/Swift/QtUI/QtEmoticonsGrid.h b/Swift/QtUI/QtEmoticonsGrid.h index b045b26..0cae9ab 100644 --- a/Swift/QtUI/QtEmoticonsGrid.h +++ b/Swift/QtUI/QtEmoticonsGrid.h @@ -20,21 +20,21 @@ class QWidget; namespace Swift { - class QtEmoticonsGrid : public QGridLayout { - Q_OBJECT - public: - explicit QtEmoticonsGrid(const std::map& emoticons, QWidget* parent = 0); - virtual ~QtEmoticonsGrid(); + class QtEmoticonsGrid : public QGridLayout { + Q_OBJECT + public: + explicit QtEmoticonsGrid(const std::map& emoticons, QWidget* parent = 0); + virtual ~QtEmoticonsGrid(); - signals: - void emoticonClicked(QString emoticonAsText); + signals: + void emoticonClicked(QString emoticonAsText); - public slots: - void emoticonClickedSlot(QString emoticonAsText); + public slots: + void emoticonClickedSlot(QString emoticonAsText); - private: - void makeUniqueEmoticonsMap(const std::map& emoticons); + private: + void makeUniqueEmoticonsMap(const std::map& emoticons); - std::map uniqueEmoticons_; - }; + std::map uniqueEmoticons_; + }; } diff --git a/Swift/QtUI/QtFileTransferListItemModel.cpp b/Swift/QtUI/QtFileTransferListItemModel.cpp index ef73f4f..d26733b 100644 --- a/Swift/QtUI/QtFileTransferListItemModel.cpp +++ b/Swift/QtUI/QtFileTransferListItemModel.cpp @@ -29,115 +29,115 @@ QtFileTransferListItemModel::QtFileTransferListItemModel(QObject *parent) : QAbs } QtFileTransferListItemModel::~QtFileTransferListItemModel() { - if (fileTransferOverview) { - fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1)); - fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this)); - } + if (fileTransferOverview) { + fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1)); + fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this)); + } } void QtFileTransferListItemModel::setFileTransferOverview(FileTransferOverview *overview) { - if (fileTransferOverview) { - fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1)); - fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this)); - } - fileTransferOverview = overview; - if (fileTransferOverview) { - fileTransferOverview->onNewFileTransferController.connect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1)); - fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this)); - } - emit layoutAboutToBeChanged(); - emit layoutChanged(); + if (fileTransferOverview) { + fileTransferOverview->onNewFileTransferController.disconnect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1)); + fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this)); + } + fileTransferOverview = overview; + if (fileTransferOverview) { + fileTransferOverview->onNewFileTransferController.connect(boost::bind(&QtFileTransferListItemModel::handleNewFileTransferController, this, _1)); + fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListItemModel::handleFileTransferListChanged, this)); + } + emit layoutAboutToBeChanged(); + emit layoutChanged(); } void QtFileTransferListItemModel::handleNewFileTransferController(FileTransferController* newController) { - emit layoutAboutToBeChanged(); - emit layoutChanged(); - dataChanged(createIndex(0,0), createIndex(fileTransferOverview->getFileTransfers().size(),4)); - newController->onStateChanged.connect(boost::bind(&QtFileTransferListItemModel::handleStateChange, this, fileTransferOverview->getFileTransfers().size() - 1)); - newController->onProgressChange.connect(boost::bind(&QtFileTransferListItemModel::handleProgressChange, this, fileTransferOverview->getFileTransfers().size() - 1)); + emit layoutAboutToBeChanged(); + emit layoutChanged(); + dataChanged(createIndex(0,0), createIndex(fileTransferOverview->getFileTransfers().size(),4)); + newController->onStateChanged.connect(boost::bind(&QtFileTransferListItemModel::handleStateChange, this, fileTransferOverview->getFileTransfers().size() - 1)); + newController->onProgressChange.connect(boost::bind(&QtFileTransferListItemModel::handleProgressChange, this, fileTransferOverview->getFileTransfers().size() - 1)); } void QtFileTransferListItemModel::handleFileTransferListChanged() { - emit layoutAboutToBeChanged(); - emit layoutChanged(); + emit layoutAboutToBeChanged(); + emit layoutChanged(); } void QtFileTransferListItemModel::handleStateChange(int index) { - emit dataChanged(createIndex(index, 2), createIndex(index, 2)); + emit dataChanged(createIndex(index, 2), createIndex(index, 2)); } void QtFileTransferListItemModel::handleProgressChange(int index) { - emit dataChanged(createIndex(index, 3), createIndex(index, 3)); + emit dataChanged(createIndex(index, 3), createIndex(index, 3)); } QVariant QtFileTransferListItemModel::headerData(int section, Qt::Orientation /* orientation */, int role) const { - if (role != Qt::DisplayRole) return QVariant(); - if (section == Direction) return QVariant(QObject::tr("Direction")); - if (section == OtherParty) return QVariant(QObject::tr("Other Party")); - if (section == State) return QVariant(QObject::tr("State")); - if (section == Progress) return QVariant(QObject::tr("Progress")); - if (section == OverallSize) return QVariant(QObject::tr("Size")); - return QVariant(); + if (role != Qt::DisplayRole) return QVariant(); + if (section == Direction) return QVariant(QObject::tr("Direction")); + if (section == OtherParty) return QVariant(QObject::tr("Other Party")); + if (section == State) return QVariant(QObject::tr("State")); + if (section == Progress) return QVariant(QObject::tr("Progress")); + if (section == OverallSize) return QVariant(QObject::tr("Size")); + return QVariant(); } int QtFileTransferListItemModel::columnCount(const QModelIndex& /* parent */) const { - return NoOfColumns; + return NoOfColumns; } QVariant QtFileTransferListItemModel::data(const QModelIndex &index, int role) const { - if (role != Qt::DisplayRole || !index.isValid() || - !fileTransferOverview || static_cast(index.row()) >= fileTransferOverview->getFileTransfers().size()) { - return QVariant(); - } - FileTransferController* controller = fileTransferOverview->getFileTransfers().at(index.row()); - if (index.column() == Direction) { - return controller->isIncoming() ? QVariant(QObject::tr("Incoming")) : QVariant(QObject::tr("Outgoing")); - } - if (index.column() == OtherParty) { - return QVariant(P2QSTRING(controller->getOtherParty().toString())); - } - if (index.column() == State) { - FileTransfer::State state = controller->getState(); - switch(state.type) { - case FileTransfer::State::Initial: - assert(false); - return QVariant(""); - case FileTransfer::State::WaitingForStart: - return QVariant(QObject::tr("Waiting for start")); - case FileTransfer::State::WaitingForAccept: - return QVariant(QObject::tr("Waiting for other side to accept")); - case FileTransfer::State::Negotiating: - return QVariant(QObject::tr("Negotiating")); - case FileTransfer::State::Transferring: - return QVariant(QObject::tr("Transferring")); - case FileTransfer::State::Finished: - return QVariant(QObject::tr("Finished")); - case FileTransfer::State::Failed: - return QVariant(QObject::tr("Failed")); - case FileTransfer::State::Canceled: - return QVariant(QObject::tr("Canceled")); - } - } - - if (index.column() == Progress) { - return QVariant(QString::number(controller->getProgress())); - } - if (index.column() == OverallSize) { - return QVariant(P2QSTRING(formatSize((controller->getSize())))); - } - return QVariant(); + if (role != Qt::DisplayRole || !index.isValid() || + !fileTransferOverview || static_cast(index.row()) >= fileTransferOverview->getFileTransfers().size()) { + return QVariant(); + } + FileTransferController* controller = fileTransferOverview->getFileTransfers().at(index.row()); + if (index.column() == Direction) { + return controller->isIncoming() ? QVariant(QObject::tr("Incoming")) : QVariant(QObject::tr("Outgoing")); + } + if (index.column() == OtherParty) { + return QVariant(P2QSTRING(controller->getOtherParty().toString())); + } + if (index.column() == State) { + FileTransfer::State state = controller->getState(); + switch(state.type) { + case FileTransfer::State::Initial: + assert(false); + return QVariant(""); + case FileTransfer::State::WaitingForStart: + return QVariant(QObject::tr("Waiting for start")); + case FileTransfer::State::WaitingForAccept: + return QVariant(QObject::tr("Waiting for other side to accept")); + case FileTransfer::State::Negotiating: + return QVariant(QObject::tr("Negotiating")); + case FileTransfer::State::Transferring: + return QVariant(QObject::tr("Transferring")); + case FileTransfer::State::Finished: + return QVariant(QObject::tr("Finished")); + case FileTransfer::State::Failed: + return QVariant(QObject::tr("Failed")); + case FileTransfer::State::Canceled: + return QVariant(QObject::tr("Canceled")); + } + } + + if (index.column() == Progress) { + return QVariant(QString::number(controller->getProgress())); + } + if (index.column() == OverallSize) { + return QVariant(P2QSTRING(formatSize((controller->getSize())))); + } + return QVariant(); } QModelIndex QtFileTransferListItemModel::parent(const QModelIndex& /* child */) const { - return createIndex(0,0); + return createIndex(0,0); } int QtFileTransferListItemModel::rowCount(const QModelIndex& /* parent */) const { - return fileTransferOverview ? fileTransferOverview->getFileTransfers().size() : 0; + return fileTransferOverview ? fileTransferOverview->getFileTransfers().size() : 0; } QModelIndex QtFileTransferListItemModel::index(int row, int column, const QModelIndex& /* parent */) const { - return createIndex(row, column, static_cast(0)); + return createIndex(row, column, static_cast(0)); } } diff --git a/Swift/QtUI/QtFileTransferListItemModel.h b/Swift/QtUI/QtFileTransferListItemModel.h index 64cdca4..d0e0e42 100644 --- a/Swift/QtUI/QtFileTransferListItemModel.h +++ b/Swift/QtUI/QtFileTransferListItemModel.h @@ -20,42 +20,42 @@ class FileTransferController; class FileTransferOverview; class QtFileTransferListItemModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT public: - explicit QtFileTransferListItemModel(QObject *parent = 0); - virtual ~QtFileTransferListItemModel(); + explicit QtFileTransferListItemModel(QObject *parent = 0); + virtual ~QtFileTransferListItemModel(); - void setFileTransferOverview(FileTransferOverview*); + void setFileTransferOverview(FileTransferOverview*); - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - int columnCount(const QModelIndex &parent) const; - QVariant data(const QModelIndex &index, int role) const; - QModelIndex parent(const QModelIndex &child) const; - int rowCount(const QModelIndex &parent) const; - QModelIndex index(int row, int column, const QModelIndex &parent) const; + QVariant headerData(int section, Qt::Orientation orientation, int role) const; + int columnCount(const QModelIndex &parent) const; + QVariant data(const QModelIndex &index, int role) const; + QModelIndex parent(const QModelIndex &child) const; + int rowCount(const QModelIndex &parent) const; + QModelIndex index(int row, int column, const QModelIndex &parent) const; private: - enum Columns { - Direction = 0, - OtherParty, - State, - Progress, - OverallSize, - NoOfColumns - }; + enum Columns { + Direction = 0, + OtherParty, + State, + Progress, + OverallSize, + NoOfColumns + }; private: - void handleNewFileTransferController(FileTransferController*); - void handleFileTransferListChanged(); - void handleStateChange(int index); - void handleProgressChange(int index); + void handleNewFileTransferController(FileTransferController*); + void handleFileTransferListChanged(); + void handleStateChange(int index); + void handleProgressChange(int index); signals: public slots: private: - FileTransferOverview *fileTransferOverview; + FileTransferOverview *fileTransferOverview; }; diff --git a/Swift/QtUI/QtFileTransferListWidget.cpp b/Swift/QtUI/QtFileTransferListWidget.cpp index d95cd06..f67b510 100644 --- a/Swift/QtUI/QtFileTransferListWidget.cpp +++ b/Swift/QtUI/QtFileTransferListWidget.cpp @@ -26,86 +26,86 @@ namespace Swift { QtFileTransferListWidget::QtFileTransferListWidget() : fileTransferOverview(0) { - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setSpacing(0); - layout->setContentsMargins(0,0,0,0); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setSpacing(0); + layout->setContentsMargins(0,0,0,0); - treeView = new QTreeView(this); - treeView->setRootIsDecorated(false); - treeView->setItemsExpandable(false); - layout->addWidget(treeView); + treeView = new QTreeView(this); + treeView->setRootIsDecorated(false); + treeView->setItemsExpandable(false); + layout->addWidget(treeView); - itemModel = new QtFileTransferListItemModel(); - treeView->setModel(itemModel); + itemModel = new QtFileTransferListItemModel(); + treeView->setModel(itemModel); - QWidget* bottom = new QWidget(this); - layout->addWidget(bottom); - bottom->setAutoFillBackground(true); + QWidget* bottom = new QWidget(this); + layout->addWidget(bottom); + bottom->setAutoFillBackground(true); - QHBoxLayout* buttonLayout = new QHBoxLayout(bottom); - buttonLayout->setContentsMargins(10,0,20,0); - buttonLayout->setSpacing(0); + QHBoxLayout* buttonLayout = new QHBoxLayout(bottom); + buttonLayout->setContentsMargins(10,0,20,0); + buttonLayout->setSpacing(0); - clearFinished = new QPushButton(tr("Clear all"), bottom); - clearFinished->setEnabled(false); - connect(clearFinished, SIGNAL(clicked()), this, SLOT(clearInactiveTransfers())); - buttonLayout->addWidget(clearFinished); + clearFinished = new QPushButton(tr("Clear all"), bottom); + clearFinished->setEnabled(false); + connect(clearFinished, SIGNAL(clicked()), this, SLOT(clearInactiveTransfers())); + buttonLayout->addWidget(clearFinished); - setWindowTitle(tr("File Transfer List")); - emit titleUpdated(); + setWindowTitle(tr("File Transfer List")); + emit titleUpdated(); } QtFileTransferListWidget::~QtFileTransferListWidget() { - if (fileTransferOverview) { - fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this)); - fileTransferOverview = NULL; - } - delete itemModel; + if (fileTransferOverview) { + fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this)); + fileTransferOverview = NULL; + } + delete itemModel; } void QtFileTransferListWidget::showEvent(QShowEvent* event) { - emit windowOpening(); - emit titleUpdated(); /* This just needs to be somewhere after construction */ - QWidget::showEvent(event); + emit windowOpening(); + emit titleUpdated(); /* This just needs to be somewhere after construction */ + QWidget::showEvent(event); } void QtFileTransferListWidget::handleFileTransferListChanged() { - clearFinished->setEnabled(fileTransferOverview->isClearable()); + clearFinished->setEnabled(fileTransferOverview->isClearable()); } void QtFileTransferListWidget::clearInactiveTransfers() { - fileTransferOverview->clearFinished(); + fileTransferOverview->clearFinished(); } void QtFileTransferListWidget::show() { - QWidget::show(); - emit windowOpening(); + QWidget::show(); + emit windowOpening(); } void QtFileTransferListWidget::activate() { - emit wantsToActivate(); + emit wantsToActivate(); } void QtFileTransferListWidget::setFileTransferOverview(FileTransferOverview *overview) { - if (fileTransferOverview) { - fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this)); - fileTransferOverview = NULL; - } - if (overview) { - fileTransferOverview = overview; - fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this)); - clearFinished->setEnabled(fileTransferOverview->isClearable()); - } - itemModel->setFileTransferOverview(overview); + if (fileTransferOverview) { + fileTransferOverview->onFileTransferListChanged.disconnect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this)); + fileTransferOverview = NULL; + } + if (overview) { + fileTransferOverview = overview; + fileTransferOverview->onFileTransferListChanged.connect(boost::bind(&QtFileTransferListWidget::handleFileTransferListChanged, this)); + clearFinished->setEnabled(fileTransferOverview->isClearable()); + } + itemModel->setFileTransferOverview(overview); } std::string QtFileTransferListWidget::getID() const { - return "QtFileTransferListWidget"; + return "QtFileTransferListWidget"; } void QtFileTransferListWidget::closeEvent(QCloseEvent* event) { - emit windowClosing(); - event->accept(); + emit windowClosing(); + event->accept(); } } diff --git a/Swift/QtUI/QtFileTransferListWidget.h b/Swift/QtUI/QtFileTransferListWidget.h index 740eb15..cfc7dd2 100644 --- a/Swift/QtUI/QtFileTransferListWidget.h +++ b/Swift/QtUI/QtFileTransferListWidget.h @@ -27,33 +27,33 @@ class FileTransferOverview; class QtFileTransferListItemModel; class QtFileTransferListWidget : public QtTabbable, public FileTransferListWidget { - Q_OBJECT + Q_OBJECT public: - QtFileTransferListWidget(); - virtual ~QtFileTransferListWidget(); + QtFileTransferListWidget(); + virtual ~QtFileTransferListWidget(); - void show(); - void activate(); + void show(); + void activate(); - void setFileTransferOverview(FileTransferOverview *); + void setFileTransferOverview(FileTransferOverview *); - virtual std::string getID() const; + virtual std::string getID() const; private: - virtual void closeEvent(QCloseEvent* event); - virtual void showEvent(QShowEvent* event); - void handleFileTransferListChanged(); + virtual void closeEvent(QCloseEvent* event); + virtual void showEvent(QShowEvent* event); + void handleFileTransferListChanged(); private slots: - void clearInactiveTransfers(); + void clearInactiveTransfers(); private: - QTreeView* treeView; + QTreeView* treeView; - QtFileTransferListItemModel* itemModel; - FileTransferOverview* fileTransferOverview; - QPushButton* clearFinished; + QtFileTransferListItemModel* itemModel; + FileTransferOverview* fileTransferOverview; + QPushButton* clearFinished; }; } diff --git a/Swift/QtUI/QtFormResultItemModel.cpp b/Swift/QtUI/QtFormResultItemModel.cpp index 6a48bc5..60cf0c0 100644 --- a/Swift/QtUI/QtFormResultItemModel.cpp +++ b/Swift/QtUI/QtFormResultItemModel.cpp @@ -29,67 +29,67 @@ QtFormResultItemModel::QtFormResultItemModel(QObject* parent, Form::ref formResu } void QtFormResultItemModel::setForm(Form::ref formResult) { - emit layoutAboutToBeChanged(); - formResult_ = formResult; - emit layoutChanged(); + emit layoutAboutToBeChanged(); + formResult_ = formResult; + emit layoutChanged(); } const Form::ref QtFormResultItemModel::getForm() const { - return formResult_; + return formResult_; } QVariant QtFormResultItemModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const { - if (!formResult_) return QVariant(); - if (role != Qt::DisplayRole) return QVariant(); - if (static_cast(section) >= formResult_->getReportedFields().size()) return QVariant(); - return QVariant(P2QSTRING(formResult_->getReportedFields().at(section)->getLabel())); + if (!formResult_) return QVariant(); + if (role != Qt::DisplayRole) return QVariant(); + if (static_cast(section) >= formResult_->getReportedFields().size()) return QVariant(); + return QVariant(P2QSTRING(formResult_->getReportedFields().at(section)->getLabel())); } int QtFormResultItemModel::rowCount(const QModelIndex &/*parent*/) const { - if (!formResult_) return 0; - return formResult_->getItems().size(); + if (!formResult_) return 0; + return formResult_->getItems().size(); } int QtFormResultItemModel::columnCount(const QModelIndex &/*parent*/) const { - if (!formResult_) return 0; - return formResult_->getReportedFields().size(); + if (!formResult_) return 0; + return formResult_->getReportedFields().size(); } QVariant QtFormResultItemModel::data(const QModelIndex &index, int role) const { - if (!formResult_) return QVariant(); - if (role != Qt::DisplayRole || !index.isValid()) { - return QVariant(); - } + if (!formResult_) return QVariant(); + if (role != Qt::DisplayRole || !index.isValid()) { + return QVariant(); + } - if (static_cast(index.row()) >= formResult_->getItems().size()) return QVariant(); - if (static_cast(index.column()) >= formResult_->getReportedFields().size()) return QVariant(); + if (static_cast(index.row()) >= formResult_->getItems().size()) return QVariant(); + if (static_cast(index.column()) >= formResult_->getReportedFields().size()) return QVariant(); - Form::FormItem item = formResult_->getItems().at(index.row()); + Form::FormItem item = formResult_->getItems().at(index.row()); - return QVariant(P2QSTRING(getFieldValue(item, index.column()))); + return QVariant(P2QSTRING(getFieldValue(item, index.column()))); } const std::string QtFormResultItemModel::getFieldValue(const Form::FormItem& item, const int column) const { - // determine field name - std::string name = formResult_->getReportedFields().at(column)->getName(); - - foreach(FormField::ref field, item) { - if (field->getName() == name) { - std::string delimiter = ""; - if (field->getType() == FormField::TextMultiType) { - delimiter = "\n"; - } - else if (field->getType() == FormField::JIDMultiType) { - delimiter = ", "; - } - else if (field->getType() == FormField::ListMultiType) { - delimiter = ", "; - } - return boost::algorithm::join(field->getValues(), delimiter); - } - } - - return ""; + // determine field name + std::string name = formResult_->getReportedFields().at(column)->getName(); + + foreach(FormField::ref field, item) { + if (field->getName() == name) { + std::string delimiter = ""; + if (field->getType() == FormField::TextMultiType) { + delimiter = "\n"; + } + else if (field->getType() == FormField::JIDMultiType) { + delimiter = ", "; + } + else if (field->getType() == FormField::ListMultiType) { + delimiter = ", "; + } + return boost::algorithm::join(field->getValues(), delimiter); + } + } + + return ""; } } diff --git a/Swift/QtUI/QtFormResultItemModel.h b/Swift/QtUI/QtFormResultItemModel.h index f383f74..47f3549 100644 --- a/Swift/QtUI/QtFormResultItemModel.h +++ b/Swift/QtUI/QtFormResultItemModel.h @@ -13,24 +13,24 @@ namespace Swift { class QtFormResultItemModel : public QAbstractTableModel { - Q_OBJECT - public: - QtFormResultItemModel(QObject* parent); - QtFormResultItemModel(QObject* parent, Form::ref formResult); + Q_OBJECT + public: + QtFormResultItemModel(QObject* parent); + QtFormResultItemModel(QObject* parent, Form::ref formResult); - void setForm(Form::ref formResult); - const Form::ref getForm() const; + void setForm(Form::ref formResult); + const Form::ref getForm() const; - virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; - virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; - virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; + virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; + virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - private: - const std::string getFieldValue(const Form::FormItem& item, const int column) const; + private: + const std::string getFieldValue(const Form::FormItem& item, const int column) const; - private: - Form::ref formResult_; + private: + Form::ref formResult_; }; } diff --git a/Swift/QtUI/QtFormWidget.cpp b/Swift/QtUI/QtFormWidget.cpp index ea452dc..13049ca 100644 --- a/Swift/QtUI/QtFormWidget.cpp +++ b/Swift/QtUI/QtFormWidget.cpp @@ -26,46 +26,46 @@ namespace Swift { QtFormWidget::QtFormWidget(Form::ref form, QWidget* parent) : QWidget(parent), form_(form) { - QGridLayout* thisLayout = new QGridLayout(this); - int row = 0; - if (!form->getTitle().empty()) { - QLabel* instructions = new QLabel(("" + form->getTitle() + "").c_str(), this); - thisLayout->addWidget(instructions, row++, 0, 1, 2); - } - if (!form->getInstructions().empty()) { - QLabel* instructions = new QLabel(form->getInstructions().c_str(), this); - thisLayout->addWidget(instructions, row++, 0, 1, 2); - } - QScrollArea* scrollArea = new QScrollArea(this); - thisLayout->addWidget(scrollArea); - QWidget* scroll = new QWidget(this); - QGridLayout* layout = new QGridLayout(scroll); - const std::vector items = form->getItems(); - if (items.empty()) { /* single item forms */ - foreach (FormField::ref field, form->getFields()) { - QWidget* widget = createWidget(field, field->getType(), 0); - if (widget) { - layout->addWidget(new QLabel(field->getLabel().c_str(), this), row, 0); - layout->addWidget(widget, row++, 1); - } - } - } else { /* multi-item forms */ - const Form::FormItem& headers = form->getFields(); - for (size_t i = 0; i < items.size(); ++i) { - const Form::FormItem& item = items[i]; - assert(item.size() == headers.size()); - for (size_t j = 0; j < item.size(); ++j) { - QWidget* widget = createWidget(item[j], headers[j]->getType(), i); - if (widget) { - layout->addWidget(new QLabel(item[j]->getLabel().c_str(), this), row, 0); - layout->addWidget(widget, row++, 1); - } - } - } - } - scrollArea->setWidget(scroll); - scrollArea->setWidgetResizable(true); - setEditable(form->getType() != Form::CancelType && form->getType() != Form::ResultType); + QGridLayout* thisLayout = new QGridLayout(this); + int row = 0; + if (!form->getTitle().empty()) { + QLabel* instructions = new QLabel(("" + form->getTitle() + "").c_str(), this); + thisLayout->addWidget(instructions, row++, 0, 1, 2); + } + if (!form->getInstructions().empty()) { + QLabel* instructions = new QLabel(form->getInstructions().c_str(), this); + thisLayout->addWidget(instructions, row++, 0, 1, 2); + } + QScrollArea* scrollArea = new QScrollArea(this); + thisLayout->addWidget(scrollArea); + QWidget* scroll = new QWidget(this); + QGridLayout* layout = new QGridLayout(scroll); + const std::vector items = form->getItems(); + if (items.empty()) { /* single item forms */ + foreach (FormField::ref field, form->getFields()) { + QWidget* widget = createWidget(field, field->getType(), 0); + if (widget) { + layout->addWidget(new QLabel(field->getLabel().c_str(), this), row, 0); + layout->addWidget(widget, row++, 1); + } + } + } else { /* multi-item forms */ + const Form::FormItem& headers = form->getFields(); + for (size_t i = 0; i < items.size(); ++i) { + const Form::FormItem& item = items[i]; + assert(item.size() == headers.size()); + for (size_t j = 0; j < item.size(); ++j) { + QWidget* widget = createWidget(item[j], headers[j]->getType(), i); + if (widget) { + layout->addWidget(new QLabel(item[j]->getLabel().c_str(), this), row, 0); + layout->addWidget(widget, row++, 1); + } + } + } + } + scrollArea->setWidget(scroll); + scrollArea->setWidgetResizable(true); + setEditable(form->getType() != Form::CancelType && form->getType() != Form::ResultType); } QtFormWidget::~QtFormWidget() { @@ -73,168 +73,168 @@ QtFormWidget::~QtFormWidget() { } QListWidget* QtFormWidget::createList(FormField::ref field) { - QListWidget* listWidget = new QListWidget(this); - listWidget->setSortingEnabled(false); - listWidget->setSelectionMode(field->getType() == FormField::ListMultiType ? QAbstractItemView::MultiSelection : QAbstractItemView::SingleSelection); - std::vector selected; - /* if this is an editable form, use the 'options' list, otherwise use the 'values' list */ - if (form_->getType() != Form::FormType) { - foreach (const std::string& value, field->getValues()) { - listWidget->addItem(P2QSTRING(value)); - selected.push_back(false); - } - } else { - foreach (FormField::Option option, field->getOptions()) { - listWidget->addItem(option.label.c_str()); - if (field->getType() == FormField::ListSingleType) { - selected.push_back(!field->getValues().empty() && option.value == field->getValues()[0]); - } - else if (field->getType() == FormField::ListMultiType) { - std::string text = option.value; - selected.push_back(std::find(field->getValues().begin(), field->getValues().end(), text) != field->getValues().end()); - } - } - } - for (int i = 0; i < listWidget->count(); i++) { - QListWidgetItem* item = listWidget->item(i); - item->setSelected(selected[i]); - } - return listWidget; + QListWidget* listWidget = new QListWidget(this); + listWidget->setSortingEnabled(false); + listWidget->setSelectionMode(field->getType() == FormField::ListMultiType ? QAbstractItemView::MultiSelection : QAbstractItemView::SingleSelection); + std::vector selected; + /* if this is an editable form, use the 'options' list, otherwise use the 'values' list */ + if (form_->getType() != Form::FormType) { + foreach (const std::string& value, field->getValues()) { + listWidget->addItem(P2QSTRING(value)); + selected.push_back(false); + } + } else { + foreach (FormField::Option option, field->getOptions()) { + listWidget->addItem(option.label.c_str()); + if (field->getType() == FormField::ListSingleType) { + selected.push_back(!field->getValues().empty() && option.value == field->getValues()[0]); + } + else if (field->getType() == FormField::ListMultiType) { + std::string text = option.value; + selected.push_back(std::find(field->getValues().begin(), field->getValues().end(), text) != field->getValues().end()); + } + } + } + for (int i = 0; i < listWidget->count(); i++) { + QListWidgetItem* item = listWidget->item(i); + item->setSelected(selected[i]); + } + return listWidget; } QWidget* QtFormWidget::createWidget(FormField::ref field, const FormField::Type type, const size_t index) { - QWidget* widget = NULL; - if (type == FormField::BooleanType) { - QCheckBox* checkWidget = new QCheckBox(this); - checkWidget->setCheckState(field->getBoolValue() ? Qt::Checked : Qt::Unchecked); - widget = checkWidget; - } - if (type == FormField::FixedType) { - QString value = field->getFixedValue().c_str(); - widget = new QLabel(value, this); - } - if (type == FormField::ListSingleType) { - widget = createList(field); - } - if (type == FormField::TextMultiType) { - QString value = field->getTextMultiValue().c_str(); - QTextEdit* textWidget = new QTextEdit(this); - textWidget->setPlainText(value); - widget = textWidget; - } - if (type == FormField::TextPrivateType) { - QString value = field->getTextPrivateValue().c_str(); - QLineEdit* lineWidget = new QLineEdit(value, this); - lineWidget->setEchoMode(QLineEdit::Password); - widget = lineWidget; - } - if (type == FormField::TextSingleType) { - QString value = field->getTextSingleValue().c_str(); - widget = new QLineEdit(value, this); - } - if (type == FormField::JIDSingleType) { - QString value = field->getJIDSingleValue().toString().c_str(); - widget = new QLineEdit(value, this); - } - if (type == FormField::JIDMultiType) { - QString text = boost::join(field->getValues(), "\n").c_str(); - QTextEdit* textWidget = new QTextEdit(this); - textWidget->setPlainText(text); - widget = textWidget; - } - if (type == FormField::ListMultiType) { - widget = createList(field); - } - std::string indexString; - if (index) { - /* for multi-item forms we need to distinguish between the different rows */ - indexString = boost::lexical_cast(index); - } - fields_[field->getName() + indexString] = widget; - return widget; + QWidget* widget = NULL; + if (type == FormField::BooleanType) { + QCheckBox* checkWidget = new QCheckBox(this); + checkWidget->setCheckState(field->getBoolValue() ? Qt::Checked : Qt::Unchecked); + widget = checkWidget; + } + if (type == FormField::FixedType) { + QString value = field->getFixedValue().c_str(); + widget = new QLabel(value, this); + } + if (type == FormField::ListSingleType) { + widget = createList(field); + } + if (type == FormField::TextMultiType) { + QString value = field->getTextMultiValue().c_str(); + QTextEdit* textWidget = new QTextEdit(this); + textWidget->setPlainText(value); + widget = textWidget; + } + if (type == FormField::TextPrivateType) { + QString value = field->getTextPrivateValue().c_str(); + QLineEdit* lineWidget = new QLineEdit(value, this); + lineWidget->setEchoMode(QLineEdit::Password); + widget = lineWidget; + } + if (type == FormField::TextSingleType) { + QString value = field->getTextSingleValue().c_str(); + widget = new QLineEdit(value, this); + } + if (type == FormField::JIDSingleType) { + QString value = field->getJIDSingleValue().toString().c_str(); + widget = new QLineEdit(value, this); + } + if (type == FormField::JIDMultiType) { + QString text = boost::join(field->getValues(), "\n").c_str(); + QTextEdit* textWidget = new QTextEdit(this); + textWidget->setPlainText(text); + widget = textWidget; + } + if (type == FormField::ListMultiType) { + widget = createList(field); + } + std::string indexString; + if (index) { + /* for multi-item forms we need to distinguish between the different rows */ + indexString = boost::lexical_cast(index); + } + fields_[field->getName() + indexString] = widget; + return widget; } Form::ref QtFormWidget::getCompletedForm() { - Form::ref result(new Form(Form::SubmitType)); - foreach (boost::shared_ptr field, form_->getFields()) { - boost::shared_ptr resultField = boost::make_shared(field->getType()); - if (field->getType() == FormField::BooleanType) { - resultField->setBoolValue(qobject_cast(fields_[field->getName()])->checkState() == Qt::Checked); - } - if (field->getType() == FormField::FixedType || field->getType() == FormField::HiddenType) { - resultField->addValue(field->getValues().empty() ? "" : field->getValues()[0]); - } - if (field->getType() == FormField::ListSingleType) { - QListWidget* listWidget = qobject_cast(fields_[field->getName()]); - if (listWidget->selectedItems().size() > 0) { - int i = listWidget->row(listWidget->selectedItems()[0]); - resultField->addValue(field->getOptions()[i].value); - } - } - if (field->getType() == FormField::TextMultiType) { - QTextEdit* widget = qobject_cast(fields_[field->getName()]); - QString string = widget->toPlainText(); - if (!string.isEmpty()) { - resultField->setTextMultiValue(Q2PSTRING(string)); - } - } - if (field->getType() == FormField::TextPrivateType || field->getType() == FormField::TextSingleType || field->getType() == FormField::JIDSingleType) { - QLineEdit* widget = qobject_cast(fields_[field->getName()]); - QString string = widget->text(); - if (!string.isEmpty()) { - resultField->addValue(Q2PSTRING(string)); - } - } - if (field->getType() == FormField::JIDMultiType) { - QTextEdit* widget = qobject_cast(fields_[field->getName()]); - QString string = widget->toPlainText(); - if (!string.isEmpty()) { - QStringList lines = string.split("\n"); - foreach (QString line, lines) { - resultField->addValue(Q2PSTRING(line)); - } - } - } - if (field->getType() == FormField::ListMultiType) { - QListWidget* listWidget = qobject_cast(fields_[field->getName()]); - foreach (QListWidgetItem* item, listWidget->selectedItems()) { - resultField->addValue(field->getOptions()[listWidget->row(item)].value); - } - } - resultField->setName(field->getName()); - result->addField(resultField); - } - return result; + Form::ref result(new Form(Form::SubmitType)); + foreach (boost::shared_ptr field, form_->getFields()) { + boost::shared_ptr resultField = boost::make_shared(field->getType()); + if (field->getType() == FormField::BooleanType) { + resultField->setBoolValue(qobject_cast(fields_[field->getName()])->checkState() == Qt::Checked); + } + if (field->getType() == FormField::FixedType || field->getType() == FormField::HiddenType) { + resultField->addValue(field->getValues().empty() ? "" : field->getValues()[0]); + } + if (field->getType() == FormField::ListSingleType) { + QListWidget* listWidget = qobject_cast(fields_[field->getName()]); + if (listWidget->selectedItems().size() > 0) { + int i = listWidget->row(listWidget->selectedItems()[0]); + resultField->addValue(field->getOptions()[i].value); + } + } + if (field->getType() == FormField::TextMultiType) { + QTextEdit* widget = qobject_cast(fields_[field->getName()]); + QString string = widget->toPlainText(); + if (!string.isEmpty()) { + resultField->setTextMultiValue(Q2PSTRING(string)); + } + } + if (field->getType() == FormField::TextPrivateType || field->getType() == FormField::TextSingleType || field->getType() == FormField::JIDSingleType) { + QLineEdit* widget = qobject_cast(fields_[field->getName()]); + QString string = widget->text(); + if (!string.isEmpty()) { + resultField->addValue(Q2PSTRING(string)); + } + } + if (field->getType() == FormField::JIDMultiType) { + QTextEdit* widget = qobject_cast(fields_[field->getName()]); + QString string = widget->toPlainText(); + if (!string.isEmpty()) { + QStringList lines = string.split("\n"); + foreach (QString line, lines) { + resultField->addValue(Q2PSTRING(line)); + } + } + } + if (field->getType() == FormField::ListMultiType) { + QListWidget* listWidget = qobject_cast(fields_[field->getName()]); + foreach (QListWidgetItem* item, listWidget->selectedItems()) { + resultField->addValue(field->getOptions()[listWidget->row(item)].value); + } + } + resultField->setName(field->getName()); + result->addField(resultField); + } + return result; } template void QtFormWidget::setEnabled(QWidget* rawWidget, bool editable) { - T* widget = qobject_cast(rawWidget); - if (widget) { - widget->setEnabled(editable); - } + T* widget = qobject_cast(rawWidget); + if (widget) { + widget->setEnabled(editable); + } } template void QtFormWidget::setEditable(QWidget* rawWidget, bool editable) { - T* widget = qobject_cast(rawWidget); - if (widget) { - widget->setReadOnly(!editable); - } + T* widget = qobject_cast(rawWidget); + if (widget) { + widget->setReadOnly(!editable); + } } void QtFormWidget::setEditable(bool editable) { - if (!form_) { - return; - } - foreach (boost::shared_ptr field, form_->getFields()) { - QWidget* widget = NULL; - if (field) { - widget = fields_[field->getName()]; - } - setEnabled(widget, editable); - setEnabled(widget, editable); - setEditable(widget, editable); - setEditable(widget, editable); - } + if (!form_) { + return; + } + foreach (boost::shared_ptr field, form_->getFields()) { + QWidget* widget = NULL; + if (field) { + widget = fields_[field->getName()]; + } + setEnabled(widget, editable); + setEnabled(widget, editable); + setEditable(widget, editable); + setEditable(widget, editable); + } } } diff --git a/Swift/QtUI/QtFormWidget.h b/Swift/QtUI/QtFormWidget.h index 4c6311c..1eec115 100644 --- a/Swift/QtUI/QtFormWidget.h +++ b/Swift/QtUI/QtFormWidget.h @@ -17,19 +17,19 @@ class QListWidget; namespace Swift { class QtFormWidget : public QWidget { - Q_OBJECT - public: - QtFormWidget(Form::ref form, QWidget* parent = NULL); - virtual ~QtFormWidget(); - Form::ref getCompletedForm(); - void setEditable(bool editable); - private: - QWidget* createWidget(FormField::ref field, const FormField::Type type, const size_t index); - QListWidget* createList(FormField::ref field); - template void setEnabled(QWidget* rawWidget, bool editable); - template void setEditable(QWidget* rawWidget, bool editable); - std::map fields_; - Form::ref form_; + Q_OBJECT + public: + QtFormWidget(Form::ref form, QWidget* parent = NULL); + virtual ~QtFormWidget(); + Form::ref getCompletedForm(); + void setEditable(bool editable); + private: + QWidget* createWidget(FormField::ref field, const FormField::Type type, const size_t index); + QListWidget* createList(FormField::ref field); + template void setEnabled(QWidget* rawWidget, bool editable); + template void setEditable(QWidget* rawWidget, bool editable); + std::map fields_; + Form::ref form_; }; } diff --git a/Swift/QtUI/QtHighlightEditor.cpp b/Swift/QtUI/QtHighlightEditor.cpp index 1d47c4e..fdbff9e 100644 --- a/Swift/QtUI/QtHighlightEditor.cpp +++ b/Swift/QtUI/QtHighlightEditor.cpp @@ -29,61 +29,61 @@ namespace Swift { QtHighlightEditor::QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent) - : QWidget(parent), settings_(settings), previousRow_(-1) + : QWidget(parent), settings_(settings), previousRow_(-1) { - ui_.setupUi(this); + ui_.setupUi(this); - connect(ui_.listWidget, SIGNAL(currentRowChanged(int)), SLOT(onCurrentRowChanged(int))); + connect(ui_.listWidget, SIGNAL(currentRowChanged(int)), SLOT(onCurrentRowChanged(int))); - connect(ui_.newButton, SIGNAL(clicked()), SLOT(onNewButtonClicked())); - connect(ui_.deleteButton, SIGNAL(clicked()), SLOT(onDeleteButtonClicked())); + connect(ui_.newButton, SIGNAL(clicked()), SLOT(onNewButtonClicked())); + connect(ui_.deleteButton, SIGNAL(clicked()), SLOT(onDeleteButtonClicked())); - connect(ui_.buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApplyButtonClick())); - connect(ui_.buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), SLOT(onCancelButtonClick())); - connect(ui_.buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), SLOT(onOkButtonClick())); - connect(ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), SLOT(onResetToDefaultRulesClicked())); + connect(ui_.buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(onApplyButtonClick())); + connect(ui_.buttonBox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), SLOT(onCancelButtonClick())); + connect(ui_.buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), SLOT(onOkButtonClick())); + connect(ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults), SIGNAL(clicked()), SLOT(onResetToDefaultRulesClicked())); - connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(colorOtherSelect())); - connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(colorCustomSelect())); + connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(colorOtherSelect())); + connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(colorCustomSelect())); - connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect())); - connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect())); - connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(soundCustomSelect())); + connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect())); + connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(soundOtherSelect())); + connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(soundCustomSelect())); - /* replace the static line-edit control with the roster autocompleter */ - ui_.dummySenderName->setVisible(false); - jid_ = new QtSuggestingJIDInput(this, settings); - ui_.senderName->addWidget(jid_); - jid_->onUserSelected.connect(boost::bind(&QtHighlightEditor::handleOnUserSelected, this, _1)); + /* replace the static line-edit control with the roster autocompleter */ + ui_.dummySenderName->setVisible(false); + jid_ = new QtSuggestingJIDInput(this, settings); + ui_.senderName->addWidget(jid_); + jid_->onUserSelected.connect(boost::bind(&QtHighlightEditor::handleOnUserSelected, this, _1)); - /* handle autocomplete */ - connect(jid_, SIGNAL(textEdited(QString)), SLOT(handleContactSuggestionRequested(QString))); + /* handle autocomplete */ + connect(jid_, SIGNAL(textEdited(QString)), SLOT(handleContactSuggestionRequested(QString))); - /* we need to be notified if any of the state changes so that we can update our textual rule description */ - connect(ui_.chatRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.roomRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.nickIsKeyword, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.allMsgRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.senderRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(jid_, SIGNAL(textChanged(const QString&)), SLOT(widgetClick())); - connect(ui_.keywordRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.keyword, SIGNAL(textChanged(const QString&)), SLOT(widgetClick())); - connect(ui_.matchPartialWords, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.matchCase, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(widgetClick())); - connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(widgetClick())); + /* we need to be notified if any of the state changes so that we can update our textual rule description */ + connect(ui_.chatRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.roomRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.nickIsKeyword, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.allMsgRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.senderRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(jid_, SIGNAL(textChanged(const QString&)), SLOT(widgetClick())); + connect(ui_.keywordRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.keyword, SIGNAL(textChanged(const QString&)), SLOT(widgetClick())); + connect(ui_.matchPartialWords, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.matchCase, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.noColorRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.customColorRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.noSoundRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.defaultSoundRadio, SIGNAL(clicked()), SLOT(widgetClick())); + connect(ui_.customSoundRadio, SIGNAL(clicked()), SLOT(widgetClick())); - /* allow selection of a custom sound file */ - connect(ui_.soundFileButton, SIGNAL(clicked()), SLOT(selectSoundFile())); + /* allow selection of a custom sound file */ + connect(ui_.soundFileButton, SIGNAL(clicked()), SLOT(selectSoundFile())); - /* allowing reordering items */ - connect(ui_.moveUpButton, SIGNAL(clicked()), this, SLOT(onUpButtonClicked())); - connect(ui_.moveDownButton, SIGNAL(clicked()), this, SLOT(onDownButtonClicked())); + /* allowing reordering items */ + connect(ui_.moveUpButton, SIGNAL(clicked()), this, SLOT(onUpButtonClicked())); + connect(ui_.moveDownButton, SIGNAL(clicked()), this, SLOT(onDownButtonClicked())); - setWindowTitle(tr("Highlight Rules")); + setWindowTitle(tr("Highlight Rules")); } QtHighlightEditor::~QtHighlightEditor() @@ -92,477 +92,477 @@ QtHighlightEditor::~QtHighlightEditor() std::string formatShortDescription(const HighlightRule &rule) { - const std::string chatOrRoom = (rule.getMatchChat() ? "chat" : "room"); + const std::string chatOrRoom = (rule.getMatchChat() ? "chat" : "room"); - std::vector senders = rule.getSenders(); - std::vector keywords = rule.getKeywords(); + std::vector senders = rule.getSenders(); + std::vector keywords = rule.getKeywords(); - if (senders.empty() && keywords.empty() && !rule.getNickIsKeyword()) { - return std::string("All ") + chatOrRoom + " messages."; - } + if (senders.empty() && keywords.empty() && !rule.getNickIsKeyword()) { + return std::string("All ") + chatOrRoom + " messages."; + } - if (rule.getNickIsKeyword()) { - return std::string("All ") + chatOrRoom + " messages that mention my name."; - } + if (rule.getNickIsKeyword()) { + return std::string("All ") + chatOrRoom + " messages that mention my name."; + } - if (!senders.empty()) { - return std::string("All ") + chatOrRoom + " messages from " + senders[0] + "."; - } + if (!senders.empty()) { + return std::string("All ") + chatOrRoom + " messages from " + senders[0] + "."; + } - if (!keywords.empty()) { - return std::string("All ") + chatOrRoom + " messages mentioning the keyword '" + keywords[0] + "'."; - } + if (!keywords.empty()) { + return std::string("All ") + chatOrRoom + " messages mentioning the keyword '" + keywords[0] + "'."; + } - return "Unknown Rule"; + return "Unknown Rule"; } void QtHighlightEditor::show() { - highlightManager_->loadSettings(); + highlightManager_->loadSettings(); - populateList(); + populateList(); - if (ui_.listWidget->count()) { - selectRow(0); - } + if (ui_.listWidget->count()) { + selectRow(0); + } - updateResetToDefaultRulesVisibility(); + updateResetToDefaultRulesVisibility(); - /* prepare default states */ - widgetClick(); + /* prepare default states */ + widgetClick(); - QWidget::show(); - QWidget::activateWindow(); + QWidget::show(); + QWidget::activateWindow(); } void QtHighlightEditor::setHighlightManager(HighlightManager* highlightManager) { - highlightManager_ = highlightManager; + highlightManager_ = highlightManager; } void QtHighlightEditor::setContactSuggestions(const std::vector& suggestions) { - jid_->setSuggestions(suggestions); + jid_->setSuggestions(suggestions); } void QtHighlightEditor::colorOtherSelect() { - ui_.foregroundColor->setEnabled(false); - ui_.backgroundColor->setEnabled(false); + ui_.foregroundColor->setEnabled(false); + ui_.backgroundColor->setEnabled(false); } void QtHighlightEditor::colorCustomSelect() { - ui_.foregroundColor->setEnabled(true); - ui_.backgroundColor->setEnabled(true); + ui_.foregroundColor->setEnabled(true); + ui_.backgroundColor->setEnabled(true); } void QtHighlightEditor::soundOtherSelect() { - ui_.soundFile->setEnabled(false); - ui_.soundFileButton->setEnabled(false); + ui_.soundFile->setEnabled(false); + ui_.soundFileButton->setEnabled(false); } void QtHighlightEditor::soundCustomSelect() { - ui_.soundFile->setEnabled(true); - ui_.soundFileButton->setEnabled(true); + ui_.soundFile->setEnabled(true); + ui_.soundFileButton->setEnabled(true); } void QtHighlightEditor::onNewButtonClicked() { - int row = getSelectedRow() + 1; - populateList(); - HighlightRule newRule; - newRule.setMatchMUC(true); - highlightManager_->insertRule(row, newRule); - QListWidgetItem *item = new QListWidgetItem(); - item->setText(P2QSTRING(formatShortDescription(newRule))); - QFont font; - font.setItalic(true); - item->setFont(font); - ui_.listWidget->insertItem(row, item); - selectRow(row); + int row = getSelectedRow() + 1; + populateList(); + HighlightRule newRule; + newRule.setMatchMUC(true); + highlightManager_->insertRule(row, newRule); + QListWidgetItem *item = new QListWidgetItem(); + item->setText(P2QSTRING(formatShortDescription(newRule))); + QFont font; + font.setItalic(true); + item->setFont(font); + ui_.listWidget->insertItem(row, item); + selectRow(row); } void QtHighlightEditor::onDeleteButtonClicked() { - int selectedRow = getSelectedRow(); - assert(selectedRow>=0 && selectedRowcount()); - delete ui_.listWidget->takeItem(selectedRow); - highlightManager_->removeRule(selectedRow); - - if (!ui_.listWidget->count()) { - disableDialog(); - ui_.deleteButton->setEnabled(false); - } else { - if (selectedRow == ui_.listWidget->count()) { - selectRow(ui_.listWidget->count() - 1); - } else { - selectRow(selectedRow); - } - } + int selectedRow = getSelectedRow(); + assert(selectedRow>=0 && selectedRowcount()); + delete ui_.listWidget->takeItem(selectedRow); + highlightManager_->removeRule(selectedRow); + + if (!ui_.listWidget->count()) { + disableDialog(); + ui_.deleteButton->setEnabled(false); + } else { + if (selectedRow == ui_.listWidget->count()) { + selectRow(ui_.listWidget->count() - 1); + } else { + selectRow(selectedRow); + } + } } void QtHighlightEditor::moveRowFromTo(int fromRow, int toRow) { - int verticalScrollAreaPosition = ui_.scrollArea->verticalScrollBar()->value(); - highlightManager_->swapRules(fromRow, toRow); - populateList(); - selectRow(toRow); - ui_.scrollArea->verticalScrollBar()->setValue(verticalScrollAreaPosition); + int verticalScrollAreaPosition = ui_.scrollArea->verticalScrollBar()->value(); + highlightManager_->swapRules(fromRow, toRow); + populateList(); + selectRow(toRow); + ui_.scrollArea->verticalScrollBar()->setValue(verticalScrollAreaPosition); } void QtHighlightEditor::onUpButtonClicked() { - const size_t moveFrom = ui_.listWidget->currentRow(); - const size_t moveTo = moveFrom - 1; - moveRowFromTo(moveFrom, moveTo); + const size_t moveFrom = ui_.listWidget->currentRow(); + const size_t moveTo = moveFrom - 1; + moveRowFromTo(moveFrom, moveTo); } void QtHighlightEditor::onDownButtonClicked() { - const size_t moveFrom = ui_.listWidget->currentRow(); - const size_t moveTo = moveFrom + 1; - moveRowFromTo(moveFrom, moveTo); + const size_t moveFrom = ui_.listWidget->currentRow(); + const size_t moveTo = moveFrom + 1; + moveRowFromTo(moveFrom, moveTo); } void QtHighlightEditor::onCurrentRowChanged(int currentRow) { - ui_.deleteButton->setEnabled(currentRow != -1); - ui_.moveUpButton->setEnabled(currentRow != -1 && currentRow != 0); - ui_.moveDownButton->setEnabled(currentRow != -1 && currentRow != (ui_.listWidget->count()-1)); - - if (previousRow_ != -1) { - if (ui_.listWidget->count() > previousRow_) { - QFont font; - font.setItalic(false); - ui_.listWidget->item(previousRow_)->setFont(font); - highlightManager_->setRule(previousRow_, ruleFromDialog()); - } - } - - if (currentRow != -1) { - HighlightRule rule = highlightManager_->getRule(currentRow); - ruleToDialog(rule); - if (ui_.listWidget->currentItem()) { - QFont font; - font.setItalic(true); - ui_.listWidget->currentItem()->setFont(font); - ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule))); - } - } - - /* grey the dialog if we have nothing selected */ - if (currentRow == -1) { - disableDialog(); - } - - previousRow_ = currentRow; - - updateResetToDefaultRulesVisibility(); + ui_.deleteButton->setEnabled(currentRow != -1); + ui_.moveUpButton->setEnabled(currentRow != -1 && currentRow != 0); + ui_.moveDownButton->setEnabled(currentRow != -1 && currentRow != (ui_.listWidget->count()-1)); + + if (previousRow_ != -1) { + if (ui_.listWidget->count() > previousRow_) { + QFont font; + font.setItalic(false); + ui_.listWidget->item(previousRow_)->setFont(font); + highlightManager_->setRule(previousRow_, ruleFromDialog()); + } + } + + if (currentRow != -1) { + HighlightRule rule = highlightManager_->getRule(currentRow); + ruleToDialog(rule); + if (ui_.listWidget->currentItem()) { + QFont font; + font.setItalic(true); + ui_.listWidget->currentItem()->setFont(font); + ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule))); + } + } + + /* grey the dialog if we have nothing selected */ + if (currentRow == -1) { + disableDialog(); + } + + previousRow_ = currentRow; + + updateResetToDefaultRulesVisibility(); } void QtHighlightEditor::onApplyButtonClick() { - selectRow(getSelectedRow()); /* force save */ - highlightManager_->storeSettings(); + selectRow(getSelectedRow()); /* force save */ + highlightManager_->storeSettings(); } void QtHighlightEditor::onCancelButtonClick() { - close(); + close(); } void QtHighlightEditor::onOkButtonClick() { - onApplyButtonClick(); - close(); + onApplyButtonClick(); + close(); } void QtHighlightEditor::setChildWidgetStates() { - /* disable appropriate radio button child widgets */ - - if (ui_.chatRadio->isChecked()) { - if (ui_.nickIsKeyword->isChecked()) { - /* switch to another choice before we disable this button */ - ui_.allMsgRadio->setChecked(true); - } - ui_.nickIsKeyword->setEnabled(false); - } else if (ui_.roomRadio->isChecked()) { - ui_.nickIsKeyword->setEnabled(true); - } else { /* chats and rooms */ - ui_.nickIsKeyword->setEnabled(true); - } - - if (ui_.senderRadio->isChecked()) { - jid_->setEnabled(true); - } else { - jid_->setEnabled(false); - } - - if (ui_.keywordRadio->isChecked()) { - ui_.keyword->setEnabled(true); - ui_.matchPartialWords->setEnabled(true); - ui_.matchCase->setEnabled(true); - } else { - ui_.keyword->setEnabled(false); - ui_.matchPartialWords->setEnabled(false); - ui_.matchCase->setEnabled(false); - } - - if (ui_.chatRadio->isChecked()) { - ui_.allMsgRadio->setText(tr("Apply to all chat messages")); - } else { - ui_.allMsgRadio->setText(tr("Apply to all room messages")); - } + /* disable appropriate radio button child widgets */ + + if (ui_.chatRadio->isChecked()) { + if (ui_.nickIsKeyword->isChecked()) { + /* switch to another choice before we disable this button */ + ui_.allMsgRadio->setChecked(true); + } + ui_.nickIsKeyword->setEnabled(false); + } else if (ui_.roomRadio->isChecked()) { + ui_.nickIsKeyword->setEnabled(true); + } else { /* chats and rooms */ + ui_.nickIsKeyword->setEnabled(true); + } + + if (ui_.senderRadio->isChecked()) { + jid_->setEnabled(true); + } else { + jid_->setEnabled(false); + } + + if (ui_.keywordRadio->isChecked()) { + ui_.keyword->setEnabled(true); + ui_.matchPartialWords->setEnabled(true); + ui_.matchCase->setEnabled(true); + } else { + ui_.keyword->setEnabled(false); + ui_.matchPartialWords->setEnabled(false); + ui_.matchCase->setEnabled(false); + } + + if (ui_.chatRadio->isChecked()) { + ui_.allMsgRadio->setText(tr("Apply to all chat messages")); + } else { + ui_.allMsgRadio->setText(tr("Apply to all room messages")); + } } void QtHighlightEditor::widgetClick() { - setChildWidgetStates(); + setChildWidgetStates(); - HighlightRule rule = ruleFromDialog(); + HighlightRule rule = ruleFromDialog(); - if (ui_.listWidget->currentItem()) { - ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule))); - } + if (ui_.listWidget->currentItem()) { + ui_.listWidget->currentItem()->setText(P2QSTRING(formatShortDescription(rule))); + } } void QtHighlightEditor::disableDialog() { - ui_.chatRadio->setEnabled(false); - ui_.roomRadio->setEnabled(false); - ui_.allMsgRadio->setEnabled(false); - ui_.nickIsKeyword->setEnabled(false); - ui_.senderRadio->setEnabled(false); - ui_.dummySenderName->setEnabled(false); - ui_.keywordRadio->setEnabled(false); - ui_.keyword->setEnabled(false); - ui_.matchPartialWords->setEnabled(false); - ui_.matchCase->setEnabled(false); - ui_.noColorRadio->setEnabled(false); - ui_.customColorRadio->setEnabled(false); - ui_.foregroundColor->setEnabled(false); - ui_.backgroundColor->setEnabled(false); - ui_.noSoundRadio->setEnabled(false); - ui_.defaultSoundRadio->setEnabled(false); - ui_.customSoundRadio->setEnabled(false); - ui_.soundFile->setEnabled(false); - ui_.soundFileButton->setEnabled(false); + ui_.chatRadio->setEnabled(false); + ui_.roomRadio->setEnabled(false); + ui_.allMsgRadio->setEnabled(false); + ui_.nickIsKeyword->setEnabled(false); + ui_.senderRadio->setEnabled(false); + ui_.dummySenderName->setEnabled(false); + ui_.keywordRadio->setEnabled(false); + ui_.keyword->setEnabled(false); + ui_.matchPartialWords->setEnabled(false); + ui_.matchCase->setEnabled(false); + ui_.noColorRadio->setEnabled(false); + ui_.customColorRadio->setEnabled(false); + ui_.foregroundColor->setEnabled(false); + ui_.backgroundColor->setEnabled(false); + ui_.noSoundRadio->setEnabled(false); + ui_.defaultSoundRadio->setEnabled(false); + ui_.customSoundRadio->setEnabled(false); + ui_.soundFile->setEnabled(false); + ui_.soundFileButton->setEnabled(false); } void QtHighlightEditor::handleContactSuggestionRequested(const QString& text) { - std::string stdText = Q2PSTRING(text); - onContactSuggestionsRequested(stdText); + std::string stdText = Q2PSTRING(text); + onContactSuggestionsRequested(stdText); } void QtHighlightEditor::selectSoundFile() { - QString path = QFileDialog::getOpenFileName(this, tr("Select sound file..."), QString(), "Sounds (*.wav)"); - ui_.soundFile->setText(path); + QString path = QFileDialog::getOpenFileName(this, tr("Select sound file..."), QString(), "Sounds (*.wav)"); + ui_.soundFile->setText(path); } void QtHighlightEditor::onResetToDefaultRulesClicked() { - highlightManager_->resetToDefaultRulesList(); - populateList(); - updateResetToDefaultRulesVisibility(); + highlightManager_->resetToDefaultRulesList(); + populateList(); + updateResetToDefaultRulesVisibility(); } void QtHighlightEditor::handleOnUserSelected(const Contact::ref& contact) { - /* this might seem like it should be standard behaviour for the suggesting input box, but is not desirable in all cases */ - if (contact->jid.isValid()) { - jid_->setText(P2QSTRING(contact->jid.toString())); - } else { - jid_->setText(P2QSTRING(contact->name)); - } + /* this might seem like it should be standard behaviour for the suggesting input box, but is not desirable in all cases */ + if (contact->jid.isValid()) { + jid_->setText(P2QSTRING(contact->jid.toString())); + } else { + jid_->setText(P2QSTRING(contact->name)); + } } void QtHighlightEditor::populateList() { - previousRow_ = -1; - ui_.listWidget->clear(); - HighlightRulesListPtr rules = highlightManager_->getRules(); - for (size_t i = 0; i < rules->getSize(); ++i) { - const HighlightRule& rule = rules->getRule(i); - QListWidgetItem *item = new QListWidgetItem(); - item->setText(P2QSTRING(formatShortDescription(rule))); - ui_.listWidget->addItem(item); - } + previousRow_ = -1; + ui_.listWidget->clear(); + HighlightRulesListPtr rules = highlightManager_->getRules(); + for (size_t i = 0; i < rules->getSize(); ++i) { + const HighlightRule& rule = rules->getRule(i); + QListWidgetItem *item = new QListWidgetItem(); + item->setText(P2QSTRING(formatShortDescription(rule))); + ui_.listWidget->addItem(item); + } } void QtHighlightEditor::selectRow(int row) { - for (int i = 0; i < ui_.listWidget->count(); ++i) { - if (i == row) { - ui_.listWidget->item(i)->setSelected(true); - onCurrentRowChanged(i); - } else { - ui_.listWidget->item(i)->setSelected(false); - } - } - ui_.listWidget->setCurrentRow(row); + for (int i = 0; i < ui_.listWidget->count(); ++i) { + if (i == row) { + ui_.listWidget->item(i)->setSelected(true); + onCurrentRowChanged(i); + } else { + ui_.listWidget->item(i)->setSelected(false); + } + } + ui_.listWidget->setCurrentRow(row); } int QtHighlightEditor::getSelectedRow() const { - for (int i = 0; i < ui_.listWidget->count(); ++i) { - if (ui_.listWidget->item(i)->isSelected()) { - return i; - } - } - return -1; + for (int i = 0; i < ui_.listWidget->count(); ++i) { + if (ui_.listWidget->item(i)->isSelected()) { + return i; + } + } + return -1; } HighlightRule QtHighlightEditor::ruleFromDialog() { - HighlightRule rule; - HighlightAction& action = rule.getAction(); - - if (ui_.chatRadio->isChecked()) { - rule.setMatchChat(true); - rule.setMatchMUC(false); - } else { - rule.setMatchChat(false); - rule.setMatchMUC(true); - } - - if (ui_.allMsgRadio->isChecked()) { - action.setHighlightWholeMessage(true); - } - - if (ui_.senderRadio->isChecked()) { - QString senderName = jid_->text(); - if (!senderName.isEmpty()) { - std::vector senders; - senders.push_back(Q2PSTRING(senderName)); - rule.setSenders(senders); - action.setHighlightWholeMessage(true); - } - } - - if (ui_.keywordRadio->isChecked()) { - QString keywordString = ui_.keyword->text(); - if (!keywordString.isEmpty()) { - std::vector keywords; - keywords.push_back(Q2PSTRING(keywordString)); - rule.setKeywords(keywords); - } - } - - if (ui_.nickIsKeyword->isChecked()) { - rule.setNickIsKeyword(true); - rule.setMatchWholeWords(true); - rule.setMatchCase(true); - } else { - rule.setMatchWholeWords(!ui_.matchPartialWords->isChecked()); - rule.setMatchCase(ui_.matchCase->isChecked()); - } - - if (ui_.noColorRadio->isChecked()) { - action.setTextColor(""); - action.setTextBackground(""); - } else { - action.setTextColor(Q2PSTRING(ui_.foregroundColor->getColor().name())); - action.setTextBackground(Q2PSTRING(ui_.backgroundColor->getColor().name())); - } - - if (ui_.noSoundRadio->isChecked()) { - action.setPlaySound(false); - } else if (ui_.defaultSoundRadio->isChecked()) { - action.setPlaySound(true); - action.setSoundFile(""); - } else { - action.setPlaySound(true); - action.setSoundFile(Q2PSTRING(ui_.soundFile->text())); - } - - return rule; + HighlightRule rule; + HighlightAction& action = rule.getAction(); + + if (ui_.chatRadio->isChecked()) { + rule.setMatchChat(true); + rule.setMatchMUC(false); + } else { + rule.setMatchChat(false); + rule.setMatchMUC(true); + } + + if (ui_.allMsgRadio->isChecked()) { + action.setHighlightWholeMessage(true); + } + + if (ui_.senderRadio->isChecked()) { + QString senderName = jid_->text(); + if (!senderName.isEmpty()) { + std::vector senders; + senders.push_back(Q2PSTRING(senderName)); + rule.setSenders(senders); + action.setHighlightWholeMessage(true); + } + } + + if (ui_.keywordRadio->isChecked()) { + QString keywordString = ui_.keyword->text(); + if (!keywordString.isEmpty()) { + std::vector keywords; + keywords.push_back(Q2PSTRING(keywordString)); + rule.setKeywords(keywords); + } + } + + if (ui_.nickIsKeyword->isChecked()) { + rule.setNickIsKeyword(true); + rule.setMatchWholeWords(true); + rule.setMatchCase(true); + } else { + rule.setMatchWholeWords(!ui_.matchPartialWords->isChecked()); + rule.setMatchCase(ui_.matchCase->isChecked()); + } + + if (ui_.noColorRadio->isChecked()) { + action.setTextColor(""); + action.setTextBackground(""); + } else { + action.setTextColor(Q2PSTRING(ui_.foregroundColor->getColor().name())); + action.setTextBackground(Q2PSTRING(ui_.backgroundColor->getColor().name())); + } + + if (ui_.noSoundRadio->isChecked()) { + action.setPlaySound(false); + } else if (ui_.defaultSoundRadio->isChecked()) { + action.setPlaySound(true); + action.setSoundFile(""); + } else { + action.setPlaySound(true); + action.setSoundFile(Q2PSTRING(ui_.soundFile->text())); + } + + return rule; } void QtHighlightEditor::ruleToDialog(const HighlightRule& rule) { - ui_.chatRadio->setEnabled(true); - ui_.roomRadio->setEnabled(true); - - if (rule.getMatchMUC()) { - ui_.chatRadio->setChecked(false); - ui_.roomRadio->setChecked(true); - } else { - ui_.chatRadio->setChecked(true); - ui_.roomRadio->setChecked(false); - } - - ui_.allMsgRadio->setEnabled(true); - ui_.allMsgRadio->setChecked(true); /* this is the default radio button */ - jid_->setText(""); - ui_.keyword->setText(""); - ui_.matchPartialWords->setChecked(false); - ui_.matchCase->setChecked(false); - - ui_.nickIsKeyword->setEnabled(true); - if (rule.getNickIsKeyword()) { - ui_.nickIsKeyword->setChecked(true); - } - - ui_.senderRadio->setEnabled(true); - std::vector senders = rule.getSenders(); - if (!senders.empty()) { - ui_.senderRadio->setChecked(true); - jid_->setText(P2QSTRING(senders[0])); - } - - ui_.keywordRadio->setEnabled(true); - std::vector keywords = rule.getKeywords(); - if (!keywords.empty()) { - ui_.keywordRadio->setChecked(true); - ui_.keyword->setText(P2QSTRING(keywords[0])); - ui_.matchPartialWords->setChecked(!rule.getMatchWholeWords()); - ui_.matchCase->setChecked(rule.getMatchCase()); - } - - const HighlightAction& action = rule.getAction(); - - ui_.noColorRadio->setEnabled(true); - ui_.customColorRadio->setEnabled(true); - if (action.getTextColor().empty() && action.getTextBackground().empty()) { - ui_.noColorRadio->setChecked(true); - ui_.foregroundColor->setEnabled(false); - ui_.backgroundColor->setEnabled(false); - } else { - ui_.foregroundColor->setEnabled(true); - ui_.backgroundColor->setEnabled(true); - QColor foregroundColor(P2QSTRING(action.getTextColor())); - ui_.foregroundColor->setColor(foregroundColor); - QColor backgroundColor(P2QSTRING(action.getTextBackground())); - ui_.backgroundColor->setColor(backgroundColor); - ui_.customColorRadio->setChecked(true); - } - - ui_.noSoundRadio->setEnabled(true); - ui_.defaultSoundRadio->setEnabled(true); - ui_.customSoundRadio->setEnabled(true); - ui_.soundFile->setText(""); - ui_.soundFile->setEnabled(false); - ui_.soundFileButton->setEnabled(false); - if (action.playSound()) { - if (action.getSoundFile().empty()) { - ui_.defaultSoundRadio->setChecked(true); - } else { - ui_.customSoundRadio->setChecked(true); - ui_.soundFile->setText(P2QSTRING(action.getSoundFile())); - ui_.soundFile->setEnabled(true); - ui_.soundFileButton->setEnabled(true); - } - } else { - ui_.noSoundRadio->setChecked(true); - } - - /* set radio button child option states */ - setChildWidgetStates(); + ui_.chatRadio->setEnabled(true); + ui_.roomRadio->setEnabled(true); + + if (rule.getMatchMUC()) { + ui_.chatRadio->setChecked(false); + ui_.roomRadio->setChecked(true); + } else { + ui_.chatRadio->setChecked(true); + ui_.roomRadio->setChecked(false); + } + + ui_.allMsgRadio->setEnabled(true); + ui_.allMsgRadio->setChecked(true); /* this is the default radio button */ + jid_->setText(""); + ui_.keyword->setText(""); + ui_.matchPartialWords->setChecked(false); + ui_.matchCase->setChecked(false); + + ui_.nickIsKeyword->setEnabled(true); + if (rule.getNickIsKeyword()) { + ui_.nickIsKeyword->setChecked(true); + } + + ui_.senderRadio->setEnabled(true); + std::vector senders = rule.getSenders(); + if (!senders.empty()) { + ui_.senderRadio->setChecked(true); + jid_->setText(P2QSTRING(senders[0])); + } + + ui_.keywordRadio->setEnabled(true); + std::vector keywords = rule.getKeywords(); + if (!keywords.empty()) { + ui_.keywordRadio->setChecked(true); + ui_.keyword->setText(P2QSTRING(keywords[0])); + ui_.matchPartialWords->setChecked(!rule.getMatchWholeWords()); + ui_.matchCase->setChecked(rule.getMatchCase()); + } + + const HighlightAction& action = rule.getAction(); + + ui_.noColorRadio->setEnabled(true); + ui_.customColorRadio->setEnabled(true); + if (action.getTextColor().empty() && action.getTextBackground().empty()) { + ui_.noColorRadio->setChecked(true); + ui_.foregroundColor->setEnabled(false); + ui_.backgroundColor->setEnabled(false); + } else { + ui_.foregroundColor->setEnabled(true); + ui_.backgroundColor->setEnabled(true); + QColor foregroundColor(P2QSTRING(action.getTextColor())); + ui_.foregroundColor->setColor(foregroundColor); + QColor backgroundColor(P2QSTRING(action.getTextBackground())); + ui_.backgroundColor->setColor(backgroundColor); + ui_.customColorRadio->setChecked(true); + } + + ui_.noSoundRadio->setEnabled(true); + ui_.defaultSoundRadio->setEnabled(true); + ui_.customSoundRadio->setEnabled(true); + ui_.soundFile->setText(""); + ui_.soundFile->setEnabled(false); + ui_.soundFileButton->setEnabled(false); + if (action.playSound()) { + if (action.getSoundFile().empty()) { + ui_.defaultSoundRadio->setChecked(true); + } else { + ui_.customSoundRadio->setChecked(true); + ui_.soundFile->setText(P2QSTRING(action.getSoundFile())); + ui_.soundFile->setEnabled(true); + ui_.soundFileButton->setEnabled(true); + } + } else { + ui_.noSoundRadio->setChecked(true); + } + + /* set radio button child option states */ + setChildWidgetStates(); } void QtHighlightEditor::updateResetToDefaultRulesVisibility() { - ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setVisible(!highlightManager_->isDefaultRulesList()); + ui_.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setVisible(!highlightManager_->isDefaultRulesList()); } } diff --git a/Swift/QtUI/QtHighlightEditor.h b/Swift/QtUI/QtHighlightEditor.h index e45963c..2a9f06b 100644 --- a/Swift/QtUI/QtHighlightEditor.h +++ b/Swift/QtUI/QtHighlightEditor.h @@ -19,56 +19,56 @@ namespace Swift { - class QtSettingsProvider; - class QtSuggestingJIDInput; - class QtWebKitChatView; + class QtSettingsProvider; + class QtSuggestingJIDInput; + class QtWebKitChatView; - class QtHighlightEditor : public QWidget, public HighlightEditorWindow { - Q_OBJECT + class QtHighlightEditor : public QWidget, public HighlightEditorWindow { + Q_OBJECT - public: - QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent = NULL); - virtual ~QtHighlightEditor(); + public: + QtHighlightEditor(QtSettingsProvider* settings, QWidget* parent = NULL); + virtual ~QtHighlightEditor(); - virtual void show(); - virtual void setHighlightManager(HighlightManager* highlightManager); - virtual void setContactSuggestions(const std::vector& suggestions); + virtual void show(); + virtual void setHighlightManager(HighlightManager* highlightManager); + virtual void setContactSuggestions(const std::vector& suggestions); - private slots: - void colorOtherSelect(); - void colorCustomSelect(); - void soundOtherSelect(); - void soundCustomSelect(); - void onNewButtonClicked(); - void onDeleteButtonClicked(); - void onUpButtonClicked(); - void onDownButtonClicked(); - void onCurrentRowChanged(int currentRow); - void onApplyButtonClick(); - void onCancelButtonClick(); - void onOkButtonClick(); - void setChildWidgetStates(); - void widgetClick(); - void disableDialog(); - void handleContactSuggestionRequested(const QString& text); - void selectSoundFile(); - void onResetToDefaultRulesClicked(); + private slots: + void colorOtherSelect(); + void colorCustomSelect(); + void soundOtherSelect(); + void soundCustomSelect(); + void onNewButtonClicked(); + void onDeleteButtonClicked(); + void onUpButtonClicked(); + void onDownButtonClicked(); + void onCurrentRowChanged(int currentRow); + void onApplyButtonClick(); + void onCancelButtonClick(); + void onOkButtonClick(); + void setChildWidgetStates(); + void widgetClick(); + void disableDialog(); + void handleContactSuggestionRequested(const QString& text); + void selectSoundFile(); + void onResetToDefaultRulesClicked(); - private: - void handleOnUserSelected(const Contact::ref& contact); - void populateList(); - void selectRow(int row); - int getSelectedRow() const; - HighlightRule ruleFromDialog(); - void ruleToDialog(const HighlightRule& rule); - void updateResetToDefaultRulesVisibility(); - void moveRowFromTo(int fromRow, int toRow); + private: + void handleOnUserSelected(const Contact::ref& contact); + void populateList(); + void selectRow(int row); + int getSelectedRow() const; + HighlightRule ruleFromDialog(); + void ruleToDialog(const HighlightRule& rule); + void updateResetToDefaultRulesVisibility(); + void moveRowFromTo(int fromRow, int toRow); - Ui::QtHighlightEditor ui_; - QtSettingsProvider* settings_; - HighlightManager* highlightManager_; - QtSuggestingJIDInput* jid_; - int previousRow_; - }; + Ui::QtHighlightEditor ui_; + QtSettingsProvider* settings_; + HighlightManager* highlightManager_; + QtSuggestingJIDInput* jid_; + int previousRow_; + }; } diff --git a/Swift/QtUI/QtHistoryWindow.cpp b/Swift/QtUI/QtHistoryWindow.cpp index 0a1f07a..5ed8114 100644 --- a/Swift/QtUI/QtHistoryWindow.cpp +++ b/Swift/QtUI/QtHistoryWindow.cpp @@ -42,227 +42,227 @@ namespace Swift { QtHistoryWindow::QtHistoryWindow(SettingsProvider* settings, UIEventStream* eventStream) : - previousTopMessageWasSelf_(false), - previousBottomMessageWasSelf_(false) { - ui_.setupUi(this); - - theme_ = new QtChatTheme(""); - idCounter_ = 0; - - delete ui_.conversation_; - conversation_ = new QtWebKitChatView(NULL, NULL, theme_, this, true); // Horrible unsafe. Do not do this. FIXME - QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - sizePolicy.setHorizontalStretch(80); - sizePolicy.setVerticalStretch(0); - conversation_->setSizePolicy(sizePolicy); - - ui_.conversation_ = conversation_; - ui_.bottomLayout_->addWidget(conversation_); - - delete ui_.conversationRoster_; - conversationRoster_ = new QtTreeWidget(eventStream, settings, QtTreeWidget::MessageDefaultJID, this); - QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Expanding); - sizePolicy2.setVerticalStretch(80); - conversationRoster_->setSizePolicy(sizePolicy2); - ui_.conversationRoster_ = conversationRoster_; - ui_.bottomLeftLayout_->setDirection(QBoxLayout::BottomToTop); - ui_.bottomLeftLayout_->addWidget(conversationRoster_); - - setWindowTitle(tr("History")); - - conversationRoster_->onSomethingSelectedChanged.connect(boost::bind(&QtHistoryWindow::handleSomethingSelectedChanged, this, _1)); - connect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int))); - connect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop())); - connect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom())); - connect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int))); - connect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed())); - connect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); - connect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); - connect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked())); - connect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked())); + previousTopMessageWasSelf_(false), + previousBottomMessageWasSelf_(false) { + ui_.setupUi(this); + + theme_ = new QtChatTheme(""); + idCounter_ = 0; + + delete ui_.conversation_; + conversation_ = new QtWebKitChatView(NULL, NULL, theme_, this, true); // Horrible unsafe. Do not do this. FIXME + QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + sizePolicy.setHorizontalStretch(80); + sizePolicy.setVerticalStretch(0); + conversation_->setSizePolicy(sizePolicy); + + ui_.conversation_ = conversation_; + ui_.bottomLayout_->addWidget(conversation_); + + delete ui_.conversationRoster_; + conversationRoster_ = new QtTreeWidget(eventStream, settings, QtTreeWidget::MessageDefaultJID, this); + QSizePolicy sizePolicy2(QSizePolicy::Preferred, QSizePolicy::Expanding); + sizePolicy2.setVerticalStretch(80); + conversationRoster_->setSizePolicy(sizePolicy2); + ui_.conversationRoster_ = conversationRoster_; + ui_.bottomLeftLayout_->setDirection(QBoxLayout::BottomToTop); + ui_.bottomLeftLayout_->addWidget(conversationRoster_); + + setWindowTitle(tr("History")); + + conversationRoster_->onSomethingSelectedChanged.connect(boost::bind(&QtHistoryWindow::handleSomethingSelectedChanged, this, _1)); + connect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int))); + connect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop())); + connect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom())); + connect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int))); + connect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed())); + connect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); + connect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); + connect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked())); + connect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked())); } QtHistoryWindow::~QtHistoryWindow() { - disconnect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int))); - disconnect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop())); - disconnect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom())); - disconnect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int))); - disconnect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed())); - disconnect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); - disconnect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); - disconnect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked())); - disconnect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked())); - - delete theme_; - delete conversation_; - // TODO: delete ui_ + disconnect(conversation_, SIGNAL(scrollRequested(int)), this, SLOT(handleScrollRequested(int))); + disconnect(conversation_, SIGNAL(scrollReachedTop()), this, SLOT(handleScrollReachedTop())); + disconnect(conversation_, SIGNAL(scrollReachedBottom()), this, SLOT(handleScrollReachedBottom())); + disconnect(conversation_, SIGNAL(fontResized(int)), this, SLOT(handleFontResized(int))); + disconnect(ui_.searchBox_->lineEdit(), SIGNAL(returnPressed()), this, SLOT(handleReturnPressed())); + disconnect(ui_.calendarWidget_, SIGNAL(clicked(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); + disconnect(ui_.calendarWidget_, SIGNAL(activated(const QDate&)), this, SLOT(handleCalendarClicked(const QDate&))); + disconnect(ui_.previousButton_, SIGNAL(clicked(bool)), this, SLOT(handlePreviousButtonClicked())); + disconnect(ui_.nextButton_, SIGNAL(clicked(bool)), this, SLOT(handleNextButtonClicked())); + + delete theme_; + delete conversation_; + // TODO: delete ui_ } void QtHistoryWindow::activate() { - emit wantsToActivate(); + emit wantsToActivate(); } void QtHistoryWindow::showEvent(QShowEvent* event) { - emit windowOpening(); - emit titleUpdated(); - QWidget::showEvent(event); + emit windowOpening(); + emit titleUpdated(); + QWidget::showEvent(event); } void QtHistoryWindow::closeEvent(QCloseEvent* event) { - emit windowClosing(); - event->accept(); + emit windowClosing(); + event->accept(); } void QtHistoryWindow::setRosterModel(Roster* model) { - conversationRoster_->setRosterModel(model); + conversationRoster_->setRosterModel(model); } void QtHistoryWindow::addMessage(const std::string &message, const std::string &senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop) { - QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str()); - - QString messageHTML(P2QSTRING(message)); - messageHTML = QtUtilities::htmlEscape(messageHTML); - QString searchTerm = ui_.searchBox_->lineEdit()->text(); - if (searchTerm.length()) { - messageHTML.replace(searchTerm, "" + searchTerm + ""); - } - - // note: time uses localtime - QDate date = QDate(time.date().year(), time.date().month(), time.date().day()); - QTime dayTime = QTime(time.time_of_day().hours(), time.time_of_day().minutes(), time.time_of_day().seconds()); - QDateTime qTime = QDateTime(date, dayTime); - - std::string id = "id" + boost::lexical_cast(idCounter_++); - - QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded(); - - if (addAtTheTop) { - bool appendToPrevious = ((senderIsSelf && previousTopMessageWasSelf_) || (!senderIsSelf && !previousTopMessageWasSelf_&& previousTopSenderName_ == P2QSTRING(senderName))); - conversation_->addMessageTop(boost::shared_ptr(new MessageSnippet(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message)))); - - previousTopMessageWasSelf_ = senderIsSelf; - previousTopSenderName_ = P2QSTRING(senderName); - } - else { - bool appendToPrevious = ((senderIsSelf && previousBottomMessageWasSelf_) || (!senderIsSelf && !previousBottomMessageWasSelf_&& previousBottomSenderName_ == P2QSTRING(senderName))); - conversation_->addMessageBottom(boost::make_shared(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message))); - previousBottomMessageWasSelf_ = senderIsSelf; - previousBottomSenderName_ = P2QSTRING(senderName); - } - - // keep track of the days viewable in the chatView - if (!dates_.count(date)) { - dates_.insert(date); - } + QString scaledAvatarPath = QtScaledAvatarCache(32).getScaledAvatarPath(avatarPath.c_str()); + + QString messageHTML(P2QSTRING(message)); + messageHTML = QtUtilities::htmlEscape(messageHTML); + QString searchTerm = ui_.searchBox_->lineEdit()->text(); + if (searchTerm.length()) { + messageHTML.replace(searchTerm, "" + searchTerm + ""); + } + + // note: time uses localtime + QDate date = QDate(time.date().year(), time.date().month(), time.date().day()); + QTime dayTime = QTime(time.time_of_day().hours(), time.time_of_day().minutes(), time.time_of_day().seconds()); + QDateTime qTime = QDateTime(date, dayTime); + + std::string id = "id" + boost::lexical_cast(idCounter_++); + + QString qAvatarPath = scaledAvatarPath.isEmpty() ? "qrc:/icons/avatar.png" : QUrl::fromLocalFile(scaledAvatarPath).toEncoded(); + + if (addAtTheTop) { + bool appendToPrevious = ((senderIsSelf && previousTopMessageWasSelf_) || (!senderIsSelf && !previousTopMessageWasSelf_&& previousTopSenderName_ == P2QSTRING(senderName))); + conversation_->addMessageTop(boost::shared_ptr(new MessageSnippet(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message)))); + + previousTopMessageWasSelf_ = senderIsSelf; + previousTopSenderName_ = P2QSTRING(senderName); + } + else { + bool appendToPrevious = ((senderIsSelf && previousBottomMessageWasSelf_) || (!senderIsSelf && !previousBottomMessageWasSelf_&& previousBottomSenderName_ == P2QSTRING(senderName))); + conversation_->addMessageBottom(boost::make_shared(messageHTML, QtUtilities::htmlEscape(P2QSTRING(senderName)), qTime, qAvatarPath, senderIsSelf, appendToPrevious, theme_, P2QSTRING(id), ChatSnippet::getDirection(message))); + previousBottomMessageWasSelf_ = senderIsSelf; + previousBottomSenderName_ = P2QSTRING(senderName); + } + + // keep track of the days viewable in the chatView + if (!dates_.count(date)) { + dates_.insert(date); + } } void QtHistoryWindow::handleSomethingSelectedChanged(RosterItem* item) { - onSelectedContactChanged(item); + onSelectedContactChanged(item); } void QtHistoryWindow::resetConversationView() { - previousTopMessageWasSelf_ = false; - previousBottomMessageWasSelf_ = false; - previousTopSenderName_.clear(); - previousBottomSenderName_.clear(); + previousTopMessageWasSelf_ = false; + previousBottomMessageWasSelf_ = false; + previousTopSenderName_.clear(); + previousBottomSenderName_.clear(); - dates_.clear(); - conversation_->resetView(); + dates_.clear(); + conversation_->resetView(); } void QtHistoryWindow::handleScrollRequested(int pos) { - // first message starts with offset 5 - if (pos < 5) { - pos = 5; - } - - QDate currentDate; - foreach (const QDate& date, dates_) { - int snippetPosition = conversation_->getSnippetPositionByDate(date); - if (snippetPosition <= pos) { - currentDate = date; - } - } - - if (ui_.calendarWidget_->selectedDate() != currentDate) { - ui_.calendarWidget_->setSelectedDate(currentDate); - } + // first message starts with offset 5 + if (pos < 5) { + pos = 5; + } + + QDate currentDate; + foreach (const QDate& date, dates_) { + int snippetPosition = conversation_->getSnippetPositionByDate(date); + if (snippetPosition <= pos) { + currentDate = date; + } + } + + if (ui_.calendarWidget_->selectedDate() != currentDate) { + ui_.calendarWidget_->setSelectedDate(currentDate); + } } void QtHistoryWindow::handleScrollReachedTop() { - if (dates_.empty()) { - return; - } - - int year, month, day; - QDate firstDate = *dates_.begin(); - firstDate.getDate(&year, &month, &day); - onScrollReachedTop(boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day))); + if (dates_.empty()) { + return; + } + + int year, month, day; + QDate firstDate = *dates_.begin(); + firstDate.getDate(&year, &month, &day); + onScrollReachedTop(boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day))); } void QtHistoryWindow::handleScrollReachedBottom() { - if (dates_.empty()) { - return; - } - - int year, month, day; - QDate lastDate = *dates_.rbegin(); - lastDate.getDate(&year, &month, &day); - onScrollReachedBottom(boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day))); + if (dates_.empty()) { + return; + } + + int year, month, day; + QDate lastDate = *dates_.rbegin(); + lastDate.getDate(&year, &month, &day); + onScrollReachedBottom(boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day))); } void QtHistoryWindow::handleReturnPressed() { - onReturnPressed(ui_.searchBox_->lineEdit()->text().toStdString()); + onReturnPressed(ui_.searchBox_->lineEdit()->text().toStdString()); } void QtHistoryWindow::handleCalendarClicked(const QDate& date) { - int year, month, day; - QDate tempDate = date; // getDate discards const qualifier - tempDate.getDate(&year, &month, &day); - onCalendarClicked(boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day))); + int year, month, day; + QDate tempDate = date; // getDate discards const qualifier + tempDate.getDate(&year, &month, &day); + onCalendarClicked(boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day))); } void QtHistoryWindow::setDate(const boost::gregorian::date& date) { - ui_.calendarWidget_->setSelectedDate(QDate::fromJulianDay(date.julian_day())); + ui_.calendarWidget_->setSelectedDate(QDate::fromJulianDay(date.julian_day())); } void QtHistoryWindow::handleNextButtonClicked() { - onNextButtonClicked(); + onNextButtonClicked(); } void QtHistoryWindow::handlePreviousButtonClicked() { - onPreviousButtonClicked(); + onPreviousButtonClicked(); } void QtHistoryWindow::handleFontResized(int fontSizeSteps) { - conversation_->resizeFont(fontSizeSteps); + conversation_->resizeFont(fontSizeSteps); - emit fontResized(fontSizeSteps); + emit fontResized(fontSizeSteps); } void QtHistoryWindow::resetConversationViewTopInsertPoint() { - previousTopMessageWasSelf_ = false; - previousTopSenderName_ = QString(); - conversation_->resetTopInsertPoint(); + previousTopMessageWasSelf_ = false; + previousTopSenderName_ = QString(); + conversation_->resetTopInsertPoint(); } std::string QtHistoryWindow::getSearchBoxText() { - return ui_.searchBox_->lineEdit()->text().toStdString(); + return ui_.searchBox_->lineEdit()->text().toStdString(); } boost::gregorian::date QtHistoryWindow::getLastVisibleDate() { - if (!dates_.empty()) { - QDate lastDate = *dates_.rbegin(); - int year, month, day; - lastDate.getDate(&year, &month, &day); - - return boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day)); - } - return boost::gregorian::date(boost::gregorian::not_a_date_time); + if (!dates_.empty()) { + QDate lastDate = *dates_.rbegin(); + int year, month, day; + lastDate.getDate(&year, &month, &day); + + return boost::gregorian::date(boost::numeric_cast(year), boost::numeric_cast(month), boost::numeric_cast(day)); + } + return boost::gregorian::date(boost::gregorian::not_a_date_time); } std::string QtHistoryWindow::getID() const { - return "QtHistoryWindow"; + return "QtHistoryWindow"; } } diff --git a/Swift/QtUI/QtHistoryWindow.h b/Swift/QtUI/QtHistoryWindow.h index 2008079..02d7fb8 100644 --- a/Swift/QtUI/QtHistoryWindow.h +++ b/Swift/QtUI/QtHistoryWindow.h @@ -22,61 +22,61 @@ #include namespace Swift { - class QtTabbable; - class QtTreeWidget; - class QtWebKitChatView; - class QtChatTheme; - class SettingsProvider; - class UIEventStream; - - class QtHistoryWindow : public QtTabbable, public HistoryWindow { - Q_OBJECT - - public: - QtHistoryWindow(SettingsProvider*, UIEventStream*); - ~QtHistoryWindow(); - void activate(); - void setRosterModel(Roster*); - void addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop); - void resetConversationView(); - void resetConversationViewTopInsertPoint(); - void setDate(const boost::gregorian::date& date); - - void closeEvent(QCloseEvent* event); - void showEvent(QShowEvent* event); - - std::string getSearchBoxText(); - boost::gregorian::date getLastVisibleDate(); - - virtual std::string getID() const; - - signals: - void fontResized(int); - - public slots: - void handleFontResized(int fontSizeSteps); - - protected slots: - void handleScrollRequested(int pos); - void handleScrollReachedTop(); - void handleScrollReachedBottom(); - void handleReturnPressed(); - void handleCalendarClicked(const QDate& date); - void handlePreviousButtonClicked(); - void handleNextButtonClicked(); - - private: - void handleSomethingSelectedChanged(RosterItem* item); - - Ui::QtHistoryWindow ui_; - QtChatTheme* theme_; - QtWebKitChatView* conversation_; - QtTreeWidget* conversationRoster_; - std::set dates_; - int idCounter_; - bool previousTopMessageWasSelf_; - QString previousTopSenderName_; - bool previousBottomMessageWasSelf_; - QString previousBottomSenderName_; - }; + class QtTabbable; + class QtTreeWidget; + class QtWebKitChatView; + class QtChatTheme; + class SettingsProvider; + class UIEventStream; + + class QtHistoryWindow : public QtTabbable, public HistoryWindow { + Q_OBJECT + + public: + QtHistoryWindow(SettingsProvider*, UIEventStream*); + ~QtHistoryWindow(); + void activate(); + void setRosterModel(Roster*); + void addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const std::string& avatarPath, const boost::posix_time::ptime& time, bool addAtTheTop); + void resetConversationView(); + void resetConversationViewTopInsertPoint(); + void setDate(const boost::gregorian::date& date); + + void closeEvent(QCloseEvent* event); + void showEvent(QShowEvent* event); + + std::string getSearchBoxText(); + boost::gregorian::date getLastVisibleDate(); + + virtual std::string getID() const; + + signals: + void fontResized(int); + + public slots: + void handleFontResized(int fontSizeSteps); + + protected slots: + void handleScrollRequested(int pos); + void handleScrollReachedTop(); + void handleScrollReachedBottom(); + void handleReturnPressed(); + void handleCalendarClicked(const QDate& date); + void handlePreviousButtonClicked(); + void handleNextButtonClicked(); + + private: + void handleSomethingSelectedChanged(RosterItem* item); + + Ui::QtHistoryWindow ui_; + QtChatTheme* theme_; + QtWebKitChatView* conversation_; + QtTreeWidget* conversationRoster_; + std::set dates_; + int idCounter_; + bool previousTopMessageWasSelf_; + QString previousTopSenderName_; + bool previousBottomMessageWasSelf_; + QString previousBottomSenderName_; + }; } diff --git a/Swift/QtUI/QtJoinMUCWindow.cpp b/Swift/QtUI/QtJoinMUCWindow.cpp index 53944da..7225b06 100644 --- a/Swift/QtUI/QtJoinMUCWindow.cpp +++ b/Swift/QtUI/QtJoinMUCWindow.cpp @@ -17,59 +17,59 @@ namespace Swift { QtJoinMUCWindow::QtJoinMUCWindow(UIEventStream* uiEventStream) : uiEventStream(uiEventStream) { - ui.setupUi(this); + ui.setupUi(this); #if QT_VERSION >= 0x040700 - ui.room->setPlaceholderText(tr("someroom@rooms.example.com")); + ui.room->setPlaceholderText(tr("someroom@rooms.example.com")); #endif - connect(ui.room, SIGNAL(returnPressed()), this, SLOT(handleJoin())); - connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch())); - connect(ui.joinButton, SIGNAL(clicked()), this, SLOT(handleJoin())); + connect(ui.room, SIGNAL(returnPressed()), this, SLOT(handleJoin())); + connect(ui.searchButton, SIGNAL(clicked()), this, SLOT(handleSearch())); + connect(ui.joinButton, SIGNAL(clicked()), this, SLOT(handleJoin())); #if QT_VERSION < 0x050200 - // FIXME: Temporarily set focus on the nickName field first, so that the - // placeholder for the room is visible. This is just because Qt hides - // the placeholder when a widget is focused for some reason. - // Tracked upstream as QTBUG-33237 and fixed with Qt 5.2.0. - ui.nickName->setFocus(); + // FIXME: Temporarily set focus on the nickName field first, so that the + // placeholder for the room is visible. This is just because Qt hides + // the placeholder when a widget is focused for some reason. + // Tracked upstream as QTBUG-33237 and fixed with Qt 5.2.0. + ui.nickName->setFocus(); #endif - ui.instantRoom->setChecked(true); - ui.nickName->setValidator(new NickValidator(this)); - ui.room->setValidator(new RoomJIDValidator(this)); + ui.instantRoom->setChecked(true); + ui.nickName->setValidator(new NickValidator(this)); + ui.room->setValidator(new RoomJIDValidator(this)); } void QtJoinMUCWindow::handleJoin() { - if (ui.room->text().isEmpty() || !ui.room->hasAcceptableInput()) { - QToolTip::showText(ui.room->mapToGlobal(QPoint()), tr("Please enter a valid room address."), ui.room); - return; - } - if (ui.nickName->text().isEmpty() || !ui.nickName->hasAcceptableInput()) { - QToolTip::showText(ui.nickName->mapToGlobal(QPoint()), tr("Please enter a valid nickname."), ui.nickName); - return; - } + if (ui.room->text().isEmpty() || !ui.room->hasAcceptableInput()) { + QToolTip::showText(ui.room->mapToGlobal(QPoint()), tr("Please enter a valid room address."), ui.room); + return; + } + if (ui.nickName->text().isEmpty() || !ui.nickName->hasAcceptableInput()) { + QToolTip::showText(ui.nickName->mapToGlobal(QPoint()), tr("Please enter a valid nickname."), ui.nickName); + return; + } - lastSetNick = Q2PSTRING(ui.nickName->text()); - std::string password = Q2PSTRING(ui.password->text()); - JID room(Q2PSTRING(ui.room->text())); - uiEventStream->send(boost::make_shared(room, password, lastSetNick, ui.joinAutomatically->isChecked(), !ui.instantRoom->isChecked())); - hide(); + lastSetNick = Q2PSTRING(ui.nickName->text()); + std::string password = Q2PSTRING(ui.password->text()); + JID room(Q2PSTRING(ui.room->text())); + uiEventStream->send(boost::make_shared(room, password, lastSetNick, ui.joinAutomatically->isChecked(), !ui.instantRoom->isChecked())); + hide(); } void QtJoinMUCWindow::handleSearch() { - onSearchMUC(); + onSearchMUC(); } void QtJoinMUCWindow::setNick(const std::string& nick) { - ui.nickName->setText(P2QSTRING(nick)); - lastSetNick = nick; + ui.nickName->setText(P2QSTRING(nick)); + lastSetNick = nick; } void QtJoinMUCWindow::setMUC(const std::string& nick) { - ui.room->setText(P2QSTRING(nick)); + ui.room->setText(P2QSTRING(nick)); } void QtJoinMUCWindow::show() { - QWidget::show(); - QWidget::activateWindow(); - ui.password->setText(""); + QWidget::show(); + QWidget::activateWindow(); + ui.password->setText(""); } } diff --git a/Swift/QtUI/QtJoinMUCWindow.h b/Swift/QtUI/QtJoinMUCWindow.h index 618f2e9..c2e8068 100644 --- a/Swift/QtUI/QtJoinMUCWindow.h +++ b/Swift/QtUI/QtJoinMUCWindow.h @@ -16,60 +16,60 @@ #include namespace Swift { - class UIEventStream; - class NickValidator : public QValidator { - Q_OBJECT - public: - NickValidator(QObject* parent) : QValidator(parent) { - } - - virtual QValidator::State validate(QString& input, int& /*pos*/) const { - if (input.isEmpty()) { - return QValidator::Intermediate; - } - JID test("alice", "wonderland.lit", Q2PSTRING(input)); - - return test.isValid() ? QValidator::Acceptable : QValidator::Invalid; - } - }; - - class RoomJIDValidator : public QValidator { - Q_OBJECT - public: - RoomJIDValidator(QObject* parent) : QValidator(parent) { - } - - virtual QValidator::State validate(QString& input, int& /*pos*/) const { - if (input.isEmpty()) { - return QValidator::Intermediate; - } - JID roomJID(Q2PSTRING(input)); - - if (roomJID.getNode().empty() || roomJID.getDomain().empty()) { - return QValidator::Intermediate; - } - - return (roomJID.getResource().empty() && !roomJID.getNode().empty() && !roomJID.getDomain().empty() && roomJID.isValid()) ? QValidator::Acceptable : QValidator::Invalid; - } - }; - - class QtJoinMUCWindow : public QWidget, public JoinMUCWindow { - Q_OBJECT - public: - QtJoinMUCWindow(UIEventStream* uiEventStream); - - virtual void setNick(const std::string& nick); - virtual void setMUC(const std::string& nick); - - virtual void show(); - - private slots: - void handleJoin(); - void handleSearch(); - - private: - Ui::QtJoinMUCWindow ui; - std::string lastSetNick; - UIEventStream* uiEventStream; - }; + class UIEventStream; + class NickValidator : public QValidator { + Q_OBJECT + public: + NickValidator(QObject* parent) : QValidator(parent) { + } + + virtual QValidator::State validate(QString& input, int& /*pos*/) const { + if (input.isEmpty()) { + return QValidator::Intermediate; + } + JID test("alice", "wonderland.lit", Q2PSTRING(input)); + + return test.isValid() ? QValidator::Acceptable : QValidator::Invalid; + } + }; + + class RoomJIDValidator : public QValidator { + Q_OBJECT + public: + RoomJIDValidator(QObject* parent) : QValidator(parent) { + } + + virtual QValidator::State validate(QString& input, int& /*pos*/) const { + if (input.isEmpty()) { + return QValidator::Intermediate; + } + JID roomJID(Q2PSTRING(input)); + + if (roomJID.getNode().empty() || roomJID.getDomain().empty()) { + return QValidator::Intermediate; + } + + return (roomJID.getResource().empty() && !roomJID.getNode().empty() && !roomJID.getDomain().empty() && roomJID.isValid()) ? QValidator::Acceptable : QValidator::Invalid; + } + }; + + class QtJoinMUCWindow : public QWidget, public JoinMUCWindow { + Q_OBJECT + public: + QtJoinMUCWindow(UIEventStream* uiEventStream); + + virtual void setNick(const std::string& nick); + virtual void setMUC(const std::string& nick); + + virtual void show(); + + private slots: + void handleJoin(); + void handleSearch(); + + private: + Ui::QtJoinMUCWindow ui; + std::string lastSetNick; + UIEventStream* uiEventStream; + }; } diff --git a/Swift/QtUI/QtLineEdit.cpp b/Swift/QtUI/QtLineEdit.cpp index a98663c..d3ec4c4 100644 --- a/Swift/QtUI/QtLineEdit.cpp +++ b/Swift/QtUI/QtLineEdit.cpp @@ -14,10 +14,10 @@ QtLineEdit::QtLineEdit(QWidget* parent) : QLineEdit(parent) { } void QtLineEdit::keyPressEvent(QKeyEvent* event) { - if (event->key() == Qt::Key_Escape) { - emit escapePressed(); - } - QLineEdit::keyPressEvent(event); + if (event->key() == Qt::Key_Escape) { + emit escapePressed(); + } + QLineEdit::keyPressEvent(event); } } diff --git a/Swift/QtUI/QtLineEdit.h b/Swift/QtUI/QtLineEdit.h index 1c7240a..557f025 100644 --- a/Swift/QtUI/QtLineEdit.h +++ b/Swift/QtUI/QtLineEdit.h @@ -9,13 +9,13 @@ #include namespace Swift { - class QtLineEdit : public QLineEdit { - Q_OBJECT - public: - QtLineEdit(QWidget* parent = NULL); - signals: - void escapePressed(); - protected: - virtual void keyPressEvent(QKeyEvent* event); - }; + class QtLineEdit : public QLineEdit { + Q_OBJECT + public: + QtLineEdit(QWidget* parent = NULL); + signals: + void escapePressed(); + protected: + virtual void keyPressEvent(QKeyEvent* event); + }; } diff --git a/Swift/QtUI/QtLoginWindow.cpp b/Swift/QtUI/QtLoginWindow.cpp index 229df7f..5f15f4c 100644 --- a/Swift/QtUI/QtLoginWindow.cpp +++ b/Swift/QtUI/QtLoginWindow.cpp @@ -54,524 +54,524 @@ namespace Swift{ QtLoginWindow::QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory) : QMainWindow(), settings_(settings), timerFactory_(timerFactory) { - uiEventStream_ = uiEventStream; + uiEventStream_ = uiEventStream; - setWindowTitle("Swift"); + setWindowTitle("Swift"); #ifndef Q_OS_MAC #ifdef Q_OS_WIN32 - setWindowIcon(QIcon(":/logo-icon-16-win.png")); + setWindowIcon(QIcon(":/logo-icon-16-win.png")); #else - setWindowIcon(QIcon(":/logo-icon-16.png")); + setWindowIcon(QIcon(":/logo-icon-16.png")); #endif #endif - QtUtilities::setX11Resource(this, "Main"); - setAccessibleName(tr("Swift Login Window")); - //setAccessibleDescription(tr("This window is used for providing credentials to log into your XMPP service")); - - resize(200, 500); - setContentsMargins(0,0,0,0); - QWidget *centralWidget = new QWidget(this); - setCentralWidget(centralWidget); - QBoxLayout *topLayout = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget); - stack_ = new QStackedWidget(centralWidget); - topLayout->addWidget(stack_); - topLayout->setMargin(0); - loginWidgetWrapper_ = new QWidget(this); - loginWidgetWrapper_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); - QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, loginWidgetWrapper_); - layout->addStretch(2); - - QLabel* logo = new QLabel(this); - logo->setPixmap(QPixmap(":/logo-shaded-text.256.png")); - logo->setScaledContents(true); - logo->setFixedSize(192,192); - - QWidget *logoWidget = new QWidget(this); - QHBoxLayout *logoLayout = new QHBoxLayout(); - logoLayout->setMargin(0); - logoLayout->addStretch(0); - logoLayout->addWidget(logo); - logoLayout->addStretch(0); - logoWidget->setLayout(logoLayout); - layout->addWidget(logoWidget); - - layout->addStretch(2); - - QLabel* jidLabel = new QLabel(this); - jidLabel->setText("" + tr("User address:") + ""); - layout->addWidget(jidLabel); - - - username_ = new QComboBox(this); - username_->setEditable(true); - username_->setWhatsThis(tr("User address - looks like someuser@someserver.com")); - username_->setToolTip(tr("User address - looks like someuser@someserver.com")); - username_->view()->installEventFilter(this); - username_->setAccessibleName(tr("User address (of the form someuser@someserver.com)")); - username_->setAccessibleDescription(tr("This is the user address that you'll be using to log in with")); - layout->addWidget(username_); - QLabel* jidHintLabel = new QLabel(this); - jidHintLabel->setText("" + tr("Example: alice@wonderland.lit") + ""); - jidHintLabel->setAlignment(Qt::AlignRight); - layout->addWidget(jidHintLabel); - - - QLabel* passwordLabel = new QLabel(); - passwordLabel->setText("" + tr("Password:") + ""); - passwordLabel->setAccessibleName(tr("User password")); - passwordLabel->setAccessibleDescription(tr("This is the password you'll use to log in to the XMPP service")); - layout->addWidget(passwordLabel); - - - QWidget* w = new QWidget(this); - w->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); - layout->addWidget(w); - - QHBoxLayout* credentialsLayout = new QHBoxLayout(w); - credentialsLayout->setMargin(0); - credentialsLayout->setSpacing(3); - password_ = new QLineEdit(this); - password_->setEchoMode(QLineEdit::Password); - connect(password_, SIGNAL(returnPressed()), this, SLOT(loginClicked())); - connect(username_->lineEdit(), SIGNAL(returnPressed()), password_, SLOT(setFocus())); - connect(username_, SIGNAL(editTextChanged(const QString&)), this, SLOT(handleUsernameTextChanged())); - credentialsLayout->addWidget(password_); - - certificateButton_ = new QToolButton(this); - certificateButton_->setCheckable(true); - certificateButton_->setIcon(QIcon(":/icons/certificate.png")); - certificateButton_->setToolTip(tr("Click if you have a personal certificate used for login to the service.")); - certificateButton_->setWhatsThis(tr("Click if you have a personal certificate used for login to the service.")); - certificateButton_->setAccessibleName(tr("Login with certificate")); - certificateButton_->setAccessibleDescription(tr("Click if you have a personal certificate used for login to the service.")); - - credentialsLayout->addWidget(certificateButton_); - connect(certificateButton_, SIGNAL(clicked(bool)), SLOT(handleCertficateChecked(bool))); - - loginButton_ = new QPushButton(this); - loginButton_->setText(tr("Connect")); - loginButton_->setAutoDefault(true); - loginButton_->setDefault(true); - loginButton_->setAccessibleName(tr("Connect now")); - layout->addWidget(loginButton_); - - QLabel* connectionOptionsLabel = new QLabel(this); - connectionOptionsLabel->setText("" + QObject::tr("Connection Options") + ""); - connectionOptionsLabel->setTextFormat(Qt::RichText); - connectionOptionsLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter); - layout->addWidget(connectionOptionsLabel); - connect(connectionOptionsLabel, SIGNAL(linkActivated(const QString&)), SLOT(handleOpenConnectionOptions())); - - message_ = new QLabel(this); - message_->setTextFormat(Qt::RichText); - message_->setWordWrap(true); - layout->addWidget(message_); - - layout->addStretch(2); - remember_ = new QCheckBox(tr("Remember Password?"), this); - layout->addWidget(remember_); - loginAutomatically_ = new QCheckBox(tr("Login Automatically?"), this); - layout->addWidget(loginAutomatically_); - - connect(loginButton_, SIGNAL(clicked()), SLOT(loginClicked())); - stack_->addWidget(loginWidgetWrapper_); + QtUtilities::setX11Resource(this, "Main"); + setAccessibleName(tr("Swift Login Window")); + //setAccessibleDescription(tr("This window is used for providing credentials to log into your XMPP service")); + + resize(200, 500); + setContentsMargins(0,0,0,0); + QWidget *centralWidget = new QWidget(this); + setCentralWidget(centralWidget); + QBoxLayout *topLayout = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget); + stack_ = new QStackedWidget(centralWidget); + topLayout->addWidget(stack_); + topLayout->setMargin(0); + loginWidgetWrapper_ = new QWidget(this); + loginWidgetWrapper_->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); + QBoxLayout *layout = new QBoxLayout(QBoxLayout::TopToBottom, loginWidgetWrapper_); + layout->addStretch(2); + + QLabel* logo = new QLabel(this); + logo->setPixmap(QPixmap(":/logo-shaded-text.256.png")); + logo->setScaledContents(true); + logo->setFixedSize(192,192); + + QWidget *logoWidget = new QWidget(this); + QHBoxLayout *logoLayout = new QHBoxLayout(); + logoLayout->setMargin(0); + logoLayout->addStretch(0); + logoLayout->addWidget(logo); + logoLayout->addStretch(0); + logoWidget->setLayout(logoLayout); + layout->addWidget(logoWidget); + + layout->addStretch(2); + + QLabel* jidLabel = new QLabel(this); + jidLabel->setText("" + tr("User address:") + ""); + layout->addWidget(jidLabel); + + + username_ = new QComboBox(this); + username_->setEditable(true); + username_->setWhatsThis(tr("User address - looks like someuser@someserver.com")); + username_->setToolTip(tr("User address - looks like someuser@someserver.com")); + username_->view()->installEventFilter(this); + username_->setAccessibleName(tr("User address (of the form someuser@someserver.com)")); + username_->setAccessibleDescription(tr("This is the user address that you'll be using to log in with")); + layout->addWidget(username_); + QLabel* jidHintLabel = new QLabel(this); + jidHintLabel->setText("" + tr("Example: alice@wonderland.lit") + ""); + jidHintLabel->setAlignment(Qt::AlignRight); + layout->addWidget(jidHintLabel); + + + QLabel* passwordLabel = new QLabel(); + passwordLabel->setText("" + tr("Password:") + ""); + passwordLabel->setAccessibleName(tr("User password")); + passwordLabel->setAccessibleDescription(tr("This is the password you'll use to log in to the XMPP service")); + layout->addWidget(passwordLabel); + + + QWidget* w = new QWidget(this); + w->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); + layout->addWidget(w); + + QHBoxLayout* credentialsLayout = new QHBoxLayout(w); + credentialsLayout->setMargin(0); + credentialsLayout->setSpacing(3); + password_ = new QLineEdit(this); + password_->setEchoMode(QLineEdit::Password); + connect(password_, SIGNAL(returnPressed()), this, SLOT(loginClicked())); + connect(username_->lineEdit(), SIGNAL(returnPressed()), password_, SLOT(setFocus())); + connect(username_, SIGNAL(editTextChanged(const QString&)), this, SLOT(handleUsernameTextChanged())); + credentialsLayout->addWidget(password_); + + certificateButton_ = new QToolButton(this); + certificateButton_->setCheckable(true); + certificateButton_->setIcon(QIcon(":/icons/certificate.png")); + certificateButton_->setToolTip(tr("Click if you have a personal certificate used for login to the service.")); + certificateButton_->setWhatsThis(tr("Click if you have a personal certificate used for login to the service.")); + certificateButton_->setAccessibleName(tr("Login with certificate")); + certificateButton_->setAccessibleDescription(tr("Click if you have a personal certificate used for login to the service.")); + + credentialsLayout->addWidget(certificateButton_); + connect(certificateButton_, SIGNAL(clicked(bool)), SLOT(handleCertficateChecked(bool))); + + loginButton_ = new QPushButton(this); + loginButton_->setText(tr("Connect")); + loginButton_->setAutoDefault(true); + loginButton_->setDefault(true); + loginButton_->setAccessibleName(tr("Connect now")); + layout->addWidget(loginButton_); + + QLabel* connectionOptionsLabel = new QLabel(this); + connectionOptionsLabel->setText("" + QObject::tr("Connection Options") + ""); + connectionOptionsLabel->setTextFormat(Qt::RichText); + connectionOptionsLabel->setAlignment(Qt::AlignRight|Qt::AlignVCenter); + layout->addWidget(connectionOptionsLabel); + connect(connectionOptionsLabel, SIGNAL(linkActivated(const QString&)), SLOT(handleOpenConnectionOptions())); + + message_ = new QLabel(this); + message_->setTextFormat(Qt::RichText); + message_->setWordWrap(true); + layout->addWidget(message_); + + layout->addStretch(2); + remember_ = new QCheckBox(tr("Remember Password?"), this); + layout->addWidget(remember_); + loginAutomatically_ = new QCheckBox(tr("Login Automatically?"), this); + layout->addWidget(loginAutomatically_); + + connect(loginButton_, SIGNAL(clicked()), SLOT(loginClicked())); + stack_->addWidget(loginWidgetWrapper_); #ifdef SWIFTEN_PLATFORM_MACOSX - menuBar_ = new QMenuBar(NULL); + menuBar_ = new QMenuBar(NULL); #else - menuBar_ = menuBar(); + menuBar_ = menuBar(); #endif - QApplication::setQuitOnLastWindowClosed(false); + QApplication::setQuitOnLastWindowClosed(false); - swiftMenu_ = new QMenu(tr("&Swift"), this); + swiftMenu_ = new QMenu(tr("&Swift"), this); #ifdef SWIFTEN_PLATFORM_MACOSX - generalMenu_ = new QMenu(tr("&General"), this); + generalMenu_ = new QMenu(tr("&General"), this); #else - generalMenu_ = swiftMenu_; + generalMenu_ = swiftMenu_; #endif #ifdef SWIFTEN_PLATFORM_MACOSX - QAction* aboutAction = new QAction(QString("&About %1").arg("Swift"), this); + QAction* aboutAction = new QAction(QString("&About %1").arg("Swift"), this); #else - QAction* aboutAction = new QAction(QString(tr("&About %1")).arg("Swift"), this); + QAction* aboutAction = new QAction(QString(tr("&About %1")).arg("Swift"), this); #endif - connect(aboutAction, SIGNAL(triggered()), SLOT(handleAbout())); - swiftMenu_->addAction(aboutAction); + connect(aboutAction, SIGNAL(triggered()), SLOT(handleAbout())); + swiftMenu_->addAction(aboutAction); - xmlConsoleAction_ = new QAction(tr("&Show Debug Console"), this); - connect(xmlConsoleAction_, SIGNAL(triggered()), SLOT(handleShowXMLConsole())); - generalMenu_->addAction(xmlConsoleAction_); + xmlConsoleAction_ = new QAction(tr("&Show Debug Console"), this); + connect(xmlConsoleAction_, SIGNAL(triggered()), SLOT(handleShowXMLConsole())); + generalMenu_->addAction(xmlConsoleAction_); #ifdef SWIFT_EXPERIMENTAL_FT - fileTransferOverviewAction_ = new QAction(tr("Show &File Transfer Overview"), this); - connect(fileTransferOverviewAction_, SIGNAL(triggered()), SLOT(handleShowFileTransferOverview())); - generalMenu_->addAction(fileTransferOverviewAction_); + fileTransferOverviewAction_ = new QAction(tr("Show &File Transfer Overview"), this); + connect(fileTransferOverviewAction_, SIGNAL(triggered()), SLOT(handleShowFileTransferOverview())); + generalMenu_->addAction(fileTransferOverviewAction_); #endif - highlightEditorAction_ = new QAction(tr("&Edit Highlight Rules"), this); - connect(highlightEditorAction_, SIGNAL(triggered()), SLOT(handleShowHighlightEditor())); - generalMenu_->addAction(highlightEditorAction_); + highlightEditorAction_ = new QAction(tr("&Edit Highlight Rules"), this); + connect(highlightEditorAction_, SIGNAL(triggered()), SLOT(handleShowHighlightEditor())); + generalMenu_->addAction(highlightEditorAction_); - toggleSoundsAction_ = new QAction(tr("&Play Sounds"), this); - toggleSoundsAction_->setCheckable(true); - toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS)); - connect(toggleSoundsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleSounds(bool))); - generalMenu_->addAction(toggleSoundsAction_); + toggleSoundsAction_ = new QAction(tr("&Play Sounds"), this); + toggleSoundsAction_->setCheckable(true); + toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS)); + connect(toggleSoundsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleSounds(bool))); + generalMenu_->addAction(toggleSoundsAction_); - toggleNotificationsAction_ = new QAction(tr("Display Pop-up &Notifications"), this); - toggleNotificationsAction_->setCheckable(true); - toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); - connect(toggleNotificationsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleNotifications(bool))); + toggleNotificationsAction_ = new QAction(tr("Display Pop-up &Notifications"), this); + toggleNotificationsAction_->setCheckable(true); + toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); + connect(toggleNotificationsAction_, SIGNAL(toggled(bool)), SLOT(handleToggleNotifications(bool))); #ifndef SWIFTEN_PLATFORM_MACOSX - swiftMenu_->addSeparator(); + swiftMenu_->addSeparator(); #endif #ifdef SWIFTEN_PLATFORM_MACOSX - QAction* quitAction = new QAction("&Quit", this); + QAction* quitAction = new QAction("&Quit", this); #else - QAction* quitAction = new QAction(tr("&Quit"), this); + QAction* quitAction = new QAction(tr("&Quit"), this); #endif - connect(quitAction, SIGNAL(triggered()), SLOT(handleQuit())); - swiftMenu_->addAction(quitAction); + connect(quitAction, SIGNAL(triggered()), SLOT(handleQuit())); + swiftMenu_->addAction(quitAction); - setInitialMenus(); - settings_->onSettingChanged.connect(boost::bind(&QtLoginWindow::handleSettingChanged, this, _1)); + setInitialMenus(); + settings_->onSettingChanged.connect(boost::bind(&QtLoginWindow::handleSettingChanged, this, _1)); - bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); - remember_->setEnabled(!eagle); - loginAutomatically_->setEnabled(!eagle); - xmlConsoleAction_->setEnabled(!eagle); - if (eagle) { - remember_->setChecked(false); - loginAutomatically_->setChecked(false); - } + bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); + remember_->setEnabled(!eagle); + loginAutomatically_->setEnabled(!eagle); + xmlConsoleAction_->setEnabled(!eagle); + if (eagle) { + remember_->setChecked(false); + loginAutomatically_->setChecked(false); + } #ifdef SWIFTEN_PLATFORM_MACOSX - // Temporary workaround for case 501. Could be that this code is still - // needed when Qt provides a proper fix - qApp->installEventFilter(this); + // Temporary workaround for case 501. Could be that this code is still + // needed when Qt provides a proper fix + qApp->installEventFilter(this); #endif - this->show(); + this->show(); } void QtLoginWindow::setShowNotificationToggle(bool toggle) { - if (toggle) { - QList< QAction* > generalMenuActions = generalMenu_->actions(); - generalMenu_->insertAction(generalMenuActions.at(generalMenuActions.count()-2), toggleNotificationsAction_); - } - else { - generalMenu_->removeAction(toggleNotificationsAction_); - } + if (toggle) { + QList< QAction* > generalMenuActions = generalMenu_->actions(); + generalMenu_->insertAction(generalMenuActions.at(generalMenuActions.count()-2), toggleNotificationsAction_); + } + else { + generalMenu_->removeAction(toggleNotificationsAction_); + } } bool QtLoginWindow::eventFilter(QObject *obj, QEvent *event) { - if (obj == username_->view() && event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); - if (keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace) { - QString jid(username_->view()->currentIndex().data().toString()); - int result = QMessageBox::question(this, tr("Remove profile"), tr("Remove the profile '%1'?").arg(jid), QMessageBox::Yes | QMessageBox::No); - if (result == QMessageBox::Yes) { - onPurgeSavedLoginRequest(Q2PSTRING(jid)); - } - return true; - } - } + if (obj == username_->view() && event->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = static_cast(event); + if (keyEvent->key() == Qt::Key_Delete || keyEvent->key() == Qt::Key_Backspace) { + QString jid(username_->view()->currentIndex().data().toString()); + int result = QMessageBox::question(this, tr("Remove profile"), tr("Remove the profile '%1'?").arg(jid), QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) { + onPurgeSavedLoginRequest(Q2PSTRING(jid)); + } + return true; + } + } #ifdef SWIFTEN_PLATFORM_MACOSX - // Dock clicked - // Temporary workaround for case 501. Could be that this code is still - // needed when Qt provides a proper fix - if (obj == qApp && event->type() == QEvent::ApplicationActivate && !isVisible()) { - bringToFront(); - } + // Dock clicked + // Temporary workaround for case 501. Could be that this code is still + // needed when Qt provides a proper fix + if (obj == qApp && event->type() == QEvent::ApplicationActivate && !isVisible()) { + bringToFront(); + } #endif - return QObject::eventFilter(obj, event); + return QObject::eventFilter(obj, event); } void QtLoginWindow::handleSettingChanged(const std::string& settingPath) { - if (settingPath == SettingConstants::PLAY_SOUNDS.getKey()) { - toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS)); - } - if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) { - toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); - } + if (settingPath == SettingConstants::PLAY_SOUNDS.getKey()) { + toggleSoundsAction_->setChecked(settings_->getSetting(SettingConstants::PLAY_SOUNDS)); + } + if (settingPath == SettingConstants::SHOW_NOTIFICATIONS.getKey()) { + toggleNotificationsAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_NOTIFICATIONS)); + } } void QtLoginWindow::selectUser(const std::string& username) { - for (int i = 0; i < usernames_.count(); i++) { - if (P2QSTRING(username) == usernames_[i]) { - username_->setCurrentIndex(i); - password_->setFocus(); - break; - } - } + for (int i = 0; i < usernames_.count(); i++) { + if (P2QSTRING(username) == usernames_[i]) { + username_->setCurrentIndex(i); + password_->setFocus(); + break; + } + } } void QtLoginWindow::removeAvailableAccount(const std::string& jid) { - QString username = P2QSTRING(jid); - int index = -1; - for (int i = 0; i < usernames_.count(); i++) { - if (username == usernames_[i]) { - index = i; - } - } - if (index >= 0) { - usernames_.removeAt(index); - passwords_.removeAt(index); - certificateFiles_.removeAt(index); - username_->removeItem(index); - } + QString username = P2QSTRING(jid); + int index = -1; + for (int i = 0; i < usernames_.count(); i++) { + if (username == usernames_[i]) { + index = i; + } + } + if (index >= 0) { + usernames_.removeAt(index); + passwords_.removeAt(index); + certificateFiles_.removeAt(index); + username_->removeItem(index); + } } void QtLoginWindow::addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options) { - QString username = P2QSTRING(defaultJID); - int index = -1; - for (int i = 0; i < usernames_.count(); i++) { - if (username == usernames_[i]) { - index = i; - } - } - if (index == -1) { - usernames_.append(username); - passwords_.append(P2QSTRING(defaultPassword)); - certificateFiles_.append(P2QSTRING(defaultCertificate)); - options_.push_back(options); - username_->addItem(username); - } else { - usernames_[index] = username; - passwords_[index] = P2QSTRING(defaultPassword); - certificateFiles_[index] = P2QSTRING(defaultCertificate); - options_[index] = options; - } + QString username = P2QSTRING(defaultJID); + int index = -1; + for (int i = 0; i < usernames_.count(); i++) { + if (username == usernames_[i]) { + index = i; + } + } + if (index == -1) { + usernames_.append(username); + passwords_.append(P2QSTRING(defaultPassword)); + certificateFiles_.append(P2QSTRING(defaultCertificate)); + options_.push_back(options); + username_->addItem(username); + } else { + usernames_[index] = username; + passwords_[index] = P2QSTRING(defaultPassword); + certificateFiles_[index] = P2QSTRING(defaultCertificate); + options_[index] = options; + } } void QtLoginWindow::handleUsernameTextChanged() { - QString username = username_->currentText(); - for (int i = 0; i < usernames_.count(); i++) { - if (username_->currentText() == usernames_[i]) { - certificateFile_ = certificateFiles_[i]; - password_->setText(passwords_[i]); - remember_->setChecked(password_->text() != ""); - currentOptions_ = options_[i]; - } - } - certificateButton_->setChecked(!certificateFile_.isEmpty()); + QString username = username_->currentText(); + for (int i = 0; i < usernames_.count(); i++) { + if (username_->currentText() == usernames_[i]) { + certificateFile_ = certificateFiles_[i]; + password_->setText(passwords_[i]); + remember_->setChecked(password_->text() != ""); + currentOptions_ = options_[i]; + } + } + certificateButton_->setChecked(!certificateFile_.isEmpty()); } void QtLoginWindow::loggedOut() { - stack_->removeWidget(stack_->currentWidget()); - stack_->addWidget(loginWidgetWrapper_); - stack_->setCurrentWidget(loginWidgetWrapper_); - setInitialMenus(); - setIsLoggingIn(false); + stack_->removeWidget(stack_->currentWidget()); + stack_->addWidget(loginWidgetWrapper_); + stack_->setCurrentWidget(loginWidgetWrapper_); + setInitialMenus(); + setIsLoggingIn(false); } void QtLoginWindow::setIsLoggingIn(bool loggingIn) { - /* Change the for loop as well if you add to this.*/ - QWidget* widgets[5] = {username_, password_, remember_, loginAutomatically_, certificateButton_}; - loginButton_->setText(loggingIn ? tr("Cancel") : tr("Connect")); - for (int i = 0; i < 5; i++) { - widgets[i]->setEnabled(!loggingIn); - } - bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); - remember_->setEnabled(!eagle); - loginAutomatically_->setEnabled(!eagle); + /* Change the for loop as well if you add to this.*/ + QWidget* widgets[5] = {username_, password_, remember_, loginAutomatically_, certificateButton_}; + loginButton_->setText(loggingIn ? tr("Cancel") : tr("Connect")); + for (int i = 0; i < 5; i++) { + widgets[i]->setEnabled(!loggingIn); + } + bool eagle = settings_->getSetting(SettingConstants::FORGET_PASSWORDS); + remember_->setEnabled(!eagle); + loginAutomatically_->setEnabled(!eagle); } void QtLoginWindow::loginClicked() { - if (username_->isEnabled()) { - std::string banner = settings_->getSetting(QtUISettingConstants::CLICKTHROUGH_BANNER); - if (!banner.empty()) { - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Confirm terms of use")); - msgBox.setText(""); - msgBox.setInformativeText(P2QSTRING(banner)); - msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); - msgBox.setDefaultButton(QMessageBox::No); - if (msgBox.exec() != QMessageBox::Yes) { - return; - } - } - CertificateWithKey::ref certificate; - std::string certificateString = Q2PSTRING(certificateFile_); - if (!certificateString.empty()) { + if (username_->isEnabled()) { + std::string banner = settings_->getSetting(QtUISettingConstants::CLICKTHROUGH_BANNER); + if (!banner.empty()) { + QMessageBox msgBox; + msgBox.setWindowTitle(tr("Confirm terms of use")); + msgBox.setText(""); + msgBox.setInformativeText(P2QSTRING(banner)); + msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); + msgBox.setDefaultButton(QMessageBox::No); + if (msgBox.exec() != QMessageBox::Yes) { + return; + } + } + CertificateWithKey::ref certificate; + std::string certificateString = Q2PSTRING(certificateFile_); + if (!certificateString.empty()) { #if defined(HAVE_SCHANNEL) - if (isCAPIURI(certificateString)) { - certificate = boost::make_shared(certificateString, timerFactory_); - } else { - certificate = boost::make_shared(certificateString, createSafeByteArray(Q2PSTRING(password_->text()))); - } + if (isCAPIURI(certificateString)) { + certificate = boost::make_shared(certificateString, timerFactory_); + } else { + certificate = boost::make_shared(certificateString, createSafeByteArray(Q2PSTRING(password_->text()))); + } #else - certificate = boost::make_shared(certificateString, createSafeByteArray(Q2PSTRING(password_->text()))); + certificate = boost::make_shared(certificateString, createSafeByteArray(Q2PSTRING(password_->text()))); #endif - } + } - onLoginRequest(Q2PSTRING(username_->currentText()), Q2PSTRING(password_->text()), certificateString, certificate, currentOptions_, remember_->isChecked(), loginAutomatically_->isChecked()); - if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { /* Mustn't remember logins */ - username_->clearEditText(); - password_->setText(""); - } - } else { - onCancelLoginRequest(); - } + onLoginRequest(Q2PSTRING(username_->currentText()), Q2PSTRING(password_->text()), certificateString, certificate, currentOptions_, remember_->isChecked(), loginAutomatically_->isChecked()); + if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) { /* Mustn't remember logins */ + username_->clearEditText(); + password_->setText(""); + } + } else { + onCancelLoginRequest(); + } } void QtLoginWindow::setLoginAutomatically(bool loginAutomatically) { - loginAutomatically_->setChecked(loginAutomatically); + loginAutomatically_->setChecked(loginAutomatically); } void QtLoginWindow::handleCertficateChecked(bool checked) { - if (checked) { + if (checked) { #ifdef HAVE_SCHANNEL - certificateFile_ = P2QSTRING(selectCAPICertificate()); - if (certificateFile_.isEmpty()) { - certificateButton_->setChecked(false); - } + certificateFile_ = P2QSTRING(selectCAPICertificate()); + if (certificateFile_.isEmpty()) { + certificateButton_->setChecked(false); + } #else - certificateFile_ = QFileDialog::getOpenFileName(this, tr("Select an authentication certificate"), QString(), tr("P12 files (*.cert *.p12 *.pfx);;All files (*.*)")); - if (certificateFile_.isEmpty()) { - certificateButton_->setChecked(false); - } + certificateFile_ = QFileDialog::getOpenFileName(this, tr("Select an authentication certificate"), QString(), tr("P12 files (*.cert *.p12 *.pfx);;All files (*.*)")); + if (certificateFile_.isEmpty()) { + certificateButton_->setChecked(false); + } #endif - } - else { - certificateFile_ = ""; - } + } + else { + certificateFile_ = ""; + } } void QtLoginWindow::handleAbout() { - if (!aboutDialog_) { - aboutDialog_ = new QtAboutWidget(); - aboutDialog_->show(); - } - else { - aboutDialog_->show(); - aboutDialog_->raise(); - aboutDialog_->activateWindow(); - } + if (!aboutDialog_) { + aboutDialog_ = new QtAboutWidget(); + aboutDialog_->show(); + } + else { + aboutDialog_->show(); + aboutDialog_->raise(); + aboutDialog_->activateWindow(); + } } void QtLoginWindow::handleShowXMLConsole() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtLoginWindow::handleShowFileTransferOverview() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtLoginWindow::handleShowHighlightEditor() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtLoginWindow::handleToggleSounds(bool enabled) { - settings_->storeSetting(SettingConstants::PLAY_SOUNDS, enabled); + settings_->storeSetting(SettingConstants::PLAY_SOUNDS, enabled); } void QtLoginWindow::handleToggleNotifications(bool enabled) { - settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled); + settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled); } void QtLoginWindow::handleQuit() { - onQuitRequest(); + onQuitRequest(); } void QtLoginWindow::quit() { - QApplication::quit(); + QApplication::quit(); } void QtLoginWindow::setInitialMenus() { - menuBar_->clear(); - menuBar_->addMenu(swiftMenu_); + menuBar_->clear(); + menuBar_->addMenu(swiftMenu_); #ifdef SWIFTEN_PLATFORM_MACOSX - menuBar_->addMenu(generalMenu_); + menuBar_->addMenu(generalMenu_); #endif } void QtLoginWindow::morphInto(MainWindow *mainWindow) { - setEnabled(false); - QtMainWindow *qtMainWindow = dynamic_cast(mainWindow); - assert(qtMainWindow); - stack_->removeWidget(loginWidgetWrapper_); - stack_->addWidget(qtMainWindow); - stack_->setCurrentWidget(qtMainWindow); - setEnabled(true); - setInitialMenus(); - std::vector mainWindowMenus = qtMainWindow->getMenus(); - viewMenu_ = mainWindowMenus[0]; - foreach (QMenu* menu, mainWindowMenus) { - menuBar_->addMenu(menu); - } - setFocus(); + setEnabled(false); + QtMainWindow *qtMainWindow = dynamic_cast(mainWindow); + assert(qtMainWindow); + stack_->removeWidget(loginWidgetWrapper_); + stack_->addWidget(qtMainWindow); + stack_->setCurrentWidget(qtMainWindow); + setEnabled(true); + setInitialMenus(); + std::vector mainWindowMenus = qtMainWindow->getMenus(); + viewMenu_ = mainWindowMenus[0]; + foreach (QMenu* menu, mainWindowMenus) { + menuBar_->addMenu(menu); + } + setFocus(); } void QtLoginWindow::setMessage(const std::string& message) { - if (!message.empty()) { - message_->setText("
" + P2QSTRING(message) + "
"); - } - else { - message_->setText(""); - } + if (!message.empty()) { + message_->setText("
" + P2QSTRING(message) + "
"); + } + else { + message_->setText(""); + } } void QtLoginWindow::toggleBringToFront() { - if (!isVisible()) { - bringToFront(); - } - else { - window()->hide(); - } + if (!isVisible()) { + bringToFront(); + } + else { + window()->hide(); + } } void QtLoginWindow::bringToFront() { - window()->showNormal(); - window()->raise(); - window()->activateWindow(); + window()->showNormal(); + window()->raise(); + window()->activateWindow(); } void QtLoginWindow::hide() { - window()->hide(); + window()->hide(); } QtLoginWindow::QtMenus QtLoginWindow::getMenus() const { - return QtMenus(swiftMenu_, generalMenu_); + return QtMenus(swiftMenu_, generalMenu_); } void QtLoginWindow::resizeEvent(QResizeEvent*) { - emit geometryChanged(); + emit geometryChanged(); } void QtLoginWindow::moveEvent(QMoveEvent*) { - emit geometryChanged(); + emit geometryChanged(); } bool QtLoginWindow::askUserToTrustCertificatePermanently(const std::string& message, const std::vector& certificates) { - QMessageBox dialog(this); - - dialog.setText(tr("The certificate presented by the server is not valid.")); - dialog.setInformativeText(P2QSTRING(message) + "\n\n" + tr("Would you like to permanently trust this certificate? This must only be done if you know it is correct.")); - - dialog.addButton(tr("Show Certificate"), QMessageBox::HelpRole); - dialog.addButton(QMessageBox::Yes); - dialog.addButton(QMessageBox::No); - dialog.setDefaultButton(QMessageBox::No); - while (true) { - int result = dialog.exec(); - if (result == QMessageBox::Yes || result == QMessageBox::No) { - return result == QMessageBox::Yes; - } - // FIXME: This isn't very nice, because the dialog disappears every time. We actually need a real - // dialog with a custom button. - QtMainWindow::openCertificateDialog(certificates, &dialog); - } + QMessageBox dialog(this); + + dialog.setText(tr("The certificate presented by the server is not valid.")); + dialog.setInformativeText(P2QSTRING(message) + "\n\n" + tr("Would you like to permanently trust this certificate? This must only be done if you know it is correct.")); + + dialog.addButton(tr("Show Certificate"), QMessageBox::HelpRole); + dialog.addButton(QMessageBox::Yes); + dialog.addButton(QMessageBox::No); + dialog.setDefaultButton(QMessageBox::No); + while (true) { + int result = dialog.exec(); + if (result == QMessageBox::Yes || result == QMessageBox::No) { + return result == QMessageBox::Yes; + } + // FIXME: This isn't very nice, because the dialog disappears every time. We actually need a real + // dialog with a custom button. + QtMainWindow::openCertificateDialog(certificates, &dialog); + } } void QtLoginWindow::handleOpenConnectionOptions() { - QtConnectionSettingsWindow connectionSettings(currentOptions_); - if (connectionSettings.exec() == QDialog::Accepted) { - currentOptions_ = connectionSettings.getOptions(); - } + QtConnectionSettingsWindow connectionSettings(currentOptions_); + if (connectionSettings.exec() == QDialog::Accepted) { + currentOptions_ = connectionSettings.getOptions(); + } } } diff --git a/Swift/QtUI/QtLoginWindow.h b/Swift/QtUI/QtLoginWindow.h index e8e2e20..91b21f6 100644 --- a/Swift/QtUI/QtLoginWindow.h +++ b/Swift/QtUI/QtLoginWindow.h @@ -25,89 +25,89 @@ class QToolButton; class QComboBox; namespace Swift { - class SettingsProvider; - class TimerFactory; + class SettingsProvider; + class TimerFactory; - class QtLoginWindow : public QMainWindow, public LoginWindow { - Q_OBJECT - public: - struct QtMenus { - QtMenus(QMenu* swiftMenu, QMenu* generalMenu) : swiftMenu(swiftMenu), generalMenu(generalMenu) {} - QMenu* swiftMenu; - QMenu* generalMenu; - }; + class QtLoginWindow : public QMainWindow, public LoginWindow { + Q_OBJECT + public: + struct QtMenus { + QtMenus(QMenu* swiftMenu, QMenu* generalMenu) : swiftMenu(swiftMenu), generalMenu(generalMenu) {} + QMenu* swiftMenu; + QMenu* generalMenu; + }; - public: - QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory); + public: + QtLoginWindow(UIEventStream* uiEventStream, SettingsProvider* settings, TimerFactory* timerFactory); - void morphInto(MainWindow *mainWindow); - virtual void loggedOut(); - virtual void setShowNotificationToggle(bool); - virtual void setMessage(const std::string& message); - virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options); - virtual void removeAvailableAccount(const std::string& jid); - virtual void setLoginAutomatically(bool loginAutomatically); - virtual void setIsLoggingIn(bool loggingIn); - void selectUser(const std::string& user); - bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector& certificate); - void hide(); - QtMenus getMenus() const; - virtual void quit(); + void morphInto(MainWindow *mainWindow); + virtual void loggedOut(); + virtual void setShowNotificationToggle(bool); + virtual void setMessage(const std::string& message); + virtual void addAvailableAccount(const std::string& defaultJID, const std::string& defaultPassword, const std::string& defaultCertificate, const ClientOptions& options); + virtual void removeAvailableAccount(const std::string& jid); + virtual void setLoginAutomatically(bool loginAutomatically); + virtual void setIsLoggingIn(bool loggingIn); + void selectUser(const std::string& user); + bool askUserToTrustCertificatePermanently(const std::string& message, const std::vector& certificate); + void hide(); + QtMenus getMenus() const; + virtual void quit(); - signals: - void geometryChanged(); + signals: + void geometryChanged(); - private slots: - void loginClicked(); - void handleCertficateChecked(bool); - void handleQuit(); - void handleShowXMLConsole(); - void handleShowFileTransferOverview(); - void handleShowHighlightEditor(); - void handleToggleSounds(bool enabled); - void handleToggleNotifications(bool enabled); - void handleAbout(); - void bringToFront(); - void toggleBringToFront(); - void handleUsernameTextChanged(); - void resizeEvent(QResizeEvent* event); - void moveEvent(QMoveEvent* event); - void handleSettingChanged(const std::string& settingPath); - void handleOpenConnectionOptions(); + private slots: + void loginClicked(); + void handleCertficateChecked(bool); + void handleQuit(); + void handleShowXMLConsole(); + void handleShowFileTransferOverview(); + void handleShowHighlightEditor(); + void handleToggleSounds(bool enabled); + void handleToggleNotifications(bool enabled); + void handleAbout(); + void bringToFront(); + void toggleBringToFront(); + void handleUsernameTextChanged(); + void resizeEvent(QResizeEvent* event); + void moveEvent(QMoveEvent* event); + void handleSettingChanged(const std::string& settingPath); + void handleOpenConnectionOptions(); - protected: - bool eventFilter(QObject *obj, QEvent *event); + protected: + bool eventFilter(QObject *obj, QEvent *event); - private: - void setInitialMenus(); - QWidget* loginWidgetWrapper_; - QStringList usernames_; - QStringList passwords_; - QStringList certificateFiles_; - std::vector options_; - QComboBox* username_; - QLineEdit* password_; - QPushButton* loginButton_; - /* If you add a widget here, change setLoggingIn as well.*/ - QCheckBox* remember_; - QCheckBox* loginAutomatically_; - QStackedWidget* stack_; - QLabel* message_; - QString certificateFile_; - QToolButton* certificateButton_; - QMenuBar* menuBar_; - QMenu* swiftMenu_; - QMenu* generalMenu_; - QMenu* viewMenu_; - QAction* toggleSoundsAction_; - QAction* toggleNotificationsAction_; - UIEventStream* uiEventStream_; - QPointer aboutDialog_; - SettingsProvider* settings_; - QAction* xmlConsoleAction_; - QAction* fileTransferOverviewAction_; - QAction* highlightEditorAction_; - TimerFactory* timerFactory_; - ClientOptions currentOptions_; - }; + private: + void setInitialMenus(); + QWidget* loginWidgetWrapper_; + QStringList usernames_; + QStringList passwords_; + QStringList certificateFiles_; + std::vector options_; + QComboBox* username_; + QLineEdit* password_; + QPushButton* loginButton_; + /* If you add a widget here, change setLoggingIn as well.*/ + QCheckBox* remember_; + QCheckBox* loginAutomatically_; + QStackedWidget* stack_; + QLabel* message_; + QString certificateFile_; + QToolButton* certificateButton_; + QMenuBar* menuBar_; + QMenu* swiftMenu_; + QMenu* generalMenu_; + QMenu* viewMenu_; + QAction* toggleSoundsAction_; + QAction* toggleNotificationsAction_; + UIEventStream* uiEventStream_; + QPointer aboutDialog_; + SettingsProvider* settings_; + QAction* xmlConsoleAction_; + QAction* fileTransferOverviewAction_; + QAction* highlightEditorAction_; + TimerFactory* timerFactory_; + ClientOptions currentOptions_; + }; } diff --git a/Swift/QtUI/QtMUCConfigurationWindow.cpp b/Swift/QtUI/QtMUCConfigurationWindow.cpp index a4ef9e3..629e94f 100644 --- a/Swift/QtUI/QtMUCConfigurationWindow.cpp +++ b/Swift/QtUI/QtMUCConfigurationWindow.cpp @@ -16,30 +16,30 @@ namespace Swift { QtMUCConfigurationWindow::QtMUCConfigurationWindow(Form::ref form) : closed_(false) { - setAttribute(Qt::WA_DeleteOnClose); - - QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this); - layout->setContentsMargins(0,0,0,0); - layout->setSpacing(2); - //QLabel* label = new QLabel(this); - //label->setText(tr("Room configuration")); - //layout->addWidget(label); - - formWidget_ = NULL; - formWidget_ = new QtFormWidget(form, this); - layout->addWidget(formWidget_); - - QWidget* buttonsWidget = new QWidget(this); - layout->addWidget(buttonsWidget); - - QBoxLayout* buttonsLayout = new QBoxLayout(QBoxLayout::LeftToRight, buttonsWidget); - cancelButton_ = new QPushButton(tr("Cancel"), buttonsWidget); - buttonsLayout->addWidget(cancelButton_); - connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked())); - okButton_ = new QPushButton(tr("OK"), buttonsWidget); - buttonsLayout->addWidget(okButton_); - connect(okButton_, SIGNAL(clicked()), this, SLOT(handleOKClicked())); - show(); + setAttribute(Qt::WA_DeleteOnClose); + + QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom, this); + layout->setContentsMargins(0,0,0,0); + layout->setSpacing(2); + //QLabel* label = new QLabel(this); + //label->setText(tr("Room configuration")); + //layout->addWidget(label); + + formWidget_ = NULL; + formWidget_ = new QtFormWidget(form, this); + layout->addWidget(formWidget_); + + QWidget* buttonsWidget = new QWidget(this); + layout->addWidget(buttonsWidget); + + QBoxLayout* buttonsLayout = new QBoxLayout(QBoxLayout::LeftToRight, buttonsWidget); + cancelButton_ = new QPushButton(tr("Cancel"), buttonsWidget); + buttonsLayout->addWidget(cancelButton_); + connect(cancelButton_, SIGNAL(clicked()), this, SLOT(handleCancelClicked())); + okButton_ = new QPushButton(tr("OK"), buttonsWidget); + buttonsLayout->addWidget(okButton_); + connect(okButton_, SIGNAL(clicked()), this, SLOT(handleOKClicked())); + show(); } QtMUCConfigurationWindow::~QtMUCConfigurationWindow() { @@ -47,19 +47,19 @@ QtMUCConfigurationWindow::~QtMUCConfigurationWindow() { } void QtMUCConfigurationWindow::closeEvent(QCloseEvent* /*event*/) { - if (!closed_) { - onFormCancelled(); - } + if (!closed_) { + onFormCancelled(); + } } void QtMUCConfigurationWindow::handleCancelClicked() { - close(); + close(); } void QtMUCConfigurationWindow::handleOKClicked() { - onFormComplete(formWidget_->getCompletedForm()); - closed_ = true; - close(); + onFormComplete(formWidget_->getCompletedForm()); + closed_ = true; + close(); } diff --git a/Swift/QtUI/QtMUCConfigurationWindow.h b/Swift/QtUI/QtMUCConfigurationWindow.h index bae7556..c8835e4 100644 --- a/Swift/QtUI/QtMUCConfigurationWindow.h +++ b/Swift/QtUI/QtMUCConfigurationWindow.h @@ -17,23 +17,23 @@ class QBoxLayout; class QCloseEvent; namespace Swift { - class QtFormWidget; - class QtMUCConfigurationWindow : public QWidget { - Q_OBJECT - public: - QtMUCConfigurationWindow(Form::ref form); - virtual ~QtMUCConfigurationWindow(); - boost::signal onFormComplete; - boost::signal onFormCancelled; - private slots: - void handleCancelClicked(); - void handleOKClicked(); - protected: - virtual void closeEvent(QCloseEvent* event); - private: - QtFormWidget* formWidget_; - QPushButton* okButton_; - QPushButton* cancelButton_; - bool closed_; - }; + class QtFormWidget; + class QtMUCConfigurationWindow : public QWidget { + Q_OBJECT + public: + QtMUCConfigurationWindow(Form::ref form); + virtual ~QtMUCConfigurationWindow(); + boost::signal onFormComplete; + boost::signal onFormCancelled; + private slots: + void handleCancelClicked(); + void handleOKClicked(); + protected: + virtual void closeEvent(QCloseEvent* event); + private: + QtFormWidget* formWidget_; + QPushButton* okButton_; + QPushButton* cancelButton_; + bool closed_; + }; } diff --git a/Swift/QtUI/QtMainWindow.cpp b/Swift/QtUI/QtMainWindow.cpp index e2092f6..d61026a 100644 --- a/Swift/QtUI/QtMainWindow.cpp +++ b/Swift/QtUI/QtMainWindow.cpp @@ -52,373 +52,373 @@ namespace Swift { QtMainWindow::QtMainWindow(SettingsProvider* settings, UIEventStream* uiEventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID) : QWidget(), MainWindow(false), loginMenus_(loginMenus) { - uiEventStream_ = uiEventStream; - settings_ = settings; - setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); - QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this); - mainLayout->setContentsMargins(0,0,0,0); - mainLayout->setSpacing(0); - meView_ = new QtRosterHeader(settings, statusCache, this); - mainLayout->addWidget(meView_); - connect(meView_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleStatusChanged(StatusShow::Type, const QString&))); - connect(meView_, SIGNAL(onEditProfileRequest()), this, SLOT(handleEditProfileRequest())); - connect(meView_, SIGNAL(onShowCertificateInfo()), this, SLOT(handleShowCertificateInfo())); - - tabs_ = new QtTabWidget(this); + uiEventStream_ = uiEventStream; + settings_ = settings; + setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); + QBoxLayout *mainLayout = new QBoxLayout(QBoxLayout::TopToBottom, this); + mainLayout->setContentsMargins(0,0,0,0); + mainLayout->setSpacing(0); + meView_ = new QtRosterHeader(settings, statusCache, this); + mainLayout->addWidget(meView_); + connect(meView_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleStatusChanged(StatusShow::Type, const QString&))); + connect(meView_, SIGNAL(onEditProfileRequest()), this, SLOT(handleEditProfileRequest())); + connect(meView_, SIGNAL(onShowCertificateInfo()), this, SLOT(handleShowCertificateInfo())); + + tabs_ = new QtTabWidget(this); #if QT_VERSION >= 0x040500 - tabs_->setDocumentMode(true); + tabs_->setDocumentMode(true); #endif - tabs_->setTabPosition(QTabWidget::South); - mainLayout->addWidget(tabs_); - contactsTabWidget_ = new QWidget(this); - contactsTabWidget_->setContentsMargins(0, 0, 0, 0); - QBoxLayout *contactTabLayout = new QBoxLayout(QBoxLayout::TopToBottom, contactsTabWidget_); - contactsTabWidget_->setLayout(contactTabLayout); - contactTabLayout->setSpacing(0); - contactTabLayout->setContentsMargins(0, 0, 0, 0); - - treeWidget_ = new QtRosterWidget(uiEventStream_, settings_, this); - - contactTabLayout->addWidget(treeWidget_); - new QtFilterWidget(this, treeWidget_, uiEventStream_, contactTabLayout); - - tabs_->addTab(contactsTabWidget_, tr("&Contacts")); - - eventWindow_ = new QtEventWindow(uiEventStream_); - connect(eventWindow_, SIGNAL(onNewEventCountUpdated(int)), this, SLOT(handleEventCountUpdated(int))); - - chatListWindow_ = new QtChatListWindow(uiEventStream_, settings_); - connect(chatListWindow_, SIGNAL(onCountUpdated(int)), this, SLOT(handleChatCountUpdated(int))); - - tabs_->addTab(chatListWindow_, tr("C&hats")); - tabs_->addTab(eventWindow_, tr("&Notices")); - - tabs_->setCurrentIndex(settings_->getSetting(QtUISettingConstants::CURRENT_ROSTER_TAB)); - - connect(tabs_, SIGNAL(currentChanged(int)), this, SLOT(handleTabChanged(int))); - - tabBarCombo_ = NULL; - if (settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) { - tabs_->tabBar()->hide(); - tabBarCombo_ = new QComboBox(this); - tabBarCombo_->setAccessibleName("Current View"); - tabBarCombo_->addItem(tr("Contacts")); - tabBarCombo_->addItem(tr("Chats")); - tabBarCombo_->addItem(tr("Notices")); - tabBarCombo_->setCurrentIndex(tabs_->currentIndex()); - mainLayout->addWidget(tabBarCombo_); - connect(tabBarCombo_, SIGNAL(currentIndexChanged(int)), tabs_, SLOT(setCurrentIndex(int))); - } - - - this->setLayout(mainLayout); - - QMenu* viewMenu = new QMenu(tr("&View"), this); - menus_.push_back(viewMenu); - - compactRosterAction_ = new QAction(tr("&Compact Roster"), this); - compactRosterAction_->setCheckable(true); - compactRosterAction_->setChecked(false); - connect(compactRosterAction_, SIGNAL(toggled(bool)), SLOT(handleCompactRosterToggled(bool))); - viewMenu->addAction(compactRosterAction_); - handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); - - showOfflineAction_ = new QAction(tr("&Show offline contacts"), this); - showOfflineAction_->setCheckable(true); - showOfflineAction_->setChecked(false); - connect(showOfflineAction_, SIGNAL(toggled(bool)), SLOT(handleShowOfflineToggled(bool))); - viewMenu->addAction(showOfflineAction_); - handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); - - if (emoticonsExist) { - showEmoticonsAction_ = new QAction(tr("&Show Emoticons"), this); - showEmoticonsAction_->setCheckable(true); - showEmoticonsAction_->setChecked(false); - connect(showEmoticonsAction_, SIGNAL(toggled(bool)), SLOT(handleShowEmoticonsToggled(bool))); - viewMenu->addAction(showEmoticonsAction_); - handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); - } - - QMenu* actionsMenu = new QMenu(tr("&Actions"), this); - menus_.push_back(actionsMenu); - QAction* editProfileAction = new QAction(tr("Edit &Profile…"), this); - connect(editProfileAction, SIGNAL(triggered()), SLOT(handleEditProfileAction())); - actionsMenu->addAction(editProfileAction); - onlineOnlyActions_ << editProfileAction; - QAction* joinMUCAction = new QAction(tr("Enter &Room…"), this); - connect(joinMUCAction, SIGNAL(triggered()), SLOT(handleJoinMUCAction())); - actionsMenu->addAction(joinMUCAction); - onlineOnlyActions_ << joinMUCAction; + tabs_->setTabPosition(QTabWidget::South); + mainLayout->addWidget(tabs_); + contactsTabWidget_ = new QWidget(this); + contactsTabWidget_->setContentsMargins(0, 0, 0, 0); + QBoxLayout *contactTabLayout = new QBoxLayout(QBoxLayout::TopToBottom, contactsTabWidget_); + contactsTabWidget_->setLayout(contactTabLayout); + contactTabLayout->setSpacing(0); + contactTabLayout->setContentsMargins(0, 0, 0, 0); + + treeWidget_ = new QtRosterWidget(uiEventStream_, settings_, this); + + contactTabLayout->addWidget(treeWidget_); + new QtFilterWidget(this, treeWidget_, uiEventStream_, contactTabLayout); + + tabs_->addTab(contactsTabWidget_, tr("&Contacts")); + + eventWindow_ = new QtEventWindow(uiEventStream_); + connect(eventWindow_, SIGNAL(onNewEventCountUpdated(int)), this, SLOT(handleEventCountUpdated(int))); + + chatListWindow_ = new QtChatListWindow(uiEventStream_, settings_); + connect(chatListWindow_, SIGNAL(onCountUpdated(int)), this, SLOT(handleChatCountUpdated(int))); + + tabs_->addTab(chatListWindow_, tr("C&hats")); + tabs_->addTab(eventWindow_, tr("&Notices")); + + tabs_->setCurrentIndex(settings_->getSetting(QtUISettingConstants::CURRENT_ROSTER_TAB)); + + connect(tabs_, SIGNAL(currentChanged(int)), this, SLOT(handleTabChanged(int))); + + tabBarCombo_ = NULL; + if (settings_->getSetting(QtUISettingConstants::USE_SCREENREADER)) { + tabs_->tabBar()->hide(); + tabBarCombo_ = new QComboBox(this); + tabBarCombo_->setAccessibleName("Current View"); + tabBarCombo_->addItem(tr("Contacts")); + tabBarCombo_->addItem(tr("Chats")); + tabBarCombo_->addItem(tr("Notices")); + tabBarCombo_->setCurrentIndex(tabs_->currentIndex()); + mainLayout->addWidget(tabBarCombo_); + connect(tabBarCombo_, SIGNAL(currentIndexChanged(int)), tabs_, SLOT(setCurrentIndex(int))); + } + + + this->setLayout(mainLayout); + + QMenu* viewMenu = new QMenu(tr("&View"), this); + menus_.push_back(viewMenu); + + compactRosterAction_ = new QAction(tr("&Compact Roster"), this); + compactRosterAction_->setCheckable(true); + compactRosterAction_->setChecked(false); + connect(compactRosterAction_, SIGNAL(toggled(bool)), SLOT(handleCompactRosterToggled(bool))); + viewMenu->addAction(compactRosterAction_); + handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); + + showOfflineAction_ = new QAction(tr("&Show offline contacts"), this); + showOfflineAction_->setCheckable(true); + showOfflineAction_->setChecked(false); + connect(showOfflineAction_, SIGNAL(toggled(bool)), SLOT(handleShowOfflineToggled(bool))); + viewMenu->addAction(showOfflineAction_); + handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); + + if (emoticonsExist) { + showEmoticonsAction_ = new QAction(tr("&Show Emoticons"), this); + showEmoticonsAction_->setCheckable(true); + showEmoticonsAction_->setChecked(false); + connect(showEmoticonsAction_, SIGNAL(toggled(bool)), SLOT(handleShowEmoticonsToggled(bool))); + viewMenu->addAction(showEmoticonsAction_); + handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); + } + + QMenu* actionsMenu = new QMenu(tr("&Actions"), this); + menus_.push_back(actionsMenu); + QAction* editProfileAction = new QAction(tr("Edit &Profile…"), this); + connect(editProfileAction, SIGNAL(triggered()), SLOT(handleEditProfileAction())); + actionsMenu->addAction(editProfileAction); + onlineOnlyActions_ << editProfileAction; + QAction* joinMUCAction = new QAction(tr("Enter &Room…"), this); + connect(joinMUCAction, SIGNAL(triggered()), SLOT(handleJoinMUCAction())); + actionsMenu->addAction(joinMUCAction); + onlineOnlyActions_ << joinMUCAction; #ifdef SWIFT_EXPERIMENTAL_HISTORY - QAction* viewLogsAction = new QAction(tr("&View History…"), this); - connect(viewLogsAction, SIGNAL(triggered()), SLOT(handleViewLogsAction())); - actionsMenu->addAction(viewLogsAction); + QAction* viewLogsAction = new QAction(tr("&View History…"), this); + connect(viewLogsAction, SIGNAL(triggered()), SLOT(handleViewLogsAction())); + actionsMenu->addAction(viewLogsAction); #endif - openBlockingListEditor_ = new QAction(tr("Edit &Blocking List…"), this); - connect(openBlockingListEditor_, SIGNAL(triggered()), SLOT(handleEditBlockingList())); - actionsMenu->addAction(openBlockingListEditor_); - onlineOnlyActions_ << openBlockingListEditor_; - openBlockingListEditor_->setVisible(false); - addUserAction_ = new QAction(tr("&Add Contact…"), this); - addUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D)); - addUserAction_->setShortcutContext(Qt::ApplicationShortcut); - connect(addUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleAddUserActionTriggered(bool))); - actionsMenu->addAction(addUserAction_); - onlineOnlyActions_ << addUserAction_; - editUserAction_ = new QAction(tr("&Edit Selected Contact…"), this); - connect(editUserAction_, SIGNAL(triggered(bool)), treeWidget_, SLOT(handleEditUserActionTriggered(bool))); - actionsMenu->addAction(editUserAction_); - onlineOnlyActions_ << editUserAction_; - editUserAction_->setEnabled(false); - chatUserAction_ = new QAction(tr("Start &Chat…"), this); - chatUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N)); - chatUserAction_->setShortcutContext(Qt::ApplicationShortcut); - connect(chatUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleChatUserActionTriggered(bool))); - actionsMenu->addAction(chatUserAction_); - onlineOnlyActions_ << chatUserAction_; - if (enableAdHocCommandOnJID) { - otherAdHocAction_ = new QAction(tr("Run Other Command"), this); - connect(otherAdHocAction_, SIGNAL(triggered()), this, SLOT(handleOtherAdHocActionTriggered())); - actionsMenu->addAction(otherAdHocAction_); - onlineOnlyActions_ << otherAdHocAction_; - } - serverAdHocMenu_ = new QMenu(tr("Run Server Command"), this); - actionsMenu->addMenu(serverAdHocMenu_); - actionsMenu->addSeparator(); - QAction* signOutAction = new QAction(tr("&Sign Out"), this); - connect(signOutAction, SIGNAL(triggered()), SLOT(handleSignOutAction())); - actionsMenu->addAction(signOutAction); - - toggleRequestDeliveryReceipts_ = new QAction(tr("&Request Delivery Receipts"), this); - toggleRequestDeliveryReceipts_->setCheckable(true); - toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS)); - connect(toggleRequestDeliveryReceipts_, SIGNAL(toggled(bool)), SLOT(handleToggleRequestDeliveryReceipts(bool))); - - QList< QAction* > generalMenuActions = loginMenus_.generalMenu->actions(); - loginMenus_.generalMenu->insertAction(generalMenuActions.at(generalMenuActions.count()-2),toggleRequestDeliveryReceipts_); - - treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtMainWindow::handleSomethingSelectedChanged, this, _1)); - - setAvailableAdHocCommands(std::vector()); - QAction* adHocAction = new QAction(tr("Collecting commands..."), this); - adHocAction->setEnabled(false); - serverAdHocMenu_->addAction(adHocAction); - serverAdHocCommandActions_.append(adHocAction); - - settings_->onSettingChanged.connect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1)); + openBlockingListEditor_ = new QAction(tr("Edit &Blocking List…"), this); + connect(openBlockingListEditor_, SIGNAL(triggered()), SLOT(handleEditBlockingList())); + actionsMenu->addAction(openBlockingListEditor_); + onlineOnlyActions_ << openBlockingListEditor_; + openBlockingListEditor_->setVisible(false); + addUserAction_ = new QAction(tr("&Add Contact…"), this); + addUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D)); + addUserAction_->setShortcutContext(Qt::ApplicationShortcut); + connect(addUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleAddUserActionTriggered(bool))); + actionsMenu->addAction(addUserAction_); + onlineOnlyActions_ << addUserAction_; + editUserAction_ = new QAction(tr("&Edit Selected Contact…"), this); + connect(editUserAction_, SIGNAL(triggered(bool)), treeWidget_, SLOT(handleEditUserActionTriggered(bool))); + actionsMenu->addAction(editUserAction_); + onlineOnlyActions_ << editUserAction_; + editUserAction_->setEnabled(false); + chatUserAction_ = new QAction(tr("Start &Chat…"), this); + chatUserAction_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_N)); + chatUserAction_->setShortcutContext(Qt::ApplicationShortcut); + connect(chatUserAction_, SIGNAL(triggered(bool)), this, SLOT(handleChatUserActionTriggered(bool))); + actionsMenu->addAction(chatUserAction_); + onlineOnlyActions_ << chatUserAction_; + if (enableAdHocCommandOnJID) { + otherAdHocAction_ = new QAction(tr("Run Other Command"), this); + connect(otherAdHocAction_, SIGNAL(triggered()), this, SLOT(handleOtherAdHocActionTriggered())); + actionsMenu->addAction(otherAdHocAction_); + onlineOnlyActions_ << otherAdHocAction_; + } + serverAdHocMenu_ = new QMenu(tr("Run Server Command"), this); + actionsMenu->addMenu(serverAdHocMenu_); + actionsMenu->addSeparator(); + QAction* signOutAction = new QAction(tr("&Sign Out"), this); + connect(signOutAction, SIGNAL(triggered()), SLOT(handleSignOutAction())); + actionsMenu->addAction(signOutAction); + + toggleRequestDeliveryReceipts_ = new QAction(tr("&Request Delivery Receipts"), this); + toggleRequestDeliveryReceipts_->setCheckable(true); + toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS)); + connect(toggleRequestDeliveryReceipts_, SIGNAL(toggled(bool)), SLOT(handleToggleRequestDeliveryReceipts(bool))); + + QList< QAction* > generalMenuActions = loginMenus_.generalMenu->actions(); + loginMenus_.generalMenu->insertAction(generalMenuActions.at(generalMenuActions.count()-2),toggleRequestDeliveryReceipts_); + + treeWidget_->onSomethingSelectedChanged.connect(boost::bind(&QtMainWindow::handleSomethingSelectedChanged, this, _1)); + + setAvailableAdHocCommands(std::vector()); + QAction* adHocAction = new QAction(tr("Collecting commands..."), this); + adHocAction->setEnabled(false); + serverAdHocMenu_->addAction(adHocAction); + serverAdHocCommandActions_.append(adHocAction); + + settings_->onSettingChanged.connect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1)); } QtMainWindow::~QtMainWindow() { - settings_->onSettingChanged.disconnect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1)); + settings_->onSettingChanged.disconnect(boost::bind(&QtMainWindow::handleSettingChanged, this, _1)); } void QtMainWindow::handleTabChanged(int index) { - settings_->storeSetting(QtUISettingConstants::CURRENT_ROSTER_TAB, index); + settings_->storeSetting(QtUISettingConstants::CURRENT_ROSTER_TAB, index); } void QtMainWindow::handleToggleRequestDeliveryReceipts(bool enabled) { - settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, enabled); + settings_->storeSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS, enabled); } void QtMainWindow::handleShowCertificateInfo() { - onShowCertificateRequest(); + onShowCertificateRequest(); } void QtMainWindow::handleEditBlockingList() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtMainWindow::handleSomethingSelectedChanged(bool itemSelected) { - bool isOnline = addUserAction_->isEnabled(); - editUserAction_->setEnabled(isOnline && itemSelected); + bool isOnline = addUserAction_->isEnabled(); + editUserAction_->setEnabled(isOnline && itemSelected); } QtEventWindow* QtMainWindow::getEventWindow() { - return eventWindow_; + return eventWindow_; } QtChatListWindow* QtMainWindow::getChatListWindow() { - return chatListWindow_; + return chatListWindow_; } void QtMainWindow::setRosterModel(Roster* roster) { - treeWidget_->setRosterModel(roster); + treeWidget_->setRosterModel(roster); } void QtMainWindow::handleEditProfileRequest() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtMainWindow::handleEventCountUpdated(int count) { - QColor eventTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default - int eventIndex = 2; - tabs_->tabBar()->setTabTextColor(eventIndex, eventTabColor); - QString text = tr("&Notices"); - if (count > 0) { - text += QString(" (%1)").arg(count); - } - tabs_->setTabText(eventIndex, text); + QColor eventTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default + int eventIndex = 2; + tabs_->tabBar()->setTabTextColor(eventIndex, eventTabColor); + QString text = tr("&Notices"); + if (count > 0) { + text += QString(" (%1)").arg(count); + } + tabs_->setTabText(eventIndex, text); } void QtMainWindow::handleChatCountUpdated(int count) { - QColor chatTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default - int chatIndex = 1; - tabs_->tabBar()->setTabTextColor(chatIndex, chatTabColor); - QString text = tr("C&hats"); - if (count > 0) { - text += QString(" (%1)").arg(count); - } - tabs_->setTabText(chatIndex, text); + QColor chatTabColor = (count == 0) ? QColor() : QColor(255, 0, 0); // invalid resets to default + int chatIndex = 1; + tabs_->tabBar()->setTabTextColor(chatIndex, chatTabColor); + QString text = tr("C&hats"); + if (count > 0) { + text += QString(" (%1)").arg(count); + } + tabs_->setTabText(chatIndex, text); } void QtMainWindow::handleAddUserActionTriggered(bool /*checked*/) { - boost::shared_ptr event(new RequestAddUserDialogUIEvent()); - uiEventStream_->send(event); + boost::shared_ptr event(new RequestAddUserDialogUIEvent()); + uiEventStream_->send(event); } void QtMainWindow::handleChatUserActionTriggered(bool /*checked*/) { - boost::shared_ptr event(new RequestChatWithUserDialogUIEvent()); - uiEventStream_->send(event); + boost::shared_ptr event(new RequestChatWithUserDialogUIEvent()); + uiEventStream_->send(event); } void QtMainWindow::handleOtherAdHocActionTriggered() { - new QtAdHocCommandWithJIDWindow(uiEventStream_); + new QtAdHocCommandWithJIDWindow(uiEventStream_); } void QtMainWindow::handleSignOutAction() { - loginMenus_.generalMenu->removeAction(toggleRequestDeliveryReceipts_); - onSignOutRequest(); + loginMenus_.generalMenu->removeAction(toggleRequestDeliveryReceipts_); + onSignOutRequest(); } void QtMainWindow::handleEditProfileAction() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtMainWindow::handleJoinMUCAction() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtMainWindow::handleViewLogsAction() { - uiEventStream_->send(boost::make_shared()); + uiEventStream_->send(boost::make_shared()); } void QtMainWindow::handleStatusChanged(StatusShow::Type showType, const QString &statusMessage) { - onChangeStatusRequest(showType, Q2PSTRING(statusMessage)); + onChangeStatusRequest(showType, Q2PSTRING(statusMessage)); } void QtMainWindow::handleSettingChanged(const std::string& settingPath) { - if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) { - handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); - } - if (settingPath == QtUISettingConstants::SHOW_EMOTICONS.getKey()) { - handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); - } - if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) { - toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS)); - } - if (settingPath == QtUISettingConstants::COMPACT_ROSTER.getKey()) { - handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); - } + if (settingPath == SettingConstants::SHOW_OFFLINE.getKey()) { + handleShowOfflineToggled(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); + } + if (settingPath == QtUISettingConstants::SHOW_EMOTICONS.getKey()) { + handleShowEmoticonsToggled(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); + } + if (settingPath == SettingConstants::REQUEST_DELIVERYRECEIPTS.getKey()) { + toggleRequestDeliveryReceipts_->setChecked(settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS)); + } + if (settingPath == QtUISettingConstants::COMPACT_ROSTER.getKey()) { + handleCompactRosterToggled(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); + } } void QtMainWindow::handleCompactRosterToggled(bool state) { - settings_->storeSetting(QtUISettingConstants::COMPACT_ROSTER, state); - compactRosterAction_->setChecked(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); + settings_->storeSetting(QtUISettingConstants::COMPACT_ROSTER, state); + compactRosterAction_->setChecked(settings_->getSetting(QtUISettingConstants::COMPACT_ROSTER)); } void QtMainWindow::handleShowOfflineToggled(bool state) { - settings_->storeSetting(SettingConstants::SHOW_OFFLINE, state); - showOfflineAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); + settings_->storeSetting(SettingConstants::SHOW_OFFLINE, state); + showOfflineAction_->setChecked(settings_->getSetting(SettingConstants::SHOW_OFFLINE)); } void QtMainWindow::handleShowEmoticonsToggled(bool state) { - settings_->storeSetting(QtUISettingConstants::SHOW_EMOTICONS, state); - showEmoticonsAction_->setChecked(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); + settings_->storeSetting(QtUISettingConstants::SHOW_EMOTICONS, state); + showEmoticonsAction_->setChecked(settings_->getSetting(QtUISettingConstants::SHOW_EMOTICONS)); } void QtMainWindow::setMyNick(const std::string& nick) { - meView_->setNick(P2QSTRING(nick)); + meView_->setNick(P2QSTRING(nick)); } void QtMainWindow::setMyJID(const JID& jid) { - meView_->setJID(P2QSTRING(jid.toBare().toString())); + meView_->setJID(P2QSTRING(jid.toBare().toString())); } void QtMainWindow::setMyAvatarPath(const std::string& path) { - meView_->setAvatar(P2QSTRING(path)); + meView_->setAvatar(P2QSTRING(path)); } void QtMainWindow::setMyStatusText(const std::string& status) { - meView_->setStatusText(P2QSTRING(status)); + meView_->setStatusText(P2QSTRING(status)); } void QtMainWindow::setMyStatusType(StatusShow::Type type) { - meView_->setStatusType(type); - const bool online = (type != StatusShow::None); - treeWidget_->setOnline(online); - chatListWindow_->setOnline(online); - foreach (QAction *action, onlineOnlyActions_) { - action->setEnabled(online); - } - serverAdHocMenu_->setEnabled(online); + meView_->setStatusType(type); + const bool online = (type != StatusShow::None); + treeWidget_->setOnline(online); + chatListWindow_->setOnline(online); + foreach (QAction *action, onlineOnlyActions_) { + action->setEnabled(online); + } + serverAdHocMenu_->setEnabled(online); } void QtMainWindow::setMyContactRosterItem(boost::shared_ptr contact) { - meView_->setContactRosterItem(contact); + meView_->setContactRosterItem(contact); } void QtMainWindow::setConnecting() { - meView_->setConnecting(); + meView_->setConnecting(); } void QtMainWindow::setStreamEncryptionStatus(bool tlsInPlaceAndValid) { - meView_->setStreamEncryptionStatus(tlsInPlaceAndValid); + meView_->setStreamEncryptionStatus(tlsInPlaceAndValid); } void QtMainWindow::openCertificateDialog(const std::vector& chain) { - openCertificateDialog(chain, this); + openCertificateDialog(chain, this); } void QtMainWindow::openCertificateDialog(const std::vector& chain, QWidget* parent) { #if defined(SWIFTEN_PLATFORM_MACOSX) - CocoaUIHelpers::displayCertificateChainAsSheet(parent, chain); + CocoaUIHelpers::displayCertificateChainAsSheet(parent, chain); #elif defined(SWIFTEN_PLATFORM_WINDOWS) - WinUIHelpers::displayCertificateChainAsSheet(parent, chain); + WinUIHelpers::displayCertificateChainAsSheet(parent, chain); #else - QtCertificateViewerDialog::displayCertificateChainAsSheet(parent, chain); + QtCertificateViewerDialog::displayCertificateChainAsSheet(parent, chain); #endif } void QtMainWindow::handleAdHocActionTriggered(bool /*checked*/) { - QAction* action = qobject_cast(sender()); - assert(action); - DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)]; - uiEventStream_->send(boost::shared_ptr(new RequestAdHocUIEvent(command))); + QAction* action = qobject_cast(sender()); + assert(action); + DiscoItems::Item command = serverAdHocCommands_[serverAdHocCommandActions_.indexOf(action)]; + uiEventStream_->send(boost::shared_ptr(new RequestAdHocUIEvent(command))); } void QtMainWindow::setAvailableAdHocCommands(const std::vector& commands) { - serverAdHocCommands_ = commands; - foreach (QAction* action, serverAdHocCommandActions_) { - delete action; - } - serverAdHocMenu_->clear(); - serverAdHocCommandActions_.clear(); - foreach (DiscoItems::Item command, commands) { - QAction* action = new QAction(P2QSTRING(command.getName()), this); - connect(action, SIGNAL(triggered(bool)), this, SLOT(handleAdHocActionTriggered(bool))); - serverAdHocMenu_->addAction(action); - serverAdHocCommandActions_.append(action); - } - if (serverAdHocCommandActions_.isEmpty()) { - QAction* action = new QAction(tr("No Available Commands"), this); - action->setEnabled(false); - serverAdHocMenu_->addAction(action); - serverAdHocCommandActions_.append(action); - } + serverAdHocCommands_ = commands; + foreach (QAction* action, serverAdHocCommandActions_) { + delete action; + } + serverAdHocMenu_->clear(); + serverAdHocCommandActions_.clear(); + foreach (DiscoItems::Item command, commands) { + QAction* action = new QAction(P2QSTRING(command.getName()), this); + connect(action, SIGNAL(triggered(bool)), this, SLOT(handleAdHocActionTriggered(bool))); + serverAdHocMenu_->addAction(action); + serverAdHocCommandActions_.append(action); + } + if (serverAdHocCommandActions_.isEmpty()) { + QAction* action = new QAction(tr("No Available Commands"), this); + action->setEnabled(false); + serverAdHocMenu_->addAction(action); + serverAdHocCommandActions_.append(action); + } } void QtMainWindow::setBlockingCommandAvailable(bool isAvailable) { - openBlockingListEditor_->setVisible(isAvailable); + openBlockingListEditor_->setVisible(isAvailable); } } diff --git a/Swift/QtUI/QtMainWindow.h b/Swift/QtUI/QtMainWindow.h index 71a5783..d90dade 100644 --- a/Swift/QtUI/QtMainWindow.h +++ b/Swift/QtUI/QtMainWindow.h @@ -28,83 +28,83 @@ class QMenu; class QTabWidget; namespace Swift { - class QtRosterWidget; - class TreeWidget; - class UIEventStream; - class QtTabWidget; - class SettingsProvider; - class QtUIPreferences; - class StatusCache; + class QtRosterWidget; + class TreeWidget; + class UIEventStream; + class QtTabWidget; + class SettingsProvider; + class QtUIPreferences; + class StatusCache; - class QtMainWindow : public QWidget, public MainWindow { - Q_OBJECT - public: - QtMainWindow(SettingsProvider*, UIEventStream* eventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID); - virtual ~QtMainWindow(); - std::vector getMenus() {return menus_;} - void setMyNick(const std::string& name); - void setMyJID(const JID& jid); - void setMyAvatarPath(const std::string& path); - void setMyStatusText(const std::string& status); - void setMyStatusType(StatusShow::Type type); - void setMyContactRosterItem(boost::shared_ptr contact); - void setConnecting(); - void setStreamEncryptionStatus(bool tlsInPlaceAndValid); - void openCertificateDialog(const std::vector& chain); - static void openCertificateDialog(const std::vector& chain, QWidget* parent); - QtEventWindow* getEventWindow(); - QtChatListWindow* getChatListWindow(); - void setRosterModel(Roster* roster); - void setAvailableAdHocCommands(const std::vector& commands); - void setBlockingCommandAvailable(bool isAvailable); - private slots: - void handleStatusChanged(StatusShow::Type showType, const QString &statusMessage); - void handleSettingChanged(const std::string& settingPath); - void handleCompactRosterToggled(bool); - void handleShowOfflineToggled(bool); - void handleShowEmoticonsToggled(bool); - void handleJoinMUCAction(); - void handleViewLogsAction(); - void handleSignOutAction(); - void handleEditProfileAction(); - void handleAddUserActionTriggered(bool checked); - void handleChatUserActionTriggered(bool checked); - void handleOtherAdHocActionTriggered(); - void handleAdHocActionTriggered(bool checked); - void handleEventCountUpdated(int count); - void handleChatCountUpdated(int count); - void handleEditProfileRequest(); - void handleTabChanged(int index); - void handleToggleRequestDeliveryReceipts(bool enabled); - void handleShowCertificateInfo(); - void handleEditBlockingList(); - void handleSomethingSelectedChanged(bool itemSelected); + class QtMainWindow : public QWidget, public MainWindow { + Q_OBJECT + public: + QtMainWindow(SettingsProvider*, UIEventStream* eventStream, QtLoginWindow::QtMenus loginMenus, StatusCache* statusCache, bool emoticonsExist, bool enableAdHocCommandOnJID); + virtual ~QtMainWindow(); + std::vector getMenus() {return menus_;} + void setMyNick(const std::string& name); + void setMyJID(const JID& jid); + void setMyAvatarPath(const std::string& path); + void setMyStatusText(const std::string& status); + void setMyStatusType(StatusShow::Type type); + void setMyContactRosterItem(boost::shared_ptr contact); + void setConnecting(); + void setStreamEncryptionStatus(bool tlsInPlaceAndValid); + void openCertificateDialog(const std::vector& chain); + static void openCertificateDialog(const std::vector& chain, QWidget* parent); + QtEventWindow* getEventWindow(); + QtChatListWindow* getChatListWindow(); + void setRosterModel(Roster* roster); + void setAvailableAdHocCommands(const std::vector& commands); + void setBlockingCommandAvailable(bool isAvailable); + private slots: + void handleStatusChanged(StatusShow::Type showType, const QString &statusMessage); + void handleSettingChanged(const std::string& settingPath); + void handleCompactRosterToggled(bool); + void handleShowOfflineToggled(bool); + void handleShowEmoticonsToggled(bool); + void handleJoinMUCAction(); + void handleViewLogsAction(); + void handleSignOutAction(); + void handleEditProfileAction(); + void handleAddUserActionTriggered(bool checked); + void handleChatUserActionTriggered(bool checked); + void handleOtherAdHocActionTriggered(); + void handleAdHocActionTriggered(bool checked); + void handleEventCountUpdated(int count); + void handleChatCountUpdated(int count); + void handleEditProfileRequest(); + void handleTabChanged(int index); + void handleToggleRequestDeliveryReceipts(bool enabled); + void handleShowCertificateInfo(); + void handleEditBlockingList(); + void handleSomethingSelectedChanged(bool itemSelected); - private: - SettingsProvider* settings_; - QtLoginWindow::QtMenus loginMenus_; - std::vector menus_; - QtRosterWidget* treeWidget_; - QtRosterHeader* meView_; - QAction* addUserAction_; - QAction* editUserAction_; - QAction* chatUserAction_; - QAction* otherAdHocAction_; - QAction* showOfflineAction_; - QAction* compactRosterAction_; - QAction* showEmoticonsAction_; - QAction* openBlockingListEditor_; - QAction* toggleRequestDeliveryReceipts_; - QMenu* serverAdHocMenu_; - QtTabWidget* tabs_; - QComboBox* tabBarCombo_; - QWidget* contactsTabWidget_; - QWidget* eventsTabWidget_; - QtEventWindow* eventWindow_; - QtChatListWindow* chatListWindow_; - UIEventStream* uiEventStream_; - std::vector serverAdHocCommands_; - QList serverAdHocCommandActions_; - QList onlineOnlyActions_; - }; + private: + SettingsProvider* settings_; + QtLoginWindow::QtMenus loginMenus_; + std::vector menus_; + QtRosterWidget* treeWidget_; + QtRosterHeader* meView_; + QAction* addUserAction_; + QAction* editUserAction_; + QAction* chatUserAction_; + QAction* otherAdHocAction_; + QAction* showOfflineAction_; + QAction* compactRosterAction_; + QAction* showEmoticonsAction_; + QAction* openBlockingListEditor_; + QAction* toggleRequestDeliveryReceipts_; + QMenu* serverAdHocMenu_; + QtTabWidget* tabs_; + QComboBox* tabBarCombo_; + QWidget* contactsTabWidget_; + QWidget* eventsTabWidget_; + QtEventWindow* eventWindow_; + QtChatListWindow* chatListWindow_; + UIEventStream* uiEventStream_; + std::vector serverAdHocCommands_; + QList serverAdHocCommandActions_; + QList onlineOnlyActions_; + }; } diff --git a/Swift/QtUI/QtNameWidget.cpp b/Swift/QtUI/QtNameWidget.cpp index cf668c8..0610a00 100644 --- a/Swift/QtUI/QtNameWidget.cpp +++ b/Swift/QtUI/QtNameWidget.cpp @@ -18,80 +18,80 @@ namespace Swift { QtNameWidget::QtNameWidget(SettingsProvider* settings, QWidget *parent) : QWidget(parent), settings(settings), isOnline_(false) { - QHBoxLayout* mainLayout = new QHBoxLayout(this); - mainLayout->setSpacing(0); - mainLayout->setContentsMargins(0,0,0,0); + QHBoxLayout* mainLayout = new QHBoxLayout(this); + mainLayout->setSpacing(0); + mainLayout->setContentsMargins(0,0,0,0); - mode = settings->getSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER) ? ShowNick : ShowJID; + mode = settings->getSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER) ? ShowNick : ShowJID; - textLabel = new QtElidingLabel(this); - QFont font = textLabel->font(); - font.setBold(true); - textLabel->setFont(font); - mainLayout->addWidget(textLabel); + textLabel = new QtElidingLabel(this); + QFont font = textLabel->font(); + font.setBold(true); + textLabel->setFont(font); + mainLayout->addWidget(textLabel); } void QtNameWidget::setNick(const QString& nick) { - this->nick = nick; - updateText(); + this->nick = nick; + updateText(); } void QtNameWidget::setJID(const QString& jid) { - this->jid = jid; - updateText(); + this->jid = jid; + updateText(); } void QtNameWidget::setOnline(const bool isOnline) { - isOnline_ = isOnline; + isOnline_ = isOnline; } void QtNameWidget::mousePressEvent(QMouseEvent* event) { - QMenu menu; - bool hasNick = !nick.isEmpty(); - - QAction* showAsNick = new QAction(hasNick ? tr("Show Nickname") : tr("(No Nickname Set)"), this); - showAsNick->setCheckable(true); - showAsNick->setEnabled(hasNick); - if (mode == ShowNick && hasNick) { - showAsNick->setChecked(true); - } - menu.addAction(showAsNick); - - QAction* showAsJID = new QAction(tr("Show Address"), this); - showAsJID->setCheckable(true); - if (mode == ShowJID || !hasNick) { - showAsJID->setChecked(true); - } - menu.addAction(showAsJID); - - QAction* editProfile = new QAction(tr("Edit Profile"), this); - menu.addAction(editProfile); - editProfile->setEnabled(isOnline_); - - QAction* result = menu.exec(event->globalPos()); - if (result == showAsJID) { - mode = ShowJID; - } - else if (result == showAsNick) { - mode = ShowNick; - } - else if (result == editProfile) { - emit onChangeNickRequest(); - } - settings->storeSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER, mode == ShowNick); - updateText(); + QMenu menu; + bool hasNick = !nick.isEmpty(); + + QAction* showAsNick = new QAction(hasNick ? tr("Show Nickname") : tr("(No Nickname Set)"), this); + showAsNick->setCheckable(true); + showAsNick->setEnabled(hasNick); + if (mode == ShowNick && hasNick) { + showAsNick->setChecked(true); + } + menu.addAction(showAsNick); + + QAction* showAsJID = new QAction(tr("Show Address"), this); + showAsJID->setCheckable(true); + if (mode == ShowJID || !hasNick) { + showAsJID->setChecked(true); + } + menu.addAction(showAsJID); + + QAction* editProfile = new QAction(tr("Edit Profile"), this); + menu.addAction(editProfile); + editProfile->setEnabled(isOnline_); + + QAction* result = menu.exec(event->globalPos()); + if (result == showAsJID) { + mode = ShowJID; + } + else if (result == showAsNick) { + mode = ShowNick; + } + else if (result == editProfile) { + emit onChangeNickRequest(); + } + settings->storeSetting(QtUISettingConstants::SHOW_NICK_IN_ROSTER_HEADER, mode == ShowNick); + updateText(); } void QtNameWidget::updateText() { - QString text; - if (mode == ShowNick && !nick.isEmpty()) { - text = nick; - } - else { - text = jid; - } - text.replace("<","<"); - textLabel->setText(text); + QString text; + if (mode == ShowNick && !nick.isEmpty()) { + text = nick; + } + else { + text = jid; + } + text.replace("<","<"); + textLabel->setText(text); } } diff --git a/Swift/QtUI/QtNameWidget.h b/Swift/QtUI/QtNameWidget.h index 5f9962b..0da0ff6 100644 --- a/Swift/QtUI/QtNameWidget.h +++ b/Swift/QtUI/QtNameWidget.h @@ -9,38 +9,38 @@ #include namespace Swift { - class QtElidingLabel; - class SettingsProvider; - - class QtNameWidget : public QWidget { - Q_OBJECT - - public: - QtNameWidget(SettingsProvider* settings, QWidget *parent); - - void setNick(const QString& text); - void setJID(const QString& jid); - void setOnline(const bool isOnline); - - signals: - void onChangeNickRequest(); - - private: - void updateText(); - virtual void mousePressEvent(QMouseEvent* event); - - private: - enum Mode { - ShowNick, - ShowJID - }; - - SettingsProvider* settings; - Mode mode; - QtElidingLabel* textLabel; - QString jid; - QString nick; - bool isOnline_; - }; + class QtElidingLabel; + class SettingsProvider; + + class QtNameWidget : public QWidget { + Q_OBJECT + + public: + QtNameWidget(SettingsProvider* settings, QWidget *parent); + + void setNick(const QString& text); + void setJID(const QString& jid); + void setOnline(const bool isOnline); + + signals: + void onChangeNickRequest(); + + private: + void updateText(); + virtual void mousePressEvent(QMouseEvent* event); + + private: + enum Mode { + ShowNick, + ShowJID + }; + + SettingsProvider* settings; + Mode mode; + QtElidingLabel* textLabel; + QString jid; + QString nick; + bool isOnline_; + }; } diff --git a/Swift/QtUI/QtPlainChatView.cpp b/Swift/QtUI/QtPlainChatView.cpp index 3144080..9dc815a 100644 --- a/Swift/QtUI/QtPlainChatView.cpp +++ b/Swift/QtUI/QtPlainChatView.cpp @@ -31,402 +31,402 @@ namespace Swift { QtPlainChatView::QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream) : QtChatView(window), window_(window), eventStream_(eventStream), idGenerator_(0) { - QVBoxLayout* mainLayout = new QVBoxLayout(this); - mainLayout->setSpacing(0); - mainLayout->setContentsMargins(0,0,0,0); - log_ = new LogTextEdit(this); - log_->setReadOnly(true); - log_->setAccessibleName(tr("Chat Messages")); - mainLayout->addWidget(log_); + QVBoxLayout* mainLayout = new QVBoxLayout(this); + mainLayout->setSpacing(0); + mainLayout->setContentsMargins(0,0,0,0); + log_ = new LogTextEdit(this); + log_->setReadOnly(true); + log_->setAccessibleName(tr("Chat Messages")); + mainLayout->addWidget(log_); } QtPlainChatView::~QtPlainChatView() { } QString chatMessageToString(const ChatWindow::ChatMessage& message) { - QString result; - foreach (boost::shared_ptr part, message.getParts()) { - boost::shared_ptr textPart; - boost::shared_ptr uriPart; - boost::shared_ptr emoticonPart; - boost::shared_ptr highlightPart; - - if ((textPart = boost::dynamic_pointer_cast(part))) { - QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text)); - text.replace("\n","
"); - result += text; - continue; - } - if ((uriPart = boost::dynamic_pointer_cast(part))) { - QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target)); - result += "" + uri + ""; - continue; - } - if ((emoticonPart = boost::dynamic_pointer_cast(part))) { - result += P2QSTRING(emoticonPart->alternativeText); - continue; - } - if ((highlightPart = boost::dynamic_pointer_cast(part))) { - //FIXME: Maybe do something here. Anything, really. - continue; - } - } - return result; + QString result; + foreach (boost::shared_ptr part, message.getParts()) { + boost::shared_ptr textPart; + boost::shared_ptr uriPart; + boost::shared_ptr emoticonPart; + boost::shared_ptr highlightPart; + + if ((textPart = boost::dynamic_pointer_cast(part))) { + QString text = QtUtilities::htmlEscape(P2QSTRING(textPart->text)); + text.replace("\n","
"); + result += text; + continue; + } + if ((uriPart = boost::dynamic_pointer_cast(part))) { + QString uri = QtUtilities::htmlEscape(P2QSTRING(uriPart->target)); + result += "" + uri + ""; + continue; + } + if ((emoticonPart = boost::dynamic_pointer_cast(part))) { + result += P2QSTRING(emoticonPart->alternativeText); + continue; + } + if ((highlightPart = boost::dynamic_pointer_cast(part))) { + //FIXME: Maybe do something here. Anything, really. + continue; + } + } + return result; } std::string QtPlainChatView::addMessage(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) { - QString text = "

"; - if (label) { - text += P2QSTRING(label->getLabel()) + "
"; - } - QString name = senderIsSelf ? "you" : P2QSTRING(senderName); - text += QString(tr("At %1 %2 said:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "
"; - text += chatMessageToString(message); - text += "

"; - log_->append(text); - const std::string idx = senderIsSelf ? "" : senderName; - lastMessageLabel_[idx] = label; - return idx; + QString text = "

"; + if (label) { + text += P2QSTRING(label->getLabel()) + "
"; + } + QString name = senderIsSelf ? "you" : P2QSTRING(senderName); + text += QString(tr("At %1 %2 said:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "
"; + text += chatMessageToString(message); + text += "

"; + log_->append(text); + const std::string idx = senderIsSelf ? "" : senderName; + lastMessageLabel_[idx] = label; + return idx; } std::string QtPlainChatView::addAction(const ChatWindow::ChatMessage& message, const std::string& senderName, bool senderIsSelf, boost::shared_ptr label, const std::string& /*avatarPath*/, const boost::posix_time::ptime& time) { - QString text = "

"; - if (label) { - text += P2QSTRING(label->getLabel()) + "
"; - } - QString name = senderIsSelf ? "you" : P2QSTRING(senderName); - text += QString(tr("At %1 %2 ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name); - text += chatMessageToString(message); - text += "

"; - log_->append(text); - const std::string idx = senderIsSelf ? "" : senderName; - lastMessageLabel_[idx] = label; - return idx; + QString text = "

"; + if (label) { + text += P2QSTRING(label->getLabel()) + "
"; + } + QString name = senderIsSelf ? "you" : P2QSTRING(senderName); + text += QString(tr("At %1 %2 ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name); + text += chatMessageToString(message); + text += "

"; + log_->append(text); + const std::string idx = senderIsSelf ? "" : senderName; + lastMessageLabel_[idx] = label; + return idx; } std::string QtPlainChatView::addSystemMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction /*direction*/) { - QString text = "

"; - text += chatMessageToString(message); - text += "

"; - log_->append(text); - return ""; + QString text = "

"; + text += chatMessageToString(message); + text += "

"; + log_->append(text); + return ""; } void QtPlainChatView::addPresenceMessage(const ChatWindow::ChatMessage& message, ChatWindow::Direction /*direction*/) { - QString text = "

"; - text += chatMessageToString(message); - text += "

"; - log_->append(text); + QString text = "

"; + text += chatMessageToString(message); + text += "

"; + log_->append(text); } void QtPlainChatView::addErrorMessage(const ChatWindow::ChatMessage& message) { - QString text = "

"; - text += chatMessageToString(message); - text += "

"; - log_->append(text); + QString text = "

"; + text += chatMessageToString(message); + text += "

"; + log_->append(text); } void QtPlainChatView::replaceMessage(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) { - QString text = "

"; - if (lastMessageLabel_[id]) { - text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "
"; - } - QString name = id.empty() ? "you" : P2QSTRING(id); - text += QString(tr("At %1 %2 corrected the last message to:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "
"; - text += chatMessageToString(message); - text += "

"; - log_->append(text); + QString text = "

"; + if (lastMessageLabel_[id]) { + text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "
"; + } + QString name = id.empty() ? "you" : P2QSTRING(id); + text += QString(tr("At %1 %2 corrected the last message to:")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name) + "
"; + text += chatMessageToString(message); + text += "

"; + log_->append(text); } void QtPlainChatView::replaceWithAction(const ChatWindow::ChatMessage& message, const std::string& id, const boost::posix_time::ptime& time) { - QString text = "

"; - if (lastMessageLabel_[id]) { - text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "
"; - } - QString name = id.empty() ? "you" : P2QSTRING(id); - text += QString(tr("At %1 %2 corrected the last action to: ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name); - text += chatMessageToString(message); - text += "

"; - log_->append(text); + QString text = "

"; + if (lastMessageLabel_[id]) { + text += P2QSTRING(lastMessageLabel_[id]->getLabel()) + "
"; + } + QString name = id.empty() ? "you" : P2QSTRING(id); + text += QString(tr("At %1 %2 corrected the last action to: ")).arg(ChatSnippet::timeToEscapedString(B2QDATE(time))).arg(name); + text += chatMessageToString(message); + text += "

"; + log_->append(text); } void QtPlainChatView::replaceLastMessage(const ChatWindow::ChatMessage& message, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) { - QString text = "

The last message was corrected to:
"; - text += chatMessageToString(message); - text += "

"; - log_->append(text); + QString text = "

The last message was corrected to:
"; + text += chatMessageToString(message); + text += "

"; + log_->append(text); } void QtPlainChatView::replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& /*id*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/) { - QString text = "

"; - text += chatMessageToString(message); - text += "

"; - log_->append(text); + QString text = "

"; + text += chatMessageToString(message); + text += "

"; + log_->append(text); } void QtPlainChatView::setAckState(const std::string& /*id*/, ChatWindow::AckState state) { - if (state == ChatWindow::Failed) { - addSystemMessage(ChatWindow::ChatMessage("Message delivery failed due to disconnection from server."), ChatWindow::DefaultDirection); - } + if (state == ChatWindow::Failed) { + addSystemMessage(ChatWindow::ChatMessage("Message delivery failed due to disconnection from server."), ChatWindow::DefaultDirection); + } } std::string QtPlainChatView::addFileTransfer(const std::string& senderName, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) { - const std::string ftId = "ft" + boost::lexical_cast(idGenerator_++); - const std::string sizeString = formatSize(sizeInBytes); - - FileTransfer* transfer; - if (senderIsSelf) { - QString description = QInputDialog::getText(this, tr("File transfer description"), - tr("Description:"), QLineEdit::Normal, ""); - /* NOTE: it is not possible to abort if description is not provided, since we must always return a valid transfer id */ - const std::string descriptionMessage = description.isEmpty() ? "" : (" \"" + Q2PSTRING(description) + "\""); - const std::string message = std::string() + "Confirm file transfer: " + filename + " (" + sizeString + " bytes)" + descriptionMessage; - transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, Q2PSTRING(description), message, true); - addSystemMessage(ChatWindow::ChatMessage("Preparing to start file transfer..."), ChatWindow::DefaultDirection); - } else { /* incoming transfer */ - const std::string descriptionMessage = description.empty() ? "" : (" \"" + description + "\""); - const std::string message = std::string() + "Incoming file transfer: " + filename + " (" + sizeString + " bytes)" + descriptionMessage; - transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, "", message, true); - addSystemMessage("Incoming file transfer from " + senderName + "...", ChatWindow::DefaultDirection); - } - - fileTransfers_[ftId] = transfer; - layout()->addWidget(transfer->dialog_); - - return ftId; + const std::string ftId = "ft" + boost::lexical_cast(idGenerator_++); + const std::string sizeString = formatSize(sizeInBytes); + + FileTransfer* transfer; + if (senderIsSelf) { + QString description = QInputDialog::getText(this, tr("File transfer description"), + tr("Description:"), QLineEdit::Normal, ""); + /* NOTE: it is not possible to abort if description is not provided, since we must always return a valid transfer id */ + const std::string descriptionMessage = description.isEmpty() ? "" : (" \"" + Q2PSTRING(description) + "\""); + const std::string message = std::string() + "Confirm file transfer: " + filename + " (" + sizeString + " bytes)" + descriptionMessage; + transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, Q2PSTRING(description), message, true); + addSystemMessage(ChatWindow::ChatMessage("Preparing to start file transfer..."), ChatWindow::DefaultDirection); + } else { /* incoming transfer */ + const std::string descriptionMessage = description.empty() ? "" : (" \"" + description + "\""); + const std::string message = std::string() + "Incoming file transfer: " + filename + " (" + sizeString + " bytes)" + descriptionMessage; + transfer = new FileTransfer(this, senderIsSelf, ftId, filename, ChatWindow::WaitingForAccept, "", message, true); + addSystemMessage("Incoming file transfer from " + senderName + "...", ChatWindow::DefaultDirection); + } + + fileTransfers_[ftId] = transfer; + layout()->addWidget(transfer->dialog_); + + return ftId; } void QtPlainChatView::setFileTransferProgress(std::string id, const int percentageDone) { - FileTransferMap::iterator transfer = fileTransfers_.find(id); - if (transfer != fileTransfers_.end()) { - transfer->second->bar_->setValue(percentageDone); - } + FileTransferMap::iterator transfer = fileTransfers_.find(id); + if (transfer != fileTransfers_.end()) { + transfer->second->bar_->setValue(percentageDone); + } } void QtPlainChatView::setFileTransferStatus(std::string id, const ChatWindow::FileTransferState state, const std::string& msg) { - FileTransferMap::iterator transferIter = fileTransfers_.find(id); - if (transferIter == fileTransfers_.end()) { - return; - } - - /* store the layout index so we can restore it to the same location */ - FileTransfer* oldTransfer = transferIter->second; - const int layoutIndex = layout()->indexOf(oldTransfer->dialog_); - layout()->removeWidget(oldTransfer->dialog_); - const std::string &label = (!msg.empty() ? msg : oldTransfer->message_); - FileTransfer* transfer = new FileTransfer(this, oldTransfer->senderIsSelf_, oldTransfer->ftId_, oldTransfer->filename_, state, oldTransfer->description_, label, false); - fileTransfers_[oldTransfer->ftId_] = transfer; /* replace the transfer object for this file id */ - delete oldTransfer; - - /* insert the new dialog at the old position in the layout list */ - QBoxLayout* parentLayout = dynamic_cast(layout()); - assert(parentLayout); - parentLayout->insertWidget(layoutIndex, transfer->dialog_); - - /* log the transfer end result as a system message */ - if (state == ChatWindow::Finished) { - addSystemMessage(ChatWindow::ChatMessage("The file transfer completed successfully."), ChatWindow::DefaultDirection); - } else if (state == ChatWindow::Canceled) { - addSystemMessage(ChatWindow::ChatMessage("The file transfer was canceled."), ChatWindow::DefaultDirection); - } else if (state == ChatWindow::FTFailed) { - addSystemMessage(ChatWindow::ChatMessage("The file transfer failed."), ChatWindow::DefaultDirection); - } + FileTransferMap::iterator transferIter = fileTransfers_.find(id); + if (transferIter == fileTransfers_.end()) { + return; + } + + /* store the layout index so we can restore it to the same location */ + FileTransfer* oldTransfer = transferIter->second; + const int layoutIndex = layout()->indexOf(oldTransfer->dialog_); + layout()->removeWidget(oldTransfer->dialog_); + const std::string &label = (!msg.empty() ? msg : oldTransfer->message_); + FileTransfer* transfer = new FileTransfer(this, oldTransfer->senderIsSelf_, oldTransfer->ftId_, oldTransfer->filename_, state, oldTransfer->description_, label, false); + fileTransfers_[oldTransfer->ftId_] = transfer; /* replace the transfer object for this file id */ + delete oldTransfer; + + /* insert the new dialog at the old position in the layout list */ + QBoxLayout* parentLayout = dynamic_cast(layout()); + assert(parentLayout); + parentLayout->insertWidget(layoutIndex, transfer->dialog_); + + /* log the transfer end result as a system message */ + if (state == ChatWindow::Finished) { + addSystemMessage(ChatWindow::ChatMessage("The file transfer completed successfully."), ChatWindow::DefaultDirection); + } else if (state == ChatWindow::Canceled) { + addSystemMessage(ChatWindow::ChatMessage("The file transfer was canceled."), ChatWindow::DefaultDirection); + } else if (state == ChatWindow::FTFailed) { + addSystemMessage(ChatWindow::ChatMessage("The file transfer failed."), ChatWindow::DefaultDirection); + } } void QtPlainChatView::addMUCInvitation(const std::string& senderName, const JID& jid, const std::string& /*reason*/, const std::string& password, bool /*direct*/, bool isImpromptu, bool isContinuation) { - PopupDialog *invite = new PopupDialog(this); + PopupDialog *invite = new PopupDialog(this); - QLabel* statusLabel = new QLabel; - std::string msg = senderName + " has invited you to join " + jid.toString() + "..."; - statusLabel->setText(P2QSTRING(msg)); - invite->layout_->addWidget(statusLabel); - invite->layout_->addWidget(new QLabel); /* padding */ + QLabel* statusLabel = new QLabel; + std::string msg = senderName + " has invited you to join " + jid.toString() + "..."; + statusLabel->setText(P2QSTRING(msg)); + invite->layout_->addWidget(statusLabel); + invite->layout_->addWidget(new QLabel); /* padding */ - AcceptMUCInviteAction* accept = new AcceptMUCInviteAction(invite, "Accept", jid, senderName, password, isImpromptu, isContinuation); - connect(accept, SIGNAL(clicked()), SLOT(acceptMUCInvite())); - invite->layout_->addWidget(accept); + AcceptMUCInviteAction* accept = new AcceptMUCInviteAction(invite, "Accept", jid, senderName, password, isImpromptu, isContinuation); + connect(accept, SIGNAL(clicked()), SLOT(acceptMUCInvite())); + invite->layout_->addWidget(accept); - AcceptMUCInviteAction* reject = new AcceptMUCInviteAction(invite, "Reject", jid, senderName, password, isImpromptu, isContinuation); - connect(reject, SIGNAL(clicked()), SLOT(rejectMUCInvite())); - invite->layout_->addWidget(reject); - statusLabel->setText(P2QSTRING(msg)); + AcceptMUCInviteAction* reject = new AcceptMUCInviteAction(invite, "Reject", jid, senderName, password, isImpromptu, isContinuation); + connect(reject, SIGNAL(clicked()), SLOT(rejectMUCInvite())); + invite->layout_->addWidget(reject); + statusLabel->setText(P2QSTRING(msg)); - layout()->addWidget(invite->dialog_); + layout()->addWidget(invite->dialog_); - addSystemMessage(ChatWindow::ChatMessage(msg), ChatWindow::DefaultDirection); + addSystemMessage(ChatWindow::ChatMessage(msg), ChatWindow::DefaultDirection); } void QtPlainChatView::scrollToBottom() { - log_->ensureCursorVisible(); - log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum()); + log_->ensureCursorVisible(); + log_->verticalScrollBar()->setValue(log_->verticalScrollBar()->maximum()); } void QtPlainChatView::fileTransferAccept() { - FileTransfer::Action* action = dynamic_cast(sender()); - if (!action) { - return; - } - - FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_); - if (transferIter == fileTransfers_.end()) { - return; - } - - FileTransfer* transfer = transferIter->second; - - const std::string message = transfer->message_; - - if (transfer->senderIsSelf_) { /* if we are the sender, kick of the transfer */ - window_->onFileTransferStart(transfer->ftId_, transfer->description_); - } else { /* ask the user where to save the file first */ - QString path = QFileDialog::getSaveFileName(this, tr("Save File"), P2QSTRING(transfer->filename_)); - if (path.isEmpty()) { - fileTransferReject(); /* because the user did not select a desintation path */ - return; - } - window_->onFileTransferAccept(transfer->ftId_, Q2PSTRING(path)); - } - - setFileTransferStatus(transfer->ftId_, ChatWindow::Negotiating, message); + FileTransfer::Action* action = dynamic_cast(sender()); + if (!action) { + return; + } + + FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_); + if (transferIter == fileTransfers_.end()) { + return; + } + + FileTransfer* transfer = transferIter->second; + + const std::string message = transfer->message_; + + if (transfer->senderIsSelf_) { /* if we are the sender, kick of the transfer */ + window_->onFileTransferStart(transfer->ftId_, transfer->description_); + } else { /* ask the user where to save the file first */ + QString path = QFileDialog::getSaveFileName(this, tr("Save File"), P2QSTRING(transfer->filename_)); + if (path.isEmpty()) { + fileTransferReject(); /* because the user did not select a desintation path */ + return; + } + window_->onFileTransferAccept(transfer->ftId_, Q2PSTRING(path)); + } + + setFileTransferStatus(transfer->ftId_, ChatWindow::Negotiating, message); } void QtPlainChatView::fileTransferReject() { - FileTransfer::Action* action = dynamic_cast(sender()); - if (action) { - window_->onFileTransferCancel(action->id_); - fileTransferFinish(); - } + FileTransfer::Action* action = dynamic_cast(sender()); + if (action) { + window_->onFileTransferCancel(action->id_); + fileTransferFinish(); + } } void QtPlainChatView::fileTransferFinish() { - FileTransfer::Action* action = dynamic_cast(sender()); - if (action) { - FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_); - if (transferIter != fileTransfers_.end()) { - delete transferIter->second; /* cause the dialog to close */ - fileTransfers_.erase(transferIter); - } - } + FileTransfer::Action* action = dynamic_cast(sender()); + if (action) { + FileTransferMap::iterator transferIter = fileTransfers_.find(action->id_); + if (transferIter != fileTransfers_.end()) { + delete transferIter->second; /* cause the dialog to close */ + fileTransfers_.erase(transferIter); + } + } } void QtPlainChatView::acceptMUCInvite() { - AcceptMUCInviteAction *action = dynamic_cast(sender()); - if (action) { - eventStream_->send(boost::make_shared(action->jid_.toString(), action->password_, boost::optional(), false, false, action->isImpromptu_, action->isContinuation_)); - delete action->parent_; - } + AcceptMUCInviteAction *action = dynamic_cast(sender()); + if (action) { + eventStream_->send(boost::make_shared(action->jid_.toString(), action->password_, boost::optional(), false, false, action->isImpromptu_, action->isContinuation_)); + delete action->parent_; + } } void QtPlainChatView::rejectMUCInvite() { - AcceptMUCInviteAction *action = dynamic_cast(sender()); - if (action) { - /* NOTE: no action required to reject an invite? */ - delete action->parent_; - } + AcceptMUCInviteAction *action = dynamic_cast(sender()); + if (action) { + /* NOTE: no action required to reject an invite? */ + delete action->parent_; + } } QtPlainChatView::FileTransfer::FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string &desc, const std::string& msg, bool initializing) : PopupDialog(parent), bar_(0), senderIsSelf_(senderIsSelf), ftId_(ftId), filename_(filename), description_(desc), message_(msg), initializing_(initializing) { - QHBoxLayout* layout = new QHBoxLayout; - QLabel* statusLabel = new QLabel; - layout_->addWidget(statusLabel); - layout_->addWidget(new QLabel); /* padding */ - - if (initializing_) { - FileTransfer::Action* accept = new FileTransfer::Action(senderIsSelf?"Confirm":"Accept", ftId); - parent->connect(accept, SIGNAL(clicked()), SLOT(fileTransferAccept())); - layout_->addWidget(accept); - FileTransfer::Action* reject = new FileTransfer::Action(senderIsSelf?"Cancel":"Reject", ftId); - parent->connect(reject, SIGNAL(clicked()), SLOT(fileTransferReject())); - layout_->addWidget(reject); - statusLabel->setText(P2QSTRING(msg)); - return; - } - - std::string status = msg; - - switch (state) { - case ChatWindow::Initialisation: { - status = "Preparing to send "+ filename + "..."; - FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); - parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); - layout_->addWidget(cancel); - break; - } - case ChatWindow::WaitingForAccept: { - status = "Waiting for user to accept " + filename + "..."; - FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); - parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); - layout_->addWidget(cancel); - break; - } - case ChatWindow::Negotiating: { - status = "Preparing to transfer " + filename + "..."; - FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); - parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); - layout_->addWidget(cancel); - break; - } - case ChatWindow::Transferring: { - status = "Transferring " + filename + "..."; - bar_ = new QProgressBar; - bar_->setRange(0, 100); - bar_->setValue(0); - layout->addWidget(bar_); - FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); - parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); - layout_->addWidget(cancel); - break; - } - case ChatWindow::Canceled: { - status = "File " + filename + " was canceled."; - FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId); - parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish())); - layout_->addWidget(finish); - break; - } - case ChatWindow::Finished: { - status = "File " + filename + " was transfered successfully."; - FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId); - parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish())); - layout_->addWidget(finish); - break; - } - case ChatWindow::FTFailed: { - status = "File transfer failed: " + filename + ""; - FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId); - parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish())); - layout_->addWidget(finish); - break; - } - } - - statusLabel->setText(P2QSTRING(status)); + QHBoxLayout* layout = new QHBoxLayout; + QLabel* statusLabel = new QLabel; + layout_->addWidget(statusLabel); + layout_->addWidget(new QLabel); /* padding */ + + if (initializing_) { + FileTransfer::Action* accept = new FileTransfer::Action(senderIsSelf?"Confirm":"Accept", ftId); + parent->connect(accept, SIGNAL(clicked()), SLOT(fileTransferAccept())); + layout_->addWidget(accept); + FileTransfer::Action* reject = new FileTransfer::Action(senderIsSelf?"Cancel":"Reject", ftId); + parent->connect(reject, SIGNAL(clicked()), SLOT(fileTransferReject())); + layout_->addWidget(reject); + statusLabel->setText(P2QSTRING(msg)); + return; + } + + std::string status = msg; + + switch (state) { + case ChatWindow::Initialisation: { + status = "Preparing to send "+ filename + "..."; + FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); + parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); + layout_->addWidget(cancel); + break; + } + case ChatWindow::WaitingForAccept: { + status = "Waiting for user to accept " + filename + "..."; + FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); + parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); + layout_->addWidget(cancel); + break; + } + case ChatWindow::Negotiating: { + status = "Preparing to transfer " + filename + "..."; + FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); + parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); + layout_->addWidget(cancel); + break; + } + case ChatWindow::Transferring: { + status = "Transferring " + filename + "..."; + bar_ = new QProgressBar; + bar_->setRange(0, 100); + bar_->setValue(0); + layout->addWidget(bar_); + FileTransfer::Action* cancel = new FileTransfer::Action("Cancel", ftId); + parent->connect(cancel, SIGNAL(clicked()), SLOT(fileTransferReject())); + layout_->addWidget(cancel); + break; + } + case ChatWindow::Canceled: { + status = "File " + filename + " was canceled."; + FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId); + parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish())); + layout_->addWidget(finish); + break; + } + case ChatWindow::Finished: { + status = "File " + filename + " was transfered successfully."; + FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId); + parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish())); + layout_->addWidget(finish); + break; + } + case ChatWindow::FTFailed: { + status = "File transfer failed: " + filename + ""; + FileTransfer::Action* finish = new FileTransfer::Action("Hide", ftId); + parent->connect(finish, SIGNAL(clicked()), SLOT(fileTransferFinish())); + layout_->addWidget(finish); + break; + } + } + + statusLabel->setText(P2QSTRING(status)); } void QtPlainChatView::LogTextEdit::contextMenuEvent(QContextMenuEvent *event) { - QMenu *menu = createStandardContextMenu(); - menu->exec(event->globalPos()); - delete menu; + QMenu *menu = createStandardContextMenu(); + menu->exec(event->globalPos()); + delete menu; } } diff --git a/Swift/QtUI/QtPlainChatView.h b/Swift/QtUI/QtPlainChatView.h index fc293ff..cd6ab7e 100644 --- a/Swift/QtUI/QtPlainChatView.h +++ b/Swift/QtUI/QtPlainChatView.h @@ -23,112 +23,112 @@ class QTextEdit; class QProgressBar; namespace Swift { - class HighlightAction; - class SecurityLabel; - - class QtPlainChatView : public QtChatView { - Q_OBJECT - public: - QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream); - virtual ~QtPlainChatView(); - - /** Add message to window. - * @return id of added message (for acks). - */ - virtual std::string addMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/); - /** Adds action to window. - * @return id of added message (for acks); - */ - virtual std::string addAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/); - - virtual std::string addSystemMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/); - virtual void addPresenceMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/); - virtual void addErrorMessage(const ChatWindow::ChatMessage& /*message*/); - - virtual void replaceMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/); - virtual void replaceWithAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/); - virtual void replaceLastMessage(const ChatWindow::ChatMessage& /*message*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/); - virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/); - virtual void setAckState(const std::string& /*id*/, ChatWindow::AckState /*state*/); - - virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/, const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/); - virtual void setFileTransferProgress(std::string, const int /*percentageDone*/); - virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState /*state*/, const std::string& /*msg*/ = ""); - virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool /*direct*/, bool /*isImpromptu*/, bool /*isContinuation*/); - virtual std::string addWhiteboardRequest(const QString& /*contact*/, bool /*senderIsSelf*/) {return "";}; - virtual void setWhiteboardSessionStatus(const std::string& /*id*/, const ChatWindow::WhiteboardSessionState /*state*/) {}; - virtual void setMessageReceiptState(const std::string& /*id*/, ChatWindow::ReceiptState /*state*/) {}; - - virtual void showEmoticons(bool /*show*/) {}; - virtual void addLastSeenLine() {}; - - public slots: - virtual void resizeFont(int /*fontSizeSteps*/) {}; - virtual void scrollToBottom(); - virtual void handleKeyPressEvent(QKeyEvent* /*event*/) {}; - virtual void fileTransferAccept(); - virtual void fileTransferReject(); - virtual void fileTransferFinish(); - virtual void acceptMUCInvite(); - virtual void rejectMUCInvite(); - - private: - struct PopupDialog { - PopupDialog(QtPlainChatView* parent) { - dialog_ = new QFrame(parent); - dialog_->setFrameShape(QFrame::Panel); - dialog_->setFrameShadow(QFrame::Raised); - layout_ = new QHBoxLayout; - dialog_->setLayout(layout_); - } - virtual ~PopupDialog() { - delete dialog_; - } - QFrame* dialog_; - QHBoxLayout* layout_; - }; - - struct AcceptMUCInviteAction : public QPushButton { - AcceptMUCInviteAction(PopupDialog* parent, const std::string& text, const JID& jid, const std::string& senderName, const std::string& password, bool isImpromptu, bool isContinuation) - : QPushButton(P2QSTRING(text)), parent_(parent), jid_(jid), senderName_(senderName), password_(password), isImpromptu_(isImpromptu), isContinuation_(isContinuation) {} - PopupDialog *parent_; - JID jid_; - std::string senderName_; - std::string password_; - bool isImpromptu_; - bool isContinuation_; - }; - - struct FileTransfer : public PopupDialog { - struct Action : QPushButton { - Action(const std::string& text, const std::string& id) - : QPushButton(P2QSTRING(text)), id_(id) {} - std::string id_; - }; - FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string& desc, const std::string& msg, bool initializing); - QProgressBar* bar_; - bool senderIsSelf_; - std::string ftId_; - std::string filename_; - std::string description_; - std::string message_; - bool initializing_; - }; - - class LogTextEdit : public QTextEdit { - public: - LogTextEdit(QWidget* parent) : QTextEdit(parent) {} - virtual ~LogTextEdit() {} - virtual void contextMenuEvent(QContextMenuEvent *event); - }; - - typedef std::map FileTransferMap; - QtChatWindow* window_; - UIEventStream* eventStream_; - LogTextEdit* log_; - FileTransferMap fileTransfers_; - std::map > lastMessageLabel_; - int idGenerator_; - - }; + class HighlightAction; + class SecurityLabel; + + class QtPlainChatView : public QtChatView { + Q_OBJECT + public: + QtPlainChatView(QtChatWindow *window, UIEventStream* eventStream); + virtual ~QtPlainChatView(); + + /** Add message to window. + * @return id of added message (for acks). + */ + virtual std::string addMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/); + /** Adds action to window. + * @return id of added message (for acks); + */ + virtual std::string addAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*senderName*/, bool /*senderIsSelf*/, boost::shared_ptr /*label*/, const std::string& /*avatarPath*/, const boost::posix_time::ptime& /*time*/); + + virtual std::string addSystemMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/); + virtual void addPresenceMessage(const ChatWindow::ChatMessage& /*message*/, ChatWindow::Direction /*direction*/); + virtual void addErrorMessage(const ChatWindow::ChatMessage& /*message*/); + + virtual void replaceMessage(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/); + virtual void replaceWithAction(const ChatWindow::ChatMessage& /*message*/, const std::string& /*id*/, const boost::posix_time::ptime& /*time*/); + virtual void replaceLastMessage(const ChatWindow::ChatMessage& /*message*/, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/); + virtual void replaceSystemMessage(const ChatWindow::ChatMessage& message, const std::string& id, const ChatWindow::TimestampBehaviour /*timestampBehaviour*/); + virtual void setAckState(const std::string& /*id*/, ChatWindow::AckState /*state*/); + + virtual std::string addFileTransfer(const std::string& /*senderName*/, bool /*senderIsSelf*/, const std::string& /*filename*/, const boost::uintmax_t /*sizeInBytes*/, const std::string& /*description*/); + virtual void setFileTransferProgress(std::string, const int /*percentageDone*/); + virtual void setFileTransferStatus(std::string, const ChatWindow::FileTransferState /*state*/, const std::string& /*msg*/ = ""); + virtual void addMUCInvitation(const std::string& /*senderName*/, const JID& /*jid*/, const std::string& /*reason*/, const std::string& /*password*/, bool /*direct*/, bool /*isImpromptu*/, bool /*isContinuation*/); + virtual std::string addWhiteboardRequest(const QString& /*contact*/, bool /*senderIsSelf*/) {return "";}; + virtual void setWhiteboardSessionStatus(const std::string& /*id*/, const ChatWindow::WhiteboardSessionState /*state*/) {}; + virtual void setMessageReceiptState(const std::string& /*id*/, ChatWindow::ReceiptState /*state*/) {}; + + virtual void showEmoticons(bool /*show*/) {}; + virtual void addLastSeenLine() {}; + + public slots: + virtual void resizeFont(int /*fontSizeSteps*/) {}; + virtual void scrollToBottom(); + virtual void handleKeyPressEvent(QKeyEvent* /*event*/) {}; + virtual void fileTransferAccept(); + virtual void fileTransferReject(); + virtual void fileTransferFinish(); + virtual void acceptMUCInvite(); + virtual void rejectMUCInvite(); + + private: + struct PopupDialog { + PopupDialog(QtPlainChatView* parent) { + dialog_ = new QFrame(parent); + dialog_->setFrameShape(QFrame::Panel); + dialog_->setFrameShadow(QFrame::Raised); + layout_ = new QHBoxLayout; + dialog_->setLayout(layout_); + } + virtual ~PopupDialog() { + delete dialog_; + } + QFrame* dialog_; + QHBoxLayout* layout_; + }; + + struct AcceptMUCInviteAction : public QPushButton { + AcceptMUCInviteAction(PopupDialog* parent, const std::string& text, const JID& jid, const std::string& senderName, const std::string& password, bool isImpromptu, bool isContinuation) + : QPushButton(P2QSTRING(text)), parent_(parent), jid_(jid), senderName_(senderName), password_(password), isImpromptu_(isImpromptu), isContinuation_(isContinuation) {} + PopupDialog *parent_; + JID jid_; + std::string senderName_; + std::string password_; + bool isImpromptu_; + bool isContinuation_; + }; + + struct FileTransfer : public PopupDialog { + struct Action : QPushButton { + Action(const std::string& text, const std::string& id) + : QPushButton(P2QSTRING(text)), id_(id) {} + std::string id_; + }; + FileTransfer(QtPlainChatView* parent, bool senderIsSelf, const std::string& ftId, const std::string& filename, const ChatWindow::FileTransferState state, const std::string& desc, const std::string& msg, bool initializing); + QProgressBar* bar_; + bool senderIsSelf_; + std::string ftId_; + std::string filename_; + std::string description_; + std::string message_; + bool initializing_; + }; + + class LogTextEdit : public QTextEdit { + public: + LogTextEdit(QWidget* parent) : QTextEdit(parent) {} + virtual ~LogTextEdit() {} + virtual void contextMenuEvent(QContextMenuEvent *event); + }; + + typedef std::map FileTransferMap; + QtChatWindow* window_; + UIEventStream* eventStream_; + LogTextEdit* log_; + FileTransferMap fileTransfers_; + std::map > lastMessageLabel_; + int idGenerator_; + + }; } diff --git a/Swift/QtUI/QtProfileWindow.cpp b/Swift/QtUI/QtProfileWindow.cpp index 8b4b044..461ea38 100644 --- a/Swift/QtUI/QtProfileWindow.cpp +++ b/Swift/QtUI/QtProfileWindow.cpp @@ -25,143 +25,143 @@ namespace Swift { QtProfileWindow::QtProfileWindow() : - QWidget(), - ui(new Ui::QtProfileWindow) { - ui->setupUi(this); + QWidget(), + ui(new Ui::QtProfileWindow) { + ui->setupUi(this); - ui->statusLabel->setText(tr("Retrieving profile information for this user.")); - ui->statusLabel->setVisible(false); + ui->statusLabel->setText(tr("Retrieving profile information for this user.")); + ui->statusLabel->setVisible(false); - ui->emptyLabel->setText(tr("No profile information is available for this user.")); - ui->emptyLabel->setVisible(false); + ui->emptyLabel->setText(tr("No profile information is available for this user.")); + ui->emptyLabel->setVisible(false); - new QShortcut(QKeySequence::Close, this, SLOT(close())); - ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this)); - connect(ui->savePushButton, SIGNAL(clicked()), SLOT(handleSave())); - setEditable(false); - setAttribute(Qt::WA_DeleteOnClose); - setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); + new QShortcut(QKeySequence::Close, this, SLOT(close())); + ui->throbberLabel->setMovie(new QMovie(":/icons/throbber.gif", QByteArray(), this)); + connect(ui->savePushButton, SIGNAL(clicked()), SLOT(handleSave())); + setEditable(false); + setAttribute(Qt::WA_DeleteOnClose); + setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); - adjustSizeTimer.setSingleShot(true); - connect(&adjustSizeTimer, SIGNAL(timeout()), SLOT(handleAdjustSizeTimeout())); + adjustSizeTimer.setSingleShot(true); + connect(&adjustSizeTimer, SIGNAL(timeout()), SLOT(handleAdjustSizeTimeout())); } QtProfileWindow::~QtProfileWindow() { - delete ui; + delete ui; } void QtProfileWindow::setJID(const JID& jid) { - this->jid = jid; - updateTitle(); + this->jid = jid; + updateTitle(); } void QtProfileWindow::setVCard(VCard::ref vcard) { - ui->vcard->setVCard(vcard); - if (vcard->isEmpty()) { - ui->vcard->setVisible(false); - ui->emptyLabel->setVisible(true); - } else { - ui->vcard->setVisible(true); - ui->emptyLabel->setVisible(false); - } - updateWindowSize(); + ui->vcard->setVCard(vcard); + if (vcard->isEmpty()) { + ui->vcard->setVisible(false); + ui->emptyLabel->setVisible(true); + } else { + ui->vcard->setVisible(true); + ui->emptyLabel->setVisible(false); + } + updateWindowSize(); } void QtProfileWindow::setEnabled(bool b) { - ui->vcard->setEnabled(b); - ui->savePushButton->setEnabled(b); + ui->vcard->setEnabled(b); + ui->savePushButton->setEnabled(b); } void QtProfileWindow::setEditable(bool b) { - ui->throbberLabel->setVisible(b); - ui->errorLabel->setVisible(b); - ui->savePushButton->setVisible(b); - ui->vcard->setEditable(b); - updateTitle(); - updateWindowSize(); + ui->throbberLabel->setVisible(b); + ui->errorLabel->setVisible(b); + ui->savePushButton->setVisible(b); + ui->vcard->setEditable(b); + updateTitle(); + updateWindowSize(); } void QtProfileWindow::setProcessing(bool processing) { - if (processing) { - ui->throbberLabel->movie()->start(); - ui->throbberLabel->show(); - ui->statusLabel->setVisible(true); - ui->vcard->setVisible(false); - } - else { - ui->throbberLabel->hide(); - ui->throbberLabel->movie()->stop(); - ui->statusLabel->setVisible(false); - ui->vcard->setVisible(true); - } + if (processing) { + ui->throbberLabel->movie()->start(); + ui->throbberLabel->show(); + ui->statusLabel->setVisible(true); + ui->vcard->setVisible(false); + } + else { + ui->throbberLabel->hide(); + ui->throbberLabel->movie()->stop(); + ui->statusLabel->setVisible(false); + ui->vcard->setVisible(true); + } } void QtProfileWindow::setError(const std::string& error) { - if (!error.empty()) { - ui->errorLabel->setText("" + QtUtilities::htmlEscape(P2QSTRING(error)) + ""); - } - else { - ui->errorLabel->setText(""); - } + if (!error.empty()) { + ui->errorLabel->setText("" + QtUtilities::htmlEscape(P2QSTRING(error)) + ""); + } + else { + ui->errorLabel->setText(""); + } } void QtProfileWindow::show() { - QWidget::showNormal(); - QWidget::activateWindow(); - QWidget::raise(); + QWidget::showNormal(); + QWidget::activateWindow(); + QWidget::raise(); } void QtProfileWindow::hide() { - QWidget::hide(); + QWidget::hide(); } QSize QtProfileWindow::sizeHint() const { - return QWidget::sizeHint(); + return QWidget::sizeHint(); } void QtProfileWindow::updateTitle() { - QString jidString; - if (jid.isValid()) { - jidString = QString(" ( %1 )").arg(P2QSTRING(jid.toString())); - } + QString jidString; + if (jid.isValid()) { + jidString = QString(" ( %1 )").arg(P2QSTRING(jid.toString())); + } - if (ui->vcard->isEditable()) { - setWindowTitle(tr("Edit Profile") + jidString); - } else { - setWindowTitle(tr("Show Profile") + jidString); - } + if (ui->vcard->isEditable()) { + setWindowTitle(tr("Edit Profile") + jidString); + } else { + setWindowTitle(tr("Show Profile") + jidString); + } } void QtProfileWindow::updateWindowSize() { - // Delay resizing to the end of the event loop, because Qt calculates the correct layout asynchronously. - // Qt will post LayoutRequests for widgets on the event loop on show and widgets will recaluclate their - // layout as they process these events. - // We use the complete and correct size hint from the freshly calculated layout by delaying execution of - // the resize code to the end of Qt's event loop. - if (!adjustSizeTimer.isActive()) { - adjustSizeTimer.start(0); - } + // Delay resizing to the end of the event loop, because Qt calculates the correct layout asynchronously. + // Qt will post LayoutRequests for widgets on the event loop on show and widgets will recaluclate their + // layout as they process these events. + // We use the complete and correct size hint from the freshly calculated layout by delaying execution of + // the resize code to the end of Qt's event loop. + if (!adjustSizeTimer.isActive()) { + adjustSizeTimer.start(0); + } } void QtProfileWindow::closeEvent(QCloseEvent* event) { - event->accept(); - onWindowAboutToBeClosed(jid); + event->accept(); + onWindowAboutToBeClosed(jid); } void QtProfileWindow::handleSave() { - onVCardChangeRequest(ui->vcard->getVCard()); + onVCardChangeRequest(ui->vcard->getVCard()); } void QtProfileWindow::handleAdjustSizeTimeout() { - // Force recaluclation of all layout geometry in children widgets. - // This is required on Windows to have the correct size even on first show. - QList children = findChildren(); - foreach(QWidget* child, children) { - child->updateGeometry(); - } - - updateGeometry(); - adjustSize(); + // Force recaluclation of all layout geometry in children widgets. + // This is required on Windows to have the correct size even on first show. + QList children = findChildren(); + foreach(QWidget* child, children) { + child->updateGeometry(); + } + + updateGeometry(); + adjustSize(); } } diff --git a/Swift/QtUI/QtProfileWindow.h b/Swift/QtUI/QtProfileWindow.h index 0821444..7315807 100644 --- a/Swift/QtUI/QtProfileWindow.h +++ b/Swift/QtUI/QtProfileWindow.h @@ -20,44 +20,44 @@ #include namespace Ui { - class QtProfileWindow; + class QtProfileWindow; } namespace Swift { class QtProfileWindow : public QWidget, public ProfileWindow { - Q_OBJECT + Q_OBJECT - public: - QtProfileWindow(); - virtual ~QtProfileWindow(); + public: + QtProfileWindow(); + virtual ~QtProfileWindow(); - virtual void setJID(const JID& jid); - virtual void setVCard(VCard::ref vcard); + virtual void setJID(const JID& jid); + virtual void setVCard(VCard::ref vcard); - virtual void setEnabled(bool b); - virtual void setProcessing(bool processing); - virtual void setError(const std::string& error); - virtual void setEditable(bool b); + virtual void setEnabled(bool b); + virtual void setProcessing(bool processing); + virtual void setError(const std::string& error); + virtual void setEditable(bool b); - virtual void show(); - virtual void hide(); + virtual void show(); + virtual void hide(); - virtual QSize sizeHint() const; + virtual QSize sizeHint() const; - private: - void updateTitle(); - void updateWindowSize(); - virtual void closeEvent(QCloseEvent* event); + private: + void updateTitle(); + void updateWindowSize(); + virtual void closeEvent(QCloseEvent* event); - private slots: - void handleSave(); - void handleAdjustSizeTimeout(); + private slots: + void handleSave(); + void handleAdjustSizeTimeout(); - private: - Ui::QtProfileWindow* ui; - JID jid; - QTimer adjustSizeTimer; + private: + Ui::QtProfileWindow* ui; + JID jid; + QTimer adjustSizeTimer; }; } diff --git a/Swift/QtUI/QtResourceHelper.cpp b/Swift/QtUI/QtResourceHelper.cpp index f76c438..a802b19 100644 --- a/Swift/QtUI/QtResourceHelper.cpp +++ b/Swift/QtUI/QtResourceHelper.cpp @@ -9,16 +9,16 @@ namespace Swift { QString statusShowTypeToIconPath(StatusShow::Type type) { - QString iconString; - switch (type) { - case StatusShow::Online: iconString = "online";break; - case StatusShow::Away: iconString = "away";break; - case StatusShow::XA: iconString = "away";break; - case StatusShow::FFC: iconString = "online";break; - case StatusShow::DND: iconString = "dnd";break; - case StatusShow::None: iconString = "offline";break; - } - return QString(":/icons/%1.png").arg(iconString); + QString iconString; + switch (type) { + case StatusShow::Online: iconString = "online";break; + case StatusShow::Away: iconString = "away";break; + case StatusShow::XA: iconString = "away";break; + case StatusShow::FFC: iconString = "online";break; + case StatusShow::DND: iconString = "dnd";break; + case StatusShow::None: iconString = "offline";break; + } + return QString(":/icons/%1.png").arg(iconString); } } diff --git a/Swift/QtUI/QtRosterHeader.cpp b/Swift/QtUI/QtRosterHeader.cpp index 4783a64..f8a4cdb 100644 --- a/Swift/QtUI/QtRosterHeader.cpp +++ b/Swift/QtUI/QtRosterHeader.cpp @@ -28,112 +28,112 @@ namespace Swift { QtRosterHeader::QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent) : QWidget(parent), statusEdit_(NULL) { - QHBoxLayout* topLayout = new QHBoxLayout(); - topLayout->setSpacing(3); - topLayout->setContentsMargins(4,4,4,4); - setLayout(topLayout); - setMinimumHeight(50); - setMaximumHeight(50); - - avatarLabel_ = new QtClickableLabel(this); - avatarLabel_->setMinimumSize(avatarSize_, avatarSize_); - avatarLabel_->setMaximumSize(avatarSize_, avatarSize_); - avatarLabel_->setAlignment(Qt::AlignCenter); - setAvatar(":/icons/avatar.png"); - avatarLabel_->setScaledContents(false); - topLayout->addWidget(avatarLabel_); - connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest())); - - QVBoxLayout* rightLayout = new QVBoxLayout(); - rightLayout->setSpacing(4); - rightLayout->setContentsMargins(4,0,0,0); - topLayout->addLayout(rightLayout); - - QHBoxLayout* nameAndSecurityLayout = new QHBoxLayout(); - nameAndSecurityLayout->setContentsMargins(4,0,0,0); - - nameWidget_ = new QtNameWidget(settings, this); - connect(nameWidget_, SIGNAL(onChangeNickRequest()), this, SIGNAL(onEditProfileRequest())); - nameAndSecurityLayout->addWidget(nameWidget_); - - securityInfoButton_ = new QToolButton(this); - securityInfoButton_->setStyleSheet("QToolButton { border: none; } QToolButton:hover { border: 1px solid #bebebe; } QToolButton:pressed { border: 1px solid #757575; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777777, stop: 1 #d4d4d4);}"); - //securityInfoButton_->setAutoRaise(true); - securityInfoButton_->setIcon(QIcon(":/icons/lock.png")); - securityInfoButton_->setToolTip(tr("Connection is secured")); - connect(securityInfoButton_, SIGNAL(clicked()), this, SIGNAL(onShowCertificateInfo())); - nameAndSecurityLayout->addWidget(securityInfoButton_); - - rightLayout->addLayout(nameAndSecurityLayout); - - statusWidget_ = new QtStatusWidget(statusCache, this); - connect(statusWidget_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleChangeStatusRequest(StatusShow::Type, const QString&))); - rightLayout->addWidget(statusWidget_); - - show(); + QHBoxLayout* topLayout = new QHBoxLayout(); + topLayout->setSpacing(3); + topLayout->setContentsMargins(4,4,4,4); + setLayout(topLayout); + setMinimumHeight(50); + setMaximumHeight(50); + + avatarLabel_ = new QtClickableLabel(this); + avatarLabel_->setMinimumSize(avatarSize_, avatarSize_); + avatarLabel_->setMaximumSize(avatarSize_, avatarSize_); + avatarLabel_->setAlignment(Qt::AlignCenter); + setAvatar(":/icons/avatar.png"); + avatarLabel_->setScaledContents(false); + topLayout->addWidget(avatarLabel_); + connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest())); + + QVBoxLayout* rightLayout = new QVBoxLayout(); + rightLayout->setSpacing(4); + rightLayout->setContentsMargins(4,0,0,0); + topLayout->addLayout(rightLayout); + + QHBoxLayout* nameAndSecurityLayout = new QHBoxLayout(); + nameAndSecurityLayout->setContentsMargins(4,0,0,0); + + nameWidget_ = new QtNameWidget(settings, this); + connect(nameWidget_, SIGNAL(onChangeNickRequest()), this, SIGNAL(onEditProfileRequest())); + nameAndSecurityLayout->addWidget(nameWidget_); + + securityInfoButton_ = new QToolButton(this); + securityInfoButton_->setStyleSheet("QToolButton { border: none; } QToolButton:hover { border: 1px solid #bebebe; } QToolButton:pressed { border: 1px solid #757575; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #777777, stop: 1 #d4d4d4);}"); + //securityInfoButton_->setAutoRaise(true); + securityInfoButton_->setIcon(QIcon(":/icons/lock.png")); + securityInfoButton_->setToolTip(tr("Connection is secured")); + connect(securityInfoButton_, SIGNAL(clicked()), this, SIGNAL(onShowCertificateInfo())); + nameAndSecurityLayout->addWidget(securityInfoButton_); + + rightLayout->addLayout(nameAndSecurityLayout); + + statusWidget_ = new QtStatusWidget(statusCache, this); + connect(statusWidget_, SIGNAL(onChangeStatusRequest(StatusShow::Type, const QString&)), this, SLOT(handleChangeStatusRequest(StatusShow::Type, const QString&))); + rightLayout->addWidget(statusWidget_); + + show(); } void QtRosterHeader::handleChangeStatusRequest(StatusShow::Type type, const QString& text) { - emit onChangeStatusRequest(type, text); + emit onChangeStatusRequest(type, text); } void QtRosterHeader::setStatusText(const QString& statusMessage) { - statusWidget_->setStatusText(statusMessage); + statusWidget_->setStatusText(statusMessage); } void QtRosterHeader::setStatusType(StatusShow::Type type) { - statusWidget_->setStatusType(type); - if (type == StatusShow::None) { - nameWidget_->setOnline(false); - disconnect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest())); - } - else { - nameWidget_->setOnline(true); - connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()), Qt::UniqueConnection); - } + statusWidget_->setStatusType(type); + if (type == StatusShow::None) { + nameWidget_->setOnline(false); + disconnect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest())); + } + else { + nameWidget_->setOnline(true); + connect(avatarLabel_, SIGNAL(clicked()), this, SIGNAL(onEditProfileRequest()), Qt::UniqueConnection); + } } void QtRosterHeader::setConnecting() { - statusWidget_->setConnecting(); + statusWidget_->setConnecting(); } void QtRosterHeader::setStreamEncryptionStatus(bool tlsInPlace) { - securityInfoButton_->setVisible(tlsInPlace); + securityInfoButton_->setVisible(tlsInPlace); } bool QtRosterHeader::event(QEvent* event) { - if (event->type() == QEvent::ToolTip) { - QHelpEvent *helpEvent = static_cast(event); - QtScaledAvatarCache scaledAvatarCache(avatarSize_); - QString text = RosterTooltip::buildDetailedTooltip(contact_.get(), &scaledAvatarCache); - QToolTip::showText(helpEvent->globalPos(), text); - return true; - } - return QWidget::event(event); + if (event->type() == QEvent::ToolTip) { + QHelpEvent *helpEvent = static_cast(event); + QtScaledAvatarCache scaledAvatarCache(avatarSize_); + QString text = RosterTooltip::buildDetailedTooltip(contact_.get(), &scaledAvatarCache); + QToolTip::showText(helpEvent->globalPos(), text); + return true; + } + return QWidget::event(event); } void QtRosterHeader::setAvatar(const QString& path) { - QString scaledAvatarPath = QtScaledAvatarCache(avatarSize_).getScaledAvatarPath(path); - QPixmap avatar; - if (QFileInfo(scaledAvatarPath).exists()) { - avatar.load(scaledAvatarPath); - } - else { - avatar = QPixmap(":/icons/avatar.png").scaled(avatarSize_, avatarSize_, Qt::KeepAspectRatio, Qt::SmoothTransformation); - } - avatarLabel_->setPixmap(avatar); + QString scaledAvatarPath = QtScaledAvatarCache(avatarSize_).getScaledAvatarPath(path); + QPixmap avatar; + if (QFileInfo(scaledAvatarPath).exists()) { + avatar.load(scaledAvatarPath); + } + else { + avatar = QPixmap(":/icons/avatar.png").scaled(avatarSize_, avatarSize_, Qt::KeepAspectRatio, Qt::SmoothTransformation); + } + avatarLabel_->setPixmap(avatar); } void QtRosterHeader::setNick(const QString& nick) { - nameWidget_->setNick(nick); + nameWidget_->setNick(nick); } void QtRosterHeader::setContactRosterItem(boost::shared_ptr contact) { - contact_ = contact; + contact_ = contact; } void QtRosterHeader::setJID(const QString& jid) { - nameWidget_->setJID(jid); + nameWidget_->setJID(jid); } diff --git a/Swift/QtUI/QtRosterHeader.h b/Swift/QtUI/QtRosterHeader.h index 49c3338..b556504 100644 --- a/Swift/QtUI/QtRosterHeader.h +++ b/Swift/QtUI/QtRosterHeader.h @@ -24,43 +24,43 @@ class QHBoxLayout; namespace Swift { - class QtClickableLabel; - class QtStatusWidget; - class QtNameWidget; - class SettingsProvider; - class StatusCache; - - class QtRosterHeader : public QWidget { - Q_OBJECT - public: - QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = NULL); - void setAvatar(const QString& path); + class QtClickableLabel; + class QtStatusWidget; + class QtNameWidget; + class SettingsProvider; + class StatusCache; - void setJID(const QString& jid); - void setNick(const QString& nick); - void setContactRosterItem(boost::shared_ptr contact); + class QtRosterHeader : public QWidget { + Q_OBJECT + public: + QtRosterHeader(SettingsProvider* settings, StatusCache* statusCache, QWidget* parent = NULL); + void setAvatar(const QString& path); - void setStatusText(const QString& statusMessage); - void setStatusType(StatusShow::Type type); - void setConnecting(); - void setStreamEncryptionStatus(bool tlsInPlace); - private: - bool event(QEvent* event); - signals: - void onChangeStatusRequest(StatusShow::Type showType, const QString &statusMessage); - void onEditProfileRequest(); - void onShowCertificateInfo(); + void setJID(const QString& jid); + void setNick(const QString& nick); + void setContactRosterItem(boost::shared_ptr contact); - private slots: - void handleChangeStatusRequest(StatusShow::Type type, const QString &statusMessage); - private: - QString name_; - QtClickableLabel* avatarLabel_; - QtNameWidget* nameWidget_; - QtTextEdit* statusEdit_; - QtStatusWidget* statusWidget_; - QToolButton* securityInfoButton_; - static const int avatarSize_; - boost::shared_ptr contact_; - }; + void setStatusText(const QString& statusMessage); + void setStatusType(StatusShow::Type type); + void setConnecting(); + void setStreamEncryptionStatus(bool tlsInPlace); + private: + bool event(QEvent* event); + signals: + void onChangeStatusRequest(StatusShow::Type showType, const QString &statusMessage); + void onEditProfileRequest(); + void onShowCertificateInfo(); + + private slots: + void handleChangeStatusRequest(StatusShow::Type type, const QString &statusMessage); + private: + QString name_; + QtClickableLabel* avatarLabel_; + QtNameWidget* nameWidget_; + QtTextEdit* statusEdit_; + QtStatusWidget* statusWidget_; + QToolButton* securityInfoButton_; + static const int avatarSize_; + boost::shared_ptr contact_; + }; } diff --git a/Swift/QtUI/QtScaledAvatarCache.cpp b/Swift/QtUI/QtScaledAvatarCache.cpp index 9668336..6d683bd 100644 --- a/Swift/QtUI/QtScaledAvatarCache.cpp +++ b/Swift/QtUI/QtScaledAvatarCache.cpp @@ -24,39 +24,39 @@ QtScaledAvatarCache::QtScaledAvatarCache(int size) : size(size) { } QString QtScaledAvatarCache::getScaledAvatarPath(const QString& path) { - QFileInfo avatarFile(path); - if (avatarFile.exists()) { - if (!avatarFile.dir().exists(QString::number(size))) { - if (!avatarFile.dir().mkdir(QString::number(size))) { - return path; - } - } - QDir targetDir(avatarFile.dir().absoluteFilePath(QString::number(size))); - QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName()); - if (!QFileInfo(targetFile).exists()) { - QPixmap avatarPixmap; - if (avatarPixmap.load(path)) { - QPixmap maskedAvatar(avatarPixmap.size()); - maskedAvatar.fill(QColor(0, 0, 0, 0)); - QPainter maskPainter(&maskedAvatar); - maskPainter.setBrush(Qt::black); - maskPainter.drawRoundedRect(maskedAvatar.rect(), 25.0, 25.0, Qt::RelativeSize); - maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); - maskPainter.drawPixmap(0, 0, avatarPixmap); - maskPainter.end(); - - if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) { - return path; - } - } else { - SWIFT_LOG(debug) << "Failed to load " << Q2PSTRING(path) << std::endl; - } - } - return targetFile; - } - else { - return path; - } + QFileInfo avatarFile(path); + if (avatarFile.exists()) { + if (!avatarFile.dir().exists(QString::number(size))) { + if (!avatarFile.dir().mkdir(QString::number(size))) { + return path; + } + } + QDir targetDir(avatarFile.dir().absoluteFilePath(QString::number(size))); + QString targetFile = targetDir.absoluteFilePath(avatarFile.baseName()); + if (!QFileInfo(targetFile).exists()) { + QPixmap avatarPixmap; + if (avatarPixmap.load(path)) { + QPixmap maskedAvatar(avatarPixmap.size()); + maskedAvatar.fill(QColor(0, 0, 0, 0)); + QPainter maskPainter(&maskedAvatar); + maskPainter.setBrush(Qt::black); + maskPainter.drawRoundedRect(maskedAvatar.rect(), 25.0, 25.0, Qt::RelativeSize); + maskPainter.setCompositionMode(QPainter::CompositionMode_SourceIn); + maskPainter.drawPixmap(0, 0, avatarPixmap); + maskPainter.end(); + + if (!maskedAvatar.scaled(size, size, Qt::KeepAspectRatio, Qt::SmoothTransformation).save(targetFile, "PNG")) { + return path; + } + } else { + SWIFT_LOG(debug) << "Failed to load " << Q2PSTRING(path) << std::endl; + } + } + return targetFile; + } + else { + return path; + } } diff --git a/Swift/QtUI/QtScaledAvatarCache.h b/Swift/QtUI/QtScaledAvatarCache.h index 4ee583d..748fb40 100644 --- a/Swift/QtUI/QtScaledAvatarCache.h +++ b/Swift/QtUI/QtScaledAvatarCache.h @@ -11,13 +11,13 @@ #include namespace Swift { - class QtScaledAvatarCache { - public: - QtScaledAvatarCache(int size); + class QtScaledAvatarCache { + public: + QtScaledAvatarCache(int size); - QString getScaledAvatarPath(const QString& path); + QString getScaledAvatarPath(const QString& path); - private: - int size; - }; + private: + int size; + }; } diff --git a/Swift/QtUI/QtSettingsProvider.cpp b/Swift/QtUI/QtSettingsProvider.cpp index d60fa2b..3c32dc8 100644 --- a/Swift/QtUI/QtSettingsProvider.cpp +++ b/Swift/QtUI/QtSettingsProvider.cpp @@ -19,105 +19,105 @@ QtSettingsProvider::~QtSettingsProvider() { } bool QtSettingsProvider::hasSetting(const std::string& key) { - return !settings_.value(key.c_str()).isNull(); + return !settings_.value(key.c_str()).isNull(); } std::string QtSettingsProvider::getSetting(const Setting& setting) { - QVariant variant = settings_.value(setting.getKey().c_str()); - return variant.isNull() ? setting.getDefaultValue() : std::string(variant.toString().toUtf8()); + QVariant variant = settings_.value(setting.getKey().c_str()); + return variant.isNull() ? setting.getDefaultValue() : std::string(variant.toString().toUtf8()); } void QtSettingsProvider::storeSetting(const Setting& setting, const std::string& settingValue) { - bool changed = false; - if (getSetting(setting) != settingValue) { - changed = true; - } - settings_.setValue(setting.getKey().c_str(), settingValue.c_str()); - if (changed) { - onSettingChanged(setting.getKey()); - } - updatePermissions(); + bool changed = false; + if (getSetting(setting) != settingValue) { + changed = true; + } + settings_.setValue(setting.getKey().c_str(), settingValue.c_str()); + if (changed) { + onSettingChanged(setting.getKey()); + } + updatePermissions(); } bool QtSettingsProvider::getSetting(const Setting& setting) { - QVariant variant = settings_.value(setting.getKey().c_str()); - return variant.isNull() ? setting.getDefaultValue() : variant.toBool(); + QVariant variant = settings_.value(setting.getKey().c_str()); + return variant.isNull() ? setting.getDefaultValue() : variant.toBool(); } void QtSettingsProvider::storeSetting(const Setting& setting, const bool& settingValue) { - bool changed = false; - if (getSetting(setting) != settingValue) { - changed = true; - } - settings_.setValue(setting.getKey().c_str(), settingValue); - if (changed) { - onSettingChanged(setting.getKey()); - } - updatePermissions(); + bool changed = false; + if (getSetting(setting) != settingValue) { + changed = true; + } + settings_.setValue(setting.getKey().c_str(), settingValue); + if (changed) { + onSettingChanged(setting.getKey()); + } + updatePermissions(); } int QtSettingsProvider::getSetting(const Setting& setting) { - QVariant variant = settings_.value(setting.getKey().c_str()); - return variant.isNull() ? setting.getDefaultValue() : variant.toInt(); + QVariant variant = settings_.value(setting.getKey().c_str()); + return variant.isNull() ? setting.getDefaultValue() : variant.toInt(); } void QtSettingsProvider::storeSetting(const Setting& setting, const int& settingValue) { - bool changed = false; - if (getSetting(setting) != settingValue) { - changed = true; - } - settings_.setValue(setting.getKey().c_str(), settingValue); - if (changed) { - onSettingChanged(setting.getKey()); - } - updatePermissions(); + bool changed = false; + if (getSetting(setting) != settingValue) { + changed = true; + } + settings_.setValue(setting.getKey().c_str(), settingValue); + if (changed) { + onSettingChanged(setting.getKey()); + } + updatePermissions(); } std::vector QtSettingsProvider::getAvailableProfiles() { - std::vector profiles; - QVariant profilesVariant = settings_.value("profileList"); - foreach(QString profileQString, profilesVariant.toStringList()) { - profiles.push_back(std::string(profileQString.toUtf8())); - } - return profiles; + std::vector profiles; + QVariant profilesVariant = settings_.value("profileList"); + foreach(QString profileQString, profilesVariant.toStringList()) { + profiles.push_back(std::string(profileQString.toUtf8())); + } + return profiles; } void QtSettingsProvider::createProfile(const std::string& profile) { - QStringList stringList = settings_.value("profileList").toStringList(); - stringList.append(profile.c_str()); - settings_.setValue("profileList", stringList); - updatePermissions(); + QStringList stringList = settings_.value("profileList").toStringList(); + stringList.append(profile.c_str()); + settings_.setValue("profileList", stringList); + updatePermissions(); } void QtSettingsProvider::removeProfile(const std::string& profile) { - QString profileStart(QString(profile.c_str()) + ":"); - foreach (QString key, settings_.allKeys()) { - if (key.startsWith(profileStart)) { - settings_.remove(key); - } - } - QStringList stringList = settings_.value("profileList").toStringList(); - stringList.removeAll(profile.c_str()); - settings_.setValue("profileList", stringList); - updatePermissions(); + QString profileStart(QString(profile.c_str()) + ":"); + foreach (QString key, settings_.allKeys()) { + if (key.startsWith(profileStart)) { + settings_.remove(key); + } + } + QStringList stringList = settings_.value("profileList").toStringList(); + stringList.removeAll(profile.c_str()); + settings_.setValue("profileList", stringList); + updatePermissions(); } QSettings* QtSettingsProvider::getQSettings() { - return &settings_; + return &settings_; } void QtSettingsProvider::updatePermissions() { #if !defined(Q_OS_WIN) && !defined(Q_OS_MAC) - QFile file(settings_.fileName()); - if (file.exists()) { - file.setPermissions(QFile::ReadOwner|QFile::WriteOwner); - } + QFile file(settings_.fileName()); + if (file.exists()) { + file.setPermissions(QFile::ReadOwner|QFile::WriteOwner); + } #endif } bool QtSettingsProvider::getIsSettingFinal(const std::string& /*settingPath*/) { - return false; + return false; } } diff --git a/Swift/QtUI/QtSettingsProvider.h b/Swift/QtUI/QtSettingsProvider.h index 06984f5..21e9211 100644 --- a/Swift/QtUI/QtSettingsProvider.h +++ b/Swift/QtUI/QtSettingsProvider.h @@ -13,28 +13,28 @@ namespace Swift { class QtSettingsProvider : public SettingsProvider { - public: - QtSettingsProvider(); - virtual ~QtSettingsProvider(); - virtual std::string getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const std::string& value); - virtual bool getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const bool& value); - virtual int getSetting(const Setting& setting); - virtual void storeSetting(const Setting& setting, const int& value); - virtual std::vector getAvailableProfiles(); - virtual void createProfile(const std::string& profile); - virtual void removeProfile(const std::string& profile); - virtual bool hasSetting(const std::string& key); - QSettings* getQSettings(); - protected: - virtual bool getIsSettingFinal(const std::string& settingPath); - - private: - void updatePermissions(); - - private: - QSettings settings_; + public: + QtSettingsProvider(); + virtual ~QtSettingsProvider(); + virtual std::string getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const std::string& value); + virtual bool getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const bool& value); + virtual int getSetting(const Setting& setting); + virtual void storeSetting(const Setting& setting, const int& value); + virtual std::vector getAvailableProfiles(); + virtual void createProfile(const std::string& profile); + virtual void removeProfile(const std::string& profile); + virtual bool hasSetting(const std::string& key); + QSettings* getQSettings(); + protected: + virtual bool getIsSettingFinal(const std::string& settingPath); + + private: + void updatePermissions(); + + private: + QSettings settings_; }; } diff --git a/Swift/QtUI/QtSingleWindow.cpp b/Swift/QtUI/QtSingleWindow.cpp index 8613d62..db7f7dc 100644 --- a/Swift/QtUI/QtSingleWindow.cpp +++ b/Swift/QtUI/QtSingleWindow.cpp @@ -17,13 +17,13 @@ static const QString SINGLE_WINDOW_GEOMETRY = QString("SINGLE_WINDOW_GEOMETRY"); static const QString SINGLE_WINDOW_SPLITS = QString("SINGLE_WINDOW_SPLITS"); QtSingleWindow::QtSingleWindow(QtSettingsProvider* settings) : QSplitter() { - settings_ = settings; - QVariant geometryVariant = settings_->getQSettings()->value(SINGLE_WINDOW_GEOMETRY); - if (geometryVariant.isValid()) { - restoreGeometry(geometryVariant.toByteArray()); - } - connect(this, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int))); - restoreSplitters(); + settings_ = settings; + QVariant geometryVariant = settings_->getQSettings()->value(SINGLE_WINDOW_GEOMETRY); + if (geometryVariant.isValid()) { + restoreGeometry(geometryVariant.toByteArray()); + } + connect(this, SIGNAL(splitterMoved(int, int)), this, SLOT(handleSplitterMoved(int, int))); + restoreSplitters(); } QtSingleWindow::~QtSingleWindow() { @@ -31,51 +31,51 @@ QtSingleWindow::~QtSingleWindow() { } void QtSingleWindow::addWidget(QWidget* widget) { - QtChatTabs* tabs = dynamic_cast(widget); - if (tabs) { - connect(tabs, SIGNAL(onTitleChanged(const QString&)), this, SLOT(handleTabsTitleChanged(const QString&))); - } - QSplitter::addWidget(widget); + QtChatTabs* tabs = dynamic_cast(widget); + if (tabs) { + connect(tabs, SIGNAL(onTitleChanged(const QString&)), this, SLOT(handleTabsTitleChanged(const QString&))); + } + QSplitter::addWidget(widget); } void QtSingleWindow::handleTabsTitleChanged(const QString& title) { - setWindowTitle(title); + setWindowTitle(title); } void QtSingleWindow::handleSplitterMoved(int, int) { - QList variantValues; - QList intValues = sizes(); - foreach (int value, intValues) { - variantValues.append(QVariant(value)); - } - settings_->getQSettings()->setValue(SINGLE_WINDOW_SPLITS, QVariant(variantValues)); + QList variantValues; + QList intValues = sizes(); + foreach (int value, intValues) { + variantValues.append(QVariant(value)); + } + settings_->getQSettings()->setValue(SINGLE_WINDOW_SPLITS, QVariant(variantValues)); } void QtSingleWindow::restoreSplitters() { - QList variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList(); - QList intValues; - foreach (QVariant value, variantValues) { - intValues.append(value.toInt()); - } - setSizes(intValues); + QList variantValues = settings_->getQSettings()->value(SINGLE_WINDOW_SPLITS).toList(); + QList intValues; + foreach (QVariant value, variantValues) { + intValues.append(value.toInt()); + } + setSizes(intValues); } void QtSingleWindow::insertAtFront(QWidget* widget) { - insertWidget(0, widget); - restoreSplitters(); + insertWidget(0, widget); + restoreSplitters(); } void QtSingleWindow::handleGeometryChanged() { - settings_->getQSettings()->setValue(SINGLE_WINDOW_GEOMETRY, saveGeometry()); + settings_->getQSettings()->setValue(SINGLE_WINDOW_GEOMETRY, saveGeometry()); } void QtSingleWindow::resizeEvent(QResizeEvent*) { - handleGeometryChanged(); + handleGeometryChanged(); } void QtSingleWindow::moveEvent(QMoveEvent*) { - handleGeometryChanged(); + handleGeometryChanged(); } } diff --git a/Swift/QtUI/QtSingleWindow.h b/Swift/QtUI/QtSingleWindow.h index e430c56..804be65 100644 --- a/Swift/QtUI/QtSingleWindow.h +++ b/Swift/QtUI/QtSingleWindow.h @@ -9,29 +9,29 @@ #include namespace Swift { - class QtSettingsProvider; - - class QtSingleWindow : public QSplitter { - Q_OBJECT - public: - QtSingleWindow(QtSettingsProvider* settings); - virtual ~QtSingleWindow(); - void insertAtFront(QWidget* widget); - void addWidget(QWidget* widget); - protected: - void resizeEvent(QResizeEvent*); - void moveEvent(QMoveEvent*); - private slots: - void handleSplitterMoved(int, int); - void handleTabsTitleChanged(const QString& title); - private: - void handleGeometryChanged(); - void restoreSplitters(); - - private: - - QtSettingsProvider* settings_; - }; + class QtSettingsProvider; + + class QtSingleWindow : public QSplitter { + Q_OBJECT + public: + QtSingleWindow(QtSettingsProvider* settings); + virtual ~QtSingleWindow(); + void insertAtFront(QWidget* widget); + void addWidget(QWidget* widget); + protected: + void resizeEvent(QResizeEvent*); + void moveEvent(QMoveEvent*); + private slots: + void handleSplitterMoved(int, int); + void handleTabsTitleChanged(const QString& title); + private: + void handleGeometryChanged(); + void restoreSplitters(); + + private: + + QtSettingsProvider* settings_; + }; } diff --git a/Swift/QtUI/QtSoundPlayer.cpp b/Swift/QtUI/QtSoundPlayer.cpp index f047427..22f544d 100644 --- a/Swift/QtUI/QtSoundPlayer.cpp +++ b/Swift/QtUI/QtSoundPlayer.cpp @@ -17,30 +17,30 @@ #include namespace Swift { - + QtSoundPlayer::QtSoundPlayer(ApplicationPathProvider* applicationPathProvider) : applicationPathProvider(applicationPathProvider) { } void QtSoundPlayer::playSound(SoundEffect sound, const std::string& soundResource) { - switch (sound) { - case MessageReceived: - playSound(soundResource.empty() ? "/sounds/message-received.wav" : soundResource); - break; - } + switch (sound) { + case MessageReceived: + playSound(soundResource.empty() ? "/sounds/message-received.wav" : soundResource); + break; + } } void QtSoundPlayer::playSound(const std::string& soundResource) { - boost::filesystem::path resourcePath = applicationPathProvider->getResourcePath(soundResource); - if (boost::filesystem::exists(resourcePath)) { - QSound::play(P2QSTRING(pathToString(resourcePath))); - } - else if (boost::filesystem::exists(soundResource)) { - QSound::play(P2QSTRING(soundResource)); - } - else { - std::cerr << "Unable to find sound: " << soundResource << std::endl; - } + boost::filesystem::path resourcePath = applicationPathProvider->getResourcePath(soundResource); + if (boost::filesystem::exists(resourcePath)) { + QSound::play(P2QSTRING(pathToString(resourcePath))); + } + else if (boost::filesystem::exists(soundResource)) { + QSound::play(P2QSTRING(soundResource)); + } + else { + std::cerr << "Unable to find sound: " << soundResource << std::endl; + } } } diff --git a/Swift/QtUI/QtSoundPlayer.h b/Swift/QtUI/QtSoundPlayer.h index e34529e..8a0b8fe 100644 --- a/Swift/QtUI/QtSoundPlayer.h +++ b/Swift/QtUI/QtSoundPlayer.h @@ -11,20 +11,20 @@ #include namespace Swift { - class ApplicationPathProvider; - + class ApplicationPathProvider; - class QtSoundPlayer : public QObject, public SoundPlayer { - Q_OBJECT - public: - QtSoundPlayer(ApplicationPathProvider* applicationPathProvider); - void playSound(SoundEffect sound, const std::string& soundResource); + class QtSoundPlayer : public QObject, public SoundPlayer { + Q_OBJECT + public: + QtSoundPlayer(ApplicationPathProvider* applicationPathProvider); - private: - void playSound(const std::string& soundResource); + void playSound(SoundEffect sound, const std::string& soundResource); - private: - ApplicationPathProvider* applicationPathProvider; - }; + private: + void playSound(const std::string& soundResource); + + private: + ApplicationPathProvider* applicationPathProvider; + }; } diff --git a/Swift/QtUI/QtSpellCheckHighlighter.cpp b/Swift/QtUI/QtSpellCheckHighlighter.cpp index 0112d7a..6565b06 100644 --- a/Swift/QtUI/QtSpellCheckHighlighter.cpp +++ b/Swift/QtUI/QtSpellCheckHighlighter.cpp @@ -21,21 +21,21 @@ QtSpellCheckHighlighter::~QtSpellCheckHighlighter() { } void QtSpellCheckHighlighter::highlightBlock(const QString& text) { - misspelledPositions_.clear(); - std::string fragment = Q2PSTRING(text); - checker_->checkFragment(fragment, misspelledPositions_); + misspelledPositions_.clear(); + std::string fragment = Q2PSTRING(text); + checker_->checkFragment(fragment, misspelledPositions_); - QTextCharFormat spellingErrorFormat; - spellingErrorFormat.setUnderlineColor(QColor(Qt::red)); - spellingErrorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); + QTextCharFormat spellingErrorFormat; + spellingErrorFormat.setUnderlineColor(QColor(Qt::red)); + spellingErrorFormat.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); - foreach (PositionPair position, misspelledPositions_) { - setFormat(boost::get<0>(position), boost::get<1>(position) - boost::get<0>(position), spellingErrorFormat); - }; + foreach (PositionPair position, misspelledPositions_) { + setFormat(boost::get<0>(position), boost::get<1>(position) - boost::get<0>(position), spellingErrorFormat); + }; } PositionPairList QtSpellCheckHighlighter::getMisspelledPositions() const { - return misspelledPositions_; + return misspelledPositions_; } } diff --git a/Swift/QtUI/QtSpellCheckHighlighter.h b/Swift/QtUI/QtSpellCheckHighlighter.h index 7fa48de..5519a1d 100644 --- a/Swift/QtUI/QtSpellCheckHighlighter.h +++ b/Swift/QtUI/QtSpellCheckHighlighter.h @@ -18,20 +18,20 @@ namespace Swift { class SpellChecker; class QtSpellCheckHighlighter : public QSyntaxHighlighter { - Q_OBJECT + Q_OBJECT public: - QtSpellCheckHighlighter(QTextDocument* parent, SpellChecker* spellChecker); - virtual ~QtSpellCheckHighlighter(); + QtSpellCheckHighlighter(QTextDocument* parent, SpellChecker* spellChecker); + virtual ~QtSpellCheckHighlighter(); - PositionPairList getMisspelledPositions() const; + PositionPairList getMisspelledPositions() const; protected: - virtual void highlightBlock(const QString& text); + virtual void highlightBlock(const QString& text); private: - SpellChecker* checker_; - PositionPairList misspelledPositions_; + SpellChecker* checker_; + PositionPairList misspelledPositions_; }; diff --git a/Swift/QtUI/QtSpellCheckerWindow.cpp b/Swift/QtUI/QtSpellCheckerWindow.cpp index ba4dbd3..9232b19 100644 --- a/Swift/QtUI/QtSpellCheckerWindow.cpp +++ b/Swift/QtUI/QtSpellCheckerWindow.cpp @@ -27,96 +27,96 @@ namespace Swift { QtSpellCheckerWindow::QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent) : QDialog(parent) { - settings_ = settings; - ui_.setupUi(this); + settings_ = settings; + ui_.setupUi(this); #ifdef HAVE_HUNSPELL - ui_.hunspellOptions->show(); + ui_.hunspellOptions->show(); #else - ui_.hunspellOptions->hide(); - QTimer::singleShot(0, this, SLOT(shrinkWindow())); + ui_.hunspellOptions->hide(); + QTimer::singleShot(0, this, SLOT(shrinkWindow())); #endif - connect(ui_.spellChecker, SIGNAL(toggled(bool)), this, SLOT(handleChecker(bool))); - connect(ui_.cancel, SIGNAL(clicked()), this, SLOT(handleCancel())); - connect(ui_.apply, SIGNAL(clicked()), this, SLOT(handleApply())); - connect(ui_.pathButton, SIGNAL(clicked()), this, SLOT(handlePathButton())); - setFromSettings(); + connect(ui_.spellChecker, SIGNAL(toggled(bool)), this, SLOT(handleChecker(bool))); + connect(ui_.cancel, SIGNAL(clicked()), this, SLOT(handleCancel())); + connect(ui_.apply, SIGNAL(clicked()), this, SLOT(handleApply())); + connect(ui_.pathButton, SIGNAL(clicked()), this, SLOT(handlePathButton())); + setFromSettings(); } void QtSpellCheckerWindow::shrinkWindow() { - resize(0,0); + resize(0,0); } void QtSpellCheckerWindow::setFromSettings() { - ui_.spellChecker->setChecked(settings_->getSetting(SettingConstants::SPELL_CHECKER)); - ui_.pathContent->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_PATH))); - ui_.currentLanguageValue->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_FILE))); - std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH); - QString filename = "*.dic"; - QDir dictDirectory = QDir(P2QSTRING(currentPath)); - QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files); - showFiles(files); - setEnabled(settings_->getSetting(SettingConstants::SPELL_CHECKER)); + ui_.spellChecker->setChecked(settings_->getSetting(SettingConstants::SPELL_CHECKER)); + ui_.pathContent->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_PATH))); + ui_.currentLanguageValue->setText(P2QSTRING(settings_->getSetting(SettingConstants::DICT_FILE))); + std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH); + QString filename = "*.dic"; + QDir dictDirectory = QDir(P2QSTRING(currentPath)); + QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files); + showFiles(files); + setEnabled(settings_->getSetting(SettingConstants::SPELL_CHECKER)); } void QtSpellCheckerWindow::handleChecker(bool state) { - setEnabled(state); + setEnabled(state); } void QtSpellCheckerWindow::setEnabled(bool state) { - ui_.pathContent->setEnabled(state); - ui_.languageView->setEnabled(state); - ui_.pathButton->setEnabled(state); - ui_.pathLabel->setEnabled(state); - ui_.currentLanguage->setEnabled(state); - ui_.currentLanguageValue->setEnabled(state); - ui_.language->setEnabled(state); + ui_.pathContent->setEnabled(state); + ui_.languageView->setEnabled(state); + ui_.pathButton->setEnabled(state); + ui_.pathLabel->setEnabled(state); + ui_.currentLanguage->setEnabled(state); + ui_.currentLanguageValue->setEnabled(state); + ui_.language->setEnabled(state); } void QtSpellCheckerWindow::handleApply() { - settings_->storeSetting(SettingConstants::SPELL_CHECKER, ui_.spellChecker->isChecked()); - QList selectedLanguage = ui_.languageView->selectedItems(); - if (!selectedLanguage.empty()) { - settings_->storeSetting(SettingConstants::DICT_FILE, Q2PSTRING((selectedLanguage.first())->text())); - } - this->done(0); + settings_->storeSetting(SettingConstants::SPELL_CHECKER, ui_.spellChecker->isChecked()); + QList selectedLanguage = ui_.languageView->selectedItems(); + if (!selectedLanguage.empty()) { + settings_->storeSetting(SettingConstants::DICT_FILE, Q2PSTRING((selectedLanguage.first())->text())); + } + this->done(0); } void QtSpellCheckerWindow::handleCancel() { - this->done(0); + this->done(0); } void QtSpellCheckerWindow::handlePathButton() { - std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH); - QString dirpath = QFileDialog::getExistingDirectory(this, tr("Dictionary Path"), P2QSTRING(currentPath)); - if (dirpath != P2QSTRING(currentPath)) { - ui_.languageView->clear(); - settings_->storeSetting(SettingConstants::DICT_FILE, ""); - ui_.currentLanguageValue->setText(" "); - } - if (!dirpath.isEmpty()) { - if (!dirpath.endsWith("/")) { - dirpath.append("/"); - } - settings_->storeSetting(SettingConstants::DICT_PATH, Q2PSTRING(dirpath)); - QDir dictDirectory = QDir(dirpath); - ui_.pathContent->setText(dirpath); - QString filename = "*.dic"; - QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files); - showFiles(files); - } + std::string currentPath = settings_->getSetting(SettingConstants::DICT_PATH); + QString dirpath = QFileDialog::getExistingDirectory(this, tr("Dictionary Path"), P2QSTRING(currentPath)); + if (dirpath != P2QSTRING(currentPath)) { + ui_.languageView->clear(); + settings_->storeSetting(SettingConstants::DICT_FILE, ""); + ui_.currentLanguageValue->setText(" "); + } + if (!dirpath.isEmpty()) { + if (!dirpath.endsWith("/")) { + dirpath.append("/"); + } + settings_->storeSetting(SettingConstants::DICT_PATH, Q2PSTRING(dirpath)); + QDir dictDirectory = QDir(dirpath); + ui_.pathContent->setText(dirpath); + QString filename = "*.dic"; + QStringList files = dictDirectory.entryList(QStringList(filename), QDir::Files); + showFiles(files); + } } void QtSpellCheckerWindow::handlePersonalPathButton() { - std::string currentPath = settings_->getSetting(SettingConstants::PERSONAL_DICT_PATH); - QString filename = QFileDialog::getOpenFileName(this, tr("Select Personal Dictionary"), P2QSTRING(currentPath), tr("(*.dic")); - settings_->storeSetting(SettingConstants::PERSONAL_DICT_PATH, Q2PSTRING(filename)); + std::string currentPath = settings_->getSetting(SettingConstants::PERSONAL_DICT_PATH); + QString filename = QFileDialog::getOpenFileName(this, tr("Select Personal Dictionary"), P2QSTRING(currentPath), tr("(*.dic")); + settings_->storeSetting(SettingConstants::PERSONAL_DICT_PATH, Q2PSTRING(filename)); } void QtSpellCheckerWindow::showFiles(const QStringList& files) { - ui_.languageView->clear(); - for (int i = 0; i < files.size(); ++i) { - ui_.languageView->insertItem(i, files[i]); - } + ui_.languageView->clear(); + for (int i = 0; i < files.size(); ++i) { + ui_.languageView->insertItem(i, files[i]); + } } } diff --git a/Swift/QtUI/QtSpellCheckerWindow.h b/Swift/QtUI/QtSpellCheckerWindow.h index 0e43ddd..95e0725 100644 --- a/Swift/QtUI/QtSpellCheckerWindow.h +++ b/Swift/QtUI/QtSpellCheckerWindow.h @@ -17,24 +17,24 @@ #include namespace Swift { - class SettingsProvider; - class QtSpellCheckerWindow : public QDialog, protected Ui::QtSpellCheckerWindow { - Q_OBJECT - public: - QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent = NULL); - public slots: - void handleChecker(bool state); - void handleCancel(); - void handlePathButton(); - void handlePersonalPathButton(); - void handleApply(); - private slots: - void shrinkWindow(); - private: - void setEnabled(bool state); - void setFromSettings(); - void showFiles(const QStringList& files); - SettingsProvider* settings_; - Ui::QtSpellCheckerWindow ui_; - }; + class SettingsProvider; + class QtSpellCheckerWindow : public QDialog, protected Ui::QtSpellCheckerWindow { + Q_OBJECT + public: + QtSpellCheckerWindow(SettingsProvider* settings, QWidget* parent = NULL); + public slots: + void handleChecker(bool state); + void handleCancel(); + void handlePathButton(); + void handlePersonalPathButton(); + void handleApply(); + private slots: + void shrinkWindow(); + private: + void setEnabled(bool state); + void setFromSettings(); + void showFiles(const QStringList& files); + SettingsProvider* settings_; + Ui::QtSpellCheckerWindow ui_; + }; } diff --git a/Swift/QtUI/QtStatusWidget.cpp b/Swift/QtUI/QtStatusWidget.cpp index 78b2c5a..2e9e4cc 100644 --- a/Swift/QtUI/QtStatusWidget.cpp +++ b/Swift/QtUI/QtStatusWidget.cpp @@ -37,266 +37,266 @@ namespace lambda = boost::lambda; namespace Swift { QtStatusWidget::QtStatusWidget(StatusCache* statusCache, QWidget *parent) : QWidget(parent), statusCache_(statusCache), editCursor_(Qt::IBeamCursor), viewCursor_(Qt::PointingHandCursor) { - allTypes_.push_back(StatusShow::Online); - allTypes_.push_back(StatusShow::FFC); - allTypes_.push_back(StatusShow::Away); - allTypes_.push_back(StatusShow::XA); - allTypes_.push_back(StatusShow::DND); - allTypes_.push_back(StatusShow::None); - - isClicking_ = false; - connecting_ = false; - setMaximumHeight(24); - - connectingMovie_ = new QMovie(":/icons/connecting.mng"); - - QHBoxLayout* mainLayout = new QHBoxLayout(this); - mainLayout->setSpacing(0); - mainLayout->setContentsMargins(0,0,0,0); - - stack_ = new QStackedWidget(this); - stack_->setLineWidth(2); - stack_->setFrameShape(QFrame::StyledPanel); - mainLayout->addWidget(stack_); - - QWidget* page1 = new QWidget(this); - stack_->addWidget(page1); - QHBoxLayout* page1Layout = new QHBoxLayout(page1); - page1Layout->setSpacing(0); - page1Layout->setContentsMargins(0,0,0,0); - page1->setCursor(viewCursor_); - - statusIcon_ = new QLabel(this); - statusIcon_->setMinimumSize(16, 16); - statusIcon_->setMaximumSize(16, 16); - page1Layout->addWidget(statusIcon_); - - statusTextLabel_ = new QtElidingLabel(this); - QFont font = statusTextLabel_->font(); - font.setItalic(true); - statusTextLabel_->setFont(font); - page1Layout->addWidget(statusTextLabel_); - - icons_[StatusShow::Online] = QIcon(":/icons/online.png"); - icons_[StatusShow::Away] = QIcon(":/icons/away.png"); - icons_[StatusShow::DND] = QIcon(":/icons/dnd.png"); - icons_[StatusShow::None] = QIcon(":/icons/offline.png"); - - setStatusType(StatusShow::None); - - QWidget* page2 = new QWidget(this); - QHBoxLayout* page2Layout = new QHBoxLayout(page2); - page2Layout->setSpacing(0); - page2Layout->setContentsMargins(0,0,0,0); - stack_->addWidget(page2); - - statusEdit_ = new QtLineEdit(this); - page2Layout->addWidget(statusEdit_); - connect(statusEdit_, SIGNAL(returnPressed()), this, SLOT(handleEditComplete())); - connect(statusEdit_, SIGNAL(escapePressed()), this, SLOT(handleEditCancelled())); - connect(statusEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(generateList())); - - setStatusText(""); - - - menu_ = new QListWidget(); - menu_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint ); - menu_->setAlternatingRowColors(true); - menu_->setFocusProxy(statusEdit_); - menu_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - menu_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - QSizePolicy policy(menu_->sizePolicy()); - policy.setVerticalPolicy(QSizePolicy::Expanding); - menu_->setSizePolicy(policy); - - - connect(menu_, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(handleItemClicked(QListWidgetItem*))); - - viewMode(); + allTypes_.push_back(StatusShow::Online); + allTypes_.push_back(StatusShow::FFC); + allTypes_.push_back(StatusShow::Away); + allTypes_.push_back(StatusShow::XA); + allTypes_.push_back(StatusShow::DND); + allTypes_.push_back(StatusShow::None); + + isClicking_ = false; + connecting_ = false; + setMaximumHeight(24); + + connectingMovie_ = new QMovie(":/icons/connecting.mng"); + + QHBoxLayout* mainLayout = new QHBoxLayout(this); + mainLayout->setSpacing(0); + mainLayout->setContentsMargins(0,0,0,0); + + stack_ = new QStackedWidget(this); + stack_->setLineWidth(2); + stack_->setFrameShape(QFrame::StyledPanel); + mainLayout->addWidget(stack_); + + QWidget* page1 = new QWidget(this); + stack_->addWidget(page1); + QHBoxLayout* page1Layout = new QHBoxLayout(page1); + page1Layout->setSpacing(0); + page1Layout->setContentsMargins(0,0,0,0); + page1->setCursor(viewCursor_); + + statusIcon_ = new QLabel(this); + statusIcon_->setMinimumSize(16, 16); + statusIcon_->setMaximumSize(16, 16); + page1Layout->addWidget(statusIcon_); + + statusTextLabel_ = new QtElidingLabel(this); + QFont font = statusTextLabel_->font(); + font.setItalic(true); + statusTextLabel_->setFont(font); + page1Layout->addWidget(statusTextLabel_); + + icons_[StatusShow::Online] = QIcon(":/icons/online.png"); + icons_[StatusShow::Away] = QIcon(":/icons/away.png"); + icons_[StatusShow::DND] = QIcon(":/icons/dnd.png"); + icons_[StatusShow::None] = QIcon(":/icons/offline.png"); + + setStatusType(StatusShow::None); + + QWidget* page2 = new QWidget(this); + QHBoxLayout* page2Layout = new QHBoxLayout(page2); + page2Layout->setSpacing(0); + page2Layout->setContentsMargins(0,0,0,0); + stack_->addWidget(page2); + + statusEdit_ = new QtLineEdit(this); + page2Layout->addWidget(statusEdit_); + connect(statusEdit_, SIGNAL(returnPressed()), this, SLOT(handleEditComplete())); + connect(statusEdit_, SIGNAL(escapePressed()), this, SLOT(handleEditCancelled())); + connect(statusEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(generateList())); + + setStatusText(""); + + + menu_ = new QListWidget(); + menu_->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint ); + menu_->setAlternatingRowColors(true); + menu_->setFocusProxy(statusEdit_); + menu_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + menu_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + QSizePolicy policy(menu_->sizePolicy()); + policy.setVerticalPolicy(QSizePolicy::Expanding); + menu_->setSizePolicy(policy); + + + connect(menu_, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(handleItemClicked(QListWidgetItem*))); + + viewMode(); } QtStatusWidget::~QtStatusWidget() { - delete menu_; - delete connectingMovie_; + delete menu_; + delete connectingMovie_; } void QtStatusWidget::handleApplicationFocusChanged(QWidget* /*old*/, QWidget* /*now*/) { - QWidget* now = qApp->focusWidget(); - if (!editing_ || stack_->currentIndex() == 0) { - return; - } - if (!now || (now != menu_ && now != statusEdit_ && !now->isAncestorOf(statusEdit_) && !now->isAncestorOf(menu_) && !statusEdit_->isAncestorOf(now) && !menu_->isAncestorOf(now))) { - handleEditCancelled(); - } - + QWidget* now = qApp->focusWidget(); + if (!editing_ || stack_->currentIndex() == 0) { + return; + } + if (!now || (now != menu_ && now != statusEdit_ && !now->isAncestorOf(statusEdit_) && !now->isAncestorOf(menu_) && !statusEdit_->isAncestorOf(now) && !menu_->isAncestorOf(now))) { + handleEditCancelled(); + } + } void QtStatusWidget::mousePressEvent(QMouseEvent*) { - if (stack_->currentIndex() == 0) { - handleClicked(); - } + if (stack_->currentIndex() == 0) { + handleClicked(); + } } void QtStatusWidget::generateList() { - if (!editing_) { - return; - } - QString text = statusEdit_->text(); - newStatusText_ = text; - menu_->clear(); - foreach (StatusShow::Type type, icons_.keys()) { - QListWidgetItem* item = new QListWidgetItem(text == "" ? getNoMessage() : text, menu_); - item->setIcon(icons_[type]); - item->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(type)) + ": " + item->text()); - item->setStatusTip(item->toolTip()); - item->setData(Qt::UserRole, QVariant(type)); - } - std::vector previousStatuses = statusCache_->getMatches(Q2PSTRING(text), 8); - foreach (StatusCache::PreviousStatus savedStatus, previousStatuses) { - if (savedStatus.first.empty() || std::find_if(allTypes_.begin(), allTypes_.end(), - savedStatus.second == lambda::_1 && savedStatus.first == lambda::bind(&statusShowTypeToFriendlyName, lambda::_1)) != allTypes_.end()) { - continue; - } - QListWidgetItem* item = new QListWidgetItem(P2QSTRING(savedStatus.first), menu_); - item->setIcon(icons_[savedStatus.second]); - item->setToolTip(item->text()); - item->setStatusTip(item->toolTip()); - item->setData(Qt::UserRole, QVariant(savedStatus.second)); - } - foreach (StatusShow::Type type, icons_.keys()) { - if (Q2PSTRING(text) == statusShowTypeToFriendlyName(type)) { - continue; - } - QListWidgetItem* item = new QListWidgetItem(P2QSTRING(statusShowTypeToFriendlyName(type)), menu_); - item->setIcon(icons_[type]); - item->setToolTip(item->text()); - item->setStatusTip(item->toolTip()); - item->setData(Qt::UserRole, QVariant(type)); - } - resizeMenu(); + if (!editing_) { + return; + } + QString text = statusEdit_->text(); + newStatusText_ = text; + menu_->clear(); + foreach (StatusShow::Type type, icons_.keys()) { + QListWidgetItem* item = new QListWidgetItem(text == "" ? getNoMessage() : text, menu_); + item->setIcon(icons_[type]); + item->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(type)) + ": " + item->text()); + item->setStatusTip(item->toolTip()); + item->setData(Qt::UserRole, QVariant(type)); + } + std::vector previousStatuses = statusCache_->getMatches(Q2PSTRING(text), 8); + foreach (StatusCache::PreviousStatus savedStatus, previousStatuses) { + if (savedStatus.first.empty() || std::find_if(allTypes_.begin(), allTypes_.end(), + savedStatus.second == lambda::_1 && savedStatus.first == lambda::bind(&statusShowTypeToFriendlyName, lambda::_1)) != allTypes_.end()) { + continue; + } + QListWidgetItem* item = new QListWidgetItem(P2QSTRING(savedStatus.first), menu_); + item->setIcon(icons_[savedStatus.second]); + item->setToolTip(item->text()); + item->setStatusTip(item->toolTip()); + item->setData(Qt::UserRole, QVariant(savedStatus.second)); + } + foreach (StatusShow::Type type, icons_.keys()) { + if (Q2PSTRING(text) == statusShowTypeToFriendlyName(type)) { + continue; + } + QListWidgetItem* item = new QListWidgetItem(P2QSTRING(statusShowTypeToFriendlyName(type)), menu_); + item->setIcon(icons_[type]); + item->setToolTip(item->text()); + item->setStatusTip(item->toolTip()); + item->setData(Qt::UserRole, QVariant(type)); + } + resizeMenu(); } void QtStatusWidget::resizeMenu() { - int height = menu_->sizeHintForRow(0) * menu_->count(); - int marginLeft; - int marginTop; - int marginRight; - int marginBottom; - menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom); - height += marginTop + marginBottom; - - menu_->setGeometry(menu_->x(), menu_->y(), menu_->width(), height); + int height = menu_->sizeHintForRow(0) * menu_->count(); + int marginLeft; + int marginTop; + int marginRight; + int marginBottom; + menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom); + height += marginTop + marginBottom; + + menu_->setGeometry(menu_->x(), menu_->y(), menu_->width(), height); } void QtStatusWidget::handleClicked() { - editing_ = true; - QDesktopWidget* desktop = QApplication::desktop(); - int screen = desktop->screenNumber(this); - QPoint point = mapToGlobal(QPoint(0, height())); - QRect geometry = desktop->availableGeometry(screen); - int x = point.x(); - int y = point.y(); - int width = 200; - int height = 80; - - int screenWidth = geometry.x() + geometry.width(); - if (x + width > screenWidth) { - x = screenWidth - width; - } - //foreach (StatusShow::Type type, allTypes_) { - // if (statusEdit_->text() == P2QSTRING(statusShowTypeToFriendlyName(type))) { - statusEdit_->setText(""); - // } - //} - generateList(); - - height = menu_->sizeHintForRow(0) * menu_->count(); - int marginLeft; - int marginTop; - int marginRight; - int marginBottom; - menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom); - height += marginTop + marginBottom; - width += marginLeft + marginRight; - - menu_->setGeometry(x, y, width, height); - menu_->move(x, y); - menu_->setMaximumWidth(width); - menu_->show(); - activateWindow(); - statusEdit_->selectAll(); - stack_->setCurrentIndex(1); - statusEdit_->setFocus(); - connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection); + editing_ = true; + QDesktopWidget* desktop = QApplication::desktop(); + int screen = desktop->screenNumber(this); + QPoint point = mapToGlobal(QPoint(0, height())); + QRect geometry = desktop->availableGeometry(screen); + int x = point.x(); + int y = point.y(); + int width = 200; + int height = 80; + + int screenWidth = geometry.x() + geometry.width(); + if (x + width > screenWidth) { + x = screenWidth - width; + } + //foreach (StatusShow::Type type, allTypes_) { + // if (statusEdit_->text() == P2QSTRING(statusShowTypeToFriendlyName(type))) { + statusEdit_->setText(""); + // } + //} + generateList(); + + height = menu_->sizeHintForRow(0) * menu_->count(); + int marginLeft; + int marginTop; + int marginRight; + int marginBottom; + menu_->getContentsMargins(&marginLeft, &marginTop, &marginRight, &marginBottom); + height += marginTop + marginBottom; + width += marginLeft + marginRight; + + menu_->setGeometry(x, y, width, height); + menu_->move(x, y); + menu_->setMaximumWidth(width); + menu_->show(); + activateWindow(); + statusEdit_->selectAll(); + stack_->setCurrentIndex(1); + statusEdit_->setFocus(); + connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*)), Qt::QueuedConnection); } void QtStatusWidget::viewMode() { - disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*))); - editing_ = false; - menu_->hide(); - stack_->setCurrentIndex(0); + disconnect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(handleApplicationFocusChanged(QWidget*, QWidget*))); + editing_ = false; + menu_->hide(); + stack_->setCurrentIndex(0); } void QtStatusWidget::handleEditComplete() { - editing_ = false; - statusText_ = newStatusText_; - viewMode(); - emit onChangeStatusRequest(selectedStatusType_, statusText_); - statusCache_->addRecent(Q2PSTRING(statusText_), selectedStatusType_); + editing_ = false; + statusText_ = newStatusText_; + viewMode(); + emit onChangeStatusRequest(selectedStatusType_, statusText_); + statusCache_->addRecent(Q2PSTRING(statusText_), selectedStatusType_); } void QtStatusWidget::handleEditCancelled() { - editing_ = false; - setStatusText(statusText_); - viewMode(); + editing_ = false; + setStatusText(statusText_); + viewMode(); } StatusShow::Type QtStatusWidget::getSelectedStatusShow() { - return selectedStatusType_; + return selectedStatusType_; } void QtStatusWidget::handleItemClicked(QListWidgetItem* item) { - editing_ = false; - selectedStatusType_ = static_cast(item->data(Qt::UserRole).toInt()); - QString message = item->data(Qt::DisplayRole).toString(); - newStatusText_ = message == getNoMessage() ? "" : message; - statusEdit_->setText(newStatusText_); - handleEditComplete(); + editing_ = false; + selectedStatusType_ = static_cast(item->data(Qt::UserRole).toInt()); + QString message = item->data(Qt::DisplayRole).toString(); + newStatusText_ = message == getNoMessage() ? "" : message; + statusEdit_->setText(newStatusText_); + handleEditComplete(); } void QtStatusWidget::setNewToolTip() { - if (connecting_) { - statusTextLabel_->setToolTip(tr("Connecting")); - } else { - statusTextLabel_->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(selectedStatusType_)) + ": " + statusTextLabel_->text()); - } + if (connecting_) { + statusTextLabel_->setToolTip(tr("Connecting")); + } else { + statusTextLabel_->setToolTip(P2QSTRING(statusShowTypeToFriendlyName(selectedStatusType_)) + ": " + statusTextLabel_->text()); + } } void QtStatusWidget::setStatusText(const QString& text) { - connectingMovie_->stop(); - statusText_ = text; - statusEdit_->setText(text); - QString escapedText(text.isEmpty() ? getNoMessage() : text); - statusTextLabel_->setText(escapedText); - setNewToolTip(); + connectingMovie_->stop(); + statusText_ = text; + statusEdit_->setText(text); + QString escapedText(text.isEmpty() ? getNoMessage() : text); + statusTextLabel_->setText(escapedText); + setNewToolTip(); } void QtStatusWidget::setConnecting() { - connecting_ = true; - statusIcon_->setMovie(connectingMovie_); - connectingMovie_->start(); - setNewToolTip(); + connecting_ = true; + statusIcon_->setMovie(connectingMovie_); + connectingMovie_->start(); + setNewToolTip(); } void QtStatusWidget::setStatusType(StatusShow::Type type) { - connecting_ = false; - selectedStatusType_ = icons_.contains(type) ? type : StatusShow::Online; - statusIcon_->setPixmap(icons_[selectedStatusType_].pixmap(16, 16)); - setNewToolTip(); + connecting_ = false; + selectedStatusType_ = icons_.contains(type) ? type : StatusShow::Online; + statusIcon_->setPixmap(icons_[selectedStatusType_].pixmap(16, 16)); + setNewToolTip(); } QString QtStatusWidget::getNoMessage() { - return QString(tr("(No message)")); + return QString(tr("(No message)")); } } diff --git a/Swift/QtUI/QtStatusWidget.h b/Swift/QtUI/QtStatusWidget.h index b835490..f346868 100644 --- a/Swift/QtUI/QtStatusWidget.h +++ b/Swift/QtUI/QtStatusWidget.h @@ -20,55 +20,55 @@ class QListWidgetItem; class QMovie; namespace Swift { - class QtLineEdit; - class QtElidingLabel; - class StatusCache; + class QtLineEdit; + class QtElidingLabel; + class StatusCache; - class QtStatusWidget : public QWidget { - Q_OBJECT - public: - QtStatusWidget(StatusCache* statusCache, QWidget *parent); - ~QtStatusWidget(); - StatusShow::Type getSelectedStatusShow(); - void setStatusType(StatusShow::Type type); - void setConnecting(); - signals: - void onChangeStatusRequest(StatusShow::Type showType, const QString& text); - public slots: - void setStatusText(const QString& text); - private slots: - void generateList(); - void handleClicked(); - void handleEditComplete(); - void handleEditCancelled(); - void handleApplicationFocusChanged(QWidget* old, QWidget* now); - protected slots: - virtual void mousePressEvent(QMouseEvent* event); - void handleItemClicked(QListWidgetItem* item); - static QString getNoMessage(); - private: - void resizeMenu(); - void viewMode(); - void setNewToolTip(); - //QComboBox *types_; - StatusCache* statusCache_; - QStackedWidget* stack_; - QLabel* statusIcon_; - QtElidingLabel* statusTextLabel_; - QtLineEdit* statusEdit_; - QString statusText_; - QString newStatusText_; - QMap icons_; - StatusShow::Type selectedStatusType_; - bool isClicking_; - QListWidget* menu_; - QCursor editCursor_; - QCursor viewCursor_; - bool editing_; - QMovie* connectingMovie_; - bool connecting_; - static const QString NO_MESSAGE; - std::vector allTypes_; - }; + class QtStatusWidget : public QWidget { + Q_OBJECT + public: + QtStatusWidget(StatusCache* statusCache, QWidget *parent); + ~QtStatusWidget(); + StatusShow::Type getSelectedStatusShow(); + void setStatusType(StatusShow::Type type); + void setConnecting(); + signals: + void onChangeStatusRequest(StatusShow::Type showType, const QString& text); + public slots: + void setStatusText(const QString& text); + private slots: + void generateList(); + void handleClicked(); + void handleEditComplete(); + void handleEditCancelled(); + void handleApplicationFocusChanged(QWidget* old, QWidget* now); + protected slots: + virtual void mousePressEvent(QMouseEvent* event); + void handleItemClicked(QListWidgetItem* item); + static QString getNoMessage(); + private: + void resizeMenu(); + void viewMode(); + void setNewToolTip(); + //QComboBox *types_; + StatusCache* statusCache_; + QStackedWidget* stack_; + QLabel* statusIcon_; + QtElidingLabel* statusTextLabel_; + QtLineEdit* statusEdit_; + QString statusText_; + QString newStatusText_; + QMap icons_; + StatusShow::Type selectedStatusType_; + bool isClicking_; + QListWidget* menu_; + QCursor editCursor_; + QCursor viewCursor_; + bool editing_; + QMovie* connectingMovie_; + bool connecting_; + static const QString NO_MESSAGE; + std::vector allTypes_; + }; } diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.cpp b/Swift/QtUI/QtSubscriptionRequestWindow.cpp index 43cdb50..9e1fc37 100644 --- a/Swift/QtUI/QtSubscriptionRequestWindow.cpp +++ b/Swift/QtUI/QtSubscriptionRequestWindow.cpp @@ -15,76 +15,76 @@ namespace Swift { QtSubscriptionRequestWindow::QtSubscriptionRequestWindow(boost::shared_ptr event, QWidget* parent) : QDialog(parent), event_(event) { - QString text = QString(tr("%1 would like to add you to their contact list.")).arg(P2QSTRING(event->getJID().toString())); - QVBoxLayout* layout = new QVBoxLayout(); - QLabel* label = new QLabel(text, this); - layout->addWidget(label); - label = new QLabel(tr("Would you like to add them to your contact list and share your status when you're online?")); - //layout->addWidget(new QLabel); - layout->addWidget(label); + QString text = QString(tr("%1 would like to add you to their contact list.")).arg(P2QSTRING(event->getJID().toString())); + QVBoxLayout* layout = new QVBoxLayout(); + QLabel* label = new QLabel(text, this); + layout->addWidget(label); + label = new QLabel(tr("Would you like to add them to your contact list and share your status when you're online?")); + //layout->addWidget(new QLabel); + layout->addWidget(label); - if (event_->getConcluded()) { - QLabel* doneLabel = new QLabel(tr("You have already replied to this request")); - QPushButton* okButton = new QPushButton(tr("OK"), this); - connect(okButton, SIGNAL(clicked()), this, SLOT(handleDefer())); - layout->addWidget(doneLabel); - layout->addWidget(okButton); - } else { - QPushButton* yesButton = new QPushButton(tr("Accept"), this); - yesButton->setDefault(true); - connect(yesButton, SIGNAL(clicked()), this, SLOT(handleYes())); - QPushButton* noButton = new QPushButton(tr("Reject"), this); - connect(noButton, SIGNAL(clicked()), this, SLOT(handleNo())); - QPushButton* deferButton = new QPushButton(tr("Defer"), this); - deferButton->setShortcut(QKeySequence(Qt::Key_Escape)); - connect(deferButton, SIGNAL(clicked()), this, SLOT(handleDefer())); + if (event_->getConcluded()) { + QLabel* doneLabel = new QLabel(tr("You have already replied to this request")); + QPushButton* okButton = new QPushButton(tr("OK"), this); + connect(okButton, SIGNAL(clicked()), this, SLOT(handleDefer())); + layout->addWidget(doneLabel); + layout->addWidget(okButton); + } else { + QPushButton* yesButton = new QPushButton(tr("Accept"), this); + yesButton->setDefault(true); + connect(yesButton, SIGNAL(clicked()), this, SLOT(handleYes())); + QPushButton* noButton = new QPushButton(tr("Reject"), this); + connect(noButton, SIGNAL(clicked()), this, SLOT(handleNo())); + QPushButton* deferButton = new QPushButton(tr("Defer"), this); + deferButton->setShortcut(QKeySequence(Qt::Key_Escape)); + connect(deferButton, SIGNAL(clicked()), this, SLOT(handleDefer())); - QHBoxLayout* buttonLayout = new QHBoxLayout(); - buttonLayout->addWidget(yesButton); - buttonLayout->addWidget(noButton); - buttonLayout->addWidget(deferButton); - layout->addWidget(new QLabel); - layout->addLayout(buttonLayout); - layout->addWidget(new QLabel); - QLabel* footer = new QLabel(tr("(If you choose to defer this choice, you will be asked again when you next login.)")); - layout->addWidget(footer); - } + QHBoxLayout* buttonLayout = new QHBoxLayout(); + buttonLayout->addWidget(yesButton); + buttonLayout->addWidget(noButton); + buttonLayout->addWidget(deferButton); + layout->addWidget(new QLabel); + layout->addLayout(buttonLayout); + layout->addWidget(new QLabel); + QLabel* footer = new QLabel(tr("(If you choose to defer this choice, you will be asked again when you next login.)")); + layout->addWidget(footer); + } - setLayout(layout); + setLayout(layout); } void QtSubscriptionRequestWindow::handleYes() { - event_->accept(); - delete this; + event_->accept(); + delete this; } void QtSubscriptionRequestWindow::handleNo() { - event_->decline(); - delete this; + event_->decline(); + delete this; } void QtSubscriptionRequestWindow::handleDefer() { - event_->defer(); - delete this; + event_->defer(); + delete this; } QtSubscriptionRequestWindow::~QtSubscriptionRequestWindow() { - windows_.removeOne(this); + windows_.removeOne(this); } QtSubscriptionRequestWindow* QtSubscriptionRequestWindow::getWindow(boost::shared_ptr event, QWidget* parent) { - foreach (QtSubscriptionRequestWindow* window, windows_) { - if (window->getEvent() == event) { - return window; - } - } - QtSubscriptionRequestWindow* window = new QtSubscriptionRequestWindow(event, parent); - windows_.append(window); - return window; + foreach (QtSubscriptionRequestWindow* window, windows_) { + if (window->getEvent() == event) { + return window; + } + } + QtSubscriptionRequestWindow* window = new QtSubscriptionRequestWindow(event, parent); + windows_.append(window); + return window; } boost::shared_ptr QtSubscriptionRequestWindow::getEvent() { - return event_; + return event_; } QList QtSubscriptionRequestWindow::windows_; diff --git a/Swift/QtUI/QtSubscriptionRequestWindow.h b/Swift/QtUI/QtSubscriptionRequestWindow.h index 02932af..1a36e19 100644 --- a/Swift/QtUI/QtSubscriptionRequestWindow.h +++ b/Swift/QtUI/QtSubscriptionRequestWindow.h @@ -13,22 +13,22 @@ #include namespace Swift { - class QtSubscriptionRequestWindow : public QDialog { - Q_OBJECT - public: - static QtSubscriptionRequestWindow* getWindow(boost::shared_ptr event, QWidget* parent = 0); - ~QtSubscriptionRequestWindow(); - boost::shared_ptr getEvent(); - private slots: - void handleYes(); - void handleNo(); - void handleDefer(); - private: - QtSubscriptionRequestWindow(boost::shared_ptr event, QWidget* parent = 0); - static QList windows_; - boost::shared_ptr event_; - /*QPushButton* yesButton_; - QPushButton* noButton_; - QPushButton* deferButton_;*/ - }; + class QtSubscriptionRequestWindow : public QDialog { + Q_OBJECT + public: + static QtSubscriptionRequestWindow* getWindow(boost::shared_ptr event, QWidget* parent = 0); + ~QtSubscriptionRequestWindow(); + boost::shared_ptr getEvent(); + private slots: + void handleYes(); + void handleNo(); + void handleDefer(); + private: + QtSubscriptionRequestWindow(boost::shared_ptr event, QWidget* parent = 0); + static QList windows_; + boost::shared_ptr event_; + /*QPushButton* yesButton_; + QPushButton* noButton_; + QPushButton* deferButton_;*/ + }; } diff --git a/Swift/QtUI/QtSwift.cpp b/Swift/QtUI/QtSwift.cpp index 6444e0c..5e8d61c 100644 --- a/Swift/QtUI/QtSwift.cpp +++ b/Swift/QtUI/QtSwift.cpp @@ -85,203 +85,203 @@ namespace Swift{ #endif po::options_description QtSwift::getOptionsDescription() { - po::options_description result("Options"); - result.add_options() - ("debug", "Turn on debug logging") - ("help", "Show this help message") - ("version", "Show version information") - ("netbook-mode", "Use netbook mode display (unsupported)") - ("no-tabs", "Don't manage chat windows in tabs (unsupported)") - ("latency-debug", "Use latency debugging (unsupported)") - ("multi-account", po::value()->default_value(1), "Number of accounts to open windows for (unsupported)") - ("start-minimized", "Don't show the login/roster window at startup") - ("enable-jid-adhocs", "Enable AdHoc commands to custom JID's.") - ("trellis", "Enable support for trellis layout") + po::options_description result("Options"); + result.add_options() + ("debug", "Turn on debug logging") + ("help", "Show this help message") + ("version", "Show version information") + ("netbook-mode", "Use netbook mode display (unsupported)") + ("no-tabs", "Don't manage chat windows in tabs (unsupported)") + ("latency-debug", "Use latency debugging (unsupported)") + ("multi-account", po::value()->default_value(1), "Number of accounts to open windows for (unsupported)") + ("start-minimized", "Don't show the login/roster window at startup") + ("enable-jid-adhocs", "Enable AdHoc commands to custom JID's.") + ("trellis", "Enable support for trellis layout") #if QT_VERSION >= 0x040800 - ("language", po::value(), "Use a specific language, instead of the system-wide one") + ("language", po::value(), "Use a specific language, instead of the system-wide one") #endif - ; - return result; + ; + return result; } XMLSettingsProvider* QtSwift::loadSettingsFile(const QString& fileName) { - QFile configFile(fileName); - if (configFile.exists() && configFile.open(QIODevice::ReadOnly)) { - QString xmlString; - while (!configFile.atEnd()) { - QByteArray line = configFile.readLine(); - xmlString += line + "\n"; - } - return new XMLSettingsProvider(Q2PSTRING(xmlString)); - } - return new XMLSettingsProvider(""); + QFile configFile(fileName); + if (configFile.exists() && configFile.open(QIODevice::ReadOnly)) { + QString xmlString; + while (!configFile.atEnd()) { + QByteArray line = configFile.readLine(); + xmlString += line + "\n"; + } + return new XMLSettingsProvider(Q2PSTRING(xmlString)); + } + return new XMLSettingsProvider(""); } void QtSwift::loadEmoticonsFile(const QString& fileName, std::map& emoticons) { - QFile file(fileName); - if (file.exists() && file.open(QIODevice::ReadOnly)) { - while (!file.atEnd()) { - QString line = file.readLine(); - line.replace("\n", ""); - line.replace("\r", ""); - QStringList tokens = line.split(" "); - if (tokens.size() == 2) { - QString emoticonFile = tokens[1]; - if (!emoticonFile.startsWith(":/") && !emoticonFile.startsWith("qrc:/")) { - emoticonFile = "file://" + emoticonFile; - } - emoticons[Q2PSTRING(tokens[0])] = Q2PSTRING(emoticonFile); - } - } - } + QFile file(fileName); + if (file.exists() && file.open(QIODevice::ReadOnly)) { + while (!file.atEnd()) { + QString line = file.readLine(); + line.replace("\n", ""); + line.replace("\r", ""); + QStringList tokens = line.split(" "); + if (tokens.size() == 2) { + QString emoticonFile = tokens[1]; + if (!emoticonFile.startsWith(":/") && !emoticonFile.startsWith("qrc:/")) { + emoticonFile = "file://" + emoticonFile; + } + emoticons[Q2PSTRING(tokens[0])] = Q2PSTRING(emoticonFile); + } + } + } } QtSwift::QtSwift(const po::variables_map& options) : networkFactories_(&clientMainThreadCaller_), autoUpdater_(NULL), idleDetector_(&idleQuerier_, networkFactories_.getTimerFactory(), 1000) { - QCoreApplication::setApplicationName(SWIFT_APPLICATION_NAME); - QCoreApplication::setOrganizationName(SWIFT_ORGANIZATION_NAME); - QCoreApplication::setOrganizationDomain(SWIFT_ORGANIZATION_DOMAIN); - QCoreApplication::setApplicationVersion(buildVersion); - - qtSettings_ = new QtSettingsProvider(); - xmlSettings_ = loadSettingsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "system-settings.xml"))); - settingsHierachy_ = new SettingsProviderHierachy(); - settingsHierachy_->addProviderToTopOfStack(xmlSettings_); - settingsHierachy_->addProviderToTopOfStack(qtSettings_); - - networkFactories_.getTLSContextFactory()->setDisconnectOnCardRemoval(settingsHierachy_->getSetting(SettingConstants::DISCONNECT_ON_CARD_REMOVAL)); - - std::map emoticons; - loadEmoticonsFile(":/emoticons/emoticons.txt", emoticons); - loadEmoticonsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "emoticons.txt")), emoticons); - - if (options.count("netbook-mode")) { - splitter_ = new QtSingleWindow(qtSettings_); - } else { - splitter_ = NULL; - } - - int numberOfAccounts = 1; - try { - numberOfAccounts = options["multi-account"].as(); - } catch (...) { - /* This seems to fail on a Mac when the .app is launched directly (the usual path).*/ - numberOfAccounts = 1; - } - - if (options.count("debug")) { - Log::setLogLevel(Swift::Log::debug); - } - - bool enableAdHocCommandOnJID = options.count("enable-jid-adhocs") > 0; - tabs_ = NULL; - if (options.count("no-tabs") && !splitter_) { - tabs_ = new QtChatTabsShortcutOnlySubstitute(); - } - else { - tabs_ = new QtChatTabs(splitter_ != NULL, settingsHierachy_, options.count("trellis")); - } - bool startMinimized = options.count("start-minimized") > 0; - applicationPathProvider_ = new PlatformApplicationPathProvider(SWIFT_APPLICATION_NAME); - storagesFactory_ = new FileStoragesFactory(applicationPathProvider_->getDataDir(), networkFactories_.getCryptoProvider()); - certificateStorageFactory_ = new CertificateFileStorageFactory(applicationPathProvider_->getDataDir(), tlsFactories_.getCertificateFactory(), networkFactories_.getCryptoProvider()); - chatWindowFactory_ = new QtChatWindowFactory(splitter_, settingsHierachy_, qtSettings_, tabs_, ":/themes/Default/", emoticons); - soundPlayer_ = new QtSoundPlayer(applicationPathProvider_); - - // Ugly, because the dock depends on the tray, but the temporary - // multi-account hack creates one tray per account. - QtSystemTray* systemTray = new QtSystemTray(); - systemTrays_.push_back(systemTray); + QCoreApplication::setApplicationName(SWIFT_APPLICATION_NAME); + QCoreApplication::setOrganizationName(SWIFT_ORGANIZATION_NAME); + QCoreApplication::setOrganizationDomain(SWIFT_ORGANIZATION_DOMAIN); + QCoreApplication::setApplicationVersion(buildVersion); + + qtSettings_ = new QtSettingsProvider(); + xmlSettings_ = loadSettingsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "system-settings.xml"))); + settingsHierachy_ = new SettingsProviderHierachy(); + settingsHierachy_->addProviderToTopOfStack(xmlSettings_); + settingsHierachy_->addProviderToTopOfStack(qtSettings_); + + networkFactories_.getTLSContextFactory()->setDisconnectOnCardRemoval(settingsHierachy_->getSetting(SettingConstants::DISCONNECT_ON_CARD_REMOVAL)); + + std::map emoticons; + loadEmoticonsFile(":/emoticons/emoticons.txt", emoticons); + loadEmoticonsFile(P2QSTRING(pathToString(Paths::getExecutablePath() / "emoticons.txt")), emoticons); + + if (options.count("netbook-mode")) { + splitter_ = new QtSingleWindow(qtSettings_); + } else { + splitter_ = NULL; + } + + int numberOfAccounts = 1; + try { + numberOfAccounts = options["multi-account"].as(); + } catch (...) { + /* This seems to fail on a Mac when the .app is launched directly (the usual path).*/ + numberOfAccounts = 1; + } + + if (options.count("debug")) { + Log::setLogLevel(Swift::Log::debug); + } + + bool enableAdHocCommandOnJID = options.count("enable-jid-adhocs") > 0; + tabs_ = NULL; + if (options.count("no-tabs") && !splitter_) { + tabs_ = new QtChatTabsShortcutOnlySubstitute(); + } + else { + tabs_ = new QtChatTabs(splitter_ != NULL, settingsHierachy_, options.count("trellis")); + } + bool startMinimized = options.count("start-minimized") > 0; + applicationPathProvider_ = new PlatformApplicationPathProvider(SWIFT_APPLICATION_NAME); + storagesFactory_ = new FileStoragesFactory(applicationPathProvider_->getDataDir(), networkFactories_.getCryptoProvider()); + certificateStorageFactory_ = new CertificateFileStorageFactory(applicationPathProvider_->getDataDir(), tlsFactories_.getCertificateFactory(), networkFactories_.getCryptoProvider()); + chatWindowFactory_ = new QtChatWindowFactory(splitter_, settingsHierachy_, qtSettings_, tabs_, ":/themes/Default/", emoticons); + soundPlayer_ = new QtSoundPlayer(applicationPathProvider_); + + // Ugly, because the dock depends on the tray, but the temporary + // multi-account hack creates one tray per account. + QtSystemTray* systemTray = new QtSystemTray(); + systemTrays_.push_back(systemTray); #if defined(HAVE_GROWL) - notifier_ = new GrowlNotifier(SWIFT_APPLICATION_NAME); + notifier_ = new GrowlNotifier(SWIFT_APPLICATION_NAME); #elif defined(SWIFTEN_PLATFORM_WINDOWS) - notifier_ = new WindowsNotifier(SWIFT_APPLICATION_NAME, applicationPathProvider_->getResourcePath("/images/logo-icon-32.png"), systemTray->getQSystemTrayIcon()); + notifier_ = new WindowsNotifier(SWIFT_APPLICATION_NAME, applicationPathProvider_->getResourcePath("/images/logo-icon-32.png"), systemTray->getQSystemTrayIcon()); #elif defined(SWIFTEN_PLATFORM_LINUX) - notifier_ = new FreeDesktopNotifier(SWIFT_APPLICATION_NAME); + notifier_ = new FreeDesktopNotifier(SWIFT_APPLICATION_NAME); #elif defined(SWIFTEN_PLATFORM_MACOSX) - notifier_ = new NotificationCenterNotifier(); + notifier_ = new NotificationCenterNotifier(); #else - notifier_ = new NullNotifier(); + notifier_ = new NullNotifier(); #endif #if defined(SWIFTEN_PLATFORM_MACOSX) - dock_ = new MacOSXDock(&cocoaApplication_); + dock_ = new MacOSXDock(&cocoaApplication_); #else - dock_ = new NullDock(); + dock_ = new NullDock(); #endif #if defined(SWIFTEN_PLATFORM_MACOSX) - uriHandler_ = new QtURIHandler(); + uriHandler_ = new QtURIHandler(); #elif defined(SWIFTEN_PLATFORM_WIN32) - uriHandler_ = new NullURIHandler(); + uriHandler_ = new NullURIHandler(); #else - uriHandler_ = new QtDBUSURIHandler(); + uriHandler_ = new QtDBUSURIHandler(); #endif - statusCache_ = new StatusCache(applicationPathProvider_); - - if (splitter_) { - splitter_->show(); - } - - for (int i = 0; i < numberOfAccounts; i++) { - if (i > 0) { - // Don't add the first tray (see note above) - systemTrays_.push_back(new QtSystemTray()); - } - QtUIFactory* uiFactory = new QtUIFactory(settingsHierachy_, qtSettings_, tabs_, splitter_, systemTrays_[i], chatWindowFactory_, networkFactories_.getTimerFactory(), statusCache_, startMinimized, !emoticons.empty(), enableAdHocCommandOnJID); - uiFactories_.push_back(uiFactory); - MainController* mainController = new MainController( - &clientMainThreadCaller_, - &networkFactories_, - uiFactory, - settingsHierachy_, - systemTrays_[i], - soundPlayer_, - storagesFactory_, - certificateStorageFactory_, - dock_, - notifier_, - uriHandler_, - &idleDetector_, - emoticons, - options.count("latency-debug") > 0); - mainControllers_.push_back(mainController); - } - - - // PlatformAutoUpdaterFactory autoUpdaterFactory; - // if (autoUpdaterFactory.isSupported()) { - // autoUpdater_ = autoUpdaterFactory.createAutoUpdater(SWIFT_APPCAST_URL); - // autoUpdater_->checkForUpdates(); - // } + statusCache_ = new StatusCache(applicationPathProvider_); + + if (splitter_) { + splitter_->show(); + } + + for (int i = 0; i < numberOfAccounts; i++) { + if (i > 0) { + // Don't add the first tray (see note above) + systemTrays_.push_back(new QtSystemTray()); + } + QtUIFactory* uiFactory = new QtUIFactory(settingsHierachy_, qtSettings_, tabs_, splitter_, systemTrays_[i], chatWindowFactory_, networkFactories_.getTimerFactory(), statusCache_, startMinimized, !emoticons.empty(), enableAdHocCommandOnJID); + uiFactories_.push_back(uiFactory); + MainController* mainController = new MainController( + &clientMainThreadCaller_, + &networkFactories_, + uiFactory, + settingsHierachy_, + systemTrays_[i], + soundPlayer_, + storagesFactory_, + certificateStorageFactory_, + dock_, + notifier_, + uriHandler_, + &idleDetector_, + emoticons, + options.count("latency-debug") > 0); + mainControllers_.push_back(mainController); + } + + + // PlatformAutoUpdaterFactory autoUpdaterFactory; + // if (autoUpdaterFactory.isSupported()) { + // autoUpdater_ = autoUpdaterFactory.createAutoUpdater(SWIFT_APPCAST_URL); + // autoUpdater_->checkForUpdates(); + // } } QtSwift::~QtSwift() { - delete autoUpdater_; - foreach (QtUIFactory* factory, uiFactories_) { - delete factory; - } - foreach (MainController* controller, mainControllers_) { - delete controller; - } - delete notifier_; - foreach (QtSystemTray* tray, systemTrays_) { - delete tray; - } - delete tabs_; - delete splitter_; - delete settingsHierachy_; - delete qtSettings_; - delete xmlSettings_; - delete statusCache_; - delete uriHandler_; - delete dock_; - delete soundPlayer_; - delete chatWindowFactory_; - delete certificateStorageFactory_; - delete storagesFactory_; - delete applicationPathProvider_; + delete autoUpdater_; + foreach (QtUIFactory* factory, uiFactories_) { + delete factory; + } + foreach (MainController* controller, mainControllers_) { + delete controller; + } + delete notifier_; + foreach (QtSystemTray* tray, systemTrays_) { + delete tray; + } + delete tabs_; + delete splitter_; + delete settingsHierachy_; + delete qtSettings_; + delete xmlSettings_; + delete statusCache_; + delete uriHandler_; + delete dock_; + delete soundPlayer_; + delete chatWindowFactory_; + delete certificateStorageFactory_; + delete storagesFactory_; + delete applicationPathProvider_; } } diff --git a/Swift/QtUI/QtSwift.h b/Swift/QtUI/QtSwift.h index a971324..9932545 100644 --- a/Swift/QtUI/QtSwift.h +++ b/Swift/QtUI/QtSwift.h @@ -30,65 +30,65 @@ namespace po = boost::program_options; class QSplitter; namespace Swift { - class QtUIFactory; - class CertificateStorageFactory; - class Dock; - class Notifier; - class StoragesFactory; - class AutoUpdater; - class ApplicationPathProvider; - class AvatarStorage; - class CapsStorage; - class MainController; - class QtSystemTray; - class QtChatTabsBase; - class QtChatWindowFactory; - class QtSoundPlayer; - class QtMUCSearchWindowFactory; - class QtUserSearchWindowFactory; - class EventLoop; - class URIHandler; - class SettingsProviderHierachy; - class XMLSettingsProvider; - class StatusCache; - class QtSingleWindow; - - class QtSwift : public QObject { - Q_OBJECT - public: - QtSwift(const po::variables_map& options); - static po::options_description getOptionsDescription(); - ~QtSwift(); - private: - XMLSettingsProvider* loadSettingsFile(const QString& fileName); - void loadEmoticonsFile(const QString& fileName, std::map& emoticons); - private: - QtEventLoop clientMainThreadCaller_; - PlatformTLSFactories tlsFactories_; - BoostNetworkFactories networkFactories_; - QtChatWindowFactory* chatWindowFactory_; - std::vector mainControllers_; - std::vector systemTrays_; - std::vector uiFactories_; - QtSettingsProvider* qtSettings_; - XMLSettingsProvider* xmlSettings_; - SettingsProviderHierachy* settingsHierachy_; - QtSingleWindow* splitter_; - QtSoundPlayer* soundPlayer_; - Dock* dock_; - URIHandler* uriHandler_; - QtChatTabsBase* tabs_; - ApplicationPathProvider* applicationPathProvider_; - StoragesFactory* storagesFactory_; - CertificateStorageFactory* certificateStorageFactory_; - AutoUpdater* autoUpdater_; - Notifier* notifier_; - StatusCache* statusCache_; - PlatformIdleQuerier idleQuerier_; - ActualIdleDetector idleDetector_; + class QtUIFactory; + class CertificateStorageFactory; + class Dock; + class Notifier; + class StoragesFactory; + class AutoUpdater; + class ApplicationPathProvider; + class AvatarStorage; + class CapsStorage; + class MainController; + class QtSystemTray; + class QtChatTabsBase; + class QtChatWindowFactory; + class QtSoundPlayer; + class QtMUCSearchWindowFactory; + class QtUserSearchWindowFactory; + class EventLoop; + class URIHandler; + class SettingsProviderHierachy; + class XMLSettingsProvider; + class StatusCache; + class QtSingleWindow; + + class QtSwift : public QObject { + Q_OBJECT + public: + QtSwift(const po::variables_map& options); + static po::options_description getOptionsDescription(); + ~QtSwift(); + private: + XMLSettingsProvider* loadSettingsFile(const QString& fileName); + void loadEmoticonsFile(const QString& fileName, std::map& emoticons); + private: + QtEventLoop clientMainThreadCaller_; + PlatformTLSFactories tlsFactories_; + BoostNetworkFactories networkFactories_; + QtChatWindowFactory* chatWindowFactory_; + std::vector mainControllers_; + std::vector systemTrays_; + std::vector uiFactories_; + QtSettingsProvider* qtSettings_; + XMLSettingsProvider* xmlSettings_; + SettingsProviderHierachy* settingsHierachy_; + QtSingleWindow* splitter_; + QtSoundPlayer* soundPlayer_; + Dock* dock_; + URIHandler* uriHandler_; + QtChatTabsBase* tabs_; + ApplicationPathProvider* applicationPathProvider_; + StoragesFactory* storagesFactory_; + CertificateStorageFactory* certificateStorageFactory_; + AutoUpdater* autoUpdater_; + Notifier* notifier_; + StatusCache* statusCache_; + PlatformIdleQuerier idleQuerier_; + ActualIdleDetector idleDetector_; #if defined(SWIFTEN_PLATFORM_MACOSX) - CocoaApplication cocoaApplication_; - CocoaApplicationActivateHelper cocoaApplicationActivateHelper_; + CocoaApplication cocoaApplication_; + CocoaApplicationActivateHelper cocoaApplicationActivateHelper_; #endif - }; + }; } diff --git a/Swift/QtUI/QtSystemTray.cpp b/Swift/QtUI/QtSystemTray.cpp index d268d16..55a7d43 100644 --- a/Swift/QtUI/QtSystemTray.cpp +++ b/Swift/QtUI/QtSystemTray.cpp @@ -20,71 +20,71 @@ namespace Swift { QtSystemTray::QtSystemTray() : QObject(), statusType_(StatusShow::None), trayMenu_(0), onlineIcon_(":icons/online.png"), awayIcon_(":icons/away.png"), dndIcon_(":icons/dnd.png"), offlineIcon_(":icons/offline.png"), newMessageIcon_(":icons/new-chat.png"), throbberMovie_(":/icons/connecting.mng"), unreadMessages_(false), connecting_(false) { - trayIcon_ = new QSystemTrayIcon(offlineIcon_); - trayIcon_->setToolTip("Swift"); - connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(handleIconActivated(QSystemTrayIcon::ActivationReason))); - connect(&throbberMovie_, SIGNAL(frameChanged(int)), this, SLOT(handleThrobberFrameChanged(int))); + trayIcon_ = new QSystemTrayIcon(offlineIcon_); + trayIcon_->setToolTip("Swift"); + connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(handleIconActivated(QSystemTrayIcon::ActivationReason))); + connect(&throbberMovie_, SIGNAL(frameChanged(int)), this, SLOT(handleThrobberFrameChanged(int))); #if defined (Q_OS_UNIX) && !defined(Q_OS_MAC) - bool isUnity = QDBusInterface("com.canonical.Unity.Launcher", "/com/canonical/Unity/Launcher").isValid(); - if (isUnity) { - // Add an activation menu, because this is the only way to get the application to the - // front on Unity. See the README for sni-qt (which handles Qt tray icons for Unity) - trayMenu_ = new QMenu(); - QAction* showAction = new QAction(QString("Show/Hide"), this); - connect(showAction, SIGNAL(triggered()), SIGNAL(clicked())); - trayMenu_->addAction(showAction); - trayIcon_->setContextMenu(trayMenu_); - } + bool isUnity = QDBusInterface("com.canonical.Unity.Launcher", "/com/canonical/Unity/Launcher").isValid(); + if (isUnity) { + // Add an activation menu, because this is the only way to get the application to the + // front on Unity. See the README for sni-qt (which handles Qt tray icons for Unity) + trayMenu_ = new QMenu(); + QAction* showAction = new QAction(QString("Show/Hide"), this); + connect(showAction, SIGNAL(triggered()), SIGNAL(clicked())); + trayMenu_->addAction(showAction); + trayIcon_->setContextMenu(trayMenu_); + } #endif - trayIcon_->show(); + trayIcon_->show(); } QtSystemTray::~QtSystemTray() { - delete trayMenu_; - delete trayIcon_; + delete trayMenu_; + delete trayIcon_; } void QtSystemTray::setUnreadMessages(bool some) { - unreadMessages_ = some; - updateStatusIcon(); + unreadMessages_ = some; + updateStatusIcon(); } void QtSystemTray::handleThrobberFrameChanged(int /*frameNumber*/) { - trayIcon_->setIcon(QIcon(throbberMovie_.currentPixmap())); + trayIcon_->setIcon(QIcon(throbberMovie_.currentPixmap())); } void QtSystemTray::setConnecting() { - connecting_ = true; - updateStatusIcon(); + connecting_ = true; + updateStatusIcon(); } void QtSystemTray::handleIconActivated(QSystemTrayIcon::ActivationReason reason) { - if (reason == QSystemTrayIcon::Trigger) { - emit clicked(); - } + if (reason == QSystemTrayIcon::Trigger) { + emit clicked(); + } } void QtSystemTray::setStatusType(StatusShow::Type type) { - connecting_ = false; - statusType_ = type; - updateStatusIcon(); + connecting_ = false; + statusType_ = type; + updateStatusIcon(); } void QtSystemTray::updateStatusIcon() { - throbberMovie_.stop(); - if (unreadMessages_) { - trayIcon_->setIcon(newMessageIcon_); - } else if (connecting_) { - throbberMovie_.start(); - } else { - switch (statusType_) { - case StatusShow::Online : trayIcon_->setIcon(onlineIcon_);break; - case StatusShow::FFC : trayIcon_->setIcon(onlineIcon_);break; - case StatusShow::Away : trayIcon_->setIcon(awayIcon_);break; - case StatusShow::XA : trayIcon_->setIcon(awayIcon_);break; - case StatusShow::DND : trayIcon_->setIcon(dndIcon_);break; - case StatusShow::None : trayIcon_->setIcon(offlineIcon_);break; - } - } + throbberMovie_.stop(); + if (unreadMessages_) { + trayIcon_->setIcon(newMessageIcon_); + } else if (connecting_) { + throbberMovie_.start(); + } else { + switch (statusType_) { + case StatusShow::Online : trayIcon_->setIcon(onlineIcon_);break; + case StatusShow::FFC : trayIcon_->setIcon(onlineIcon_);break; + case StatusShow::Away : trayIcon_->setIcon(awayIcon_);break; + case StatusShow::XA : trayIcon_->setIcon(awayIcon_);break; + case StatusShow::DND : trayIcon_->setIcon(dndIcon_);break; + case StatusShow::None : trayIcon_->setIcon(offlineIcon_);break; + } + } } } diff --git a/Swift/QtUI/QtSystemTray.h b/Swift/QtUI/QtSystemTray.h index b1dffd0..ba2c5cb 100644 --- a/Swift/QtUI/QtSystemTray.h +++ b/Swift/QtUI/QtSystemTray.h @@ -16,35 +16,35 @@ class QMenu; namespace Swift { - class QtSystemTray : public QObject, public SystemTray { - Q_OBJECT - public: - QtSystemTray(); - ~QtSystemTray(); - void setUnreadMessages(bool some); - void setStatusType(StatusShow::Type type); - void setConnecting(); - QSystemTrayIcon* getQSystemTrayIcon() { - return trayIcon_; - } + class QtSystemTray : public QObject, public SystemTray { + Q_OBJECT + public: + QtSystemTray(); + ~QtSystemTray(); + void setUnreadMessages(bool some); + void setStatusType(StatusShow::Type type); + void setConnecting(); + QSystemTrayIcon* getQSystemTrayIcon() { + return trayIcon_; + } - signals: - void clicked(); - private slots: - void handleIconActivated(QSystemTrayIcon::ActivationReason reason); - void handleThrobberFrameChanged(int); - private: - void updateStatusIcon(); - StatusShow::Type statusType_; - QSystemTrayIcon* trayIcon_; - QMenu* trayMenu_; - QIcon onlineIcon_; - QIcon awayIcon_; - QIcon dndIcon_; - QIcon offlineIcon_; - QIcon newMessageIcon_; - QMovie throbberMovie_; - bool unreadMessages_; - bool connecting_; - }; + signals: + void clicked(); + private slots: + void handleIconActivated(QSystemTrayIcon::ActivationReason reason); + void handleThrobberFrameChanged(int); + private: + void updateStatusIcon(); + StatusShow::Type statusType_; + QSystemTrayIcon* trayIcon_; + QMenu* trayMenu_; + QIcon onlineIcon_; + QIcon awayIcon_; + QIcon dndIcon_; + QIcon offlineIcon_; + QIcon newMessageIcon_; + QMovie throbberMovie_; + bool unreadMessages_; + bool connecting_; + }; } diff --git a/Swift/QtUI/QtTabWidget.cpp b/Swift/QtUI/QtTabWidget.cpp index ca9ea5d..9f353d7 100644 --- a/Swift/QtUI/QtTabWidget.cpp +++ b/Swift/QtUI/QtTabWidget.cpp @@ -17,10 +17,10 @@ QtTabWidget::~QtTabWidget() { } QTabBar* QtTabWidget::tabBar() { - return QTabWidget::tabBar(); + return QTabWidget::tabBar(); } void QtTabWidget::setTabBar(QTabBar* tabBar) { - QTabWidget::setTabBar(tabBar); + QTabWidget::setTabBar(tabBar); } } diff --git a/Swift/QtUI/QtTabWidget.h b/Swift/QtUI/QtTabWidget.h index 0a723e2..de1a846 100644 --- a/Swift/QtUI/QtTabWidget.h +++ b/Swift/QtUI/QtTabWidget.h @@ -9,13 +9,13 @@ #include namespace Swift { - class QtTabWidget : public QTabWidget { - Q_OBJECT - public: - QtTabWidget(QWidget* parent); - virtual ~QtTabWidget(); + class QtTabWidget : public QTabWidget { + Q_OBJECT + public: + QtTabWidget(QWidget* parent); + virtual ~QtTabWidget(); - QTabBar* tabBar(); - void setTabBar(QTabBar* tabBar); - }; + QTabBar* tabBar(); + void setTabBar(QTabBar* tabBar); + }; } diff --git a/Swift/QtUI/QtTabbable.cpp b/Swift/QtUI/QtTabbable.cpp index 0e08343..bad6315 100644 --- a/Swift/QtUI/QtTabbable.cpp +++ b/Swift/QtUI/QtTabbable.cpp @@ -23,47 +23,47 @@ QtTabbable::QtTabbable() : QWidget() { } QtTabbable::~QtTabbable() { - emit windowClosing(); + emit windowClosing(); } bool QtTabbable::isWidgetSelected() { - /*isActiveWindow() shouldn't be necessary, but I don't trust it as far as I can throw it*/ - if (!isActiveWindow()) { - return false; - } - QtChatTabs* parent = qobject_cast(window()); - return parent ? parent->getCurrentTab() == this : isAncestorOf(QApplication::focusWidget()); + /*isActiveWindow() shouldn't be necessary, but I don't trust it as far as I can throw it*/ + if (!isActiveWindow()) { + return false; + } + QtChatTabs* parent = qobject_cast(window()); + return parent ? parent->getCurrentTab() == this : isAncestorOf(QApplication::focusWidget()); } bool QtTabbable::event(QEvent* event) { - QKeyEvent* keyEvent = dynamic_cast(event); - if (keyEvent) { - // According to Qt's focus documentation, one can only override CTRL+TAB via reimplementing QWidget::event(). - if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Tab) { - // Only handle KeyRelease event as Linux also generate KeyPress event in case of CTRL+TAB being pressed - // in the roster of a MUC. - if (keyEvent->type() == QEvent::KeyRelease) { - emit requestNextTab(); - } - return true; - } + QKeyEvent* keyEvent = dynamic_cast(event); + if (keyEvent) { + // According to Qt's focus documentation, one can only override CTRL+TAB via reimplementing QWidget::event(). + if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Tab) { + // Only handle KeyRelease event as Linux also generate KeyPress event in case of CTRL+TAB being pressed + // in the roster of a MUC. + if (keyEvent->type() == QEvent::KeyRelease) { + emit requestNextTab(); + } + return true; + } #ifdef SWIFTEN_PLATFORM_LINUX - else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab && keyEvent->type() != QEvent::KeyRelease) { + else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab && keyEvent->type() != QEvent::KeyRelease) { #else - else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab) { + else if (keyEvent->modifiers().testFlag(QtUtilities::ctrlHardwareKeyModifier) && keyEvent->key() == Qt::Key_Backtab) { #endif #ifdef SWIFTEN_PLATFORM_WINDOWS - // Windows emits both the KeyPress and KeyRelease events. - if (keyEvent->type() == QEvent::KeyPress) { + // Windows emits both the KeyPress and KeyRelease events. + if (keyEvent->type() == QEvent::KeyPress) { #else - if (keyEvent->type() != QEvent::ShortcutOverride) { + if (keyEvent->type() != QEvent::ShortcutOverride) { #endif - emit requestPreviousTab(); - } - return true; - } - } - return QWidget::event(event); + emit requestPreviousTab(); + } + return true; + } + } + return QWidget::event(event); } } diff --git a/Swift/QtUI/QtTabbable.h b/Swift/QtUI/QtTabbable.h index db83ba9..c2d0961 100644 --- a/Swift/QtUI/QtTabbable.h +++ b/Swift/QtUI/QtTabbable.h @@ -11,29 +11,29 @@ #include namespace Swift { - class QtTabbable : public QWidget { - Q_OBJECT - public: - enum AlertType {NoActivity, WaitingActivity, ImpendingActivity}; - virtual ~QtTabbable(); - bool isWidgetSelected(); - virtual AlertType getWidgetAlertState() {return NoActivity;} - virtual int getCount() {return 0;} - virtual std::string getID() const = 0; + class QtTabbable : public QWidget { + Q_OBJECT + public: + enum AlertType {NoActivity, WaitingActivity, ImpendingActivity}; + virtual ~QtTabbable(); + bool isWidgetSelected(); + virtual AlertType getWidgetAlertState() {return NoActivity;} + virtual int getCount() {return 0;} + virtual std::string getID() const = 0; - protected: - QtTabbable(); - bool event(QEvent* event); + protected: + QtTabbable(); + bool event(QEvent* event); - signals: - void titleUpdated(); - void countUpdated(); - void windowClosing(); - void windowOpening(); - void wantsToActivate(); - void requestPreviousTab(); - void requestNextTab(); - void requestActiveTab(); - void requestFlash(); - }; + signals: + void titleUpdated(); + void countUpdated(); + void windowClosing(); + void windowOpening(); + void wantsToActivate(); + void requestPreviousTab(); + void requestNextTab(); + void requestActiveTab(); + void requestFlash(); + }; } diff --git a/Swift/QtUI/QtTextEdit.cpp b/Swift/QtUI/QtTextEdit.cpp index adf3878..d3ba914 100644 --- a/Swift/QtUI/QtTextEdit.cpp +++ b/Swift/QtUI/QtTextEdit.cpp @@ -30,202 +30,202 @@ namespace Swift { QtTextEdit::QtTextEdit(SettingsProvider* settings, QWidget* parent) : QTextEdit(parent), checker_(NULL), highlighter_(NULL) { - connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged())); - settings_ = settings; + connect(this, SIGNAL(textChanged()), this, SLOT(handleTextChanged())); + settings_ = settings; #ifdef HAVE_SPELLCHECKER - setUpSpellChecker(); + setUpSpellChecker(); #endif - handleTextChanged(); - QTextOption textOption = document()->defaultTextOption(); - textOption.setWrapMode(QTextOption::WordWrap); - document()->setDefaultTextOption(textOption); + handleTextChanged(); + QTextOption textOption = document()->defaultTextOption(); + textOption.setWrapMode(QTextOption::WordWrap); + document()->setDefaultTextOption(textOption); } QtTextEdit::~QtTextEdit() { - delete checker_; + delete checker_; } void QtTextEdit::keyPressEvent(QKeyEvent* event) { - int key = event->key(); - Qt::KeyboardModifiers modifiers = event->modifiers(); - if ((key == Qt::Key_Enter || key == Qt::Key_Return) - && (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier)) { - emit returnPressed(); - } - else if (((key == Qt::Key_PageUp || key == Qt::Key_PageDown) && modifiers == Qt::ShiftModifier) - || (key == Qt::Key_C && modifiers == Qt::ControlModifier && textCursor().selectedText().isEmpty()) - || (key == Qt::Key_W && modifiers == Qt::ControlModifier) - || (key == Qt::Key_PageUp && modifiers == Qt::ControlModifier) - || (key == Qt::Key_PageDown && modifiers == Qt::ControlModifier) - || (key == Qt::Key_Tab && modifiers == Qt::ControlModifier) - || (key == Qt::Key_A && modifiers == Qt::AltModifier) - || (key == Qt::Key_Tab) - ) { - emit unhandledKeyPressEvent(event); - } - else if ((key == Qt::Key_Up) - || (key == Qt::Key_Down)) { - emit unhandledKeyPressEvent(event); - QTextEdit::keyPressEvent(event); - } - else if ((key == Qt::Key_K && modifiers == QtUtilities::ctrlHardwareKeyModifier)) { - QTextCursor cursor = textCursor(); - cursor.setPosition(toPlainText().size(), QTextCursor::KeepAnchor); - cursor.removeSelectedText(); - } - else { - QTextEdit::keyPressEvent(event); - } + int key = event->key(); + Qt::KeyboardModifiers modifiers = event->modifiers(); + if ((key == Qt::Key_Enter || key == Qt::Key_Return) + && (modifiers == Qt::NoModifier || modifiers == Qt::KeypadModifier)) { + emit returnPressed(); + } + else if (((key == Qt::Key_PageUp || key == Qt::Key_PageDown) && modifiers == Qt::ShiftModifier) + || (key == Qt::Key_C && modifiers == Qt::ControlModifier && textCursor().selectedText().isEmpty()) + || (key == Qt::Key_W && modifiers == Qt::ControlModifier) + || (key == Qt::Key_PageUp && modifiers == Qt::ControlModifier) + || (key == Qt::Key_PageDown && modifiers == Qt::ControlModifier) + || (key == Qt::Key_Tab && modifiers == Qt::ControlModifier) + || (key == Qt::Key_A && modifiers == Qt::AltModifier) + || (key == Qt::Key_Tab) + ) { + emit unhandledKeyPressEvent(event); + } + else if ((key == Qt::Key_Up) + || (key == Qt::Key_Down)) { + emit unhandledKeyPressEvent(event); + QTextEdit::keyPressEvent(event); + } + else if ((key == Qt::Key_K && modifiers == QtUtilities::ctrlHardwareKeyModifier)) { + QTextCursor cursor = textCursor(); + cursor.setPosition(toPlainText().size(), QTextCursor::KeepAnchor); + cursor.removeSelectedText(); + } + else { + QTextEdit::keyPressEvent(event); + } } void QtTextEdit::focusInEvent(QFocusEvent* event) { - receivedFocus(); - QTextEdit::focusInEvent(event); + receivedFocus(); + QTextEdit::focusInEvent(event); } void QtTextEdit::focusOutEvent(QFocusEvent* event) { - lostFocus(); - QTextEdit::focusOutEvent(event); + lostFocus(); + QTextEdit::focusOutEvent(event); } void QtTextEdit::handleTextChanged() { - QSize previous(maximumSize()); - setMaximumSize(QSize(maximumWidth(), sizeHint().height())); - if (previous != maximumSize()) { - updateGeometry(); - } + QSize previous(maximumSize()); + setMaximumSize(QSize(maximumWidth(), sizeHint().height())); + if (previous != maximumSize()) { + updateGeometry(); + } } void QtTextEdit::replaceMisspelledWord(const QString& word, int cursorPosition) { - QTextCursor cursor = textCursor(); - PositionPair wordPosition = getWordFromCursor(cursorPosition); - cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor); - cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor); - QTextCharFormat normalFormat; - cursor.insertText(word, normalFormat); + QTextCursor cursor = textCursor(); + PositionPair wordPosition = getWordFromCursor(cursorPosition); + cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor); + cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor); + QTextCharFormat normalFormat; + cursor.insertText(word, normalFormat); } PositionPair QtTextEdit::getWordFromCursor(int cursorPosition) { - PositionPairList misspelledPositions = highlighter_->getMisspelledPositions(); - for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end(); ++it) { - if (cursorPosition >= boost::get<0>(*it) && cursorPosition <= boost::get<1>(*it)) { - return *it; - } - } - return boost::make_tuple(-1,-1); + PositionPairList misspelledPositions = highlighter_->getMisspelledPositions(); + for (PositionPairList::iterator it = misspelledPositions.begin(); it != misspelledPositions.end(); ++it) { + if (cursorPosition >= boost::get<0>(*it) && cursorPosition <= boost::get<1>(*it)) { + return *it; + } + } + return boost::make_tuple(-1,-1); } QSize QtTextEdit::sizeHint() const { - QSize hint = document()->size().toSize(); - QMargins margins = contentsMargins(); - return hint + QSize(margins.left() + margins.right(), margins.top() + margins.bottom()); + QSize hint = document()->size().toSize(); + QMargins margins = contentsMargins(); + return hint + QSize(margins.left() + margins.right(), margins.top() + margins.bottom()); } void QtTextEdit::contextMenuEvent(QContextMenuEvent* event) { - QMenu* menu = createStandardContextMenu(); - QTextCursor cursor = cursorForPosition(event->pos()); + QMenu* menu = createStandardContextMenu(); + QTextCursor cursor = cursorForPosition(event->pos()); #ifdef HAVE_SPELLCHECKER - QAction* insertPoint = menu->actions().first(); - QAction* settingsAction = new QAction(tr("Spell Checker Options"), menu); - menu->insertAction(insertPoint, settingsAction); - menu->insertAction(insertPoint, menu->addSeparator()); - addSuggestions(menu, event); - QAction* result = menu->exec(event->globalPos()); - if (result == settingsAction) { - spellCheckerSettingsWindow(); - } - for (std::vector::iterator it = replaceWordActions_.begin(); it != replaceWordActions_.end(); ++it) { - if (*it == result) { - replaceMisspelledWord((*it)->text(), cursor.position()); - } - } + QAction* insertPoint = menu->actions().first(); + QAction* settingsAction = new QAction(tr("Spell Checker Options"), menu); + menu->insertAction(insertPoint, settingsAction); + menu->insertAction(insertPoint, menu->addSeparator()); + addSuggestions(menu, event); + QAction* result = menu->exec(event->globalPos()); + if (result == settingsAction) { + spellCheckerSettingsWindow(); + } + for (std::vector::iterator it = replaceWordActions_.begin(); it != replaceWordActions_.end(); ++it) { + if (*it == result) { + replaceMisspelledWord((*it)->text(), cursor.position()); + } + } #else - menu->exec(event->globalPos()); + menu->exec(event->globalPos()); #endif - delete menu; + delete menu; } void QtTextEdit::addSuggestions(QMenu* menu, QContextMenuEvent* event) { - replaceWordActions_.clear(); - if (checker_ && highlighter_) { - QAction* insertPoint = menu->actions().first(); - QTextCursor cursor = cursorForPosition(event->pos()); - PositionPair wordPosition = getWordFromCursor(cursor.position()); - if (boost::get<0>(wordPosition) < 0) { - // The click was executed outside a spellable word so no - // suggestions are necessary - return; - } - cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor); - cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor); - std::vector wordList; - checker_->getSuggestions(Q2PSTRING(cursor.selectedText()), wordList); - if (wordList.size() == 0) { - QAction* noSuggestions = new QAction(tr("No Suggestions"), menu); - noSuggestions->setDisabled(true); - menu->insertAction(insertPoint, noSuggestions); - } - else { - for (std::vector::iterator it = wordList.begin(); it != wordList.end(); ++it) { - QAction* wordAction = new QAction(it->c_str(), menu); - menu->insertAction(insertPoint, wordAction); - replaceWordActions_.push_back(wordAction); - } - } - menu->insertAction(insertPoint, menu->addSeparator()); - } + replaceWordActions_.clear(); + if (checker_ && highlighter_) { + QAction* insertPoint = menu->actions().first(); + QTextCursor cursor = cursorForPosition(event->pos()); + PositionPair wordPosition = getWordFromCursor(cursor.position()); + if (boost::get<0>(wordPosition) < 0) { + // The click was executed outside a spellable word so no + // suggestions are necessary + return; + } + cursor.setPosition(boost::get<0>(wordPosition), QTextCursor::MoveAnchor); + cursor.setPosition(boost::get<1>(wordPosition), QTextCursor::KeepAnchor); + std::vector wordList; + checker_->getSuggestions(Q2PSTRING(cursor.selectedText()), wordList); + if (wordList.size() == 0) { + QAction* noSuggestions = new QAction(tr("No Suggestions"), menu); + noSuggestions->setDisabled(true); + menu->insertAction(insertPoint, noSuggestions); + } + else { + for (std::vector::iterator it = wordList.begin(); it != wordList.end(); ++it) { + QAction* wordAction = new QAction(it->c_str(), menu); + menu->insertAction(insertPoint, wordAction); + replaceWordActions_.push_back(wordAction); + } + } + menu->insertAction(insertPoint, menu->addSeparator()); + } } #ifdef HAVE_SPELLCHECKER void QtTextEdit::setUpSpellChecker() { - delete highlighter_; - highlighter_ = NULL; - delete checker_; - checker_ = NULL; - if (settings_->getSetting(SettingConstants::SPELL_CHECKER)) { - std::string dictPath = settings_->getSetting(SettingConstants::DICT_PATH); - std::string dictFile = settings_->getSetting(SettingConstants::DICT_FILE); - checker_ = SpellCheckerFactory().createSpellChecker(dictPath + dictFile); - if (checker_) { - highlighter_ = new QtSpellCheckHighlighter(document(), checker_); - } - else { - // Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking. - SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl; - settings_->storeSetting(SettingConstants::SPELL_CHECKER, false); - } - - } + delete highlighter_; + highlighter_ = NULL; + delete checker_; + checker_ = NULL; + if (settings_->getSetting(SettingConstants::SPELL_CHECKER)) { + std::string dictPath = settings_->getSetting(SettingConstants::DICT_PATH); + std::string dictFile = settings_->getSetting(SettingConstants::DICT_FILE); + checker_ = SpellCheckerFactory().createSpellChecker(dictPath + dictFile); + if (checker_) { + highlighter_ = new QtSpellCheckHighlighter(document(), checker_); + } + else { + // Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking. + SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl; + settings_->storeSetting(SettingConstants::SPELL_CHECKER, false); + } + + } } #endif void QtTextEdit::spellCheckerSettingsWindow() { - if (!spellCheckerWindow_) { - spellCheckerWindow_ = new QtSpellCheckerWindow(settings_); - settings_->onSettingChanged.connect(boost::bind(&QtTextEdit::handleSettingChanged, this, _1)); - spellCheckerWindow_->show(); - } - else { - spellCheckerWindow_->show(); - spellCheckerWindow_->raise(); - spellCheckerWindow_->activateWindow(); - } + if (!spellCheckerWindow_) { + spellCheckerWindow_ = new QtSpellCheckerWindow(settings_); + settings_->onSettingChanged.connect(boost::bind(&QtTextEdit::handleSettingChanged, this, _1)); + spellCheckerWindow_->show(); + } + else { + spellCheckerWindow_->show(); + spellCheckerWindow_->raise(); + spellCheckerWindow_->activateWindow(); + } } void QtTextEdit::handleSettingChanged(const std::string& settings) { - if (settings == SettingConstants::SPELL_CHECKER.getKey() - || settings == SettingConstants::DICT_PATH.getKey() - || settings == SettingConstants::DICT_FILE.getKey()) { + if (settings == SettingConstants::SPELL_CHECKER.getKey() + || settings == SettingConstants::DICT_PATH.getKey() + || settings == SettingConstants::DICT_FILE.getKey()) { #ifdef HAVE_SPELLCHECKER - setUpSpellChecker(); - if (highlighter_) { - highlighter_->rehighlight(); - } + setUpSpellChecker(); + if (highlighter_) { + highlighter_->rehighlight(); + } #endif - } + } } } diff --git a/Swift/QtUI/QtTextEdit.h b/Swift/QtUI/QtTextEdit.h index 67826ba..f03699b 100644 --- a/Swift/QtUI/QtTextEdit.h +++ b/Swift/QtUI/QtTextEdit.h @@ -17,47 +17,47 @@ #include namespace Swift { - class SpellChecker; - class QtSpellCheckerWindow; - - class QtTextEdit : public QTextEdit { - Q_OBJECT - public: - QtTextEdit(SettingsProvider* settings, QWidget* parent = 0); - virtual ~QtTextEdit(); - virtual QSize sizeHint() const; - - signals: - void wordCorrected(QString& word); - void returnPressed(); - void unhandledKeyPressEvent(QKeyEvent* event); - void receivedFocus(); - void lostFocus(); - - public slots: - void handleSettingChanged(const std::string& settings); - - protected: - virtual void keyPressEvent(QKeyEvent* event); - virtual void focusInEvent(QFocusEvent* event); - virtual void focusOutEvent(QFocusEvent* event); - virtual void contextMenuEvent(QContextMenuEvent* event); - - private slots: - void handleTextChanged(); - - private: - void addSuggestions(QMenu* menu, QContextMenuEvent* event); - void replaceMisspelledWord(const QString& word, int cursorPosition); - void setUpSpellChecker(); - void spellCheckerSettingsWindow(); - PositionPair getWordFromCursor(int cursorPosition); - - private: - SpellChecker* checker_; - QtSpellCheckHighlighter* highlighter_; - std::vector replaceWordActions_; - SettingsProvider* settings_; - QPointer spellCheckerWindow_; - }; + class SpellChecker; + class QtSpellCheckerWindow; + + class QtTextEdit : public QTextEdit { + Q_OBJECT + public: + QtTextEdit(SettingsProvider* settings, QWidget* parent = 0); + virtual ~QtTextEdit(); + virtual QSize sizeHint() const; + + signals: + void wordCorrected(QString& word); + void returnPressed(); + void unhandledKeyPressEvent(QKeyEvent* event); + void receivedFocus(); + void lostFocus(); + + public slots: + void handleSettingChanged(const std::string& settings); + + protected: + virtual void keyPressEvent(QKeyEvent* event); + virtual void focusInEvent(QFocusEvent* event); + virtual void focusOutEvent(QFocusEvent* event); + virtual void contextMenuEvent(QContextMenuEvent* event); + + private slots: + void handleTextChanged(); + + private: + void addSuggestions(QMenu* menu, QContextMenuEvent* event); + void replaceMisspelledWord(const QString& word, int cursorPosition); + void setUpSpellChecker(); + void spellCheckerSettingsWindow(); + PositionPair getWordFromCursor(int cursorPosition); + + private: + SpellChecker* checker_; + QtSpellCheckHighlighter* highlighter_; + std::vector replaceWordActions_; + SettingsProvider* settings_; + QPointer spellCheckerWindow_; + }; } diff --git a/Swift/QtUI/QtTranslator.h b/Swift/QtUI/QtTranslator.h index b74ea3e..4254324 100644 --- a/Swift/QtUI/QtTranslator.h +++ b/Swift/QtUI/QtTranslator.h @@ -11,15 +11,15 @@ #include class QtTranslator : public Swift::Translator { - public: - QtTranslator() { - } + public: + QtTranslator() { + } - virtual std::string translate(const std::string& text, const std::string& context) { + virtual std::string translate(const std::string& text, const std::string& context) { #if QT_VERSION >= 0x050000 - return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0).toUtf8()); + return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0).toUtf8()); #else - return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0, QCoreApplication::UnicodeUTF8).toUtf8()); + return std::string(QCoreApplication::translate(context.c_str(), text.c_str(), 0, QCoreApplication::UnicodeUTF8).toUtf8()); #endif - } + } }; diff --git a/Swift/QtUI/QtUIFactory.cpp b/Swift/QtUI/QtUIFactory.cpp index 0cde4e1..a1321bd 100644 --- a/Swift/QtUI/QtUIFactory.cpp +++ b/Swift/QtUI/QtUIFactory.cpp @@ -39,148 +39,148 @@ namespace Swift { QtUIFactory::QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID) : settings(settings), qtOnlySettings(qtOnlySettings), tabsBase(tabs), netbookSplitter(netbookSplitter), systemTray(systemTray), chatWindowFactory(chatWindowFactory), timerFactory_(timerFactory), lastMainWindow(NULL), loginWindow(NULL), statusCache(statusCache), startMinimized(startMinimized), emoticonsExist_(emoticonsExist), enableAdHocCommandOnJID_(enableAdHocCommandOnJID) { - chatFontSize = settings->getSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE); - historyFontSize_ = settings->getSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE); - this->tabs = dynamic_cast(tabsBase); + chatFontSize = settings->getSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE); + historyFontSize_ = settings->getSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE); + this->tabs = dynamic_cast(tabsBase); } XMLConsoleWidget* QtUIFactory::createXMLConsoleWidget() { - QtXMLConsoleWidget* widget = new QtXMLConsoleWidget(); - tabsBase->addTab(widget); - showTabs(); - widget->show(); - return widget; + QtXMLConsoleWidget* widget = new QtXMLConsoleWidget(); + tabsBase->addTab(widget); + showTabs(); + widget->show(); + return widget; } HistoryWindow* QtUIFactory::createHistoryWindow(UIEventStream* uiEventStream) { - QtHistoryWindow* window = new QtHistoryWindow(settings, uiEventStream); - tabsBase->addTab(window); - showTabs(); - connect(window, SIGNAL(fontResized(int)), this, SLOT(handleHistoryWindowFontResized(int))); + QtHistoryWindow* window = new QtHistoryWindow(settings, uiEventStream); + tabsBase->addTab(window); + showTabs(); + connect(window, SIGNAL(fontResized(int)), this, SLOT(handleHistoryWindowFontResized(int))); - window->handleFontResized(historyFontSize_); - window->show(); - return window; + window->handleFontResized(historyFontSize_); + window->show(); + return window; } void QtUIFactory::handleHistoryWindowFontResized(int size) { - historyFontSize_ = size; - settings->storeSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE, size); + historyFontSize_ = size; + settings->storeSetting(QtUISettingConstants::HISTORYWINDOW_FONT_SIZE, size); } FileTransferListWidget* QtUIFactory::createFileTransferListWidget() { - QtFileTransferListWidget* widget = new QtFileTransferListWidget(); - tabsBase->addTab(widget); - showTabs(); - widget->show(); - return widget; + QtFileTransferListWidget* widget = new QtFileTransferListWidget(); + tabsBase->addTab(widget); + showTabs(); + widget->show(); + return widget; } MainWindow* QtUIFactory::createMainWindow(UIEventStream* eventStream) { - lastMainWindow = new QtMainWindow(settings, eventStream, loginWindow->getMenus(), statusCache, emoticonsExist_, enableAdHocCommandOnJID_); - if (tabs) { - tabs->setViewMenu(lastMainWindow->getMenus()[0]); - } - return lastMainWindow; + lastMainWindow = new QtMainWindow(settings, eventStream, loginWindow->getMenus(), statusCache, emoticonsExist_, enableAdHocCommandOnJID_); + if (tabs) { + tabs->setViewMenu(lastMainWindow->getMenus()[0]); + } + return lastMainWindow; } LoginWindow* QtUIFactory::createLoginWindow(UIEventStream* eventStream) { - loginWindow = new QtLoginWindow(eventStream, settings, timerFactory_); - if (netbookSplitter) { - netbookSplitter->insertAtFront(loginWindow); - } - connect(systemTray, SIGNAL(clicked()), loginWindow, SLOT(toggleBringToFront())); + loginWindow = new QtLoginWindow(eventStream, settings, timerFactory_); + if (netbookSplitter) { + netbookSplitter->insertAtFront(loginWindow); + } + connect(systemTray, SIGNAL(clicked()), loginWindow, SLOT(toggleBringToFront())); #ifndef SWIFT_MOBILE - QVariant loginWindowGeometryVariant = qtOnlySettings->getQSettings()->value("loginWindowGeometry"); - if (loginWindowGeometryVariant.isValid()) { - loginWindow->restoreGeometry(loginWindowGeometryVariant.toByteArray()); - } - connect(loginWindow, SIGNAL(geometryChanged()), this, SLOT(handleLoginWindowGeometryChanged())); - if (startMinimized) loginWindow->hide(); + QVariant loginWindowGeometryVariant = qtOnlySettings->getQSettings()->value("loginWindowGeometry"); + if (loginWindowGeometryVariant.isValid()) { + loginWindow->restoreGeometry(loginWindowGeometryVariant.toByteArray()); + } + connect(loginWindow, SIGNAL(geometryChanged()), this, SLOT(handleLoginWindowGeometryChanged())); + if (startMinimized) loginWindow->hide(); #endif - return loginWindow; + return loginWindow; } void QtUIFactory::handleLoginWindowGeometryChanged() { - qtOnlySettings->getQSettings()->setValue("loginWindowGeometry", loginWindow->saveGeometry()); + qtOnlySettings->getQSettings()->setValue("loginWindowGeometry", loginWindow->saveGeometry()); } EventWindow* QtUIFactory::createEventWindow() { - return lastMainWindow->getEventWindow(); + return lastMainWindow->getEventWindow(); } ChatListWindow* QtUIFactory::createChatListWindow(UIEventStream*) { - return lastMainWindow->getChatListWindow(); + return lastMainWindow->getChatListWindow(); } MUCSearchWindow* QtUIFactory::createMUCSearchWindow() { - return new QtMUCSearchWindow(); + return new QtMUCSearchWindow(); } ChatWindow* QtUIFactory::createChatWindow(const JID& contact, UIEventStream* eventStream) { - QtChatWindow* window = dynamic_cast(chatWindowFactory->createChatWindow(contact, eventStream)); - chatWindows.push_back(window); - std::vector > deletions; - foreach (QPointer existingWindow, chatWindows) { - if (existingWindow.isNull()) { - deletions.push_back(existingWindow); - } else { - connect(window, SIGNAL(fontResized(int)), existingWindow, SLOT(handleFontResized(int))); - connect(existingWindow, SIGNAL(fontResized(int)), window, SLOT(handleFontResized(int))); - } - } - foreach (QPointer deletedWindow, deletions) { - chatWindows.erase(std::remove(chatWindows.begin(), chatWindows.end(), deletedWindow), chatWindows.end()); - } - connect(window, SIGNAL(fontResized(int)), this, SLOT(handleChatWindowFontResized(int))); - window->handleFontResized(chatFontSize); - return window; + QtChatWindow* window = dynamic_cast(chatWindowFactory->createChatWindow(contact, eventStream)); + chatWindows.push_back(window); + std::vector > deletions; + foreach (QPointer existingWindow, chatWindows) { + if (existingWindow.isNull()) { + deletions.push_back(existingWindow); + } else { + connect(window, SIGNAL(fontResized(int)), existingWindow, SLOT(handleFontResized(int))); + connect(existingWindow, SIGNAL(fontResized(int)), window, SLOT(handleFontResized(int))); + } + } + foreach (QPointer deletedWindow, deletions) { + chatWindows.erase(std::remove(chatWindows.begin(), chatWindows.end(), deletedWindow), chatWindows.end()); + } + connect(window, SIGNAL(fontResized(int)), this, SLOT(handleChatWindowFontResized(int))); + window->handleFontResized(chatFontSize); + return window; } void QtUIFactory::handleChatWindowFontResized(int size) { - chatFontSize = size; - settings->storeSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE, size); + chatFontSize = size; + settings->storeSetting(QtUISettingConstants::CHATWINDOW_FONT_SIZE, size); } UserSearchWindow* QtUIFactory::createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set& groups) { - return new QtUserSearchWindow(eventStream, type, groups, qtOnlySettings); + return new QtUserSearchWindow(eventStream, type, groups, qtOnlySettings); } JoinMUCWindow* QtUIFactory::createJoinMUCWindow(UIEventStream* uiEventStream) { - return new QtJoinMUCWindow(uiEventStream); + return new QtJoinMUCWindow(uiEventStream); } ProfileWindow* QtUIFactory::createProfileWindow() { - return new QtProfileWindow(); + return new QtProfileWindow(); } ContactEditWindow* QtUIFactory::createContactEditWindow() { - return new QtContactEditWindow(); + return new QtContactEditWindow(); } WhiteboardWindow* QtUIFactory::createWhiteboardWindow(boost::shared_ptr whiteboardSession) { - return new QtWhiteboardWindow(whiteboardSession); + return new QtWhiteboardWindow(whiteboardSession); } HighlightEditorWindow* QtUIFactory::createHighlightEditorWindow() { - return new QtHighlightEditor(qtOnlySettings); + return new QtHighlightEditor(qtOnlySettings); } BlockListEditorWidget *QtUIFactory::createBlockListEditorWidget() { - return new QtBlockListEditorWindow(); + return new QtBlockListEditorWindow(); } AdHocCommandWindow* QtUIFactory::createAdHocCommandWindow(boost::shared_ptr command) { - return new QtAdHocCommandWindow(command); + return new QtAdHocCommandWindow(command); } void QtUIFactory::showTabs() { - if (tabs) { - if (!tabs->isVisible()) { - tabs->show(); - } - } + if (tabs) { + if (!tabs->isVisible()) { + tabs->show(); + } + } } } diff --git a/Swift/QtUI/QtUIFactory.h b/Swift/QtUI/QtUIFactory.h index 1d935bc..c72bf63 100644 --- a/Swift/QtUI/QtUIFactory.h +++ b/Swift/QtUI/QtUIFactory.h @@ -14,70 +14,70 @@ class QSplitter; namespace Swift { - class QtSettingsProvider; - class SettingsProviderHierachy; - class QtChatTabsBase; - class QtChatTabs; - class QtSystemTray; - class QtLoginWindow; - class QtMainWindow; - class QtChatTheme; - class QtChatWindowFactory; - class QtChatWindow; - class TimerFactory; - class historyWindow_; - class WhiteboardSession; - class StatusCache; - class QtSingleWindow; + class QtSettingsProvider; + class SettingsProviderHierachy; + class QtChatTabsBase; + class QtChatTabs; + class QtSystemTray; + class QtLoginWindow; + class QtMainWindow; + class QtChatTheme; + class QtChatWindowFactory; + class QtChatWindow; + class TimerFactory; + class historyWindow_; + class WhiteboardSession; + class StatusCache; + class QtSingleWindow; - class QtUIFactory : public QObject, public UIFactory { - Q_OBJECT - public: - QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID); + class QtUIFactory : public QObject, public UIFactory { + Q_OBJECT + public: + QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider* qtOnlySettings, QtChatTabsBase* tabs, QtSingleWindow* netbookSplitter, QtSystemTray* systemTray, QtChatWindowFactory* chatWindowFactory, TimerFactory* timerFactory, StatusCache* statusCache, bool startMinimized, bool emoticonsExist, bool enableAdHocCommandOnJID); - virtual XMLConsoleWidget* createXMLConsoleWidget(); - virtual HistoryWindow* createHistoryWindow(UIEventStream*); - virtual MainWindow* createMainWindow(UIEventStream* eventStream); - virtual LoginWindow* createLoginWindow(UIEventStream* eventStream); - virtual EventWindow* createEventWindow(); - virtual ChatListWindow* createChatListWindow(UIEventStream*); - virtual MUCSearchWindow* createMUCSearchWindow(); - virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream); - virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set& groups); - virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream); - virtual ProfileWindow* createProfileWindow(); - virtual ContactEditWindow* createContactEditWindow(); - virtual FileTransferListWidget* createFileTransferListWidget(); - virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr whiteboardSession); - virtual HighlightEditorWindow* createHighlightEditorWindow(); - virtual BlockListEditorWidget* createBlockListEditorWidget(); - virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr command); + virtual XMLConsoleWidget* createXMLConsoleWidget(); + virtual HistoryWindow* createHistoryWindow(UIEventStream*); + virtual MainWindow* createMainWindow(UIEventStream* eventStream); + virtual LoginWindow* createLoginWindow(UIEventStream* eventStream); + virtual EventWindow* createEventWindow(); + virtual ChatListWindow* createChatListWindow(UIEventStream*); + virtual MUCSearchWindow* createMUCSearchWindow(); + virtual ChatWindow* createChatWindow(const JID &contact, UIEventStream* eventStream); + virtual UserSearchWindow* createUserSearchWindow(UserSearchWindow::Type type, UIEventStream* eventStream, const std::set& groups); + virtual JoinMUCWindow* createJoinMUCWindow(UIEventStream* uiEventStream); + virtual ProfileWindow* createProfileWindow(); + virtual ContactEditWindow* createContactEditWindow(); + virtual FileTransferListWidget* createFileTransferListWidget(); + virtual WhiteboardWindow* createWhiteboardWindow(boost::shared_ptr whiteboardSession); + virtual HighlightEditorWindow* createHighlightEditorWindow(); + virtual BlockListEditorWidget* createBlockListEditorWidget(); + virtual AdHocCommandWindow* createAdHocCommandWindow(boost::shared_ptr command); - private slots: - void handleLoginWindowGeometryChanged(); - void handleChatWindowFontResized(int); - void handleHistoryWindowFontResized(int); + private slots: + void handleLoginWindowGeometryChanged(); + void handleChatWindowFontResized(int); + void handleHistoryWindowFontResized(int); - private: - void showTabs(); + private: + void showTabs(); - private: - SettingsProviderHierachy* settings; - QtSettingsProvider* qtOnlySettings; - QtChatTabsBase* tabsBase; - QtChatTabs* tabs; - QtSingleWindow* netbookSplitter; - QtSystemTray* systemTray; - QtChatWindowFactory* chatWindowFactory; - TimerFactory* timerFactory_; - QtMainWindow* lastMainWindow; - QtLoginWindow* loginWindow; - StatusCache* statusCache; - std::vector > chatWindows; - bool startMinimized; - int chatFontSize; - int historyFontSize_; - bool emoticonsExist_; - bool enableAdHocCommandOnJID_; - }; + private: + SettingsProviderHierachy* settings; + QtSettingsProvider* qtOnlySettings; + QtChatTabsBase* tabsBase; + QtChatTabs* tabs; + QtSingleWindow* netbookSplitter; + QtSystemTray* systemTray; + QtChatWindowFactory* chatWindowFactory; + TimerFactory* timerFactory_; + QtMainWindow* lastMainWindow; + QtLoginWindow* loginWindow; + StatusCache* statusCache; + std::vector > chatWindows; + bool startMinimized; + int chatFontSize; + int historyFontSize_; + bool emoticonsExist_; + bool enableAdHocCommandOnJID_; + }; } diff --git a/Swift/QtUI/QtUISettingConstants.h b/Swift/QtUI/QtUISettingConstants.h index 4c17c0d..3e7291f 100644 --- a/Swift/QtUI/QtUISettingConstants.h +++ b/Swift/QtUI/QtUISettingConstants.h @@ -9,16 +9,16 @@ #include namespace Swift { - class QtUISettingConstants { - public: - static const SettingsProvider::Setting COMPACT_ROSTER; - static const SettingsProvider::Setting CLICKTHROUGH_BANNER; - static const SettingsProvider::Setting CURRENT_ROSTER_TAB; - static const SettingsProvider::Setting SHOW_NICK_IN_ROSTER_HEADER; - static const SettingsProvider::Setting CHATWINDOW_FONT_SIZE; - static const SettingsProvider::Setting HISTORYWINDOW_FONT_SIZE; - static const SettingsProvider::Setting SHOW_EMOTICONS; - static const SettingsProvider::Setting USE_PLAIN_CHATS; - static const SettingsProvider::Setting USE_SCREENREADER; - }; + class QtUISettingConstants { + public: + static const SettingsProvider::Setting COMPACT_ROSTER; + static const SettingsProvider::Setting CLICKTHROUGH_BANNER; + static const SettingsProvider::Setting CURRENT_ROSTER_TAB; + static const SettingsProvider::Setting SHOW_NICK_IN_ROSTER_HEADER; + static const SettingsProvider::Setting CHATWINDOW_FONT_SIZE; + static const SettingsProvider::Setting HISTORYWINDOW_FONT_SIZE; + static const SettingsProvider::Setting SHOW_EMOTICONS; + static const SettingsProvider::Setting USE_PLAIN_CHATS; + static const SettingsProvider::Setting USE_SCREENREADER; + }; } diff --git a/Swift/QtUI/QtURIHandler.cpp b/Swift/QtUI/QtURIHandler.cpp index e3b9a53..24bd328 100644 --- a/Swift/QtUI/QtURIHandler.cpp +++ b/Swift/QtUI/QtURIHandler.cpp @@ -15,16 +15,16 @@ using namespace Swift; QtURIHandler::QtURIHandler() { - qApp->installEventFilter(this); + qApp->installEventFilter(this); } bool QtURIHandler::eventFilter(QObject*, QEvent* event) { - if (event->type() == QEvent::FileOpen) { - QFileOpenEvent* fileOpenEvent = static_cast(event); - if (fileOpenEvent->url().scheme() == "xmpp") { - onURI(Q2PSTRING(fileOpenEvent->url().toString())); - return true; - } - } - return false; + if (event->type() == QEvent::FileOpen) { + QFileOpenEvent* fileOpenEvent = static_cast(event); + if (fileOpenEvent->url().scheme() == "xmpp") { + onURI(Q2PSTRING(fileOpenEvent->url().toString())); + return true; + } + } + return false; } diff --git a/Swift/QtUI/QtURIHandler.h b/Swift/QtUI/QtURIHandler.h index 1abcac6..309e55b 100644 --- a/Swift/QtUI/QtURIHandler.h +++ b/Swift/QtUI/QtURIHandler.h @@ -13,11 +13,11 @@ class QUrl; namespace Swift { - class QtURIHandler : public QObject, public URIHandler { - public: - QtURIHandler(); + class QtURIHandler : public QObject, public URIHandler { + public: + QtURIHandler(); - private: - bool eventFilter(QObject* obj, QEvent* event); - }; + private: + bool eventFilter(QObject* obj, QEvent* event); + }; } diff --git a/Swift/QtUI/QtURLValidator.cpp b/Swift/QtUI/QtURLValidator.cpp index 45bf528..8017710 100644 --- a/Swift/QtUI/QtURLValidator.cpp +++ b/Swift/QtUI/QtURLValidator.cpp @@ -16,10 +16,10 @@ QtURLValidator::QtURLValidator(QObject* parent) : QValidator(parent) { } QValidator::State QtURLValidator::validate(QString& input, int&) const { - URL url = URL::fromString(Q2PSTRING(input)); - bool valid = !url.isEmpty(); - valid &= (url.getScheme() == "http" || url.getScheme() == "https"); - return valid ? Acceptable : Intermediate; + URL url = URL::fromString(Q2PSTRING(input)); + bool valid = !url.isEmpty(); + valid &= (url.getScheme() == "http" || url.getScheme() == "https"); + return valid ? Acceptable : Intermediate; } } diff --git a/Swift/QtUI/QtURLValidator.h b/Swift/QtUI/QtURLValidator.h index b374ef4..887828a 100644 --- a/Swift/QtUI/QtURLValidator.h +++ b/Swift/QtUI/QtURLValidator.h @@ -7,11 +7,11 @@ #include namespace Swift { - class QtURLValidator : public QValidator { - Q_OBJECT - public: - QtURLValidator(QObject* parent); - virtual QValidator::State validate(QString& input, int& pos) const; - }; + class QtURLValidator : public QValidator { + Q_OBJECT + public: + QtURLValidator(QObject* parent); + virtual QValidator::State validate(QString& input, int& pos) const; + }; } diff --git a/Swift/QtUI/QtUtilities.cpp b/Swift/QtUI/QtUtilities.cpp index b4b1b09..401af17 100644 --- a/Swift/QtUI/QtUtilities.cpp +++ b/Swift/QtUI/QtUtilities.cpp @@ -22,23 +22,23 @@ namespace QtUtilities { void setX11Resource(QWidget* widget, const QString& c) { #if defined (Q_OS_UNIX) && !defined(Q_OS_MAC) && QT_VERSION < 0x050000 - char res_class[] = SWIFT_APPLICATION_NAME; - XClassHint hint; - QByteArray resName = (QString(SWIFT_APPLICATION_NAME) + "-" + c).toUtf8(); - hint.res_name = resName.data(); - hint.res_class = res_class; - XSetClassHint(widget->x11Info().display(), widget->winId(), &hint); + char res_class[] = SWIFT_APPLICATION_NAME; + XClassHint hint; + QByteArray resName = (QString(SWIFT_APPLICATION_NAME) + "-" + c).toUtf8(); + hint.res_name = resName.data(); + hint.res_class = res_class; + XSetClassHint(widget->x11Info().display(), widget->winId(), &hint); #else - (void) widget; - (void) c; + (void) widget; + (void) c; #endif } QString htmlEscape(const QString& s) { #if QT_VERSION >= 0x050000 - return s.toHtmlEscaped(); + return s.toHtmlEscaped(); #else - return Qt::escape(s); + return Qt::escape(s); #endif } diff --git a/Swift/QtUI/QtUtilities.h b/Swift/QtUI/QtUtilities.h index 4d71d7c..ad58499 100644 --- a/Swift/QtUI/QtUtilities.h +++ b/Swift/QtUI/QtUtilities.h @@ -12,11 +12,11 @@ class QString; #include namespace QtUtilities { - void setX11Resource(QWidget* widget, const QString& c); - QString htmlEscape(const QString& s); - #ifdef SWIFTEN_PLATFORM_MACOSX - const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::MetaModifier; - #else - const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::ControlModifier; - #endif + void setX11Resource(QWidget* widget, const QString& c); + QString htmlEscape(const QString& s); + #ifdef SWIFTEN_PLATFORM_MACOSX + const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::MetaModifier; + #else + const Qt::KeyboardModifier ctrlHardwareKeyModifier = Qt::ControlModifier; + #endif } diff --git a/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp b/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp index 9d79859..ec7941c 100644 --- a/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp +++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.cpp @@ -24,28 +24,28 @@ QtCloseButton::QtCloseButton(QWidget *parent) : QAbstractButton(parent) { } QSize QtCloseButton::sizeHint() const { - return QSize(style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0), style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0)); + return QSize(style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0), style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0)); } bool QtCloseButton::event(QEvent *e) { - if (e->type() == QEvent::Enter || e->type() == QEvent::Leave) { - update(); - } - return QAbstractButton::event(e); + if (e->type() == QEvent::Enter || e->type() == QEvent::Leave) { + update(); + } + return QAbstractButton::event(e); } void QtCloseButton::paintEvent(QPaintEvent *) { - QPainter painter(this); - painter.setRenderHint(QPainter::HighQualityAntialiasing); - QStyleOption opt; - opt.init(this); - opt.state |= QStyle::State_AutoRaise; - if (underMouse() && !isDown()) { - opt.state |= QStyle::State_Raised; - } else if (isDown()) { - opt.state |= QStyle::State_Sunken; - } - style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &painter, this); + QPainter painter(this); + painter.setRenderHint(QPainter::HighQualityAntialiasing); + QStyleOption opt; + opt.init(this); + opt.state |= QStyle::State_AutoRaise; + if (underMouse() && !isDown()) { + opt.state |= QStyle::State_Raised; + } else if (isDown()) { + opt.state |= QStyle::State_Sunken; + } + style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &painter, this); } } diff --git a/Swift/QtUI/QtVCardWidget/QtCloseButton.h b/Swift/QtUI/QtVCardWidget/QtCloseButton.h index cb92e12..1ba31a0 100644 --- a/Swift/QtUI/QtVCardWidget/QtCloseButton.h +++ b/Swift/QtUI/QtVCardWidget/QtCloseButton.h @@ -10,15 +10,15 @@ namespace Swift { - class QtCloseButton : public QAbstractButton { - Q_OBJECT - public: - explicit QtCloseButton(QWidget *parent = 0); - virtual QSize sizeHint() const; + class QtCloseButton : public QAbstractButton { + Q_OBJECT + public: + explicit QtCloseButton(QWidget *parent = 0); + virtual QSize sizeHint() const; - protected: - virtual bool event(QEvent *e); - virtual void paintEvent(QPaintEvent* ); - }; + protected: + virtual bool event(QEvent *e); + virtual void paintEvent(QPaintEvent* ); + }; } diff --git a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp index 73575f6..67c79a9 100644 --- a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp +++ b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.cpp @@ -24,42 +24,42 @@ QtRemovableItemDelegate::QtRemovableItemDelegate(const QStyle* style) : style(st } void QtRemovableItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { - QStyleOption opt; - opt.state = option.state; - opt.state |= QStyle::State_AutoRaise; - if (option.state.testFlag(QStyle::State_MouseOver)) { - opt.state |= QStyle::State_Raised; - } - opt.rect = option.rect; - painter->save(); - painter->fillRect(option.rect, option.state & QStyle::State_Selected ? option.palette.highlight() : option.palette.base()); - if (index.data().toString().isEmpty()) { + QStyleOption opt; + opt.state = option.state; + opt.state |= QStyle::State_AutoRaise; + if (option.state.testFlag(QStyle::State_MouseOver)) { + opt.state |= QStyle::State_Raised; + } + opt.rect = option.rect; + painter->save(); + painter->fillRect(option.rect, option.state & QStyle::State_Selected ? option.palette.highlight() : option.palette.base()); + if (index.data().toString().isEmpty()) { #ifdef SWIFTEN_PLATFORM_MACOSX - // workaround for Qt not painting relative to the cell we're in, on OS X - int height = style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0); - painter->translate(option.rect.x(), option.rect.y() + (option.rect.height() - height)/2); + // workaround for Qt not painting relative to the cell we're in, on OS X + int height = style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0); + painter->translate(option.rect.x(), option.rect.y() + (option.rect.height() - height)/2); #endif - style->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, painter); - } - painter->restore(); + style->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, painter); + } + painter->restore(); } QWidget* QtRemovableItemDelegate::createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const { - return NULL; + return NULL; } bool QtRemovableItemDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) { - if (index.data().toString().isEmpty() && event->type() == QEvent::MouseButtonRelease) { - model->removeRow(index.row()); - return true; - } else { - return QItemDelegate::editorEvent(event, model, option, index); - } + if (index.data().toString().isEmpty() && event->type() == QEvent::MouseButtonRelease) { + model->removeRow(index.row()); + return true; + } else { + return QItemDelegate::editorEvent(event, model, option, index); + } } QSize QtRemovableItemDelegate::sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const { - QSize size(style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0) + 2, style->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0) + 2); - return size; + QSize size(style->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, 0, 0) + 2, style->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, 0, 0) + 2); + return size; } } diff --git a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h index 75137e1..ea9e0b2 100644 --- a/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h +++ b/Swift/QtUI/QtVCardWidget/QtRemovableItemDelegate.h @@ -11,18 +11,18 @@ namespace Swift { class QtRemovableItemDelegate : public QItemDelegate { - public: - QtRemovableItemDelegate(const QStyle* style); + public: + QtRemovableItemDelegate(const QStyle* style); - virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex&) const; - virtual QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const; - virtual QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const; + virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex&) const; + virtual QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const; + virtual QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const; - protected: - virtual bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index); + protected: + virtual bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index); - private: - const QStyle* style; + private: + const QStyle* style; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp index 3492cb9..9eef970 100644 --- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp +++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.cpp @@ -16,43 +16,43 @@ namespace Swift { QtResizableLineEdit::QtResizableLineEdit(QWidget* parent) : - QLineEdit(parent), editable(false) { - connect(this, SIGNAL(textChanged(QString)), SLOT(textChanged(QString))); - setMinimumWidth(30); + QLineEdit(parent), editable(false) { + connect(this, SIGNAL(textChanged(QString)), SLOT(textChanged(QString))); + setMinimumWidth(30); } QtResizableLineEdit::~QtResizableLineEdit() { } bool QtResizableLineEdit::isEditable() const { - return editable; + return editable; } void QtResizableLineEdit::setEditable(const bool editable) { - this->editable = editable; - if (editable) { - setReadOnly(false); - } else { - setReadOnly(true); - } + this->editable = editable; + if (editable) { + setReadOnly(false); + } else { + setReadOnly(true); + } } QSize QtResizableLineEdit::sizeHint() const { - int horizontalMargin = 10; - int verticalMargin = 6; - QSize textDimensions; + int horizontalMargin = 10; + int verticalMargin = 6; + QSize textDimensions; #if QT_VERSION >= 0x040700 - textDimensions = fontMetrics().boundingRect(text().isEmpty() ? placeholderText() : text()).size(); + textDimensions = fontMetrics().boundingRect(text().isEmpty() ? placeholderText() : text()).size(); #else - textDimensions = fontMetrics().boundingRect(text().isEmpty() ? QString(" ") : text()).size(); + textDimensions = fontMetrics().boundingRect(text().isEmpty() ? QString(" ") : text()).size(); #endif - textDimensions.setWidth(textDimensions.width() + horizontalMargin); - textDimensions.setHeight(textDimensions.height() + verticalMargin); - return textDimensions; + textDimensions.setWidth(textDimensions.width() + horizontalMargin); + textDimensions.setHeight(textDimensions.height() + verticalMargin); + return textDimensions; } void QtResizableLineEdit::textChanged(QString) { - updateGeometry(); + updateGeometry(); } } diff --git a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h index 9022d38..47c6f3e 100644 --- a/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h +++ b/Swift/QtUI/QtVCardWidget/QtResizableLineEdit.h @@ -10,24 +10,24 @@ namespace Swift { - class QtResizableLineEdit : public QLineEdit { - Q_OBJECT - Q_PROPERTY(bool editable READ isEditable WRITE setEditable) + class QtResizableLineEdit : public QLineEdit { + Q_OBJECT + Q_PROPERTY(bool editable READ isEditable WRITE setEditable) - public: - explicit QtResizableLineEdit(QWidget* parent = 0); - ~QtResizableLineEdit(); + public: + explicit QtResizableLineEdit(QWidget* parent = 0); + ~QtResizableLineEdit(); - bool isEditable() const; - void setEditable(const bool); + bool isEditable() const; + void setEditable(const bool); - virtual QSize sizeHint() const; + virtual QSize sizeHint() const; - private slots: - void textChanged(QString); + private slots: + void textChanged(QString); - private: - bool editable; - }; + private: + bool editable; + }; } diff --git a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp index 7036f84..ed36580 100644 --- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp +++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.cpp @@ -18,14 +18,14 @@ namespace Swift { QtTagComboBox::QtTagComboBox(QWidget* parent) : QComboBox(parent) { - setEditable(false); - displayModel = new QStandardItemModel(this); - displayItem = new QStandardItem(); - displayItem->setText(""); - displayModel->insertRow(0, displayItem); - editMenu = new QMenu(this); - this->setModel(displayModel); - editable = true; + setEditable(false); + displayModel = new QStandardItemModel(this); + displayItem = new QStandardItem(); + displayItem->setText(""); + displayModel->insertRow(0, displayItem); + editMenu = new QMenu(this); + this->setModel(displayModel); + editable = true; } QtTagComboBox::~QtTagComboBox() { @@ -33,40 +33,40 @@ QtTagComboBox::~QtTagComboBox() { } bool QtTagComboBox::isEditable() const { - return editable; + return editable; } void QtTagComboBox::setEditable(const bool editable) { - this->editable = editable; + this->editable = editable; } void QtTagComboBox::addTag(const QString &id, const QString &label) { - QAction* tagAction = new QAction(editMenu); - tagAction->setText(label); - tagAction->setCheckable(true); - tagAction->setData(QString(id)); - editMenu->addAction(tagAction); + QAction* tagAction = new QAction(editMenu); + tagAction->setText(label); + tagAction->setCheckable(true); + tagAction->setData(QString(id)); + editMenu->addAction(tagAction); } void QtTagComboBox::setTag(const QString &id, bool value) { - QList tagActions = editMenu->actions(); - foreach(QAction* action, tagActions) { - if (action->data() == id) { - action->setChecked(value); - updateDisplayItem(); - return; - } - } + QList tagActions = editMenu->actions(); + foreach(QAction* action, tagActions) { + if (action->data() == id) { + action->setChecked(value); + updateDisplayItem(); + return; + } + } } bool QtTagComboBox::isTagSet(const QString &id) const { - QList tagActions = editMenu->actions(); - foreach(QAction* action, tagActions) { - if (action->data() == id) { - return action->isChecked(); - } - } - return false; + QList tagActions = editMenu->actions(); + foreach(QAction* action, tagActions) { + if (action->data() == id) { + return action->isChecked(); + } + } + return false; } void QtTagComboBox::showPopup() { @@ -78,31 +78,31 @@ void QtTagComboBox::hidePopup() { } bool QtTagComboBox::event(QEvent* event) { - if (event->type() == QEvent::MouseButtonPress || - event->type() == QEvent::KeyRelease) { - if (!editable) return true; - - QPoint p = mapToGlobal(QPoint(0,0)); - p += QPoint(0, height()); - editMenu->exec(p); - updateDisplayItem(); - return true; - } - return QComboBox::event(event); + if (event->type() == QEvent::MouseButtonPress || + event->type() == QEvent::KeyRelease) { + if (!editable) return true; + + QPoint p = mapToGlobal(QPoint(0,0)); + p += QPoint(0, height()); + editMenu->exec(p); + updateDisplayItem(); + return true; + } + return QComboBox::event(event); } void QtTagComboBox::updateDisplayItem() { - QList tagActions = editMenu->actions(); - QString text = ""; - foreach(QAction* action, tagActions) { - if (action->isChecked()) { - if (text != "") { - text += ", "; - } - text += action->text(); - } - } - setItemText(0, text); + QList tagActions = editMenu->actions(); + QString text = ""; + foreach(QAction* action, tagActions) { + if (action->isChecked()) { + if (text != "") { + text += ", "; + } + text += action->text(); + } + } + setItemText(0, text); } } diff --git a/Swift/QtUI/QtVCardWidget/QtTagComboBox.h b/Swift/QtUI/QtVCardWidget/QtTagComboBox.h index 37a60af..f08f136 100644 --- a/Swift/QtUI/QtVCardWidget/QtTagComboBox.h +++ b/Swift/QtUI/QtVCardWidget/QtTagComboBox.h @@ -14,33 +14,33 @@ namespace Swift { class QtTagComboBox : public QComboBox { - Q_OBJECT - Q_PROPERTY(bool editable READ isEditable WRITE setEditable) + Q_OBJECT + Q_PROPERTY(bool editable READ isEditable WRITE setEditable) - public: - explicit QtTagComboBox(QWidget* parent = 0); - ~QtTagComboBox(); + public: + explicit QtTagComboBox(QWidget* parent = 0); + ~QtTagComboBox(); - bool isEditable() const; - void setEditable(const bool); + bool isEditable() const; + void setEditable(const bool); - void addTag(const QString& id, const QString& label); - void setTag(const QString& id, bool value); - bool isTagSet(const QString& id) const; + void addTag(const QString& id, const QString& label); + void setTag(const QString& id, bool value); + bool isTagSet(const QString& id) const; - virtual void showPopup(); - virtual void hidePopup(); + virtual void showPopup(); + virtual void hidePopup(); - virtual bool event(QEvent* event); + virtual bool event(QEvent* event); - private: - void updateDisplayItem(); + private: + void updateDisplayItem(); - private: - bool editable; - QStandardItemModel* displayModel; - QStandardItem* displayItem; - QMenu* editMenu; + private: + bool editable; + QStandardItemModel* displayModel; + QStandardItem* displayItem; + QMenu* editMenu; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp index 5f9fddf..57bb2cd 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.cpp @@ -20,163 +20,163 @@ namespace Swift { QtVCardAddressField::QtVCardAddressField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address")), streetLineEdit(NULL), poboxLineEdit(NULL), addressextLineEdit(NULL), cityLineEdit(NULL), pocodeLineEdit(NULL), regionLineEdit(NULL), countryLineEdit(NULL), textFieldGridLayout(NULL), textFieldGridLayoutItem(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address")), streetLineEdit(NULL), poboxLineEdit(NULL), addressextLineEdit(NULL), cityLineEdit(NULL), pocodeLineEdit(NULL), regionLineEdit(NULL), countryLineEdit(NULL), textFieldGridLayout(NULL), textFieldGridLayoutItem(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardAddressField::~QtVCardAddressField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardAddressField::setupContentWidgets() { - textFieldGridLayout = new QGridLayout(); + textFieldGridLayout = new QGridLayout(); - streetLineEdit = new QtResizableLineEdit(this); - textFieldGridLayout->addWidget(streetLineEdit, 0, 0, Qt::AlignVCenter); + streetLineEdit = new QtResizableLineEdit(this); + textFieldGridLayout->addWidget(streetLineEdit, 0, 0, Qt::AlignVCenter); - poboxLineEdit = new QtResizableLineEdit(this); - textFieldGridLayout->addWidget(poboxLineEdit, 0, 1, Qt::AlignVCenter); + poboxLineEdit = new QtResizableLineEdit(this); + textFieldGridLayout->addWidget(poboxLineEdit, 0, 1, Qt::AlignVCenter); - addressextLineEdit = new QtResizableLineEdit(this); - textFieldGridLayout->addWidget(addressextLineEdit, 1, 0, Qt::AlignVCenter); + addressextLineEdit = new QtResizableLineEdit(this); + textFieldGridLayout->addWidget(addressextLineEdit, 1, 0, Qt::AlignVCenter); - cityLineEdit = new QtResizableLineEdit(this); - textFieldGridLayout->addWidget(cityLineEdit, 2, 0, Qt::AlignVCenter); + cityLineEdit = new QtResizableLineEdit(this); + textFieldGridLayout->addWidget(cityLineEdit, 2, 0, Qt::AlignVCenter); - pocodeLineEdit = new QtResizableLineEdit(this); - textFieldGridLayout->addWidget(pocodeLineEdit, 2, 1, Qt::AlignVCenter); + pocodeLineEdit = new QtResizableLineEdit(this); + textFieldGridLayout->addWidget(pocodeLineEdit, 2, 1, Qt::AlignVCenter); - regionLineEdit = new QtResizableLineEdit(this); - textFieldGridLayout->addWidget(regionLineEdit, 3, 0, Qt::AlignVCenter); + regionLineEdit = new QtResizableLineEdit(this); + textFieldGridLayout->addWidget(regionLineEdit, 3, 0, Qt::AlignVCenter); - countryLineEdit = new QtResizableLineEdit(this); - textFieldGridLayout->addWidget(countryLineEdit, 4, 0, Qt::AlignVCenter); - textFieldGridLayout->setVerticalSpacing(2); - getGridLayout()->addLayout(textFieldGridLayout, getGridLayout()->rowCount()-1, 2, 5, 2, Qt::AlignVCenter); - textFieldGridLayoutItem = getGridLayout()->itemAtPosition(getGridLayout()->rowCount()-1, 2); + countryLineEdit = new QtResizableLineEdit(this); + textFieldGridLayout->addWidget(countryLineEdit, 4, 0, Qt::AlignVCenter); + textFieldGridLayout->setVerticalSpacing(2); + getGridLayout()->addLayout(textFieldGridLayout, getGridLayout()->rowCount()-1, 2, 5, 2, Qt::AlignVCenter); + textFieldGridLayoutItem = getGridLayout()->itemAtPosition(getGridLayout()->rowCount()-1, 2); #if QT_VERSION >= 0x040700 - streetLineEdit->setPlaceholderText(tr("Street")); - poboxLineEdit->setPlaceholderText(tr("PO Box")); - addressextLineEdit->setPlaceholderText(tr("Address Extension")); - cityLineEdit->setPlaceholderText(tr("City")); - pocodeLineEdit->setPlaceholderText(tr("Postal Code")); - regionLineEdit->setPlaceholderText(tr("Region")); - countryLineEdit->setPlaceholderText(tr("Country")); + streetLineEdit->setPlaceholderText(tr("Street")); + poboxLineEdit->setPlaceholderText(tr("PO Box")); + addressextLineEdit->setPlaceholderText(tr("Address Extension")); + cityLineEdit->setPlaceholderText(tr("City")); + pocodeLineEdit->setPlaceholderText(tr("Postal Code")); + regionLineEdit->setPlaceholderText(tr("Region")); + countryLineEdit->setPlaceholderText(tr("Country")); #endif - deliveryTypeLabel = new QtElidingLabel(this); - deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); - getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-3, 4, Qt::AlignVCenter); + deliveryTypeLabel = new QtElidingLabel(this); + deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); + getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-3, 4, Qt::AlignVCenter); - domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this); - getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter); + domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this); + getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter); - internationalRadioButton = new QRadioButton(tr("International Delivery"), this); - getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter); + internationalRadioButton = new QRadioButton(tr("International Delivery"), this); + getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter); - buttonGroup = new QButtonGroup(this); - buttonGroup->addButton(domesticRadioButton); - buttonGroup->addButton(internationalRadioButton); + buttonGroup = new QButtonGroup(this); + buttonGroup->addButton(domesticRadioButton); + buttonGroup->addButton(internationalRadioButton); - setTabOrder(internationalRadioButton, getTagComboBox()); - getTagComboBox()->addTag("postal", tr("Postal")); - getTagComboBox()->addTag("parcel", tr("Parcel")); + setTabOrder(internationalRadioButton, getTagComboBox()); + getTagComboBox()->addTag("postal", tr("Postal")); + getTagComboBox()->addTag("parcel", tr("Parcel")); - QtVCardHomeWork::setTagComboBox(getTagComboBox()); + QtVCardHomeWork::setTagComboBox(getTagComboBox()); - textFields << streetLineEdit << poboxLineEdit << addressextLineEdit << cityLineEdit << pocodeLineEdit << regionLineEdit << countryLineEdit; - childWidgets << deliveryTypeLabel << domesticRadioButton << internationalRadioButton; + textFields << streetLineEdit << poboxLineEdit << addressextLineEdit << cityLineEdit << pocodeLineEdit << regionLineEdit << countryLineEdit; + childWidgets << deliveryTypeLabel << domesticRadioButton << internationalRadioButton; } void QtVCardAddressField::customCleanup() { - foreach(QWidget* widget, textFields) { - widget->hide(); - textFieldGridLayout->removeWidget(widget); - } - getGridLayout()->removeItem(textFieldGridLayoutItem); + foreach(QWidget* widget, textFields) { + widget->hide(); + textFieldGridLayout->removeWidget(widget); + } + getGridLayout()->removeItem(textFieldGridLayoutItem); } bool QtVCardAddressField::isEmpty() const { - return streetLineEdit->text().isEmpty() && - poboxLineEdit->text().isEmpty() && - addressextLineEdit->text().isEmpty() && - cityLineEdit->text().isEmpty() && - pocodeLineEdit->text().isEmpty() && - regionLineEdit->text().isEmpty() && - countryLineEdit->text().isEmpty(); + return streetLineEdit->text().isEmpty() && + poboxLineEdit->text().isEmpty() && + addressextLineEdit->text().isEmpty() && + cityLineEdit->text().isEmpty() && + pocodeLineEdit->text().isEmpty() && + regionLineEdit->text().isEmpty() && + countryLineEdit->text().isEmpty(); } void QtVCardAddressField::setAddress(const VCard::Address& address) { - setPreferred(address.isPreferred); - setHome(address.isHome); - setWork(address.isWork); - getTagComboBox()->setTag("postal", address.isPostal); - getTagComboBox()->setTag("parcel", address.isParcel); - domesticRadioButton->setChecked(address.deliveryType == VCard::DomesticDelivery); - internationalRadioButton->setChecked(address.deliveryType == VCard::InternationalDelivery); - streetLineEdit->setText(P2QSTRING(address.street)); - poboxLineEdit->setText(P2QSTRING(address.poBox)); - addressextLineEdit->setText(P2QSTRING(address.addressExtension)); - cityLineEdit->setText(P2QSTRING(address.locality)); - pocodeLineEdit->setText(P2QSTRING(address.postalCode)); - regionLineEdit->setText(P2QSTRING(address.region)); - countryLineEdit->setText(P2QSTRING(address.country)); + setPreferred(address.isPreferred); + setHome(address.isHome); + setWork(address.isWork); + getTagComboBox()->setTag("postal", address.isPostal); + getTagComboBox()->setTag("parcel", address.isParcel); + domesticRadioButton->setChecked(address.deliveryType == VCard::DomesticDelivery); + internationalRadioButton->setChecked(address.deliveryType == VCard::InternationalDelivery); + streetLineEdit->setText(P2QSTRING(address.street)); + poboxLineEdit->setText(P2QSTRING(address.poBox)); + addressextLineEdit->setText(P2QSTRING(address.addressExtension)); + cityLineEdit->setText(P2QSTRING(address.locality)); + pocodeLineEdit->setText(P2QSTRING(address.postalCode)); + regionLineEdit->setText(P2QSTRING(address.region)); + countryLineEdit->setText(P2QSTRING(address.country)); } VCard::Address QtVCardAddressField::getAddress() const { - VCard::Address address; - address.isPreferred = getPreferred(); - address.isHome = getHome(); - address.isWork = getWork(); - address.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None); - address.isPostal = getTagComboBox()->isTagSet("postal"); - address.isParcel = getTagComboBox()->isTagSet("parcel"); - address.street = Q2PSTRING(streetLineEdit->text()); - address.poBox = Q2PSTRING(poboxLineEdit->text()); - address.addressExtension = Q2PSTRING(addressextLineEdit->text()); - address.locality = Q2PSTRING(cityLineEdit->text()); - address.postalCode = Q2PSTRING(pocodeLineEdit->text()); - address.region = Q2PSTRING(regionLineEdit->text()); - address.country = Q2PSTRING(countryLineEdit->text()); - return address; + VCard::Address address; + address.isPreferred = getPreferred(); + address.isHome = getHome(); + address.isWork = getWork(); + address.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None); + address.isPostal = getTagComboBox()->isTagSet("postal"); + address.isParcel = getTagComboBox()->isTagSet("parcel"); + address.street = Q2PSTRING(streetLineEdit->text()); + address.poBox = Q2PSTRING(poboxLineEdit->text()); + address.addressExtension = Q2PSTRING(addressextLineEdit->text()); + address.locality = Q2PSTRING(cityLineEdit->text()); + address.postalCode = Q2PSTRING(pocodeLineEdit->text()); + address.region = Q2PSTRING(regionLineEdit->text()); + address.country = Q2PSTRING(countryLineEdit->text()); + return address; } void QtVCardAddressField::handleEditibleChanged(bool isEditable) { - assert(streetLineEdit); - assert(poboxLineEdit); - assert(addressextLineEdit); - assert(cityLineEdit); - assert(pocodeLineEdit); - assert(regionLineEdit); - assert(countryLineEdit); - assert(deliveryTypeLabel); - assert(domesticRadioButton); - assert(internationalRadioButton); - - streetLineEdit->setEditable(isEditable); - poboxLineEdit->setEditable(isEditable); - addressextLineEdit->setEditable(isEditable); - cityLineEdit->setEditable(isEditable); - pocodeLineEdit->setEditable(isEditable); - regionLineEdit->setEditable(isEditable); - countryLineEdit->setEditable(isEditable); - - deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text()); - deliveryTypeLabel->setVisible(!isEditable); - - domesticRadioButton->setVisible(isEditable); - internationalRadioButton->setVisible(isEditable); - - foreach (QWidget* widget, textFields) { - QtResizableLineEdit* lineEdit; - if ((lineEdit = dynamic_cast(widget))) { - lineEdit->setVisible(isEditable ? true : !lineEdit->text().isEmpty()); - lineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); - } - } + assert(streetLineEdit); + assert(poboxLineEdit); + assert(addressextLineEdit); + assert(cityLineEdit); + assert(pocodeLineEdit); + assert(regionLineEdit); + assert(countryLineEdit); + assert(deliveryTypeLabel); + assert(domesticRadioButton); + assert(internationalRadioButton); + + streetLineEdit->setEditable(isEditable); + poboxLineEdit->setEditable(isEditable); + addressextLineEdit->setEditable(isEditable); + cityLineEdit->setEditable(isEditable); + pocodeLineEdit->setEditable(isEditable); + regionLineEdit->setEditable(isEditable); + countryLineEdit->setEditable(isEditable); + + deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text()); + deliveryTypeLabel->setVisible(!isEditable); + + domesticRadioButton->setVisible(isEditable); + internationalRadioButton->setVisible(isEditable); + + foreach (QWidget* widget, textFields) { + QtResizableLineEdit* lineEdit; + if ((lineEdit = dynamic_cast(widget))) { + lineEdit->setVisible(isEditable ? true : !lineEdit->text().isEmpty()); + lineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); + } + } } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h index 51bc323..c90628a 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressField.h @@ -27,42 +27,42 @@ namespace Swift { class QtElidingLabel; class QtVCardAddressField : public QtVCardGeneralField, public QtVCardHomeWork { - Q_OBJECT - - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Address"), UNLIMITED_INSTANCES, QtVCardAddressField) - - QtVCardAddressField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardAddressField(); - - virtual bool isEmpty() const; - - void setAddress(const VCard::Address& address); - VCard::Address getAddress() const; - - protected: - virtual void setupContentWidgets(); - virtual void customCleanup(); - - public slots: - void handleEditibleChanged(bool isEditable); - - private: - QList textFields; - QtResizableLineEdit* streetLineEdit; - QtResizableLineEdit* poboxLineEdit; - QtResizableLineEdit* addressextLineEdit; - QtResizableLineEdit* cityLineEdit; - QtResizableLineEdit* pocodeLineEdit; - QtResizableLineEdit* regionLineEdit; - QtResizableLineEdit* countryLineEdit; - QGridLayout* textFieldGridLayout; - QLayoutItem* textFieldGridLayoutItem; - - QtElidingLabel* deliveryTypeLabel; - QRadioButton* domesticRadioButton; - QRadioButton* internationalRadioButton; - QButtonGroup* buttonGroup; + Q_OBJECT + + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Address"), UNLIMITED_INSTANCES, QtVCardAddressField) + + QtVCardAddressField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardAddressField(); + + virtual bool isEmpty() const; + + void setAddress(const VCard::Address& address); + VCard::Address getAddress() const; + + protected: + virtual void setupContentWidgets(); + virtual void customCleanup(); + + public slots: + void handleEditibleChanged(bool isEditable); + + private: + QList textFields; + QtResizableLineEdit* streetLineEdit; + QtResizableLineEdit* poboxLineEdit; + QtResizableLineEdit* addressextLineEdit; + QtResizableLineEdit* cityLineEdit; + QtResizableLineEdit* pocodeLineEdit; + QtResizableLineEdit* regionLineEdit; + QtResizableLineEdit* countryLineEdit; + QGridLayout* textFieldGridLayout; + QLayoutItem* textFieldGridLayoutItem; + + QtElidingLabel* deliveryTypeLabel; + QRadioButton* domesticRadioButton; + QRadioButton* internationalRadioButton; + QButtonGroup* buttonGroup; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp index 64d2533..7f270c5 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.cpp @@ -22,86 +22,86 @@ namespace Swift { QtVCardAddressLabelField::QtVCardAddressLabelField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address Label")), addressLabelPlainTextEdit(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Address Label")), addressLabelPlainTextEdit(NULL), deliveryTypeLabel(NULL), domesticRadioButton(NULL), internationalRadioButton(NULL), buttonGroup(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardAddressLabelField::~QtVCardAddressLabelField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardAddressLabelField::setupContentWidgets() { - addressLabelPlainTextEdit = new QPlainTextEdit(this); - addressLabelPlainTextEdit->setTabChangesFocus(true); - getGridLayout()->addWidget(addressLabelPlainTextEdit, getGridLayout()->rowCount()-1, 2, 3, 2, Qt::AlignVCenter); + addressLabelPlainTextEdit = new QPlainTextEdit(this); + addressLabelPlainTextEdit->setTabChangesFocus(true); + getGridLayout()->addWidget(addressLabelPlainTextEdit, getGridLayout()->rowCount()-1, 2, 3, 2, Qt::AlignVCenter); - deliveryTypeLabel = new QtElidingLabel(this); - deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); - getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter); + deliveryTypeLabel = new QtElidingLabel(this); + deliveryTypeLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); + getGridLayout()->addWidget(deliveryTypeLabel, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter); - domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this); - getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter); + domesticRadioButton = new QRadioButton(tr("Domestic Delivery"), this); + getGridLayout()->addWidget(domesticRadioButton, getGridLayout()->rowCount()-2, 4, Qt::AlignVCenter); - internationalRadioButton = new QRadioButton(tr("International Delivery"), this); - getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter); + internationalRadioButton = new QRadioButton(tr("International Delivery"), this); + getGridLayout()->addWidget(internationalRadioButton, getGridLayout()->rowCount()-1, 4, Qt::AlignVCenter); - buttonGroup = new QButtonGroup(this); - buttonGroup->addButton(domesticRadioButton); - buttonGroup->addButton(internationalRadioButton); + buttonGroup = new QButtonGroup(this); + buttonGroup->addButton(domesticRadioButton); + buttonGroup->addButton(internationalRadioButton); - setTabOrder(internationalRadioButton, getTagComboBox()); - getTagComboBox()->addTag("postal", tr("Postal")); - getTagComboBox()->addTag("parcel", tr("Parcel")); + setTabOrder(internationalRadioButton, getTagComboBox()); + getTagComboBox()->addTag("postal", tr("Postal")); + getTagComboBox()->addTag("parcel", tr("Parcel")); - QtVCardHomeWork::setTagComboBox(getTagComboBox()); - deliveryTypeLabel->hide(); - childWidgets << addressLabelPlainTextEdit << deliveryTypeLabel << domesticRadioButton << internationalRadioButton; + QtVCardHomeWork::setTagComboBox(getTagComboBox()); + deliveryTypeLabel->hide(); + childWidgets << addressLabelPlainTextEdit << deliveryTypeLabel << domesticRadioButton << internationalRadioButton; } bool QtVCardAddressLabelField::isEmpty() const { - return addressLabelPlainTextEdit->toPlainText().isEmpty(); + return addressLabelPlainTextEdit->toPlainText().isEmpty(); } void QtVCardAddressLabelField::setAddressLabel(const VCard::AddressLabel& addressLabel) { - setPreferred(addressLabel.isPreferred); - setHome(addressLabel.isHome); - setWork(addressLabel.isWork); - getTagComboBox()->setTag("postal", addressLabel.isPostal); - getTagComboBox()->setTag("parcel", addressLabel.isParcel); - domesticRadioButton->setChecked(addressLabel.deliveryType == VCard::DomesticDelivery); - internationalRadioButton->setChecked(addressLabel.deliveryType == VCard::InternationalDelivery); - std::string joinedLines = boost::algorithm::join(addressLabel.lines, "\n"); - addressLabelPlainTextEdit->setPlainText(P2QSTRING(joinedLines)); + setPreferred(addressLabel.isPreferred); + setHome(addressLabel.isHome); + setWork(addressLabel.isWork); + getTagComboBox()->setTag("postal", addressLabel.isPostal); + getTagComboBox()->setTag("parcel", addressLabel.isParcel); + domesticRadioButton->setChecked(addressLabel.deliveryType == VCard::DomesticDelivery); + internationalRadioButton->setChecked(addressLabel.deliveryType == VCard::InternationalDelivery); + std::string joinedLines = boost::algorithm::join(addressLabel.lines, "\n"); + addressLabelPlainTextEdit->setPlainText(P2QSTRING(joinedLines)); } VCard::AddressLabel QtVCardAddressLabelField::getAddressLabel() const { - VCard::AddressLabel addressLabel; - addressLabel.isPreferred = getPreferred(); - addressLabel.isHome = getHome(); - addressLabel.isWork = getWork(); - addressLabel.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None); - addressLabel.isPostal = getTagComboBox()->isTagSet("postal"); - addressLabel.isParcel = getTagComboBox()->isTagSet("parcel"); - - std::string lines = Q2PSTRING(addressLabelPlainTextEdit->toPlainText()); - boost::split(addressLabel.lines, lines, boost::is_any_of("\n")); - return addressLabel; + VCard::AddressLabel addressLabel; + addressLabel.isPreferred = getPreferred(); + addressLabel.isHome = getHome(); + addressLabel.isWork = getWork(); + addressLabel.deliveryType = domesticRadioButton->isChecked() ? VCard::DomesticDelivery : (internationalRadioButton->isChecked() ? VCard::InternationalDelivery : VCard::None); + addressLabel.isPostal = getTagComboBox()->isTagSet("postal"); + addressLabel.isParcel = getTagComboBox()->isTagSet("parcel"); + + std::string lines = Q2PSTRING(addressLabelPlainTextEdit->toPlainText()); + boost::split(addressLabel.lines, lines, boost::is_any_of("\n")); + return addressLabel; } void QtVCardAddressLabelField::handleEditibleChanged(bool isEditable) { - assert(addressLabelPlainTextEdit); - assert(deliveryTypeLabel); - assert(domesticRadioButton); - assert(internationalRadioButton); + assert(addressLabelPlainTextEdit); + assert(deliveryTypeLabel); + assert(domesticRadioButton); + assert(internationalRadioButton); - addressLabelPlainTextEdit->setReadOnly(!isEditable); - addressLabelPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }"); + addressLabelPlainTextEdit->setReadOnly(!isEditable); + addressLabelPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }"); - deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text()); - deliveryTypeLabel->setVisible(!isEditable); + deliveryTypeLabel->setText(buttonGroup->checkedButton() == 0 ? "" : buttonGroup->checkedButton()->text()); + deliveryTypeLabel->setVisible(!isEditable); - domesticRadioButton->setVisible(isEditable); - internationalRadioButton->setVisible(isEditable); + domesticRadioButton->setVisible(isEditable); + internationalRadioButton->setVisible(isEditable); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h index f59e482..16910b3 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardAddressLabelField.h @@ -27,32 +27,32 @@ namespace Swift { class QtElidingLabel; class QtVCardAddressLabelField : public QtVCardGeneralField, public QtVCardHomeWork { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Address Label"), UNLIMITED_INSTANCES, QtVCardAddressLabelField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Address Label"), UNLIMITED_INSTANCES, QtVCardAddressLabelField) - QtVCardAddressLabelField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardAddressLabelField(); + QtVCardAddressLabelField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardAddressLabelField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setAddressLabel(const VCard::AddressLabel& addressLabel); - VCard::AddressLabel getAddressLabel() const; + void setAddressLabel(const VCard::AddressLabel& addressLabel); + VCard::AddressLabel getAddressLabel() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QPlainTextEdit* addressLabelPlainTextEdit; + private: + QPlainTextEdit* addressLabelPlainTextEdit; - QtElidingLabel* deliveryTypeLabel; - QRadioButton* domesticRadioButton; - QRadioButton* internationalRadioButton; - QButtonGroup* buttonGroup; + QtElidingLabel* deliveryTypeLabel; + QRadioButton* domesticRadioButton; + QRadioButton* internationalRadioButton; + QButtonGroup* buttonGroup; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp index 603b8be..53dfc7f 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.cpp @@ -22,47 +22,47 @@ namespace Swift { QtVCardBirthdayField::QtVCardBirthdayField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Birthday"), false, false), birthdayLabel(NULL), birthdayDateEdit(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Birthday"), false, false), birthdayLabel(NULL), birthdayDateEdit(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardBirthdayField::~QtVCardBirthdayField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardBirthdayField::setupContentWidgets() { - birthdayLabel = new QLabel(this); - birthdayLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); - birthdayDateEdit = new QDateEdit(this); - birthdayDateEdit->setCalendarPopup(true); + birthdayLabel = new QLabel(this); + birthdayLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); + birthdayDateEdit = new QDateEdit(this); + birthdayDateEdit->setCalendarPopup(true); - QHBoxLayout* birthdayLayout = new QHBoxLayout(); - birthdayLayout->addWidget(birthdayLabel); - birthdayLayout->addWidget(birthdayDateEdit); + QHBoxLayout* birthdayLayout = new QHBoxLayout(); + birthdayLayout->addWidget(birthdayLabel); + birthdayLayout->addWidget(birthdayDateEdit); - getGridLayout()->addLayout(birthdayLayout, getGridLayout()->rowCount()-1, 2, Qt::AlignVCenter); + getGridLayout()->addLayout(birthdayLayout, getGridLayout()->rowCount()-1, 2, Qt::AlignVCenter); - getTagComboBox()->hide(); - birthdayLabel->hide(); - childWidgets << birthdayLabel << birthdayDateEdit; + getTagComboBox()->hide(); + birthdayLabel->hide(); + childWidgets << birthdayLabel << birthdayDateEdit; } bool QtVCardBirthdayField::isEmpty() const { - return false; + return false; } void QtVCardBirthdayField::setBirthday(const boost::posix_time::ptime& birthday) { - birthdayDateEdit->setDate(B2QDATE(birthday).date()); + birthdayDateEdit->setDate(B2QDATE(birthday).date()); } boost::posix_time::ptime QtVCardBirthdayField::getBirthday() const { - return boost::posix_time::from_time_t(QDateTime(birthdayDateEdit->date()).toTime_t()); + return boost::posix_time::from_time_t(QDateTime(birthdayDateEdit->date()).toTime_t()); } void QtVCardBirthdayField::handleEditibleChanged(bool isEditable) { - birthdayLabel->setText(birthdayDateEdit->date().toString(Qt::DefaultLocaleLongDate)); - birthdayDateEdit->setVisible(isEditable); - birthdayLabel->setVisible(!isEditable); + birthdayLabel->setText(birthdayDateEdit->date().toString(Qt::DefaultLocaleLongDate)); + birthdayDateEdit->setVisible(isEditable); + birthdayLabel->setVisible(!isEditable); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h index bf15a75..431751e 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardBirthdayField.h @@ -23,28 +23,28 @@ namespace Swift { class QtVCardBirthdayField : public QtVCardGeneralField { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Birthday"), 1, QtVCardBirthdayField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Birthday"), 1, QtVCardBirthdayField) - QtVCardBirthdayField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardBirthdayField(); + QtVCardBirthdayField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardBirthdayField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setBirthday(const boost::posix_time::ptime& addressLabel); - boost::posix_time::ptime getBirthday() const; + void setBirthday(const boost::posix_time::ptime& addressLabel); + boost::posix_time::ptime getBirthday() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QLabel* birthdayLabel; - QDateEdit* birthdayDateEdit; + private: + QLabel* birthdayLabel; + QDateEdit* birthdayDateEdit; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp index f3c4dbf..9926262 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.cpp @@ -22,50 +22,50 @@ namespace Swift { QtVCardDescriptionField::QtVCardDescriptionField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Description"), false, false), descriptionPlainTextEdit(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Description"), false, false), descriptionPlainTextEdit(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardDescriptionField::~QtVCardDescriptionField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardDescriptionField::setupContentWidgets() { - descriptionPlainTextEdit = new QPlainTextEdit(this); - descriptionPlainTextEdit->setMinimumHeight(70); - getGridLayout()->addWidget(descriptionPlainTextEdit, getGridLayout()->rowCount()-1, 2, 2, 2, Qt::AlignVCenter); - getTagComboBox()->hide(); - childWidgets << descriptionPlainTextEdit; + descriptionPlainTextEdit = new QPlainTextEdit(this); + descriptionPlainTextEdit->setMinimumHeight(70); + getGridLayout()->addWidget(descriptionPlainTextEdit, getGridLayout()->rowCount()-1, 2, 2, 2, Qt::AlignVCenter); + getTagComboBox()->hide(); + childWidgets << descriptionPlainTextEdit; } bool QtVCardDescriptionField::isEmpty() const { - return descriptionPlainTextEdit->toPlainText().isEmpty(); + return descriptionPlainTextEdit->toPlainText().isEmpty(); } void QtVCardDescriptionField::setDescription(const std::string& description) { - descriptionPlainTextEdit->setPlainText(P2QSTRING(description)); + descriptionPlainTextEdit->setPlainText(P2QSTRING(description)); } std::string QtVCardDescriptionField::getDescription() const { - return Q2PSTRING(descriptionPlainTextEdit->toPlainText()); + return Q2PSTRING(descriptionPlainTextEdit->toPlainText()); } void QtVCardDescriptionField::handleEditibleChanged(bool isEditable) { - assert(descriptionPlainTextEdit); + assert(descriptionPlainTextEdit); - if (isEditable) { - descriptionPlainTextEdit->setMinimumHeight(70); - } else { - QFontMetrics inputMetrics(descriptionPlainTextEdit->document()->defaultFont()); - QRect horizontalBounds = contentsRect().adjusted(0,0,0,9999); - QRect boundingRect = inputMetrics.boundingRect(horizontalBounds, Qt::TextWordWrap, descriptionPlainTextEdit->toPlainText() + "A"); - int left, top, right, bottom; - getContentsMargins(&left, &top, &right, &bottom); - int height = boundingRect.height() + top + bottom + inputMetrics.height(); - descriptionPlainTextEdit->setMinimumHeight(height > 70 ? 70 : height); - } - descriptionPlainTextEdit->setReadOnly(!isEditable); - descriptionPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }"); + if (isEditable) { + descriptionPlainTextEdit->setMinimumHeight(70); + } else { + QFontMetrics inputMetrics(descriptionPlainTextEdit->document()->defaultFont()); + QRect horizontalBounds = contentsRect().adjusted(0,0,0,9999); + QRect boundingRect = inputMetrics.boundingRect(horizontalBounds, Qt::TextWordWrap, descriptionPlainTextEdit->toPlainText() + "A"); + int left, top, right, bottom; + getContentsMargins(&left, &top, &right, &bottom); + int height = boundingRect.height() + top + bottom + inputMetrics.height(); + descriptionPlainTextEdit->setMinimumHeight(height > 70 ? 70 : height); + } + descriptionPlainTextEdit->setReadOnly(!isEditable); + descriptionPlainTextEdit->setStyleSheet(isEditable ? "" : "QPlainTextEdit { background: transparent; }"); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h index 8fb6344..489797a 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardDescriptionField.h @@ -22,27 +22,27 @@ namespace Swift { class QtVCardDescriptionField : public QtVCardGeneralField { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Description"), 1, QtVCardDescriptionField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Description"), 1, QtVCardDescriptionField) - QtVCardDescriptionField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardDescriptionField(); + QtVCardDescriptionField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardDescriptionField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setDescription(const std::string& description); - std::string getDescription() const; + void setDescription(const std::string& description); + std::string getDescription() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QPlainTextEdit* descriptionPlainTextEdit; + private: + QPlainTextEdit* descriptionPlainTextEdit; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h b/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h index 12f990a..093357a 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardFieldInfo.h @@ -18,41 +18,41 @@ #include #include #define GENERIC_QT_VCARD_FIELD_INFO(MENU_NAME, ALLOWED_INSTANCES, FIELD_CLASS) \ - class FieldInfo : public QtVCardFieldInfo { \ - public: \ - virtual ~FieldInfo() { \ - } \ - \ - virtual QString getMenuName() const { \ - return MENU_NAME; \ - } \ - \ - virtual int getAllowedInstances() const { \ - return ALLOWED_INSTANCES; \ - } \ - \ - virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const { \ - return new FIELD_CLASS(parent, layout, editable); \ - } \ - \ - virtual bool testInstance(QWidget* widget) const { \ - return dynamic_cast(widget) != 0; \ - } \ - }; + class FieldInfo : public QtVCardFieldInfo { \ + public: \ + virtual ~FieldInfo() { \ + } \ + \ + virtual QString getMenuName() const { \ + return MENU_NAME; \ + } \ + \ + virtual int getAllowedInstances() const { \ + return ALLOWED_INSTANCES; \ + } \ + \ + virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const { \ + return new FIELD_CLASS(parent, layout, editable); \ + } \ + \ + virtual bool testInstance(QWidget* widget) const { \ + return dynamic_cast(widget) != 0; \ + } \ + }; class QWidget; namespace Swift { - class QtVCardFieldInfo { - public: - static const int UNLIMITED_INSTANCES = -1; - - virtual ~QtVCardFieldInfo() { - } - virtual QString getMenuName() const = 0; - virtual int getAllowedInstances() const = 0; - virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const = 0; - virtual bool testInstance(QWidget*) const = 0; - }; + class QtVCardFieldInfo { + public: + static const int UNLIMITED_INSTANCES = -1; + + virtual ~QtVCardFieldInfo() { + } + virtual QString getMenuName() const = 0; + virtual int getAllowedInstances() const = 0; + virtual QWidget* createFieldInstance(QWidget* parent, QGridLayout* layout, bool editable) const = 0; + virtual bool testInstance(QWidget*) const = 0; + }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp index ed30ae1..44d94d7 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.cpp @@ -22,8 +22,8 @@ namespace Swift { QtVCardGeneralField::QtVCardGeneralField(QWidget* parent, QGridLayout* layout, bool editable, int row, QString label, bool preferrable, bool taggable) : - QWidget(parent), editable(editable), preferrable(preferrable), starVisible(false), taggable(taggable), layout(layout), row(row), preferredCheckBox(0), label(0), labelText(label), - tagComboBox(0), tagLabel(NULL), closeButton(0) { + QWidget(parent), editable(editable), preferrable(preferrable), starVisible(false), taggable(taggable), layout(layout), row(row), preferredCheckBox(0), label(0), labelText(label), + tagComboBox(0), tagLabel(NULL), closeButton(0) { } QtVCardGeneralField::~QtVCardGeneralField() { @@ -31,126 +31,126 @@ QtVCardGeneralField::~QtVCardGeneralField() { } void QtVCardGeneralField::initialize() { - if (preferrable) { - preferredCheckBox = new QCheckBox(this); - preferredCheckBox->setToolTip(tr("Stars can be used to mark preferred contact details.")); - preferredCheckBox->setStyleSheet( - "QCheckBox::indicator { width: 18px; height: 18px; }" - "QCheckBox::indicator:checked { image: url(:/icons/star-checked.png); }" - "QCheckBox::indicator:unchecked { image: url(:/icons/star-unchecked.png); }" - ); - layout->addWidget(preferredCheckBox, row, 0, Qt::AlignVCenter); - childWidgets << preferredCheckBox; - connect(preferredCheckBox, SIGNAL(stateChanged(int)), SLOT(handlePreferredStarStateChanged(int))); - } - label = new QLabel(this); - label->setText(labelText); - layout->addWidget(label, row, 1, Qt::AlignVCenter | Qt::AlignRight); - - tagLabel = new QtElidingLabel(this); - tagLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); - - tagComboBox = new QtTagComboBox(this); - closeButton = new QtCloseButton(this); - connect(closeButton, SIGNAL(clicked()), SLOT(handleCloseButtonClicked())); - - QHBoxLayout* tagLayout = new QHBoxLayout(); - tagLayout->addWidget(tagLabel); - tagLayout->addWidget(tagComboBox); - - setupContentWidgets(); - layout->addLayout(tagLayout, row, 4, Qt::AlignTop); - layout->addWidget(closeButton, row, 5, Qt::AlignCenter); - closeButton->resize(12, 12); - tagLabel->hide(); - - childWidgets << label << tagComboBox << tagLabel << closeButton; - setEditable(editable); + if (preferrable) { + preferredCheckBox = new QCheckBox(this); + preferredCheckBox->setToolTip(tr("Stars can be used to mark preferred contact details.")); + preferredCheckBox->setStyleSheet( + "QCheckBox::indicator { width: 18px; height: 18px; }" + "QCheckBox::indicator:checked { image: url(:/icons/star-checked.png); }" + "QCheckBox::indicator:unchecked { image: url(:/icons/star-unchecked.png); }" + ); + layout->addWidget(preferredCheckBox, row, 0, Qt::AlignVCenter); + childWidgets << preferredCheckBox; + connect(preferredCheckBox, SIGNAL(stateChanged(int)), SLOT(handlePreferredStarStateChanged(int))); + } + label = new QLabel(this); + label->setText(labelText); + layout->addWidget(label, row, 1, Qt::AlignVCenter | Qt::AlignRight); + + tagLabel = new QtElidingLabel(this); + tagLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); + + tagComboBox = new QtTagComboBox(this); + closeButton = new QtCloseButton(this); + connect(closeButton, SIGNAL(clicked()), SLOT(handleCloseButtonClicked())); + + QHBoxLayout* tagLayout = new QHBoxLayout(); + tagLayout->addWidget(tagLabel); + tagLayout->addWidget(tagComboBox); + + setupContentWidgets(); + layout->addLayout(tagLayout, row, 4, Qt::AlignTop); + layout->addWidget(closeButton, row, 5, Qt::AlignCenter); + closeButton->resize(12, 12); + tagLabel->hide(); + + childWidgets << label << tagComboBox << tagLabel << closeButton; + setEditable(editable); } bool QtVCardGeneralField::isEditable() const { - return editable; + return editable; } void QtVCardGeneralField::setEditable(bool editable) { - assert(tagComboBox); - assert(closeButton); - - this->editable = editable; - if (taggable) { - tagLabel->setText(tagComboBox->itemText(0)); - tagComboBox->setVisible(editable); - tagLabel->setVisible(!editable); - } else { - tagLabel->hide(); - tagComboBox->hide(); - } - closeButton->setVisible(editable); - updatePreferredStarVisibility(); - editableChanged(this->editable); + assert(tagComboBox); + assert(closeButton); + + this->editable = editable; + if (taggable) { + tagLabel->setText(tagComboBox->itemText(0)); + tagComboBox->setVisible(editable); + tagLabel->setVisible(!editable); + } else { + tagLabel->hide(); + tagComboBox->hide(); + } + closeButton->setVisible(editable); + updatePreferredStarVisibility(); + editableChanged(this->editable); } void QtVCardGeneralField::setStarVisible(const bool isVisible) { - starVisible = isVisible; - updatePreferredStarVisibility(); + starVisible = isVisible; + updatePreferredStarVisibility(); } bool QtVCardGeneralField::getStarVisible() const { - return starVisible; + return starVisible; } void QtVCardGeneralField::setPreferred(const bool preferred) { - if (preferredCheckBox) preferredCheckBox->setChecked(preferred); - updatePreferredStarVisibility(); + if (preferredCheckBox) preferredCheckBox->setChecked(preferred); + updatePreferredStarVisibility(); } bool QtVCardGeneralField::getPreferred() const { - return preferredCheckBox ? preferredCheckBox->isChecked() : false; + return preferredCheckBox ? preferredCheckBox->isChecked() : false; } void QtVCardGeneralField::customCleanup() { } QtTagComboBox* QtVCardGeneralField::getTagComboBox() const { - return tagComboBox; + return tagComboBox; } QGridLayout* QtVCardGeneralField::getGridLayout() const { - return layout; + return layout; } void QtVCardGeneralField::handleCloseButtonClicked() { - customCleanup(); - foreach(QWidget* widget, childWidgets) { - widget->hide(); - layout->removeWidget(widget); - } - deleteField(this); + customCleanup(); + foreach(QWidget* widget, childWidgets) { + widget->hide(); + layout->removeWidget(widget); + } + deleteField(this); } void QtVCardGeneralField::handlePreferredStarStateChanged(int state) { - if (state == Qt::Checked) { - QToolTip::showText(QCursor::pos(), tr("Marked as your preferred %1. Click again to undo.").arg(labelText)); - } + if (state == Qt::Checked) { + QToolTip::showText(QCursor::pos(), tr("Marked as your preferred %1. Click again to undo.").arg(labelText)); + } } void QtVCardGeneralField::updatePreferredStarVisibility() { - if (preferredCheckBox) { - bool showStar = false; - if (editable) { - if (starVisible) { - showStar = true; - } - else { - showStar = preferredCheckBox->isChecked(); - } - } - else { - showStar = preferredCheckBox->isChecked(); - } - preferredCheckBox->setVisible(showStar); - preferredCheckBox->setEnabled(editable); - } + if (preferredCheckBox) { + bool showStar = false; + if (editable) { + if (starVisible) { + showStar = true; + } + else { + showStar = preferredCheckBox->isChecked(); + } + } + else { + showStar = preferredCheckBox->isChecked(); + } + preferredCheckBox->setVisible(showStar); + preferredCheckBox->setEnabled(editable); + } } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h index 6583d12..d907196 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardGeneralField.h @@ -25,69 +25,69 @@ namespace Swift { class QtElidingLabel; /* - * covers features like: - * - preffered (star ceckbox) - * - combo check box - * - label - * - remove button + * covers features like: + * - preffered (star ceckbox) + * - combo check box + * - label + * - remove button */ class QtVCardGeneralField : public QWidget { - Q_OBJECT - Q_PROPERTY(bool editable READ isEditable WRITE setEditable NOTIFY editableChanged) - Q_PROPERTY(bool empty READ isEmpty) - - public: - explicit QtVCardGeneralField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false, int row = 0, QString label = QString(), - bool preferrable = true, bool taggable = true); - virtual ~QtVCardGeneralField(); - - void initialize(); - - virtual bool isEditable() const; - virtual void setEditable(bool); - - virtual bool isEmpty() const = 0; - - void setStarVisible(const bool isVisible); - bool getStarVisible() const; - - void setPreferred(const bool preferred); - bool getPreferred() const; - - protected: - virtual void setupContentWidgets() = 0; - virtual void customCleanup(); - - QtTagComboBox* getTagComboBox() const; - QGridLayout* getGridLayout() const; - - signals: - void editableChanged(bool); - void deleteField(QtVCardGeneralField*); - - public slots: - void handleCloseButtonClicked(); - void handlePreferredStarStateChanged(int statte); - - protected: - QList childWidgets; - - private: - void updatePreferredStarVisibility(); - - private: - bool editable; - bool preferrable; - bool starVisible; - bool taggable; - QGridLayout* layout; - int row; - QCheckBox* preferredCheckBox; - QLabel* label; - QString labelText; - QtTagComboBox* tagComboBox; - QtElidingLabel* tagLabel; - QtCloseButton* closeButton; + Q_OBJECT + Q_PROPERTY(bool editable READ isEditable WRITE setEditable NOTIFY editableChanged) + Q_PROPERTY(bool empty READ isEmpty) + + public: + explicit QtVCardGeneralField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false, int row = 0, QString label = QString(), + bool preferrable = true, bool taggable = true); + virtual ~QtVCardGeneralField(); + + void initialize(); + + virtual bool isEditable() const; + virtual void setEditable(bool); + + virtual bool isEmpty() const = 0; + + void setStarVisible(const bool isVisible); + bool getStarVisible() const; + + void setPreferred(const bool preferred); + bool getPreferred() const; + + protected: + virtual void setupContentWidgets() = 0; + virtual void customCleanup(); + + QtTagComboBox* getTagComboBox() const; + QGridLayout* getGridLayout() const; + + signals: + void editableChanged(bool); + void deleteField(QtVCardGeneralField*); + + public slots: + void handleCloseButtonClicked(); + void handlePreferredStarStateChanged(int statte); + + protected: + QList childWidgets; + + private: + void updatePreferredStarVisibility(); + + private: + bool editable; + bool preferrable; + bool starVisible; + bool taggable; + QGridLayout* layout; + int row; + QCheckBox* preferredCheckBox; + QLabel* label; + QString labelText; + QtTagComboBox* tagComboBox; + QtElidingLabel* tagLabel; + QtCloseButton* closeButton; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp index 3be6901..c147c68 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.cpp @@ -21,25 +21,25 @@ QtVCardHomeWork::~QtVCardHomeWork() { } void QtVCardHomeWork::setTagComboBox(QtTagComboBox* tagBox) { - tagComboBox = tagBox; - tagComboBox->addTag("home", QObject::tr("Home")); - tagComboBox->addTag("work", QObject::tr("Work")); + tagComboBox = tagBox; + tagComboBox->addTag("home", QObject::tr("Home")); + tagComboBox->addTag("work", QObject::tr("Work")); } void QtVCardHomeWork::setHome(const bool home) { - tagComboBox->setTag("home", home); + tagComboBox->setTag("home", home); } bool QtVCardHomeWork::getHome() const { - return tagComboBox->isTagSet("home"); + return tagComboBox->isTagSet("home"); } void QtVCardHomeWork::setWork(const bool work) { - tagComboBox->setTag("work", work); + tagComboBox->setTag("work", work); } bool QtVCardHomeWork::getWork() const { - return tagComboBox->isTagSet("work"); + return tagComboBox->isTagSet("work"); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h index aea2ff2..dd1452a 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardHomeWork.h @@ -19,19 +19,19 @@ namespace Swift { class QtVCardHomeWork { - public: - QtVCardHomeWork(); - virtual ~QtVCardHomeWork(); + public: + QtVCardHomeWork(); + virtual ~QtVCardHomeWork(); - void setTagComboBox(QtTagComboBox* tagBox); + void setTagComboBox(QtTagComboBox* tagBox); - void setHome(const bool home); - bool getHome() const; - void setWork(const bool work); - bool getWork() const; + void setHome(const bool home); + bool getHome() const; + void setWork(const bool work); + bool getWork() const; - private: - QtTagComboBox* tagComboBox; + private: + QtTagComboBox* tagComboBox; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp index 9be9737..e563ca2 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.cpp @@ -24,66 +24,66 @@ namespace Swift { QtVCardInternetEMailField::QtVCardInternetEMailField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("E-Mail")), emailLineEdit(NULL), emailLabel(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("E-Mail")), emailLineEdit(NULL), emailLabel(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardInternetEMailField::~QtVCardInternetEMailField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardInternetEMailField::setupContentWidgets() { - emailLabel = new QLabel(this); - emailLabel->setOpenExternalLinks(true); - emailLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); - emailLineEdit = new QtResizableLineEdit(this); + emailLabel = new QLabel(this); + emailLabel->setOpenExternalLinks(true); + emailLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); + emailLineEdit = new QtResizableLineEdit(this); #if QT_VERSION >= 0x040700 - emailLineEdit->setPlaceholderText(tr("alice@wonderland.lit")); + emailLineEdit->setPlaceholderText(tr("alice@wonderland.lit")); #endif - QHBoxLayout* emailLayout = new QHBoxLayout(); - emailLayout->addWidget(emailLabel); - emailLayout->addWidget(emailLineEdit); - getGridLayout()->addLayout(emailLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); - setTabOrder(emailLineEdit, getTagComboBox()); - QtVCardHomeWork::setTagComboBox(getTagComboBox()); - emailLabel->hide(); - childWidgets << emailLabel << emailLineEdit; + QHBoxLayout* emailLayout = new QHBoxLayout(); + emailLayout->addWidget(emailLabel); + emailLayout->addWidget(emailLineEdit); + getGridLayout()->addLayout(emailLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); + setTabOrder(emailLineEdit, getTagComboBox()); + QtVCardHomeWork::setTagComboBox(getTagComboBox()); + emailLabel->hide(); + childWidgets << emailLabel << emailLineEdit; } bool QtVCardInternetEMailField::isEmpty() const { - return emailLineEdit->text().isEmpty(); + return emailLineEdit->text().isEmpty(); } void QtVCardInternetEMailField::setInternetEMailAddress(const VCard::EMailAddress& address) { - assert(address.isInternet); - setPreferred(address.isPreferred); - setHome(address.isHome); - setWork(address.isWork); - emailLineEdit->setText(P2QSTRING(address.address)); + assert(address.isInternet); + setPreferred(address.isPreferred); + setHome(address.isHome); + setWork(address.isWork); + emailLineEdit->setText(P2QSTRING(address.address)); } VCard::EMailAddress QtVCardInternetEMailField::getInternetEMailAddress() const { - VCard::EMailAddress address; - address.isInternet = true; - address.isPreferred = getPreferred(); - address.isHome = getHome(); - address.isWork = getWork(); - address.address = Q2PSTRING(emailLineEdit->text()); - return address; + VCard::EMailAddress address; + address.isInternet = true; + address.isPreferred = getPreferred(); + address.isHome = getHome(); + address.isWork = getWork(); + address.address = Q2PSTRING(emailLineEdit->text()); + return address; } void QtVCardInternetEMailField::handleEditibleChanged(bool isEditable) { - assert(emailLineEdit); - assert(emailLabel); + assert(emailLineEdit); + assert(emailLabel); - if (isEditable) { - emailLineEdit->show(); - emailLabel->hide(); - } else { - emailLineEdit->hide(); - emailLabel->setText(QString("%1").arg(QtUtilities::htmlEscape(emailLineEdit->text()))); - emailLabel->show(); - } + if (isEditable) { + emailLineEdit->show(); + emailLabel->hide(); + } else { + emailLineEdit->hide(); + emailLabel->setText(QString("%1").arg(QtUtilities::htmlEscape(emailLineEdit->text()))); + emailLabel->show(); + } } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h index e3a5d79..63a83e2 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardInternetEMailField.h @@ -22,28 +22,28 @@ namespace Swift { class QtVCardInternetEMailField : public QtVCardGeneralField, public QtVCardHomeWork { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("E-Mail"), UNLIMITED_INSTANCES, QtVCardInternetEMailField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("E-Mail"), UNLIMITED_INSTANCES, QtVCardInternetEMailField) - QtVCardInternetEMailField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardInternetEMailField(); + QtVCardInternetEMailField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardInternetEMailField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setInternetEMailAddress(const VCard::EMailAddress& address); - VCard::EMailAddress getInternetEMailAddress() const; + void setInternetEMailAddress(const VCard::EMailAddress& address); + VCard::EMailAddress getInternetEMailAddress() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QtResizableLineEdit* emailLineEdit; - QLabel* emailLabel; + private: + QtResizableLineEdit* emailLineEdit; + QLabel* emailLabel; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp index 4c23036..705ad6b 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.cpp @@ -23,58 +23,58 @@ namespace Swift { QtVCardJIDField::QtVCardJIDField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("JID"), false, false), jidLabel(NULL), jidLineEdit(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("JID"), false, false), jidLabel(NULL), jidLineEdit(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardJIDField::~QtVCardJIDField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardJIDField::setupContentWidgets() { - jidLabel = new QLabel(this); - jidLabel->setOpenExternalLinks(true); - jidLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); - jidLineEdit = new QtResizableLineEdit(this); + jidLabel = new QLabel(this); + jidLabel->setOpenExternalLinks(true); + jidLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); + jidLineEdit = new QtResizableLineEdit(this); #if QT_VERSION >= 0x040700 - jidLineEdit->setPlaceholderText(tr("alice@wonderland.lit")); + jidLineEdit->setPlaceholderText(tr("alice@wonderland.lit")); #endif - QHBoxLayout* jidLayout = new QHBoxLayout(); - jidLayout->addWidget(jidLabel); - jidLayout->addWidget(jidLineEdit); - getGridLayout()->addLayout(jidLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); + QHBoxLayout* jidLayout = new QHBoxLayout(); + jidLayout->addWidget(jidLabel); + jidLayout->addWidget(jidLineEdit); + getGridLayout()->addLayout(jidLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); - jidLabel->hide(); - getTagComboBox()->hide(); + jidLabel->hide(); + getTagComboBox()->hide(); - childWidgets << jidLabel << jidLineEdit; + childWidgets << jidLabel << jidLineEdit; } bool QtVCardJIDField::isEmpty() const { - return jidLineEdit->text().isEmpty(); + return jidLineEdit->text().isEmpty(); } void QtVCardJIDField::setJID(const JID& jid) { - std::string jidStr = jid.toBare().toString(); - jidLineEdit->setText(P2QSTRING(jidStr)); + std::string jidStr = jid.toBare().toString(); + jidLineEdit->setText(P2QSTRING(jidStr)); } JID QtVCardJIDField::getJID() const { - return JID(Q2PSTRING(jidLineEdit->text())); + return JID(Q2PSTRING(jidLineEdit->text())); } void QtVCardJIDField::handleEditibleChanged(bool isEditable) { - assert(jidLineEdit); - assert(jidLabel); - - if (isEditable) { - jidLineEdit->show(); - jidLabel->hide(); - } else { - jidLineEdit->hide(); - jidLabel->setText(QString("%1").arg(QtUtilities::htmlEscape(jidLineEdit->text()))); - jidLabel->show(); - } + assert(jidLineEdit); + assert(jidLabel); + + if (isEditable) { + jidLineEdit->show(); + jidLabel->hide(); + } else { + jidLineEdit->hide(); + jidLabel->setText(QString("%1").arg(QtUtilities::htmlEscape(jidLineEdit->text()))); + jidLabel->show(); + } } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h index 4e75885..2e9b4ef 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardJIDField.h @@ -21,28 +21,28 @@ namespace Swift { class QtVCardJIDField : public QtVCardGeneralField { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("JID"), UNLIMITED_INSTANCES, QtVCardJIDField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("JID"), UNLIMITED_INSTANCES, QtVCardJIDField) - QtVCardJIDField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardJIDField(); + QtVCardJIDField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardJIDField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setJID(const JID& jid); - JID getJID() const; + void setJID(const JID& jid); + JID getJID() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QLabel* jidLabel; - QtResizableLineEdit* jidLineEdit; + private: + QLabel* jidLabel; + QtResizableLineEdit* jidLineEdit; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp index ba51078..8b94c42 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.cpp @@ -17,129 +17,129 @@ namespace Swift { QtVCardOrganizationField::QtVCardOrganizationField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Organization"), false, false), organizationLabel(NULL), organizationLineEdit(NULL), unitsTreeWidget(NULL), itemDelegate(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Organization"), false, false), organizationLabel(NULL), organizationLineEdit(NULL), unitsTreeWidget(NULL), itemDelegate(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardOrganizationField::~QtVCardOrganizationField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardOrganizationField::setupContentWidgets() { - organizationLabel = new QLabel(this); - organizationLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); - organizationLineEdit = new QtResizableLineEdit(this); - QHBoxLayout* organizationLayout = new QHBoxLayout(); - organizationLayout->addWidget(organizationLabel); - organizationLayout->addWidget(organizationLineEdit); + organizationLabel = new QLabel(this); + organizationLabel->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard); + organizationLineEdit = new QtResizableLineEdit(this); + QHBoxLayout* organizationLayout = new QHBoxLayout(); + organizationLayout->addWidget(organizationLabel); + organizationLayout->addWidget(organizationLineEdit); - getGridLayout()->addLayout(organizationLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); + getGridLayout()->addLayout(organizationLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); - itemDelegate = new QtRemovableItemDelegate(style()); + itemDelegate = new QtRemovableItemDelegate(style()); - unitsTreeWidget = new QTreeWidget(this); - connect(unitsTreeWidget->model(), SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(handleRowsRemoved(QModelIndex,int,int))); - unitsTreeWidget->setColumnCount(2); - unitsTreeWidget->header()->setStretchLastSection(false); - unitsTreeWidget->header()->resizeSection(1, itemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width()); + unitsTreeWidget = new QTreeWidget(this); + connect(unitsTreeWidget->model(), SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(handleRowsRemoved(QModelIndex,int,int))); + unitsTreeWidget->setColumnCount(2); + unitsTreeWidget->header()->setStretchLastSection(false); + unitsTreeWidget->header()->resizeSection(1, itemDelegate->sizeHint(QStyleOptionViewItem(), QModelIndex()).width()); #if QT_VERSION >= 0x050000 - unitsTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch); + unitsTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch); #else - unitsTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch); + unitsTreeWidget->header()->setResizeMode(0, QHeaderView::Stretch); #endif - unitsTreeWidget->setHeaderHidden(true); - unitsTreeWidget->setRootIsDecorated(false); - unitsTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked); - unitsTreeWidget->setItemDelegateForColumn(1, itemDelegate); - connect(unitsTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int))); - getGridLayout()->addWidget(unitsTreeWidget, getGridLayout()->rowCount()-1, 4, 2, 1); + unitsTreeWidget->setHeaderHidden(true); + unitsTreeWidget->setRootIsDecorated(false); + unitsTreeWidget->setEditTriggers(QAbstractItemView::DoubleClicked); + unitsTreeWidget->setItemDelegateForColumn(1, itemDelegate); + connect(unitsTreeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)), SLOT(handleItemChanged(QTreeWidgetItem*,int))); + getGridLayout()->addWidget(unitsTreeWidget, getGridLayout()->rowCount()-1, 4, 2, 1); - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << ""); - item->setFlags(item->flags() | Qt::ItemIsEditable); - unitsTreeWidget->addTopLevelItem(item); + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << ""); + item->setFlags(item->flags() | Qt::ItemIsEditable); + unitsTreeWidget->addTopLevelItem(item); - getTagComboBox()->hide(); - organizationLabel->hide(); - childWidgets << organizationLabel << organizationLineEdit << unitsTreeWidget; + getTagComboBox()->hide(); + organizationLabel->hide(); + childWidgets << organizationLabel << organizationLineEdit << unitsTreeWidget; } bool QtVCardOrganizationField::isEmpty() const { - return organizationLineEdit->text().isEmpty() && unitsTreeWidget->model()->rowCount() != 0; + return organizationLineEdit->text().isEmpty() && unitsTreeWidget->model()->rowCount() != 0; } void QtVCardOrganizationField::setOrganization(const VCard::Organization& organization) { - organizationLineEdit->setText(P2QSTRING(organization.name)); - unitsTreeWidget->clear(); - foreach(std::string unit, organization.units) { - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(unit)) << ""); - item->setFlags(item->flags() | Qt::ItemIsEditable); - unitsTreeWidget->addTopLevelItem(item); - } - - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << ""); - item->setFlags(item->flags() | Qt::ItemIsEditable); - unitsTreeWidget->addTopLevelItem(item); + organizationLineEdit->setText(P2QSTRING(organization.name)); + unitsTreeWidget->clear(); + foreach(std::string unit, organization.units) { + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList(P2QSTRING(unit)) << ""); + item->setFlags(item->flags() | Qt::ItemIsEditable); + unitsTreeWidget->addTopLevelItem(item); + } + + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << ""); + item->setFlags(item->flags() | Qt::ItemIsEditable); + unitsTreeWidget->addTopLevelItem(item); } VCard::Organization QtVCardOrganizationField::getOrganization() const { - VCard::Organization organization; - organization.name = Q2PSTRING(organizationLineEdit->text()); - for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) { - QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i); - if (!row->text(0).isEmpty()) { - organization.units.push_back(Q2PSTRING(row->text(0))); - } - } - - return organization; + VCard::Organization organization; + organization.name = Q2PSTRING(organizationLineEdit->text()); + for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) { + QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i); + if (!row->text(0).isEmpty()) { + organization.units.push_back(Q2PSTRING(row->text(0))); + } + } + + return organization; } void QtVCardOrganizationField::handleEditibleChanged(bool isEditable) { - assert(organizationLineEdit); - assert(unitsTreeWidget); - - organizationLineEdit->setVisible(isEditable); - organizationLabel->setVisible(!isEditable); - - if (!isEditable) { - QString label; - for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) { - QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i); - if (!row->text(0).isEmpty()) { - label += row->text(0) + ", "; - } - } - label += organizationLineEdit->text(); - organizationLabel->setText(label); - } - unitsTreeWidget->setVisible(isEditable); + assert(organizationLineEdit); + assert(unitsTreeWidget); + + organizationLineEdit->setVisible(isEditable); + organizationLabel->setVisible(!isEditable); + + if (!isEditable) { + QString label; + for(int i=0; i < unitsTreeWidget->topLevelItemCount(); ++i) { + QTreeWidgetItem* row = unitsTreeWidget->topLevelItem(i); + if (!row->text(0).isEmpty()) { + label += row->text(0) + ", "; + } + } + label += organizationLineEdit->text(); + organizationLabel->setText(label); + } + unitsTreeWidget->setVisible(isEditable); } void QtVCardOrganizationField::handleItemChanged(QTreeWidgetItem *, int) { - guaranteeEmptyRow(); + guaranteeEmptyRow(); } void QtVCardOrganizationField::handleRowsRemoved(const QModelIndex&, int, int) { - guaranteeEmptyRow(); + guaranteeEmptyRow(); } void QtVCardOrganizationField::guaranteeEmptyRow() { - bool hasEmptyRow = false; - QList rows = unitsTreeWidget->findItems("", Qt::MatchFixedString); - foreach(QTreeWidgetItem* row, rows) { - if (row->text(0).isEmpty()) { - hasEmptyRow = true; - } - } - - if (!hasEmptyRow) { - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << ""); - item->setFlags(item->flags() | Qt::ItemIsEditable); - unitsTreeWidget->addTopLevelItem(item); - unitsTreeWidget->setCurrentItem(item); - } + bool hasEmptyRow = false; + QList rows = unitsTreeWidget->findItems("", Qt::MatchFixedString); + foreach(QTreeWidgetItem* row, rows) { + if (row->text(0).isEmpty()) { + hasEmptyRow = true; + } + } + + if (!hasEmptyRow) { + QTreeWidgetItem* item = new QTreeWidgetItem(QStringList("") << ""); + item->setFlags(item->flags() | Qt::ItemIsEditable); + unitsTreeWidget->addTopLevelItem(item); + unitsTreeWidget->setCurrentItem(item); + } } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h index f567e92..6de3167 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardOrganizationField.h @@ -24,37 +24,37 @@ namespace Swift { class QtVCardOrganizationField : public QtVCardGeneralField { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Organization"), UNLIMITED_INSTANCES, QtVCardOrganizationField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Organization"), UNLIMITED_INSTANCES, QtVCardOrganizationField) - QtVCardOrganizationField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardOrganizationField(); + QtVCardOrganizationField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardOrganizationField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setOrganization(const VCard::Organization& organization); - VCard::Organization getOrganization() const; + void setOrganization(const VCard::Organization& organization); + VCard::Organization getOrganization() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private slots: - void handleItemChanged(QTreeWidgetItem*, int); - void handleRowsRemoved(const QModelIndex&, int, int); + private slots: + void handleItemChanged(QTreeWidgetItem*, int); + void handleRowsRemoved(const QModelIndex&, int, int); - private: - void guaranteeEmptyRow(); + private: + void guaranteeEmptyRow(); - private: - QLabel* organizationLabel; - QtResizableLineEdit* organizationLineEdit; - QTreeWidget* unitsTreeWidget; - QtRemovableItemDelegate* itemDelegate; + private: + QLabel* organizationLabel; + QtResizableLineEdit* organizationLineEdit; + QTreeWidget* unitsTreeWidget; + QtRemovableItemDelegate* itemDelegate; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp index 680fdb5..90d6e5e 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.cpp @@ -19,134 +19,134 @@ namespace Swift { QtVCardPhotoAndNameFields::QtVCardPhotoAndNameFields(QWidget* parent) : - QWidget(parent), - ui(new Ui::QtVCardPhotoAndNameFields) { - ui->setupUi(this); - ui->lineEditPREFIX->hide(); - ui->lineEditMIDDLE->hide(); - ui->lineEditSUFFIX->hide(); - ui->lineEditFN->hide(); - ui->lineEditNICKNAME->hide(); - ui->labelFN->hide(); - ui->labelNICKNAME->hide(); - ui->labelFULLNAME->hide(); + QWidget(parent), + ui(new Ui::QtVCardPhotoAndNameFields) { + ui->setupUi(this); + ui->lineEditPREFIX->hide(); + ui->lineEditMIDDLE->hide(); + ui->lineEditSUFFIX->hide(); + ui->lineEditFN->hide(); + ui->lineEditNICKNAME->hide(); + ui->labelFN->hide(); + ui->labelNICKNAME->hide(); + ui->labelFULLNAME->hide(); #if QT_VERSION >= 0x040700 - ui->lineEditFN->setPlaceholderText(tr("Formatted Name")); - ui->lineEditNICKNAME->setPlaceholderText(tr("Nickname")); - ui->lineEditPREFIX->setPlaceholderText(tr("Prefix")); - ui->lineEditGIVEN->setPlaceholderText(tr("Given Name")); - ui->lineEditMIDDLE->setPlaceholderText(tr("Middle Name")); - ui->lineEditFAMILY->setPlaceholderText(tr("Last Name")); - ui->lineEditSUFFIX->setPlaceholderText(tr("Suffix")); + ui->lineEditFN->setPlaceholderText(tr("Formatted Name")); + ui->lineEditNICKNAME->setPlaceholderText(tr("Nickname")); + ui->lineEditPREFIX->setPlaceholderText(tr("Prefix")); + ui->lineEditGIVEN->setPlaceholderText(tr("Given Name")); + ui->lineEditMIDDLE->setPlaceholderText(tr("Middle Name")); + ui->lineEditFAMILY->setPlaceholderText(tr("Last Name")); + ui->lineEditSUFFIX->setPlaceholderText(tr("Suffix")); #endif - setEditable(false); + setEditable(false); } QtVCardPhotoAndNameFields::~QtVCardPhotoAndNameFields() { - delete ui; + delete ui; } bool QtVCardPhotoAndNameFields::isEditable() const { - return editable; + return editable; } void QtVCardPhotoAndNameFields::setEditable(bool editable) { - this->editable = editable; + this->editable = editable; - ui->avatarWidget->setEditable(editable); - ui->lineEditFN->setVisible(editable); - ui->labelFN->setVisible(!editable); + ui->avatarWidget->setEditable(editable); + ui->lineEditFN->setVisible(editable); + ui->labelFN->setVisible(!editable); - ui->lineEditNICKNAME->setVisible(editable); - ui->labelNICKNAME->setVisible(!editable); + ui->lineEditNICKNAME->setVisible(editable); + ui->labelNICKNAME->setVisible(!editable); - // prefix given middle last suffix - ui->lineEditPREFIX->setVisible(editable); - ui->lineEditGIVEN->setVisible(editable); - ui->lineEditMIDDLE->setVisible(editable); - ui->lineEditFAMILY->setVisible(editable); - ui->lineEditSUFFIX->setVisible(editable); - ui->labelFULLNAME->setVisible(!editable); + // prefix given middle last suffix + ui->lineEditPREFIX->setVisible(editable); + ui->lineEditGIVEN->setVisible(editable); + ui->lineEditMIDDLE->setVisible(editable); + ui->lineEditFAMILY->setVisible(editable); + ui->lineEditSUFFIX->setVisible(editable); + ui->labelFULLNAME->setVisible(!editable); - QStringList fullname; - fullname << ui->lineEditPREFIX->text() << ui->lineEditGIVEN->text() << ui->lineEditMIDDLE->text(); - fullname << ui->lineEditFAMILY->text() << ui->lineEditSUFFIX->text(); - for (QStringList::iterator i = fullname.begin(); i != fullname.end(); i++) { - *i = i->trimmed(); - } - ui->labelFULLNAME->setText((fullname.filter(QRegExp(".+"))).join(" ")); + QStringList fullname; + fullname << ui->lineEditPREFIX->text() << ui->lineEditGIVEN->text() << ui->lineEditMIDDLE->text(); + fullname << ui->lineEditFAMILY->text() << ui->lineEditSUFFIX->text(); + for (QStringList::iterator i = fullname.begin(); i != fullname.end(); i++) { + *i = i->trimmed(); + } + ui->labelFULLNAME->setText((fullname.filter(QRegExp(".+"))).join(" ")); } void QtVCardPhotoAndNameFields::setAvatar(const ByteArray &data, const std::string &type) { - ui->avatarWidget->setAvatar(data, type); + ui->avatarWidget->setAvatar(data, type); } ByteArray QtVCardPhotoAndNameFields::getAvatarData() const { - return ui->avatarWidget->getAvatarData(); + return ui->avatarWidget->getAvatarData(); } std::string QtVCardPhotoAndNameFields::getAvatarType() const { - return ui->avatarWidget->getAvatarType(); + return ui->avatarWidget->getAvatarType(); } void QtVCardPhotoAndNameFields::setFormattedName(const QString& formattedName) { - ui->lineEditFN->setText(formattedName); - ui->labelFN->setText(formattedName); + ui->lineEditFN->setText(formattedName); + ui->labelFN->setText(formattedName); } QString QtVCardPhotoAndNameFields::getFormattedName() const { - return ui->lineEditFN->text(); + return ui->lineEditFN->text(); } void QtVCardPhotoAndNameFields::setNickname(const QString& nickname) { - ui->lineEditNICKNAME->setText(nickname); - ui->labelNICKNAME->setText(nickname); + ui->lineEditNICKNAME->setText(nickname); + ui->labelNICKNAME->setText(nickname); } QString QtVCardPhotoAndNameFields::getNickname() const { - return ui->lineEditNICKNAME->text(); + return ui->lineEditNICKNAME->text(); } void QtVCardPhotoAndNameFields::setPrefix(const QString& prefix) { - ui->lineEditPREFIX->setText(prefix); + ui->lineEditPREFIX->setText(prefix); } QString QtVCardPhotoAndNameFields::getPrefix() const { - return ui->lineEditPREFIX->text(); + return ui->lineEditPREFIX->text(); } void QtVCardPhotoAndNameFields::setGivenName(const QString& givenName) { - ui->lineEditGIVEN->setText(givenName); + ui->lineEditGIVEN->setText(givenName); } QString QtVCardPhotoAndNameFields::getGivenName() const { - return ui->lineEditGIVEN->text(); + return ui->lineEditGIVEN->text(); } void QtVCardPhotoAndNameFields::setMiddleName(const QString& middleName) { - ui->lineEditMIDDLE->setText(middleName); + ui->lineEditMIDDLE->setText(middleName); } QString QtVCardPhotoAndNameFields::getMiddleName() const { - return ui->lineEditMIDDLE->text(); + return ui->lineEditMIDDLE->text(); } void QtVCardPhotoAndNameFields::setFamilyName(const QString& familyName) { - ui->lineEditFAMILY->setText(familyName); + ui->lineEditFAMILY->setText(familyName); } QString QtVCardPhotoAndNameFields::getFamilyName() const { - return ui->lineEditFAMILY->text(); + return ui->lineEditFAMILY->text(); } void QtVCardPhotoAndNameFields::setSuffix(const QString& suffix) { - ui->lineEditSUFFIX->setText(suffix); + ui->lineEditSUFFIX->setText(suffix); } QString QtVCardPhotoAndNameFields::getSuffix() const { - return ui->lineEditSUFFIX->text(); + return ui->lineEditSUFFIX->text(); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h index ac35109..a0bbb24 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardPhotoAndNameFields.h @@ -12,51 +12,51 @@ #include namespace Ui { - class QtVCardPhotoAndNameFields; + class QtVCardPhotoAndNameFields; } namespace Swift { - class QtVCardPhotoAndNameFields : public QWidget { - Q_OBJECT - Q_PROPERTY(bool editable READ isEditable WRITE setEditable) + class QtVCardPhotoAndNameFields : public QWidget { + Q_OBJECT + Q_PROPERTY(bool editable READ isEditable WRITE setEditable) - public: - explicit QtVCardPhotoAndNameFields(QWidget* parent = 0); - ~QtVCardPhotoAndNameFields(); + public: + explicit QtVCardPhotoAndNameFields(QWidget* parent = 0); + ~QtVCardPhotoAndNameFields(); - bool isEditable() const; - void setEditable(bool); + bool isEditable() const; + void setEditable(bool); - void setAvatar(const ByteArray& data, const std::string& type); - ByteArray getAvatarData() const; - std::string getAvatarType() const; + void setAvatar(const ByteArray& data, const std::string& type); + ByteArray getAvatarData() const; + std::string getAvatarType() const; - void setFormattedName(const QString& formattedName); - QString getFormattedName() const; + void setFormattedName(const QString& formattedName); + QString getFormattedName() const; - void setNickname(const QString& nickname); - QString getNickname() const; + void setNickname(const QString& nickname); + QString getNickname() const; - void setPrefix(const QString& prefix); - QString getPrefix() const; + void setPrefix(const QString& prefix); + QString getPrefix() const; - void setGivenName(const QString& givenName); - QString getGivenName() const; + void setGivenName(const QString& givenName); + QString getGivenName() const; - void setMiddleName(const QString& middleName); - QString getMiddleName() const; + void setMiddleName(const QString& middleName); + QString getMiddleName() const; - void setFamilyName(const QString& familyName); - QString getFamilyName() const; + void setFamilyName(const QString& familyName); + QString getFamilyName() const; - void setSuffix(const QString& suffix); - QString getSuffix() const; + void setSuffix(const QString& suffix); + QString getSuffix() const; - private: - Ui::QtVCardPhotoAndNameFields* ui; - bool editable; - }; + private: + Ui::QtVCardPhotoAndNameFields* ui; + bool editable; + }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp index ce3cc2f..2881932 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.cpp @@ -21,37 +21,37 @@ namespace Swift { QtVCardRoleField::QtVCardRoleField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Role"), false, false), roleLineEdit(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Role"), false, false), roleLineEdit(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardRoleField::~QtVCardRoleField() { } void QtVCardRoleField::setupContentWidgets() { - roleLineEdit = new QtResizableLineEdit(this); - getGridLayout()->addWidget(roleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); - getTagComboBox()->hide(); - childWidgets << roleLineEdit; + roleLineEdit = new QtResizableLineEdit(this); + getGridLayout()->addWidget(roleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); + getTagComboBox()->hide(); + childWidgets << roleLineEdit; } bool QtVCardRoleField::isEmpty() const { - return roleLineEdit->text().isEmpty(); + return roleLineEdit->text().isEmpty(); } void QtVCardRoleField::setRole(const std::string& role) { - roleLineEdit->setText(P2QSTRING(role)); + roleLineEdit->setText(P2QSTRING(role)); } std::string QtVCardRoleField::getRole() const { - return Q2PSTRING(roleLineEdit->text()); + return Q2PSTRING(roleLineEdit->text()); } void QtVCardRoleField::handleEditibleChanged(bool isEditable) { - assert(roleLineEdit); + assert(roleLineEdit); - roleLineEdit->setEditable(isEditable); - roleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); + roleLineEdit->setEditable(isEditable); + roleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h index f2d5e75..40b5d0b 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardRoleField.h @@ -21,27 +21,27 @@ namespace Swift { class QtVCardRoleField : public QtVCardGeneralField { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Role"), UNLIMITED_INSTANCES, QtVCardRoleField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Role"), UNLIMITED_INSTANCES, QtVCardRoleField) - QtVCardRoleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardRoleField(); + QtVCardRoleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardRoleField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setRole(const std::string& role); - std::string getRole() const; + void setRole(const std::string& role); + std::string getRole() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QtResizableLineEdit* roleLineEdit; + private: + QtResizableLineEdit* roleLineEdit; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp index 57e2b27..4af2fa3 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.cpp @@ -19,88 +19,88 @@ namespace Swift { QtVCardTelephoneField::QtVCardTelephoneField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Telephone")), telephoneLineEdit(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Telephone")), telephoneLineEdit(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardTelephoneField::~QtVCardTelephoneField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardTelephoneField::setupContentWidgets() { - telephoneLineEdit = new QtResizableLineEdit(this); + telephoneLineEdit = new QtResizableLineEdit(this); #if QT_VERSION >= 0x040700 - telephoneLineEdit->setPlaceholderText(tr("0118 999 881 999 119 7253")); + telephoneLineEdit->setPlaceholderText(tr("0118 999 881 999 119 7253")); #endif - getGridLayout()->addWidget(telephoneLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); - setTabOrder(telephoneLineEdit, getTagComboBox()); - QtVCardHomeWork::setTagComboBox(getTagComboBox()); - - getTagComboBox()->addTag("voice", QObject::tr("Voice")); - getTagComboBox()->addTag("fax", QObject::tr("Fax")); - getTagComboBox()->addTag("pager", QObject::tr("Pager")); - getTagComboBox()->addTag("msg", QObject::tr("Voice Messaging")); - getTagComboBox()->addTag("cell", QObject::tr("Cell")); - getTagComboBox()->addTag("video", QObject::tr("Video")); - getTagComboBox()->addTag("bbs", QObject::tr("Bulletin Board System")); - getTagComboBox()->addTag("modem", QObject::tr("Modem")); - getTagComboBox()->addTag("isdn", QObject::tr("ISDN")); - getTagComboBox()->addTag("pcs", QObject::tr("Personal Communication Services")); - - childWidgets << telephoneLineEdit; + getGridLayout()->addWidget(telephoneLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); + setTabOrder(telephoneLineEdit, getTagComboBox()); + QtVCardHomeWork::setTagComboBox(getTagComboBox()); + + getTagComboBox()->addTag("voice", QObject::tr("Voice")); + getTagComboBox()->addTag("fax", QObject::tr("Fax")); + getTagComboBox()->addTag("pager", QObject::tr("Pager")); + getTagComboBox()->addTag("msg", QObject::tr("Voice Messaging")); + getTagComboBox()->addTag("cell", QObject::tr("Cell")); + getTagComboBox()->addTag("video", QObject::tr("Video")); + getTagComboBox()->addTag("bbs", QObject::tr("Bulletin Board System")); + getTagComboBox()->addTag("modem", QObject::tr("Modem")); + getTagComboBox()->addTag("isdn", QObject::tr("ISDN")); + getTagComboBox()->addTag("pcs", QObject::tr("Personal Communication Services")); + + childWidgets << telephoneLineEdit; } bool QtVCardTelephoneField::isEmpty() const { - return telephoneLineEdit->text().isEmpty(); + return telephoneLineEdit->text().isEmpty(); } void QtVCardTelephoneField::setTelephone(const VCard::Telephone& telephone) { - setPreferred(telephone.isPreferred); - setHome(telephone.isHome); - setWork(telephone.isWork); - - telephoneLineEdit->setText(P2QSTRING(telephone.number)); - - getTagComboBox()->setTag("voice", telephone.isVoice); - getTagComboBox()->setTag("fax", telephone.isFax); - getTagComboBox()->setTag("pager", telephone.isPager); - getTagComboBox()->setTag("msg", telephone.isMSG); - getTagComboBox()->setTag("cell", telephone.isCell); - getTagComboBox()->setTag("video", telephone.isVideo); - getTagComboBox()->setTag("bbs", telephone.isBBS); - getTagComboBox()->setTag("modem", telephone.isModem); - getTagComboBox()->setTag("isdn", telephone.isISDN); - getTagComboBox()->setTag("pcs", telephone.isPCS); + setPreferred(telephone.isPreferred); + setHome(telephone.isHome); + setWork(telephone.isWork); + + telephoneLineEdit->setText(P2QSTRING(telephone.number)); + + getTagComboBox()->setTag("voice", telephone.isVoice); + getTagComboBox()->setTag("fax", telephone.isFax); + getTagComboBox()->setTag("pager", telephone.isPager); + getTagComboBox()->setTag("msg", telephone.isMSG); + getTagComboBox()->setTag("cell", telephone.isCell); + getTagComboBox()->setTag("video", telephone.isVideo); + getTagComboBox()->setTag("bbs", telephone.isBBS); + getTagComboBox()->setTag("modem", telephone.isModem); + getTagComboBox()->setTag("isdn", telephone.isISDN); + getTagComboBox()->setTag("pcs", telephone.isPCS); } VCard::Telephone QtVCardTelephoneField::getTelephone() const { - VCard::Telephone telephone; - - telephone.number = Q2PSTRING(telephoneLineEdit->text()); - - telephone.isPreferred = getPreferred(); - telephone.isHome = getHome(); - telephone.isWork = getWork(); - - telephone.isVoice = getTagComboBox()->isTagSet("voice"); - telephone.isFax = getTagComboBox()->isTagSet("fax"); - telephone.isPager = getTagComboBox()->isTagSet("pager"); - telephone.isMSG = getTagComboBox()->isTagSet("msg"); - telephone.isCell = getTagComboBox()->isTagSet("cell"); - telephone.isVideo = getTagComboBox()->isTagSet("video"); - telephone.isBBS = getTagComboBox()->isTagSet("bbs"); - telephone.isModem = getTagComboBox()->isTagSet("modem"); - telephone.isISDN = getTagComboBox()->isTagSet("isdn"); - telephone.isPCS = getTagComboBox()->isTagSet("pcs"); - - return telephone; + VCard::Telephone telephone; + + telephone.number = Q2PSTRING(telephoneLineEdit->text()); + + telephone.isPreferred = getPreferred(); + telephone.isHome = getHome(); + telephone.isWork = getWork(); + + telephone.isVoice = getTagComboBox()->isTagSet("voice"); + telephone.isFax = getTagComboBox()->isTagSet("fax"); + telephone.isPager = getTagComboBox()->isTagSet("pager"); + telephone.isMSG = getTagComboBox()->isTagSet("msg"); + telephone.isCell = getTagComboBox()->isTagSet("cell"); + telephone.isVideo = getTagComboBox()->isTagSet("video"); + telephone.isBBS = getTagComboBox()->isTagSet("bbs"); + telephone.isModem = getTagComboBox()->isTagSet("modem"); + telephone.isISDN = getTagComboBox()->isTagSet("isdn"); + telephone.isPCS = getTagComboBox()->isTagSet("pcs"); + + return telephone; } void QtVCardTelephoneField::handleEditibleChanged(bool isEditable) { - assert(telephoneLineEdit); + assert(telephoneLineEdit); - telephoneLineEdit->setEditable(isEditable); - telephoneLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); + telephoneLineEdit->setEditable(isEditable); + telephoneLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h index a06eb32..1a08a5a 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardTelephoneField.h @@ -22,27 +22,27 @@ namespace Swift { class QtVCardTelephoneField : public QtVCardGeneralField, public QtVCardHomeWork { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Telephone"), UNLIMITED_INSTANCES, QtVCardTelephoneField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Telephone"), UNLIMITED_INSTANCES, QtVCardTelephoneField) - QtVCardTelephoneField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardTelephoneField(); + QtVCardTelephoneField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardTelephoneField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setTelephone(const VCard::Telephone& telephone); - VCard::Telephone getTelephone() const; + void setTelephone(const VCard::Telephone& telephone); + VCard::Telephone getTelephone() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QtResizableLineEdit* telephoneLineEdit; + private: + QtResizableLineEdit* telephoneLineEdit; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp index aab7fac..5da5763 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.cpp @@ -21,38 +21,38 @@ namespace Swift { QtVCardTitleField::QtVCardTitleField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Title"), false, false), titleLineEdit(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("Title"), false, false), titleLineEdit(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardTitleField::~QtVCardTitleField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardTitleField::setupContentWidgets() { - titleLineEdit = new QtResizableLineEdit(this); - getGridLayout()->addWidget(titleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); - getTagComboBox()->hide(); - childWidgets << titleLineEdit; + titleLineEdit = new QtResizableLineEdit(this); + getGridLayout()->addWidget(titleLineEdit, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); + getTagComboBox()->hide(); + childWidgets << titleLineEdit; } bool QtVCardTitleField::isEmpty() const { - return titleLineEdit->text().isEmpty(); + return titleLineEdit->text().isEmpty(); } void QtVCardTitleField::setTitle(const std::string& title) { - titleLineEdit->setText(P2QSTRING(title)); + titleLineEdit->setText(P2QSTRING(title)); } std::string QtVCardTitleField::getTitle() const { - return Q2PSTRING(titleLineEdit->text()); + return Q2PSTRING(titleLineEdit->text()); } void QtVCardTitleField::handleEditibleChanged(bool isEditable) { - assert(titleLineEdit); + assert(titleLineEdit); - titleLineEdit->setEditable(isEditable); - titleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); + titleLineEdit->setEditable(isEditable); + titleLineEdit->setStyleSheet(isEditable ? "" : "QLineEdit { border: none; background: transparent; }"); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h index a7feb81..ff2a04e 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardTitleField.h @@ -21,27 +21,27 @@ namespace Swift { class QtVCardTitleField : public QtVCardGeneralField { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("Title"), UNLIMITED_INSTANCES, QtVCardTitleField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("Title"), UNLIMITED_INSTANCES, QtVCardTitleField) - QtVCardTitleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardTitleField(); + QtVCardTitleField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardTitleField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setTitle(const std::string& title); - std::string getTitle() const; + void setTitle(const std::string& title); + std::string getTitle() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QtResizableLineEdit* titleLineEdit; + private: + QtResizableLineEdit* titleLineEdit; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp b/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp index 262a0e2..8abc46e 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.cpp @@ -24,54 +24,54 @@ namespace Swift { QtVCardURLField::QtVCardURLField(QWidget* parent, QGridLayout *layout, bool editable) : - QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("URL"), false, false), urlLabel(NULL), urlLineEdit(NULL) { - connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); + QtVCardGeneralField(parent, layout, editable, layout->rowCount(), tr("URL"), false, false), urlLabel(NULL), urlLineEdit(NULL) { + connect(this, SIGNAL(editableChanged(bool)), SLOT(handleEditibleChanged(bool))); } QtVCardURLField::~QtVCardURLField() { - disconnect(this, SLOT(handleEditibleChanged(bool))); + disconnect(this, SLOT(handleEditibleChanged(bool))); } void QtVCardURLField::setupContentWidgets() { - urlLabel = new QLabel(this); - urlLabel->setOpenExternalLinks(true); - urlLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); - urlLineEdit = new QtResizableLineEdit(this); - - QHBoxLayout* urlLayout = new QHBoxLayout(); - urlLayout->addWidget(urlLabel); - urlLayout->addWidget(urlLineEdit); - - getGridLayout()->addLayout(urlLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); - getTagComboBox()->hide(); - urlLabel->hide(); - childWidgets << urlLabel << urlLineEdit; + urlLabel = new QLabel(this); + urlLabel->setOpenExternalLinks(true); + urlLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); + urlLineEdit = new QtResizableLineEdit(this); + + QHBoxLayout* urlLayout = new QHBoxLayout(); + urlLayout->addWidget(urlLabel); + urlLayout->addWidget(urlLineEdit); + + getGridLayout()->addLayout(urlLayout, getGridLayout()->rowCount()-1, 2, 1, 2, Qt::AlignVCenter); + getTagComboBox()->hide(); + urlLabel->hide(); + childWidgets << urlLabel << urlLineEdit; } bool QtVCardURLField::isEmpty() const { - return urlLineEdit->text().isEmpty(); + return urlLineEdit->text().isEmpty(); } void QtVCardURLField::setURL(const std::string& url) { - urlLineEdit->setText(P2QSTRING(url)); + urlLineEdit->setText(P2QSTRING(url)); } std::string QtVCardURLField::getURL() const { - return Q2PSTRING(urlLineEdit->text()); + return Q2PSTRING(urlLineEdit->text()); } void QtVCardURLField::handleEditibleChanged(bool isEditable) { - assert(urlLineEdit); - assert(urlLabel); - - if (isEditable) { - urlLineEdit->show(); - urlLabel->hide(); - } else { - urlLineEdit->hide(); - urlLabel->setText(QString("%1").arg(QtUtilities::htmlEscape(urlLineEdit->text()))); - urlLabel->show(); - } + assert(urlLineEdit); + assert(urlLabel); + + if (isEditable) { + urlLineEdit->show(); + urlLabel->hide(); + } else { + urlLineEdit->hide(); + urlLabel->setText(QString("%1").arg(QtUtilities::htmlEscape(urlLineEdit->text()))); + urlLabel->show(); + } } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardURLField.h b/Swift/QtUI/QtVCardWidget/QtVCardURLField.h index 824879a..a1ffacd 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardURLField.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardURLField.h @@ -21,28 +21,28 @@ namespace Swift { class QtVCardURLField : public QtVCardGeneralField { - Q_OBJECT + Q_OBJECT - public: - GENERIC_QT_VCARD_FIELD_INFO(tr("URL"), UNLIMITED_INSTANCES, QtVCardURLField) + public: + GENERIC_QT_VCARD_FIELD_INFO(tr("URL"), UNLIMITED_INSTANCES, QtVCardURLField) - QtVCardURLField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); - virtual ~QtVCardURLField(); + QtVCardURLField(QWidget* parent = 0, QGridLayout* layout = 0, bool editable = false); + virtual ~QtVCardURLField(); - virtual bool isEmpty() const; + virtual bool isEmpty() const; - void setURL(const std::string& url); - std::string getURL() const; + void setURL(const std::string& url); + std::string getURL() const; - protected: - virtual void setupContentWidgets(); + protected: + virtual void setupContentWidgets(); - public slots: - void handleEditibleChanged(bool isEditable); + public slots: + void handleEditibleChanged(bool isEditable); - private: - QLabel* urlLabel; - QtResizableLineEdit* urlLineEdit; + private: + QLabel* urlLabel; + QtResizableLineEdit* urlLineEdit; }; } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp b/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp index f390d30..712cedf 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp +++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.cpp @@ -33,394 +33,394 @@ namespace Swift { QtVCardWidget::QtVCardWidget(QWidget* parent) : - QWidget(parent), - ui(new ::Ui::QtVCardWidget) { - ui->setupUi(this); - - ui->cardFields->setColumnStretch(0,0); - ui->cardFields->setColumnStretch(1,0); - ui->cardFields->setColumnStretch(2,2); - ui->cardFields->setColumnStretch(3,1); - ui->cardFields->setColumnStretch(4,2); - menu = new QMenu(this); - - toolButton = new QToolButton(this); - toolButton->setText(tr("Add Field")); - toolButton->setArrowType(Qt::NoArrow); - toolButton->setAutoRaise(false); - toolButton->setPopupMode(QToolButton::InstantPopup); - toolButton->hide(); - toolButton->setMenu(menu); - - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - addFieldType(menu, boost::make_shared()); - - setEditable(false); - setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + QWidget(parent), + ui(new ::Ui::QtVCardWidget) { + ui->setupUi(this); + + ui->cardFields->setColumnStretch(0,0); + ui->cardFields->setColumnStretch(1,0); + ui->cardFields->setColumnStretch(2,2); + ui->cardFields->setColumnStretch(3,1); + ui->cardFields->setColumnStretch(4,2); + menu = new QMenu(this); + + toolButton = new QToolButton(this); + toolButton->setText(tr("Add Field")); + toolButton->setArrowType(Qt::NoArrow); + toolButton->setAutoRaise(false); + toolButton->setPopupMode(QToolButton::InstantPopup); + toolButton->hide(); + toolButton->setMenu(menu); + + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + addFieldType(menu, boost::make_shared()); + + setEditable(false); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); } QtVCardWidget::~QtVCardWidget() { - delete ui; + delete ui; } QSize QtVCardWidget::sizeHint() const { - QSize newSizeHint = ui->photoAndName->sizeHint(); + QSize newSizeHint = ui->photoAndName->sizeHint(); - // use mininmal size that does not require scrolling - QSize fieldsWidgetSize = ui->scrollArea->widget()->minimumSize(); - fieldsWidgetSize.setWidth(ui->scrollArea->widget()->sizeHint().width()); + // use mininmal size that does not require scrolling + QSize fieldsWidgetSize = ui->scrollArea->widget()->minimumSize(); + fieldsWidgetSize.setWidth(ui->scrollArea->widget()->sizeHint().width()); - newSizeHint += QSize(0, ui->line->height()); + newSizeHint += QSize(0, ui->line->height()); - newSizeHint = QSize(std::max(newSizeHint.width(), fieldsWidgetSize.width()), newSizeHint.height() + fieldsWidgetSize.height()); + newSizeHint = QSize(std::max(newSizeHint.width(), fieldsWidgetSize.width()), newSizeHint.height() + fieldsWidgetSize.height()); - // add layout margin - newSizeHint += QSize(layout()->contentsMargins().left() + layout()->contentsMargins().right(), layout()->contentsMargins().top() + layout()->contentsMargins().bottom()); + // add layout margin + newSizeHint += QSize(layout()->contentsMargins().left() + layout()->contentsMargins().right(), layout()->contentsMargins().top() + layout()->contentsMargins().bottom()); - // the spaceing before and after the line between the profile header and its fields - newSizeHint += QSize(0, layout()->spacing() * 2); + // the spaceing before and after the line between the profile header and its fields + newSizeHint += QSize(0, layout()->spacing() * 2); - return newSizeHint; + return newSizeHint; } bool QtVCardWidget::isEditable() const { - return editable; + return editable; } void QtVCardWidget::setEditable(bool editable) { - this->editable = editable; + this->editable = editable; - ui->photoAndName->setProperty("editable", QVariant(editable)); + ui->photoAndName->setProperty("editable", QVariant(editable)); - foreach(QtVCardGeneralField* field, fields) { - field->setEditable(editable); - } - toolButton->setVisible(editable); + foreach(QtVCardGeneralField* field, fields) { + field->setEditable(editable); + } + toolButton->setVisible(editable); - editableChanged(editable); + editableChanged(editable); } void QtVCardWidget::setVCard(VCard::ref vcard) { - clearFields(); - this->vcard = boost::make_shared(*vcard); - ui->photoAndName->setFormattedName(P2QSTRING(vcard->getFullName())); - ui->photoAndName->setNickname(P2QSTRING(vcard->getNickname())); - ui->photoAndName->setPrefix(P2QSTRING(vcard->getPrefix())); - ui->photoAndName->setGivenName(P2QSTRING(vcard->getGivenName())); - ui->photoAndName->setMiddleName(P2QSTRING(vcard->getMiddleName())); - ui->photoAndName->setFamilyName(P2QSTRING(vcard->getFamilyName())); - ui->photoAndName->setSuffix(P2QSTRING(vcard->getSuffix())); - ui->photoAndName->setAvatar(vcard->getPhoto(), vcard->getPhotoType()); - - foreach (const VCard::EMailAddress& address, vcard->getEMailAddresses()) { - if (address.isInternet) { - QtVCardInternetEMailField* internetEmailField = new QtVCardInternetEMailField(this, ui->cardFields); - internetEmailField->initialize(); - internetEmailField->setInternetEMailAddress(address); - appendField(internetEmailField); - } - } - - foreach (const VCard::Telephone& telephone, vcard->getTelephones()) { - QtVCardTelephoneField* telField = new QtVCardTelephoneField(this, ui->cardFields); - telField->initialize(); - telField->setTelephone(telephone); - appendField(telField); - } - - foreach (const VCard::Address& address, vcard->getAddresses()) { - QtVCardAddressField* addressField = new QtVCardAddressField(this, ui->cardFields); - addressField->initialize(); - addressField->setAddress(address); - appendField(addressField); - } - - foreach (const VCard::AddressLabel& label, vcard->getAddressLabels()) { - QtVCardAddressLabelField* addressLabelField = new QtVCardAddressLabelField(this, ui->cardFields); - addressLabelField->initialize(); - addressLabelField->setAddressLabel(label); - appendField(addressLabelField); - } - - if (!vcard->getBirthday().is_not_a_date_time()) { - QtVCardBirthdayField* bdayField = new QtVCardBirthdayField(this, ui->cardFields); - bdayField->initialize(); - bdayField->setBirthday(vcard->getBirthday()); - appendField(bdayField); - } - - foreach (const JID& jid, vcard->getJIDs()) { - QtVCardJIDField* jidField = new QtVCardJIDField(this, ui->cardFields); - jidField->initialize(); - jidField->setJID(jid); - appendField(jidField); - } - - if (!vcard->getDescription().empty()) { - QtVCardDescriptionField* descField = new QtVCardDescriptionField(this, ui->cardFields); - descField->initialize(); - descField->setDescription(vcard->getDescription()); - appendField(descField); - } - - foreach (const VCard::Organization& org, vcard->getOrganizations()) { - QtVCardOrganizationField* orgField = new QtVCardOrganizationField(this, ui->cardFields); - orgField->initialize(); - orgField->setOrganization(org); - appendField(orgField); - } - - foreach (const std::string& role, vcard->getRoles()) { - QtVCardRoleField* roleField = new QtVCardRoleField(this, ui->cardFields); - roleField->initialize(); - roleField->setRole(role); - appendField(roleField); - } - - foreach (const std::string& title, vcard->getTitles()) { - QtVCardTitleField* titleField = new QtVCardTitleField(this, ui->cardFields); - titleField->initialize(); - titleField->setTitle(title); - appendField(titleField); - } - - foreach (const std::string& url, vcard->getURLs()) { - QtVCardURLField* urlField = new QtVCardURLField(this, ui->cardFields); - urlField->initialize(); - urlField->setURL(url); - appendField(urlField); - } - - relayoutToolButton(); - setEditable(editable); + clearFields(); + this->vcard = boost::make_shared(*vcard); + ui->photoAndName->setFormattedName(P2QSTRING(vcard->getFullName())); + ui->photoAndName->setNickname(P2QSTRING(vcard->getNickname())); + ui->photoAndName->setPrefix(P2QSTRING(vcard->getPrefix())); + ui->photoAndName->setGivenName(P2QSTRING(vcard->getGivenName())); + ui->photoAndName->setMiddleName(P2QSTRING(vcard->getMiddleName())); + ui->photoAndName->setFamilyName(P2QSTRING(vcard->getFamilyName())); + ui->photoAndName->setSuffix(P2QSTRING(vcard->getSuffix())); + ui->photoAndName->setAvatar(vcard->getPhoto(), vcard->getPhotoType()); + + foreach (const VCard::EMailAddress& address, vcard->getEMailAddresses()) { + if (address.isInternet) { + QtVCardInternetEMailField* internetEmailField = new QtVCardInternetEMailField(this, ui->cardFields); + internetEmailField->initialize(); + internetEmailField->setInternetEMailAddress(address); + appendField(internetEmailField); + } + } + + foreach (const VCard::Telephone& telephone, vcard->getTelephones()) { + QtVCardTelephoneField* telField = new QtVCardTelephoneField(this, ui->cardFields); + telField->initialize(); + telField->setTelephone(telephone); + appendField(telField); + } + + foreach (const VCard::Address& address, vcard->getAddresses()) { + QtVCardAddressField* addressField = new QtVCardAddressField(this, ui->cardFields); + addressField->initialize(); + addressField->setAddress(address); + appendField(addressField); + } + + foreach (const VCard::AddressLabel& label, vcard->getAddressLabels()) { + QtVCardAddressLabelField* addressLabelField = new QtVCardAddressLabelField(this, ui->cardFields); + addressLabelField->initialize(); + addressLabelField->setAddressLabel(label); + appendField(addressLabelField); + } + + if (!vcard->getBirthday().is_not_a_date_time()) { + QtVCardBirthdayField* bdayField = new QtVCardBirthdayField(this, ui->cardFields); + bdayField->initialize(); + bdayField->setBirthday(vcard->getBirthday()); + appendField(bdayField); + } + + foreach (const JID& jid, vcard->getJIDs()) { + QtVCardJIDField* jidField = new QtVCardJIDField(this, ui->cardFields); + jidField->initialize(); + jidField->setJID(jid); + appendField(jidField); + } + + if (!vcard->getDescription().empty()) { + QtVCardDescriptionField* descField = new QtVCardDescriptionField(this, ui->cardFields); + descField->initialize(); + descField->setDescription(vcard->getDescription()); + appendField(descField); + } + + foreach (const VCard::Organization& org, vcard->getOrganizations()) { + QtVCardOrganizationField* orgField = new QtVCardOrganizationField(this, ui->cardFields); + orgField->initialize(); + orgField->setOrganization(org); + appendField(orgField); + } + + foreach (const std::string& role, vcard->getRoles()) { + QtVCardRoleField* roleField = new QtVCardRoleField(this, ui->cardFields); + roleField->initialize(); + roleField->setRole(role); + appendField(roleField); + } + + foreach (const std::string& title, vcard->getTitles()) { + QtVCardTitleField* titleField = new QtVCardTitleField(this, ui->cardFields); + titleField->initialize(); + titleField->setTitle(title); + appendField(titleField); + } + + foreach (const std::string& url, vcard->getURLs()) { + QtVCardURLField* urlField = new QtVCardURLField(this, ui->cardFields); + urlField->initialize(); + urlField->setURL(url); + appendField(urlField); + } + + relayoutToolButton(); + setEditable(editable); } VCard::ref QtVCardWidget::getVCard() { - clearEmptyFields(); - vcard->setFullName(Q2PSTRING(ui->photoAndName->getFormattedName())); - vcard->setNickname(Q2PSTRING(ui->photoAndName->getNickname())); - vcard->setPrefix(Q2PSTRING(ui->photoAndName->getPrefix())); - vcard->setGivenName(Q2PSTRING(ui->photoAndName->getGivenName())); - vcard->setMiddleName(Q2PSTRING(ui->photoAndName->getMiddleName())); - vcard->setFamilyName(Q2PSTRING(ui->photoAndName->getFamilyName())); - vcard->setSuffix(Q2PSTRING(ui->photoAndName->getSuffix())); - vcard->setPhoto(ui->photoAndName->getAvatarData()); - vcard->setPhotoType(ui->photoAndName->getAvatarType()); - - vcard->clearEMailAddresses(); - vcard->clearJIDs(); - vcard->clearURLs(); - vcard->clearTelephones(); - vcard->clearRoles(); - vcard->clearTitles(); - vcard->clearOrganizations(); - vcard->clearAddresses(); - vcard->clearAddressLabels(); - - - QtVCardBirthdayField* bdayField = NULL; - QtVCardDescriptionField* descriptionField = NULL; - - foreach(QtVCardGeneralField* field, fields) { - QtVCardInternetEMailField* emailField; - if ((emailField = dynamic_cast(field))) { - vcard->addEMailAddress(emailField->getInternetEMailAddress()); - continue; - } - - QtVCardTelephoneField* telephoneField; - if ((telephoneField = dynamic_cast(field))) { - vcard->addTelephone(telephoneField->getTelephone()); - continue; - } - - QtVCardAddressField* addressField; - if ((addressField = dynamic_cast(field))) { - vcard->addAddress(addressField->getAddress()); - continue; - } - - QtVCardAddressLabelField* addressLabelField; - if ((addressLabelField = dynamic_cast(field))) { - vcard->addAddressLabel(addressLabelField->getAddressLabel()); - continue; - } - - if ((bdayField = dynamic_cast(field))) { - continue; - } - - QtVCardJIDField* jidField; - if ((jidField = dynamic_cast(field))) { - vcard->addJID(jidField->getJID()); - continue; - } - - if ((descriptionField = dynamic_cast(field))) { - continue; - } - - QtVCardOrganizationField* orgField; - if ((orgField = dynamic_cast(field))) { - vcard->addOrganization(orgField->getOrganization()); - continue; - } - - QtVCardRoleField* roleField; - if ((roleField = dynamic_cast(field))) { - vcard->addRole(roleField->getRole()); - continue; - } - - QtVCardTitleField* titleField; - if ((titleField = dynamic_cast(field))) { - vcard->addTitle(titleField->getTitle()); - continue; - } - - QtVCardURLField* urlField; - if ((urlField = dynamic_cast(field))) { - vcard->addURL(urlField->getURL()); - continue; - } - } - - if (bdayField) { - vcard->setBirthday(bdayField->getBirthday()); - } else { - vcard->setBirthday(boost::posix_time::ptime()); - } - - if (descriptionField) { - vcard->setDescription(descriptionField->getDescription()); - } else { - vcard->setDescription(""); - } - - return vcard; + clearEmptyFields(); + vcard->setFullName(Q2PSTRING(ui->photoAndName->getFormattedName())); + vcard->setNickname(Q2PSTRING(ui->photoAndName->getNickname())); + vcard->setPrefix(Q2PSTRING(ui->photoAndName->getPrefix())); + vcard->setGivenName(Q2PSTRING(ui->photoAndName->getGivenName())); + vcard->setMiddleName(Q2PSTRING(ui->photoAndName->getMiddleName())); + vcard->setFamilyName(Q2PSTRING(ui->photoAndName->getFamilyName())); + vcard->setSuffix(Q2PSTRING(ui->photoAndName->getSuffix())); + vcard->setPhoto(ui->photoAndName->getAvatarData()); + vcard->setPhotoType(ui->photoAndName->getAvatarType()); + + vcard->clearEMailAddresses(); + vcard->clearJIDs(); + vcard->clearURLs(); + vcard->clearTelephones(); + vcard->clearRoles(); + vcard->clearTitles(); + vcard->clearOrganizations(); + vcard->clearAddresses(); + vcard->clearAddressLabels(); + + + QtVCardBirthdayField* bdayField = NULL; + QtVCardDescriptionField* descriptionField = NULL; + + foreach(QtVCardGeneralField* field, fields) { + QtVCardInternetEMailField* emailField; + if ((emailField = dynamic_cast(field))) { + vcard->addEMailAddress(emailField->getInternetEMailAddress()); + continue; + } + + QtVCardTelephoneField* telephoneField; + if ((telephoneField = dynamic_cast(field))) { + vcard->addTelephone(telephoneField->getTelephone()); + continue; + } + + QtVCardAddressField* addressField; + if ((addressField = dynamic_cast(field))) { + vcard->addAddress(addressField->getAddress()); + continue; + } + + QtVCardAddressLabelField* addressLabelField; + if ((addressLabelField = dynamic_cast(field))) { + vcard->addAddressLabel(addressLabelField->getAddressLabel()); + continue; + } + + if ((bdayField = dynamic_cast(field))) { + continue; + } + + QtVCardJIDField* jidField; + if ((jidField = dynamic_cast(field))) { + vcard->addJID(jidField->getJID()); + continue; + } + + if ((descriptionField = dynamic_cast(field))) { + continue; + } + + QtVCardOrganizationField* orgField; + if ((orgField = dynamic_cast(field))) { + vcard->addOrganization(orgField->getOrganization()); + continue; + } + + QtVCardRoleField* roleField; + if ((roleField = dynamic_cast(field))) { + vcard->addRole(roleField->getRole()); + continue; + } + + QtVCardTitleField* titleField; + if ((titleField = dynamic_cast(field))) { + vcard->addTitle(titleField->getTitle()); + continue; + } + + QtVCardURLField* urlField; + if ((urlField = dynamic_cast(field))) { + vcard->addURL(urlField->getURL()); + continue; + } + } + + if (bdayField) { + vcard->setBirthday(bdayField->getBirthday()); + } else { + vcard->setBirthday(boost::posix_time::ptime()); + } + + if (descriptionField) { + vcard->setDescription(descriptionField->getDescription()); + } else { + vcard->setDescription(""); + } + + return vcard; } void QtVCardWidget::addField() { - QAction* action = NULL; - if ((action = dynamic_cast(sender()))) { - boost::shared_ptr fieldInfo = actionFieldInfo[action]; - QWidget* newField = fieldInfo->createFieldInstance(this, ui->cardFields, true); - QtVCardGeneralField* newGeneralField = dynamic_cast(newField); - if (newGeneralField) { - newGeneralField->initialize(); - } - appendField(newGeneralField); - relayoutToolButton(); - } + QAction* action = NULL; + if ((action = dynamic_cast(sender()))) { + boost::shared_ptr fieldInfo = actionFieldInfo[action]; + QWidget* newField = fieldInfo->createFieldInstance(this, ui->cardFields, true); + QtVCardGeneralField* newGeneralField = dynamic_cast(newField); + if (newGeneralField) { + newGeneralField->initialize(); + } + appendField(newGeneralField); + relayoutToolButton(); + } } void QtVCardWidget::removeField(QtVCardGeneralField *field) { - int sameFields = 0; - QtVCardGeneralField* fieldToChange = NULL; - foreach (QtVCardGeneralField* vcardField, fields) { - if ((vcardField != field) && (typeid(*vcardField) == typeid(*field))) { - sameFields++; - fieldToChange = vcardField; - } - } - - if ((sameFields == 1) && fieldToChange) { - fieldToChange->setStarVisible(false); - } - - fields.remove(field); - delete field; + int sameFields = 0; + QtVCardGeneralField* fieldToChange = NULL; + foreach (QtVCardGeneralField* vcardField, fields) { + if ((vcardField != field) && (typeid(*vcardField) == typeid(*field))) { + sameFields++; + fieldToChange = vcardField; + } + } + + if ((sameFields == 1) && fieldToChange) { + fieldToChange->setStarVisible(false); + } + + fields.remove(field); + delete field; } void QtVCardWidget::addFieldType(QMenu* menu, boost::shared_ptr fieldType) { - if (!fieldType->getMenuName().isEmpty()) { - QAction* action = new QAction(tr("Add %1").arg(fieldType->getMenuName()), this); - actionFieldInfo[action] = fieldType; - connect(action, SIGNAL(triggered()), this, SLOT(addField())); - menu->addAction(action); - } + if (!fieldType->getMenuName().isEmpty()) { + QAction* action = new QAction(tr("Add %1").arg(fieldType->getMenuName()), this); + actionFieldInfo[action] = fieldType; + connect(action, SIGNAL(triggered()), this, SLOT(addField())); + menu->addAction(action); + } } int QtVCardWidget::fieldTypeInstances(boost::shared_ptr fieldType) { - int instances = 0; - for (int n = 0; n < ui->cardFields->count(); n++) { - if (fieldType->testInstance(ui->cardFields->itemAt(n)->widget())) instances++; - } - return instances; + int instances = 0; + for (int n = 0; n < ui->cardFields->count(); n++) { + if (fieldType->testInstance(ui->cardFields->itemAt(n)->widget())) instances++; + } + return instances; } void layoutDeleteChildren(QLayout *layout) { - while(layout->count() > 0) { - QLayoutItem* child; - if ((child = layout->takeAt(0)) != 0) { - if (child->layout()) { - layoutDeleteChildren(child->layout()); - } - if (dynamic_cast(child->widget())) { - delete child; - break; - } - delete child->widget(); - delete child; - } - } + while(layout->count() > 0) { + QLayoutItem* child; + if ((child = layout->takeAt(0)) != 0) { + if (child->layout()) { + layoutDeleteChildren(child->layout()); + } + if (dynamic_cast(child->widget())) { + delete child; + break; + } + delete child->widget(); + delete child; + } + } } void QtVCardWidget::clearFields() { - foreach(QtVCardGeneralField* field, fields) { - delete field; - } - fields.clear(); + foreach(QtVCardGeneralField* field, fields) { + delete field; + } + fields.clear(); - assert(ui->cardFields->count() >= 0); - layoutDeleteChildren(ui->cardFields); + assert(ui->cardFields->count() >= 0); + layoutDeleteChildren(ui->cardFields); } void QtVCardWidget::clearEmptyFields() { - std::vector items_to_remove; - foreach (QtVCardGeneralField* field, fields) { - if (field->property("empty").isValid() && field->property("empty").toBool()) { - ui->cardFields->removeWidget(field); - items_to_remove.push_back(field); - delete field; - } - } - - foreach(QtVCardGeneralField* field, items_to_remove) { - fields.remove(field); - } + std::vector items_to_remove; + foreach (QtVCardGeneralField* field, fields) { + if (field->property("empty").isValid() && field->property("empty").toBool()) { + ui->cardFields->removeWidget(field); + items_to_remove.push_back(field); + delete field; + } + } + + foreach(QtVCardGeneralField* field, items_to_remove) { + fields.remove(field); + } } void QtVCardWidget::appendField(QtVCardGeneralField *field) { - connect(field, SIGNAL(deleteField(QtVCardGeneralField*)), SLOT(removeField(QtVCardGeneralField*))); - - QtVCardGeneralField* fieldToChange = NULL; - foreach (QtVCardGeneralField* vcardField, fields) { - if (typeid(*vcardField) == typeid(*field)) { - fieldToChange = vcardField; - break; - } - } - - if (fieldToChange) { - fieldToChange->setStarVisible(true); - field->setStarVisible(true); - } - - fields.push_back(field); + connect(field, SIGNAL(deleteField(QtVCardGeneralField*)), SLOT(removeField(QtVCardGeneralField*))); + + QtVCardGeneralField* fieldToChange = NULL; + foreach (QtVCardGeneralField* vcardField, fields) { + if (typeid(*vcardField) == typeid(*field)) { + fieldToChange = vcardField; + break; + } + } + + if (fieldToChange) { + fieldToChange->setStarVisible(true); + field->setStarVisible(true); + } + + fields.push_back(field); } void QtVCardWidget::relayoutToolButton() { - ui->cardFields->addWidget(toolButton, ui->cardFields->rowCount(), ui->cardFields->columnCount()-2, 1, 1, Qt::AlignRight); + ui->cardFields->addWidget(toolButton, ui->cardFields->rowCount(), ui->cardFields->columnCount()-2, 1, 1, Qt::AlignRight); } } diff --git a/Swift/QtUI/QtVCardWidget/QtVCardWidget.h b/Swift/QtUI/QtVCardWidget/QtVCardWidget.h index 8c0ff31..95283c5 100644 --- a/Swift/QtUI/QtVCardWidget/QtVCardWidget.h +++ b/Swift/QtUI/QtVCardWidget/QtVCardWidget.h @@ -24,50 +24,50 @@ #include namespace Ui { - class QtVCardWidget; + class QtVCardWidget; } namespace Swift { - class QtVCardWidget : public QWidget { - Q_OBJECT - Q_PROPERTY(bool editable READ isEditable WRITE setEditable) - - public : - explicit QtVCardWidget(QWidget* parent = 0); - ~QtVCardWidget(); - - bool isEditable() const; - void setEditable(bool); - - void setVCard(VCard::ref vcard); - VCard::ref getVCard(); - - virtual QSize sizeHint() const; - - signals: - void editableChanged(bool editable); - - private slots: - void addField(); - void removeField(QtVCardGeneralField* field); - - private: - void addFieldType(QMenu*, boost::shared_ptr); - int fieldTypeInstances(boost::shared_ptr); - void clearFields(); - void clearEmptyFields(); - void appendField(QtVCardGeneralField* field); - void relayoutToolButton(); - - private: - VCard::ref vcard; - Ui::QtVCardWidget* ui; - QToolButton* toolButton; - bool editable; - QMenu* menu; - std::list fields; - std::map > actionFieldInfo; - }; + class QtVCardWidget : public QWidget { + Q_OBJECT + Q_PROPERTY(bool editable READ isEditable WRITE setEditable) + + public : + explicit QtVCardWidget(QWidget* parent = 0); + ~QtVCardWidget(); + + bool isEditable() const; + void setEditable(bool); + + void setVCard(VCard::ref vcard); + VCard::ref getVCard(); + + virtual QSize sizeHint() const; + + signals: + void editableChanged(bool editable); + + private slots: + void addField(); + void removeField(QtVCardGeneralField* field); + + private: + void addFieldType(QMenu*, boost::shared_ptr); + int fieldTypeInstances(boost::shared_ptr); + void clearFields(); + void clearEmptyFields(); + void appendField(QtVCardGeneralField* field); + void relayoutToolButton(); + + private: + VCard::ref vcard; + Ui::QtVCardWidget* ui; + QToolButton* toolButton; + bool editable; + QMenu* menu; + std::list fields; + std::map > actionFieldInfo; + }; } diff --git a/Swift/QtUI/QtWebKitChatView.cpp b/Swift/QtUI/QtWebKitChatView.cpp index a0c65ef..4193921 100644 --- a/Swift/QtUI/QtWebKitChatView.cpp +++ b/Swift/QtUI/QtWebKitChatView.cpp @@ -50,926 +50,926 @@ const QString QtWebKitChatView::ButtonFileTransferOpenFile = QString("filetransf const QString QtWebKitChatView::ButtonMUCInvite = QString("mucinvite"); QtWebKitChatView::QtWebKitChatView(QtChatWindow* window, UIEventStream* eventStream, QtChatTheme* theme, QWidget* parent, bool disableAutoScroll) : QtChatView(parent), window_(window), eventStream_(eventStream), fontSizeSteps_(0), disableAutoScroll_(disableAutoScroll), previousMessageKind_(PreviosuMessageWasNone), previousMessageWasSelf_(false), showEmoticons_(false), insertingLastLine_(false), idCounter_(0) { - theme_ = theme; - - QVBoxLayout* mainLayout = new QVBoxLayout(this); - mainLayout->setSpacing(0); - mainLayout->setContentsMargins(0,0,0,0); - webView_ = new QtWebView(this); - connect(webView_, SIGNAL(linkClicked(const QUrl&)), SLOT(handleLinkClicked(const QUrl&))); - connect(webView_, SIGNAL(loadFinished(bool)), SLOT(handleViewLoadFinished(bool))); - connect(webView_, SIGNAL(gotFocus()), SIGNAL(gotFocus())); - connect(webView_, SIGNAL(clearRequested()), SLOT(handleClearRequested())); - connect(webView_, SIGNAL(fontGrowRequested()), SLOT(increaseFontSize())); - connect(webView_, SIGNAL(fontShrinkRequested()), SLOT(decreaseFontSize())); + theme_ = theme; + + QVBoxLayout* mainLayout = new QVBoxLayout(this); + mainLayout->setSpacing(0); + mainLayout->setContentsMargins(0,0,0,0); + webView_ = new QtWebView(this); + connect(webView_, SIGNAL(linkClicked(const QUrl&)), SLOT(handleLinkClicked(const QUrl&))); + connect(webView_, SIGNAL(loadFinished(bool)), SLOT(handleViewLoadFinished(bool))); + connect(webView_, SIGNAL(gotFocus()), SIGNAL(gotFocus())); + connect(webView_, SIGNAL(clearRequested()), SLOT(handleClearRequested())); + connect(webView_, SIGNAL(fontGrowRequested()), SLOT(increaseFontSize())); + connect(webView_, SIGNAL(fontShrinkRequested()), SLOT(decreaseFontSize())); #if defined (Q_OS_UNIX) && !defined(Q_OS_MAC) - /* To give a border on Linux, where it looks bad without */ - QStackedWidget* stack = new QStackedWidget(this); - stack->addWidget(webView_); - stack->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); - stack->setLineWidth(2); - mainLayout->addWidget(stack); + /* To give a border on Linux, where it looks bad without */ + QStackedWidget* stack = new QStackedWidget(this); + stack->addWidget(webView_); + stack->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); + stack->setLineWidth(2); + mainLayout->addWidget(stack); #else - mainLayout->addWidget(webView_); + mainLayout->addWidget(webView_); #endif #ifdef SWIFT_EXPERIMENTAL_FT - setAcceptDrops(true); + setAcceptDrops(true); #endif - webPage_ = new QWebPage(this); - webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); - if (Log::getLogLevel() == Log::debug) { - webPage_->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); - } - webView_->setPage(webPage_); - connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard())); - connect(webPage_, SIGNAL(scrollRequested(int, int, const QRect&)), SLOT(handleScrollRequested(int, int, const QRect&))); + webPage_ = new QWebPage(this); + webPage_->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); + if (Log::getLogLevel() == Log::debug) { + webPage_->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); + } + webView_->setPage(webPage_); + connect(webPage_, SIGNAL(selectionChanged()), SLOT(copySelectionToClipboard())); + connect(webPage_, SIGNAL(scrollRequested(int, int, const QRect&)), SLOT(handleScrollRequested(int, int, const QRect&))); - viewReady_ = false; - isAtBottom_ = true; - resetView(); + viewReady_ = false; + isAtBottom_ = true; + resetView(); - jsBridge = new QtChatWindowJSBridge(); - addToJSEnvironment("chatwindow", jsBridge); - connect(jsBridge, SIGNAL(buttonClicked(QString,QString,QString,QString,QString,QString)), this, SLOT(handleHTMLButtonClicked(QString,QString,QString,QString,QString,QString))); + jsBridge = new QtChatWindowJSBridge(); + addToJSEnvironment("chatwindow", jsBridge); + connect(jsBridge, SIGNAL(buttonClicked(QString,QString,QString,QString,QString,QString)), this, SLOT(handleHTMLButtonClicked(QString,QString,QString,QString,QString,QString))); } QtWebKitChatView::~QtWebKitChatView() { - delete jsBridge; + delete jsBridge; } void QtWebKitChatView::handleClearRequested() { - QMessageBox messageBox(this); - messageBox.setWindowTitle(tr("Clear log")); - messageBox.setText(tr("You are about to clear the contents of your chat log.")); - messageBox.setInformativeText(tr("Are you sure?")); - messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); - messageBox.setDefaultButton(QMessageBox::Yes); - int button = messageBox.exec(); - if (button == QMessageBox::Yes) { - logCleared(); - resetView(); - } + QMessageBox messageBox(this); + messageBox.setWindowTitle(tr("Clear log")); + messageBox.setText(tr("You are about to clear the contents of your chat log.")); + messageBox.setInformativeText(tr("Are you sure?")); + messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); + messageBox.setDefaultButton(QMessageBox::Yes); + int button = messageBox.exec(); + if (button == QMessageBox::Yes) { + logCleared(); + resetView(); + } } void QtWebKitChatView::handleKeyPressEvent(QKeyEvent* event) { - webView_->keyPressEvent(event); + webView_->keyPressEvent(event); } void QtWebKitChatView::addMessageBottom(boost::shared_ptr snippet) { - if (viewReady_) { - addToDOM(snippet); - } else { - /* If this asserts, the previous queuing code was necessary and should be reinstated */ - assert(false); - } + if (viewReady_) { + addToDOM(snippet); + } else { + /* If this asserts, the previous queuing code was necessary and should be reinstated */ + assert(false); + } } void QtWebKitChatView::addMessageTop(boost::shared_ptr /* snippet */) { - // TODO: Implement this in a sensible manner later. - assert(false); + // TODO: Implement this in a sensible manner later. + assert(false); } void QtWebKitChatView::addToDOM(boost::shared_ptr snippet) { - //qDebug() << snippet->getContent(); - rememberScrolledToBottom(); + //qDebug() << snippet->getContent(); + rememberScrolledToBottom(); - QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert"); - assert(!insertElement.isNull()); - insertElement.prependOutside(snippet->getContent()); + QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert"); + assert(!insertElement.isNull()); + insertElement.prependOutside(snippet->getContent()); - //qDebug() << "-----------------"; - //qDebug() << webPage_->mainFrame()->toHtml(); + //qDebug() << "-----------------"; + //qDebug() << webPage_->mainFrame()->toHtml(); } void QtWebKitChatView::addLastSeenLine() { - // Remove a potentially existing unread bar. - QWebElement existingUnreadBar = webPage_->mainFrame()->findFirstElement("div.unread"); - if (!existingUnreadBar.isNull()) { - existingUnreadBar.removeFromDocument(); - } + // Remove a potentially existing unread bar. + QWebElement existingUnreadBar = webPage_->mainFrame()->findFirstElement("div.unread"); + if (!existingUnreadBar.isNull()) { + existingUnreadBar.removeFromDocument(); + } - QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert"); - insertElement.prependOutside(theme_->getUnread()); + QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert"); + insertElement.prependOutside(theme_->getUnread()); } void QtWebKitChatView::replaceLastMessage(const QString& newMessage, const ChatWindow::TimestampBehaviour timestampBehaviour) { - rememberScrolledToBottom(); - QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert"); - assert(!insertElement.isNull()); + rememberScrolledToBottom(); + QWebElement insertElement = webPage_->mainFrame()->findFirstElement("#insert"); + assert(!insertElement.isNull()); - QWebElement lastMessageElement = insertElement.previousSibling(); - QWebElement messageChild = lastMessageElement.findFirst("span.swift_message"); - assert(!messageChild.isNull()); - messageChild.setInnerXml(ChatSnippet::escape(newMessage)); - if (timestampBehaviour == ChatWindow::UpdateTimestamp) { - QWebElement timeChild = lastMessageElement.findFirst("span.swift_time"); - assert(!timeChild.isNull()); - timeChild.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime())); - } + QWebElement lastMessageElement = insertElement.previousSibling(); + QWebElement messageChild = lastMessageElement.findFirst("span.swift_message"); + assert(!messageChild.isNull()); + messageChild.setInnerXml(ChatSnippet::escape(newMessage)); + if (timestampBehaviour == ChatWindow::UpdateTimestamp) { + QWebElement timeChild = lastMessageElement.findFirst("span.swift_time"); + assert(!timeChild.isNull()); + timeChild.setInnerXml(ChatSnippet::timeToEscapedString(QDateTime::currentDateTime())); + } } void QtWebKitChatView::replaceLastMessage(const QString& newMessage, const QString& note) { - rememberScrolledToBottom(); - replaceLastMessage(newMessage, ChatWindow::KeepTimestamp); - QWebElement replace = lastElement_.findFirst("span.swift_time"); - assert(!replace.isNull()); - replace.setInnerXml(ChatSnippet::escape(note)); + rememberScrolledToBottom(); + replaceLastMessage(newMessage, ChatWindow::KeepTimestamp); + QWebElement replace = lastElement_.findFirst("span.swift_time"); + assert(!replace.isNull()); + replace.setInnerXml(ChatSnippet::escape(note)); } QString QtWebKitChatView::getLastSentMessage() { - return lastElement_.toPlainText(); + return lastElement_.toPlainText(); } void QtWebKitChatView::addToJSEnvironment(const QString& name, QObject* obj) { - webView_->page()->currentFrame()->addToJavaScriptWindowObject(name, obj); + webView_->page()->currentFrame()->addToJavaScriptWindowObject(name, obj); } void QtWebKitChatView::replaceMessage(const QString& newMessage, const QString& id, const QDateTime& editTime) { - rememberScrolledToBottom(); - QWebElement message = document_.findFirst("#" + id); - if (!message.isNull()) { - QWebElement replaceContent = message.findFirst("span.swift_inner_message"); - assert(!replaceContent.isNull()); - QString old = replaceContent.toOuterXml(); - replaceContent.setInnerXml(ChatSnippet::escape(newMessage)); - QWebElement replaceTime = message.findFirst("span.swift_time"); - assert(!replaceTime.isNull()); - old = replaceTime.toOuterXml(); - replaceTime.setInnerXml(ChatSnippet::escape(tr("%1 edited").arg(ChatSnippet::timeToEscapedString(editTime)))); - } - else { - qWarning() << "Trying to replace element with id " << id << " but it's not there."; - } + rememberScrolledToBottom(); + QWebElement message = document_.findFirst("#" + id); + if (!message.isNull()) { + QWebElement replaceContent = message.findFirst("span.swift_inner_message"); + assert(!replaceContent.isNull()); + QString old = replaceContent.toOuterXml(); + replaceContent.setInnerXml(ChatSnippet::escape(newMessage)); + QWebElement replaceTime = message.findFirst("span.swift_time"); + assert(!replaceTime.isNull()); + old = replaceTime.toOuterXml(); + replaceTime.setInnerXml(ChatSnippet::escape(tr("%1 edited").arg(ChatSnippet::timeToEscapedString(editTime)))); + } + else { + qWarning() << "Trying to replace element with id " << id << " but it's not there."; + } } void QtWebKitChatView::showEmoticons(bool show) { - showEmoticons_ = show; - { - const QWebElementCollection spans = document_.findAll("span.swift_emoticon_image"); - Q_FOREACH (QWebElement span, spans) { - span.setStyleProperty("display", show ? "inline" : "none"); - } - } - { - const QWebElementCollection spans = document_.findAll("span.swift_emoticon_text"); - Q_FOREACH (QWebElement span, spans) { - span.setStyleProperty("display", show ? "none" : "inline"); - } - } + showEmoticons_ = show; + { + const QWebElementCollection spans = document_.findAll("span.swift_emoticon_image"); + Q_FOREACH (QWebElement span, spans) { + span.setStyleProperty("display", show ? "inline" : "none"); + } + } + { + const QWebElementCollection spans = document_.findAll("span.swift_emoticon_text"); + Q_FOREACH (QWebElement span, spans) { + span.setStyleProperty("display", show ? "none" : "inline"); + } + } } void QtWebKitChatView::copySelectionToClipboard() { - if (!webPage_->selectedText().isEmpty()) { - webPage_->triggerAction(QWebPage::Copy); - } + if (!webPage_->selectedText().isEmpty()) { + webPage_->triggerAction(QWebPage::Copy); + } } void QtWebKitChatView::setAckXML(const QString& id, const QString& xml) { - QWebElement message = document_.findFirst("#" + id); - /* Deliberately not asserting here, so that when we start expiring old messages it won't hit us */ - if (message.isNull()) return; - QWebElement ackElement = message.findFirst("span.swift_ack"); - assert(!ackElement.isNull()); - ackElement.setInnerXml(xml); + QWebElement message = document_.findFirst("#" + id); + /* Deliberately not asserting here, so that when we start expiring old messages it won't hit us */ + if (message.isNull()) return; + QWebElement ackElement = message.findFirst("span.swift_ack"); + assert(!ackElement.isNull()); + ackElement.setInnerXml(xml); } void QtWebKitChatView::setReceiptXML(const QString& id, const QString& xml) { - QWebElement message = document_.findFirst("#" + id); - if (message.isNull()) return; - QWebElement receiptElement = message.findFirst("span.swift_receipt"); - assert(!receiptElement.isNull()); - receiptElement.setInnerXml(xml); + QWebElement message = document_.findFirst("#" + id); + if (message.isNull()) return; + QWebElement receiptElement = message.findFirst("span.swift_receipt"); + assert(!receiptElement.isNull()); + receiptElement.setInnerXml(xml); } void QtWebKitChatView::displayReceiptInfo(const QString& id, bool showIt) { - QWebElement message = document_.findFirst("#" + id); - if (message.isNull()) return; - QWebElement receiptElement = message.findFirst("span.swift_receipt"); - assert(!receiptElement.isNull()); - receiptElement.setStyleProperty("display", showIt ? "inline" : "none"); + QWebElement message = document_.findFirst("#" + id); + if (message.isNull()) return; + QWebElement receiptElement = message.findFirst("span.swift_receipt"); + assert(!receiptElement.isNull()); + receiptElement.setStyleProperty("display", showIt ? "inline" : "none"); } void QtWebKitChatView::rememberScrolledToBottom() { - isAtBottom_ = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) >= (webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical) - 1); + isAtBottom_ = webPage_->mainFrame()->scrollBarValue(Qt::Vertical) >= (webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical) - 1); } void QtWebKitChatView::scrollToBottom() { - isAtBottom_ = true; - webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)); - webView_->update(); /* Work around redraw bug in some versions of Qt. */ + isAtBottom_ = true; + webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical)); + webView_->update(); /* Work around redraw bug in some versions of Qt. */ } void QtWebKitChatView::handleFrameSizeChanged() { - if (topMessageAdded_) { - // adjust new scrollbar position - int newMaximum = webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical); - webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, newMaximum - scrollBarMaximum_); - topMessageAdded_ = false; - } + if (topMessageAdded_) { + // adjust new scrollbar position + int newMaximum = webPage_->mainFrame()->scrollBarMaximum(Qt::Vertical); + webPage_->mainFrame()->setScrollBarValue(Qt::Vertical, newMaximum - scrollBarMaximum_); + topMessageAdded_ = false; + } - if (isAtBottom_ && !disableAutoScroll_) { - scrollToBottom(); - } + if (isAtBottom_ && !disableAutoScroll_) { + scrollToBottom(); + } } void QtWebKitChatView::handleLinkClicked(const QUrl& url) { - QDesktopServices::openUrl(url); + QDesktopServices::openUrl(url); } void QtWebKitChatView::handleViewLoadFinished(bool ok) { - Q_ASSERT(ok); - viewReady_ = true; + Q_ASSERT(ok); + viewReady_ = true; } void QtWebKitChatView::increaseFontSize(int numSteps) { - //qDebug() << "Increasing"; - fontSizeSteps_ += numSteps; - emit fontResized(fontSizeSteps_); + //qDebug() << "Increasing"; + fontSizeSteps_ += numSteps; + emit fontResized(fontSizeSteps_); } void QtWebKitChatView::decreaseFontSize() { - fontSizeSteps_--; - if (fontSizeSteps_ < 0) { - fontSizeSteps_ = 0; - } - emit fontResized(fontSizeSteps_); + fontSizeSteps_--; + if (fontSizeSteps_ < 0) { + fontSizeSteps_ = 0; + } + emit fontResized(fontSizeSteps_); } void QtWebKitChatView::resizeFont(int fontSizeSteps) { - fontSizeSteps_ = fontSizeSteps; - double size = 1.0 + 0.2 * fontSizeSteps_; - QString sizeString(QString().setNum(size, 'g', 3) + "em"); + fontSizeSteps_ = fontSizeSteps; + double size = 1.0 + 0.2 * fontSizeSteps_; + QString sizeString(QString().setNum(size, 'g', 3) + "em"); - // Set the font size in the