capybara-webkit/src/Connection.cpp

79 lines
2.4 KiB
C++
Raw Normal View History

2011-02-19 03:53:06 +00:00
#include "Connection.h"
#include "WebPage.h"
#include "WebPageManager.h"
2011-10-14 15:22:24 +00:00
#include "CommandParser.h"
#include "CommandFactory.h"
#include "PageLoadingCommand.h"
#include "TimeoutCommand.h"
#include "SocketCommand.h"
2013-02-02 22:32:54 +00:00
#include "ErrorMessage.h"
2011-02-19 03:53:06 +00:00
#include <QTcpSocket>
Connection::Connection(QTcpSocket *socket, WebPageManager *manager, QObject *parent) :
2011-02-19 03:53:06 +00:00
QObject(parent) {
m_socket = socket;
m_manager = manager;
m_commandFactory = new CommandFactory(m_manager, this);
m_commandParser = new CommandParser(socket, m_commandFactory, this);
m_pageSuccess = true;
m_pendingCommand = NULL;
2011-10-14 15:22:24 +00:00
connect(m_socket, SIGNAL(readyRead()), m_commandParser, SLOT(checkNext()));
connect(m_commandParser, SIGNAL(commandReady(Command *)), this, SLOT(commandReady(Command *)));
connect(m_manager, SIGNAL(pageFinished(bool)), this, SLOT(pendingLoadFinished(bool)));
2011-02-19 03:53:06 +00:00
}
void Connection::commandReady(Command *command) {
m_manager->log() << "Received" << command->toString();
startCommand(command);
}
void Connection::startCommand(Command *command) {
if (m_pendingCommand) {
m_pendingCommand->deleteLater();
}
if (m_pageSuccess) {
m_pendingCommand = new TimeoutCommand(new PageLoadingCommand(command, m_manager, this), m_manager, this);
connect(m_pendingCommand, SIGNAL(finished(Response *)), this, SLOT(finishCommand(Response *)));
m_pendingCommand->start();
} else {
2012-03-21 23:11:50 +00:00
writePageLoadFailure();
}
}
void Connection::pendingLoadFinished(bool success) {
m_pageSuccess = m_pageSuccess && success;
}
2012-03-21 23:11:50 +00:00
void Connection::writePageLoadFailure() {
2012-03-16 21:53:36 +00:00
m_pageSuccess = true;
QString message = currentPage()->failureString();
2013-02-02 22:32:54 +00:00
Response response(false, new ErrorMessage(message));
writeResponse(&response);
2012-03-16 21:53:36 +00:00
}
void Connection::finishCommand(Response *response) {
m_pageSuccess = true;
writeResponse(response);
sender()->deleteLater();
m_pendingCommand = NULL;
2011-02-26 19:03:30 +00:00
}
void Connection::writeResponse(Response *response) {
if (response->isSuccess())
2011-02-19 03:53:06 +00:00
m_socket->write("ok\n");
2011-02-26 19:03:30 +00:00
else
2011-02-19 03:53:06 +00:00
m_socket->write("failure\n");
2011-02-26 19:03:30 +00:00
m_manager->log() << "Wrote response" << response->isSuccess() << response->message();
QByteArray messageUtf8 = response->message();
QString messageLength = QString::number(messageUtf8.size()) + "\n";
m_socket->write(messageLength.toLatin1());
m_socket->write(messageUtf8);
2011-02-19 03:53:06 +00:00
}
WebPage *Connection::currentPage() {
return m_manager->currentPage();
}