This repository has been archived by the owner on Dec 16, 2022. It is now read-only.
forked from thoughtbot/capybara-webkit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
WebPage.cpp
329 lines (272 loc) · 9.57 KB
/
WebPage.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#include "WebPage.h"
#include "WebPageManager.h"
#include "JavascriptInvocation.h"
#include "NetworkAccessManager.h"
#include "NetworkCookieJar.h"
#include "UnsupportedContentHandler.h"
#include <QResource>
#include <iostream>
#include <QWebSettings>
#include <QUuid>
WebPage::WebPage(WebPageManager *manager, QObject *parent) : QWebPage(parent) {
m_loading = false;
m_failed = false;
m_manager = manager;
m_uuid = QUuid::createUuid().toString();
m_unsupportedContentLoaded = false;
setForwardUnsupportedContent(true);
loadJavascript();
setUserStylesheet();
m_confirm = true;
m_prompt = false;
m_prompt_text = QString();
this->setCustomNetworkAccessManager();
connect(this, SIGNAL(loadStarted()), this, SLOT(loadStarted()));
connect(this, SIGNAL(loadFinished(bool)), this, SLOT(loadFinished(bool)));
connect(this, SIGNAL(frameCreated(QWebFrame *)),
this, SLOT(frameCreated(QWebFrame *)));
connect(this, SIGNAL(unsupportedContent(QNetworkReply*)),
this, SLOT(handleUnsupportedContent(QNetworkReply*)));
resetWindowSize();
settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
}
void WebPage::resetWindowSize() {
this->setViewportSize(QSize(1680, 1050));
this->settings()->setAttribute(QWebSettings::LocalStorageDatabaseEnabled, true);
}
void WebPage::setCustomNetworkAccessManager() {
NetworkAccessManager *manager = new NetworkAccessManager(this);
manager->setCookieJar(m_manager->cookieJar());
this->setNetworkAccessManager(manager);
connect(manager, SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
this, SLOT(handleSslErrorsForReply(QNetworkReply *, QList<QSslError>)));
connect(manager, SIGNAL(requestCreated(QByteArray &, QNetworkReply *)),
SIGNAL(requestCreated(QByteArray &, QNetworkReply *)));
}
void WebPage::unsupportedContentFinishedReply(QNetworkReply *reply) {
m_unsupportedContentLoaded = true;
m_manager->replyFinished(reply);
}
void WebPage::loadJavascript() {
QResource javascript(":/capybara.js");
if (javascript.isCompressed()) {
QByteArray uncompressedBytes(qUncompress(javascript.data(), javascript.size()));
m_capybaraJavascript = QString(uncompressedBytes);
} else {
char * javascriptString = new char[javascript.size() + 1];
strcpy(javascriptString, (const char *)javascript.data());
javascriptString[javascript.size()] = 0;
m_capybaraJavascript = javascriptString;
}
}
void WebPage::setUserStylesheet() {
QString data = QString("*, :first-line, :first-letter, :before, :after { font-family: 'Arial' ! important; }").toUtf8().toBase64();
QUrl url = QUrl(QString("data:text/css;charset=utf-8;base64,") + data);
settings()->setUserStyleSheetUrl(url);
}
QString WebPage::userAgentForUrl(const QUrl &url ) const {
if (!m_userAgent.isEmpty()) {
return m_userAgent;
} else {
return QWebPage::userAgentForUrl(url);
}
}
QString WebPage::consoleMessages() {
return m_consoleMessages.join("\n");
}
QString WebPage::alertMessages() {
return m_alertMessages.join("\n");
}
QString WebPage::confirmMessages() {
return m_confirmMessages.join("\n");
}
QString WebPage::promptMessages() {
return m_promptMessages.join("\n");
}
void WebPage::setUserAgent(QString userAgent) {
m_userAgent = userAgent;
}
void WebPage::frameCreated(QWebFrame * frame) {
connect(frame, SIGNAL(javaScriptWindowObjectCleared()),
this, SLOT(injectJavascriptHelpers()));
}
void WebPage::injectJavascriptHelpers() {
QWebFrame* frame = qobject_cast<QWebFrame *>(QObject::sender());
frame->evaluateJavaScript(m_capybaraJavascript);
}
bool WebPage::shouldInterruptJavaScript() {
return false;
}
QVariant WebPage::invokeCapybaraFunction(const char *name, const QStringList &arguments) {
QString qname(name);
QString objectName("CapybaraInvocation");
JavascriptInvocation invocation(qname, arguments);
currentFrame()->addToJavaScriptWindowObject(objectName, &invocation);
QString javascript = QString("Capybara.invoke()");
return currentFrame()->evaluateJavaScript(javascript);
}
QVariant WebPage::invokeCapybaraFunction(QString &name, const QStringList &arguments) {
return invokeCapybaraFunction(name.toAscii().data(), arguments);
}
void WebPage::javaScriptConsoleMessage(const QString &message, int lineNumber, const QString &sourceID) {
QString fullMessage = QString(message);
if (!sourceID.isEmpty())
fullMessage = sourceID + "|" + QString::number(lineNumber) + "|" + fullMessage;
m_consoleMessages.append(fullMessage.replace("\n", "\\n"));
m_manager->logger() << qPrintable(fullMessage);
}
void WebPage::javaScriptAlert(QWebFrame *frame, const QString &message) {
Q_UNUSED(frame);
m_alertMessages.append(message);
m_manager->logger() << "ALERT:" << qPrintable(message);
}
bool WebPage::javaScriptConfirm(QWebFrame *frame, const QString &message) {
Q_UNUSED(frame);
m_confirmMessages.append(message);
return m_confirm;
}
bool WebPage::javaScriptPrompt(QWebFrame *frame, const QString &message, const QString &defaultValue, QString *result) {
Q_UNUSED(frame)
m_promptMessages.append(message);
if (m_prompt) {
if (m_prompt_text.isNull()) {
*result = defaultValue;
} else {
*result = m_prompt_text;
}
}
return m_prompt;
}
void WebPage::loadStarted() {
m_loading = true;
m_errorPageMessage = QString();
m_unsupportedContentLoaded = false;
}
void WebPage::loadFinished(bool success) {
Q_UNUSED(success);
m_loading = false;
emit pageFinished(!m_failed);
m_failed = false;
}
bool WebPage::isLoading() const {
return m_loading;
}
QString WebPage::failureString() {
QString message = QString("Unable to load URL: ") + currentFrame()->requestedUrl().toString();
if (m_errorPageMessage.isEmpty())
return message;
else
return message + m_errorPageMessage;
}
bool WebPage::render(const QString &fileName) {
QFileInfo fileInfo(fileName);
QDir dir;
dir.mkpath(fileInfo.absolutePath());
QSize viewportSize = this->viewportSize();
QSize pageSize = this->mainFrame()->contentsSize();
if (pageSize.isEmpty()) {
return false;
}
QImage buffer(pageSize, QImage::Format_ARGB32);
buffer.fill(qRgba(255, 255, 255, 0));
QPainter p(&buffer);
p.setRenderHint( QPainter::Antialiasing, true);
p.setRenderHint( QPainter::TextAntialiasing, true);
p.setRenderHint( QPainter::SmoothPixmapTransform, true);
this->setViewportSize(pageSize);
this->mainFrame()->render(&p);
p.end();
this->setViewportSize(viewportSize);
return buffer.save(fileName);
}
QString WebPage::chooseFile(QWebFrame *parentFrame, const QString &suggestedFile) {
Q_UNUSED(parentFrame);
Q_UNUSED(suggestedFile);
return getAttachedFileNames().first();
}
bool WebPage::extension(Extension extension, const ExtensionOption *option, ExtensionReturn *output) {
if (extension == ChooseMultipleFilesExtension) {
static_cast<ChooseMultipleFilesExtensionReturn*>(output)->fileNames = getAttachedFileNames();
return true;
}
else if (extension == QWebPage::ErrorPageExtension) {
ErrorPageExtensionOption *errorOption = (ErrorPageExtensionOption*) option;
m_errorPageMessage = " because of error loading " + errorOption->url.toString() + ": " + errorOption->errorString;
m_failed = true;
return false;
}
return false;
}
QStringList WebPage::getAttachedFileNames() {
return currentFrame()->evaluateJavaScript(QString("Capybara.attachedFiles")).toStringList();
}
void WebPage::handleSslErrorsForReply(QNetworkReply *reply, const QList<QSslError> &errors) {
if (m_manager->ignoreSslErrors())
reply->ignoreSslErrors(errors);
}
void WebPage::setSkipImageLoading(bool skip) {
settings()->setAttribute(QWebSettings::AutoLoadImages, !skip);
}
int WebPage::getLastStatus() {
return networkAccessManager()->statusFor(currentFrame()->requestedUrl());
}
const QList<QNetworkReply::RawHeaderPair> &WebPage::pageHeaders() {
return networkAccessManager()->headersFor(currentFrame()->requestedUrl());
}
NetworkAccessManager *WebPage::networkAccessManager() {
return qobject_cast<NetworkAccessManager *>(QWebPage::networkAccessManager());
}
void WebPage::handleUnsupportedContent(QNetworkReply *reply) {
QVariant contentMimeType = reply->header(QNetworkRequest::ContentTypeHeader);
if(!contentMimeType.isNull()) {
triggerAction(QWebPage::Stop);
UnsupportedContentHandler *handler = new UnsupportedContentHandler(this, reply);
if (reply->isFinished())
handler->renderNonHtmlContent();
else
handler->waitForReplyToFinish();
}
}
bool WebPage::unsupportedContentLoaded() {
return m_unsupportedContentLoaded;
}
bool WebPage::supportsExtension(Extension extension) const {
if (extension == ErrorPageExtension)
return true;
else if (extension == ChooseMultipleFilesExtension)
return true;
else
return false;
}
QWebPage *WebPage::createWindow(WebWindowType type) {
Q_UNUSED(type);
return m_manager->createPage(this);
}
QString WebPage::uuid() {
return m_uuid;
}
QString WebPage::getWindowName() {
QVariant windowName = mainFrame()->evaluateJavaScript("window.name");
if (windowName.isValid())
return windowName.toString();
else
return "";
}
bool WebPage::matchesWindowSelector(QString selector) {
return (selector == getWindowName() ||
selector == mainFrame()->title() ||
selector == mainFrame()->url().toString() ||
selector == uuid());
}
void WebPage::setFocus() {
m_manager->setCurrentPage(this);
}
void WebPage::setConfirmAction(QString action) {
m_confirm = (action == "Yes");
}
void WebPage::setPromptAction(QString action) {
m_prompt = (action == "Yes");
}
void WebPage::setPromptText(QString text) {
m_prompt_text = text;
}