#pragma once #include #include #include #include #include #include #include "chat_networking.hpp" struct receive_policy_ignore { static void message_do_what(const chat::chat_message& msg) {} static void handshake_do_what(const chat::chat_message& msg) {} static void serverdirection_do_what(const chat::chat_message& msg) {} static void login_do_what(const chat::chat_message& msg) {} static void logout_do_what(const chat::chat_message& msg) {} static void invalid_msg_do_what(const chat::chat_message& msg) { throw std::runtime_error("Invalid message received!"); } }; struct send_policy_ignore { /* this is handled in the gui: QLineEdit.setMaxLength() */ static bool check_msg_length(const chat::chat_message& msg) { return true; } }; class chat_window : public QWidget { Q_OBJECT QGridLayout* _layout; QListWidget* _chat; QListWidget* _people; QLineEdit* _msg; boost::asio::io_service _ios; boost::asio::ip::tcp::resolver::query _query; chat::client_network_manager _cnm; std::thread _iosthread; public: explicit chat_window(QWidget* parent = 0) :QWidget(parent), _ios(), _query("infoc.eet.bme.hu", "8888"), _cnm(_ios, boost::asio::ip::tcp::resolver(_ios).resolve(_query), "BATMAN"), _iosthread([this]{ _ios.run(); }) { _cnm.subscribe(std::bind(&chat_window::receive_handler, this, std::placeholders::_1)); setupUi(); } void receive_handler(chat::chat_message msg) { switch (msg.get_header()) { case chat::message::MESSAGE: case chat::message::SERVER_DIRECTION: _chat->addItem(msg.get_content().c_str()); break; case chat::message::LOGIN: _people->addItem(msg.get_content().c_str()); break; case chat::message::LOGOUT: auto list = _people->findItems(msg.get_content().c_str(), Qt::MatchExactly); if (list.size() > 0) delete list[0]; break; } } public slots: void return_handler() { _chat->addItem(_msg->text()); _cnm.send(chat::chat_message(chat::message::MESSAGE, _msg->text().toStdString())); _msg->clear(); }; private: void setupUi() { this->setWindowTitle("C++11Chat"); this->setMinimumSize(1000, 500); _layout = new QGridLayout(); _chat = new QListWidget(); _people = new QListWidget(); _msg = new QLineEdit(); _msg->setMaxLength(220); connect(_msg, &QLineEdit::returnPressed, this, &chat_window::return_handler); _layout->addWidget(_chat, 0, 0, 1, 1); _layout->addWidget(_people, 0, 1, 1, 2); _layout->addWidget(_msg, 1, 0, 1, 3); this->setLayout(_layout); } void closeEvent(QCloseEvent* event) { _cnm.close_connection(); _iosthread.join(); } };