File indexing completed on 2024-05-12 05:00:37
0001 /* 0002 SPDX-FileCopyrightText: 2016 The Qt Company Ltd. <https://www.qt.io/licensing/> 0003 0004 This file is part of the QtWebEngine module of the Qt Toolkit. 0005 SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0 OR LicenseRef-Qt-Commercial 0006 */ 0007 #ifndef WEBENGINE_TESTUTILS_H 0008 #define WEBENGINE_TESTUTILS_H 0009 0010 #include <QEventLoop> 0011 #include <QTimer> 0012 #include <QWebEnginePage> 0013 0014 template<typename T, typename R> 0015 struct RefWrapper { 0016 R &ref; 0017 void operator()(const T& result) { 0018 ref(result); 0019 } 0020 }; 0021 0022 template<typename T> 0023 class CallbackSpy { 0024 public: 0025 CallbackSpy() : called(false) { 0026 timeoutTimer.setSingleShot(true); 0027 QObject::connect(&timeoutTimer, SIGNAL(timeout()), &eventLoop, SLOT(quit())); 0028 } 0029 0030 T waitForResult() { 0031 if (!called) { 0032 timeoutTimer.start(10000); 0033 eventLoop.exec(); 0034 } 0035 return result; 0036 } 0037 0038 bool wasCalled() const { 0039 return called; 0040 } 0041 0042 void operator()(const T &result) { 0043 this->result = result; 0044 called = true; 0045 eventLoop.quit(); 0046 } 0047 0048 // Cheap rip-off of boost/std::ref 0049 RefWrapper<T, CallbackSpy<T> > ref() 0050 { 0051 RefWrapper<T, CallbackSpy<T> > wrapper = {*this}; 0052 return wrapper; 0053 } 0054 0055 private: 0056 Q_DISABLE_COPY(CallbackSpy) 0057 bool called; 0058 QTimer timeoutTimer; 0059 QEventLoop eventLoop; 0060 T result; 0061 }; 0062 0063 // taken from the qwebengine unittests 0064 static inline QVariant evaluateJavaScriptSync(QWebEnginePage *page, const QString &script) 0065 { 0066 CallbackSpy<QVariant> spy; 0067 page->runJavaScript(script, spy.ref()); 0068 return spy.waitForResult(); 0069 } 0070 0071 // Taken from QtWebEngine's tst_qwebenginepage.cpp 0072 static QPoint elementCenter(QWebEnginePage *page, const QString &id) 0073 { 0074 QVariantList rectList = evaluateJavaScriptSync(page, 0075 "(function(){" 0076 "var elem = document.getElementById('" + id + "');" 0077 "var rect = elem.getBoundingClientRect();" 0078 "return [rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top];" 0079 "})()").toList(); 0080 0081 if (rectList.count() != 4) { 0082 qWarning("elementCenter failed."); 0083 return QPoint(); 0084 } 0085 const QRect rect(rectList.at(0).toInt(), rectList.at(1).toInt(), 0086 rectList.at(2).toInt(), rectList.at(3).toInt()); 0087 return rect.center(); 0088 } 0089 #endif