From 699510fd48afc793d125793d97fd1c422cd71f39 Mon Sep 17 00:00:00 2001 From: Ariya Hidayat Date: Tue, 7 Jan 2020 16:40:13 -0800 Subject: [PATCH] Format the code using clang-format (#15404) clang-format -i --style=WebKit src/*.h src/*.cpp --- src/callback.h | 3 +- src/childprocess.cpp | 9 ++--- src/childprocess.h | 8 ++-- src/config.cpp | 14 +++---- src/config.h | 5 +-- src/consts.h | 60 ++++++++++++++--------------- src/cookiejar.cpp | 39 +++++++++---------- src/cookiejar.h | 5 +-- src/crashdump.cpp | 65 ++++++++++++++++++------------- src/encoding.h | 3 +- src/env.cpp | 4 +- src/env.h | 3 +- src/filesystem.cpp | 74 ++++++++++++++++++++++-------------- src/filesystem.h | 9 ++--- src/main.cpp | 6 +-- src/networkaccessmanager.cpp | 51 +++++++++++++------------ src/networkaccessmanager.h | 15 +++----- src/phantom.cpp | 28 +++++--------- src/phantom.h | 15 ++++---- src/repl.cpp | 53 ++++++++++++-------------- src/repl.h | 3 +- src/system.cpp | 6 +-- src/system.h | 5 +-- src/terminal.h | 3 +- src/utils.cpp | 11 +++--- src/utils.h | 26 ++++++------- src/webpage.cpp | 74 ++++++++++++++++-------------------- src/webpage.h | 10 ++--- src/webserver.cpp | 31 ++++++++------- src/webserver.h | 9 ++--- 30 files changed, 313 insertions(+), 334 deletions(-) diff --git a/src/callback.h b/src/callback.h index 318fb4fcc0..b2eac8f788 100644 --- a/src/callback.h +++ b/src/callback.h @@ -33,8 +33,7 @@ #include #include -class Callback : public QObject -{ +class Callback : public QObject { Q_OBJECT Q_PROPERTY(QVariant returnValue READ returnValue WRITE setReturnValue) diff --git a/src/childprocess.cpp b/src/childprocess.cpp index c4faeee3ff..1ad43b2d30 100644 --- a/src/childprocess.cpp +++ b/src/childprocess.cpp @@ -86,17 +86,17 @@ bool ChildProcessContext::_start(const QString& cmd, const QStringList& args) return m_proc.waitForStarted(1000); } -qint64 ChildProcessContext::_write(const QString &chunk, const QString &encoding) +qint64 ChildProcessContext::_write(const QString& chunk, const QString& encoding) { // Try to get codec for encoding - QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1()); + QTextCodec* codec = QTextCodec::codecForName(encoding.toLatin1()); // If unavailable, attempt UTF-8 codec - if ((QTextCodec *)NULL == codec) { + if ((QTextCodec*)NULL == codec) { codec = QTextCodec::codecForName("UTF-8"); // Don't even try to write if UTF-8 codec is unavailable - if ((QTextCodec *)NULL == codec) { + if ((QTextCodec*)NULL == codec) { return -1; } } @@ -139,7 +139,6 @@ void ChildProcessContext::_error(const QProcess::ProcessError error) emit exit(m_proc.exitCode()); } - // // ChildProcess // diff --git a/src/childprocess.h b/src/childprocess.h index 554ed3f830..9e76ae6121 100644 --- a/src/childprocess.h +++ b/src/childprocess.h @@ -42,8 +42,7 @@ /** * This class wraps a QProcess and facilitates emulation of node.js's ChildProcess */ -class ChildProcessContext : public QObject -{ +class ChildProcessContext : public QObject { Q_OBJECT Q_PROPERTY(qint64 pid READ pid) @@ -57,7 +56,7 @@ class ChildProcessContext : public QObject Q_INVOKABLE void _setEncoding(const QString& encoding); Q_INVOKABLE bool _start(const QString& cmd, const QStringList& args); - Q_INVOKABLE qint64 _write(const QString &chunk, const QString &encoding); + Q_INVOKABLE qint64 _write(const QString& chunk, const QString& encoding); Q_INVOKABLE void _close(); signals: @@ -86,8 +85,7 @@ private slots: /** * Helper class for child_process module */ -class ChildProcess : public QObject -{ +class ChildProcess : public QObject { Q_OBJECT public: diff --git a/src/config.cpp b/src/config.cpp index 443923a101..fa56428189 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -34,18 +34,17 @@ #include #include -#include -#include #include +#include +#include -#include "terminal.h" +#include "consts.h" #include "qcommandline.h" +#include "terminal.h" #include "utils.h" -#include "consts.h" #include - static const struct QCommandLineConfigEntry flags[] = { { QCommandLine::Option, '\0', "cookies-file", "Sets the file name to store the persistent cookies", QCommandLine::Optional }, { QCommandLine::Option, '\0', "config", "Specifies JSON-formatted configuration file", QCommandLine::Optional }, @@ -76,7 +75,7 @@ static const struct QCommandLineConfigEntry flags[] = { { QCommandLine::Option, '\0', "ssl-client-certificate-file", "Sets the location of a client certificate", QCommandLine::Optional }, { QCommandLine::Option, '\0', "ssl-client-key-file", "Sets the location of a clients' private key", QCommandLine::Optional }, { QCommandLine::Option, '\0', "ssl-client-key-passphrase", "Sets the passphrase for the clients' private key", QCommandLine::Optional }, - { QCommandLine::Param, '\0', "script", "Script", QCommandLine::Flags(QCommandLine::Optional | QCommandLine::ParameterFence)}, + { QCommandLine::Param, '\0', "script", "Script", QCommandLine::Flags(QCommandLine::Optional | QCommandLine::ParameterFence) }, { QCommandLine::Param, '\0', "argument", "Script argument", QCommandLine::OptionalMultiple }, { QCommandLine::Switch, 'h', "help", "Shows this message and quits", QCommandLine::Optional }, { QCommandLine::Switch, 'v', "version", "Prints out PhantomJS version", QCommandLine::Optional }, @@ -117,7 +116,6 @@ void Config::processArgs(const QStringList& args) m_cmdLine->setArguments(args); m_cmdLine->setConfig(flags); m_cmdLine->parse(); - } void Config::loadJsonFile(const QString& filePath) @@ -198,7 +196,6 @@ void Config::setOfflineStorageDefaultQuota(int offlineStorageDefaultQuota) m_offlineStorageDefaultQuota = offlineStorageDefaultQuota * 1024; } - QString Config::localStoragePath() const { return m_localStoragePath; @@ -478,7 +475,6 @@ bool Config::javascriptCanCloseWindows() const return m_javascriptCanCloseWindows; } - // private: void Config::resetToDefaults() { diff --git a/src/config.h b/src/config.h index eb15beea50..d175676e15 100644 --- a/src/config.h +++ b/src/config.h @@ -31,15 +31,14 @@ #ifndef CONFIG_H #define CONFIG_H +#include #include #include -#include #include class QCommandLine; -class Config: public QObject -{ +class Config : public QObject { Q_OBJECT Q_PROPERTY(QString cookiesFile READ cookiesFile WRITE setCookiesFile) Q_PROPERTY(bool diskCacheEnabled READ diskCacheEnabled WRITE setDiskCacheEnabled) diff --git a/src/consts.h b/src/consts.h index 5873d02f12..89dc249d5e 100644 --- a/src/consts.h +++ b/src/consts.h @@ -32,41 +32,41 @@ #ifndef CONSTS_H #define CONSTS_H -#define PHANTOMJS_VERSION_MAJOR 3 -#define PHANTOMJS_VERSION_MINOR 0 -#define PHANTOMJS_VERSION_PATCH 0 -#define PHANTOMJS_VERSION_STRING "3.0.0-development" +#define PHANTOMJS_VERSION_MAJOR 3 +#define PHANTOMJS_VERSION_MINOR 0 +#define PHANTOMJS_VERSION_PATCH 0 +#define PHANTOMJS_VERSION_STRING "3.0.0-development" -#define HTTP_HEADER_CONTENT_LENGTH "content-length" -#define HTTP_HEADER_CONTENT_TYPE "content-type" +#define HTTP_HEADER_CONTENT_LENGTH "content-length" +#define HTTP_HEADER_CONTENT_TYPE "content-type" -#define JAVASCRIPT_SOURCE_PLATFORM_URL "phantomjs://platform/%1" -#define JAVASCRIPT_SOURCE_CODE_URL "phantomjs://code/%1" +#define JAVASCRIPT_SOURCE_PLATFORM_URL "phantomjs://platform/%1" +#define JAVASCRIPT_SOURCE_CODE_URL "phantomjs://code/%1" -#define JS_ELEMENT_CLICK "(function (el) { " \ - "var ev = document.createEvent('MouseEvents');" \ - "ev.initEvent(\"click\", true, true);" \ - "el.dispatchEvent(ev);" \ - "})(this);" +#define JS_ELEMENT_CLICK "(function (el) { " \ + "var ev = document.createEvent('MouseEvents');" \ + "ev.initEvent(\"click\", true, true);" \ + "el.dispatchEvent(ev);" \ + "})(this);" #define JS_APPEND_SCRIPT_ELEMENT "var el = document.createElement('script');" \ - "el.onload = function() { alert('%1'); };" \ - "el.src = '%1';" \ - "document.body.appendChild(el);" + "el.onload = function() { alert('%1'); };" \ + "el.src = '%1';" \ + "document.body.appendChild(el);" -#define PAGE_SETTINGS_LOAD_IMAGES "loadImages" -#define PAGE_SETTINGS_JS_ENABLED "javascriptEnabled" -#define PAGE_SETTINGS_XSS_AUDITING "XSSAuditingEnabled" -#define PAGE_SETTINGS_USER_AGENT "userAgent" -#define PAGE_SETTINGS_PROXY "proxy" -#define PAGE_SETTINGS_LOCAL_ACCESS_REMOTE "localToRemoteUrlAccessEnabled" -#define PAGE_SETTINGS_USERNAME "userName" -#define PAGE_SETTINGS_PASSWORD "password" -#define PAGE_SETTINGS_MAX_AUTH_ATTEMPTS "maxAuthAttempts" -#define PAGE_SETTINGS_RESOURCE_TIMEOUT "resourceTimeout" -#define PAGE_SETTINGS_WEB_SECURITY_ENABLED "webSecurityEnabled" -#define PAGE_SETTINGS_JS_CAN_OPEN_WINDOWS "javascriptCanOpenWindows" -#define PAGE_SETTINGS_JS_CAN_CLOSE_WINDOWS "javascriptCanCloseWindows" -#define PAGE_SETTINGS_DPI "dpi" +#define PAGE_SETTINGS_LOAD_IMAGES "loadImages" +#define PAGE_SETTINGS_JS_ENABLED "javascriptEnabled" +#define PAGE_SETTINGS_XSS_AUDITING "XSSAuditingEnabled" +#define PAGE_SETTINGS_USER_AGENT "userAgent" +#define PAGE_SETTINGS_PROXY "proxy" +#define PAGE_SETTINGS_LOCAL_ACCESS_REMOTE "localToRemoteUrlAccessEnabled" +#define PAGE_SETTINGS_USERNAME "userName" +#define PAGE_SETTINGS_PASSWORD "password" +#define PAGE_SETTINGS_MAX_AUTH_ATTEMPTS "maxAuthAttempts" +#define PAGE_SETTINGS_RESOURCE_TIMEOUT "resourceTimeout" +#define PAGE_SETTINGS_WEB_SECURITY_ENABLED "webSecurityEnabled" +#define PAGE_SETTINGS_JS_CAN_OPEN_WINDOWS "javascriptCanOpenWindows" +#define PAGE_SETTINGS_JS_CAN_CLOSE_WINDOWS "javascriptCanCloseWindows" +#define PAGE_SETTINGS_DPI "dpi" #endif // CONSTS_H diff --git a/src/cookiejar.cpp b/src/cookiejar.cpp index 7b6874a0c7..fcd1b3668d 100644 --- a/src/cookiejar.cpp +++ b/src/cookiejar.cpp @@ -28,16 +28,16 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "phantom.h" -#include "config.h" #include "cookiejar.h" +#include "config.h" +#include "phantom.h" -#include #include +#include #include #include -#define COOKIE_JAR_VERSION 1 +#define COOKIE_JAR_VERSION 1 // Operators needed for Cookie Serialization QT_BEGIN_NAMESPACE @@ -133,12 +133,11 @@ bool CookieJar::addCookie(const QNetworkCookie& cookie, const QString& url) // Save a single cookie isCookieAdded = setCookiesFromUrl( QList() << cookie, //< unfortunately, "setCookiesFromUrl" requires a list - !url.isEmpty() ? - url : //< use given URL - QString( //< mock-up a URL - (cookie.isSecure() ? "https://" : "http://") + //< URL protocol - QString(cookie.domain().startsWith('.') ? "www" : "") + cookie.domain() + //< URL domain - (cookie.path().isEmpty() ? "/" : cookie.path()))); //< URL path + !url.isEmpty() ? url : //< use given URL + QString( //< mock-up a URL + (cookie.isSecure() ? "https://" : "http://") + //< URL protocol + QString(cookie.domain().startsWith('.') ? "www" : "") + cookie.domain() + //< URL domain + (cookie.path().isEmpty() ? "/" : cookie.path()))); //< URL path // Return "true" if the cookie was really set if (contains(cookie)) { @@ -315,11 +314,11 @@ bool CookieJar::deleteCookie(const QString& name, const QString& url) QList cookiesListAll; if (url.isEmpty()) { - if (name.isEmpty()) { //< Neither "name" or "url" provided + if (name.isEmpty()) { //< Neither "name" or "url" provided // This method has been used wrong: // "redirecting" to the right method for the job clearCookies(); - } else { //< Only "name" provided + } else { //< Only "name" provided // Delete all cookies with the given name from the CookieJar cookiesListAll = allCookies(); for (int i = cookiesListAll.length() - 1; i >= 0; --i) { @@ -337,8 +336,8 @@ bool CookieJar::deleteCookie(const QString& name, const QString& url) QList cookiesListUrl = cookies(url); cookiesListAll = allCookies(); for (int i = cookiesListAll.length() - 1; i >= 0; --i) { - if (cookiesListUrl.contains(cookiesListAll.at(i)) && //< if it part of the set of cookies visible at URL - (cookiesListAll.at(i).name() == name || name.isEmpty())) { //< and if the name matches, or no name provided + if (cookiesListUrl.contains(cookiesListAll.at(i)) && //< if it part of the set of cookies visible at URL + (cookiesListAll.at(i).name() == name || name.isEmpty())) { //< and if the name matches, or no name provided // Remove this cookie qDebug() << "CookieJar - Deleted" << cookiesListAll.at(i).toRawForm(); cookiesListAll.removeAt(i); @@ -462,14 +461,14 @@ void CookieJar::save() purgeExpiredCookies(); #ifndef QT_NO_DEBUG_OUTPUT - foreach(QNetworkCookie cookie, allCookies()) { + foreach (QNetworkCookie cookie, allCookies()) { qDebug() << "CookieJar - Saved" << cookie.toRawForm(); } #endif // Store cookies if (m_cookieStorage) { - m_cookieStorage->setValue(QLatin1String("cookies"), QVariant::fromValue >(allCookies())); + m_cookieStorage->setValue(QLatin1String("cookies"), QVariant::fromValue>(allCookies())); } } } @@ -478,11 +477,11 @@ void CookieJar::load() { if (isEnabled()) { // Register a "StreamOperator" for this Meta Type, so we can easily serialize/deserialize the cookies - qRegisterMetaTypeStreamOperators >("QList"); + qRegisterMetaTypeStreamOperators>("QList"); // Load all the cookies if (m_cookieStorage) { - setAllCookies(qvariant_cast >(m_cookieStorage->value(QLatin1String("cookies")))); + setAllCookies(qvariant_cast>(m_cookieStorage->value(QLatin1String("cookies")))); } // If any cookie has expired since last execution, purge and save before going any further @@ -491,7 +490,7 @@ void CookieJar::load() } #ifndef QT_NO_DEBUG_OUTPUT - foreach(QNetworkCookie cookie, allCookies()) { + foreach (QNetworkCookie cookie, allCookies()) { qDebug() << "CookieJar - Loaded" << cookie.toRawForm(); } #endif @@ -501,7 +500,7 @@ void CookieJar::load() bool CookieJar::contains(const QNetworkCookie& cookieToFind) const { QList cookiesList = allCookies(); - foreach(QNetworkCookie cookie, cookiesList) { + foreach (QNetworkCookie cookie, cookiesList) { if (cookieToFind == cookie) { return true; } diff --git a/src/cookiejar.h b/src/cookiejar.h index 15c46305fd..6fa3c53ca2 100644 --- a/src/cookiejar.h +++ b/src/cookiejar.h @@ -31,14 +31,13 @@ #ifndef COOKIEJAR_H #define COOKIEJAR_H -#include #include #include +#include #include #include -class CookieJar: public QNetworkCookieJar -{ +class CookieJar : public QNetworkCookieJar { Q_OBJECT Q_PROPERTY(QVariantList cookies READ cookiesToMap WRITE addCookiesFromMap) diff --git a/src/crashdump.cpp b/src/crashdump.cpp index 2e903becdc..6640143ce2 100644 --- a/src/crashdump.cpp +++ b/src/crashdump.cpp @@ -31,25 +31,24 @@ #include "crashdump.h" #include +#include #include #include -#include #include #if defined(Q_OS_WIN) #include #else -#include #include +#include #endif -void -print_crash_message() +void print_crash_message() { fputs("PhantomJS has crashed. Please read the bug reporting guide at\n" " and file a bug report.\n", - stderr); + stderr); fflush(stderr); } @@ -58,7 +57,7 @@ print_crash_message() static LONG WINAPI unhandled_exception_filter(LPEXCEPTION_POINTERS ptrs) { fprintf(stderr, "Fatal Windows exception, code 0x%08x.\n", - ptrs->ExceptionRecord->ExceptionCode); + ptrs->ExceptionRecord->ExceptionCode); print_crash_message(); return EXCEPTION_EXECUTE_HANDLER; } @@ -66,10 +65,10 @@ static LONG WINAPI unhandled_exception_filter(LPEXCEPTION_POINTERS ptrs) #if _MSC_VER >= 1400 static void invalid_parameter_handler(const wchar_t* expression, - const wchar_t* function, - const wchar_t* file, - unsigned int line, - uintptr_t /*reserved*/) + const wchar_t* function, + const wchar_t* file, + unsigned int line, + uintptr_t /*reserved*/) { // The parameters all have the value NULL unless a debug version of the CRT library is used // https://msdn.microsoft.com/en-us/library/a9yf33zb(v=VS.80).aspx @@ -81,7 +80,7 @@ invalid_parameter_handler(const wchar_t* expression, fprintf(stderr, "Invalid parameter detected.\n"); #else fprintf(stderr, "Invalid parameter detected at %ls:%u: %ls: %ls\n", - file, line, function, expression); + file, line, function, expression); #endif // _DEBUG print_crash_message(); ExitProcess(STATUS_FATAL_APP_EXIT); @@ -110,10 +109,7 @@ handle_fatal_signal(int signo) static void init_crash_handler_os() { - SetErrorMode(SEM_FAILCRITICALERRORS | - SEM_NOALIGNMENTFAULTEXCEPT | - SEM_NOGPFAULTERRORBOX | - SEM_NOOPENFILEERRORBOX); + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); SetUnhandledExceptionFilter(unhandled_exception_filter); // When the app crashes, don't print the abort message @@ -155,7 +151,9 @@ init_crash_handler_os() struct rlimit rl; rl.rlim_cur = 0; rl.rlim_max = 0; - if (setrlimit(RLIMIT_CORE, &rl)) { goto fail; } + if (setrlimit(RLIMIT_CORE, &rl)) { + goto fail; + } // Ensure that none of the signals that indicate a fatal CPU exception // are blocked. (If they are delivered while blocked, the behavior is @@ -170,7 +168,9 @@ init_crash_handler_os() sigaddset(&mask, SIGILL); sigaddset(&mask, SIGSEGV); sigaddset(&mask, SIGQUIT); - if (sigprocmask(SIG_UNBLOCK, &mask, 0)) { goto fail; } + if (sigprocmask(SIG_UNBLOCK, &mask, 0)) { + goto fail; + } // Install a signal handler for all the above signals. This will call // print_crash_message and then reraise the signal (so the exit code will @@ -179,14 +179,26 @@ init_crash_handler_os() struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_handler = handle_fatal_signal; - sa.sa_flags = SA_NODEFER | SA_RESETHAND; - - if (sigaction(SIGABRT, &sa, 0)) { goto fail; } - if (sigaction(SIGBUS, &sa, 0)) { goto fail; } - if (sigaction(SIGFPE, &sa, 0)) { goto fail; } - if (sigaction(SIGILL, &sa, 0)) { goto fail; } - if (sigaction(SIGSEGV, &sa, 0)) { goto fail; } - if (sigaction(SIGQUIT, &sa, 0)) { goto fail; } + sa.sa_flags = SA_NODEFER | SA_RESETHAND; + + if (sigaction(SIGABRT, &sa, 0)) { + goto fail; + } + if (sigaction(SIGBUS, &sa, 0)) { + goto fail; + } + if (sigaction(SIGFPE, &sa, 0)) { + goto fail; + } + if (sigaction(SIGILL, &sa, 0)) { + goto fail; + } + if (sigaction(SIGSEGV, &sa, 0)) { + goto fail; + } + if (sigaction(SIGQUIT, &sa, 0)) { + goto fail; + } return; @@ -197,8 +209,7 @@ init_crash_handler_os() #endif // not Windows -void -init_crash_handler() +void init_crash_handler() { // Qt, QtWebkit, and PhantomJS mostly don't make use of C++ exceptions, // so in the rare cases where an exception does get thrown, it will diff --git a/src/encoding.h b/src/encoding.h index 75022aba5f..8ed4a24380 100644 --- a/src/encoding.h +++ b/src/encoding.h @@ -33,8 +33,7 @@ #include -class Encoding -{ +class Encoding { public: Encoding(); Encoding(const QString& encoding); diff --git a/src/env.cpp b/src/env.cpp index 5e1edda150..0c20c42f61 100644 --- a/src/env.cpp +++ b/src/env.cpp @@ -30,9 +30,9 @@ #include "env.h" #include +#include #include #include -#include static Env* env_instance = NULL; @@ -49,7 +49,7 @@ Env::Env() : QObject(QCoreApplication::instance()) { const QProcessEnvironment& env = QProcessEnvironment::systemEnvironment(); - foreach(const QString & key, env.keys()) { + foreach (const QString& key, env.keys()) { m_map[key] = env.value(key); } } diff --git a/src/env.h b/src/env.h index e83662550c..fa320955f5 100644 --- a/src/env.h +++ b/src/env.h @@ -33,8 +33,7 @@ #include #include -class Env : public QObject -{ +class Env : public QObject { Q_OBJECT public: diff --git a/src/filesystem.cpp b/src/filesystem.cpp index 9160d8a05f..16a7d6ffe7 100644 --- a/src/filesystem.cpp +++ b/src/filesystem.cpp @@ -29,18 +29,18 @@ #include "filesystem.h" +#include +#include +#include #include #include -#include -#include -#include // File // public: -File::File(QFile* openfile, QTextCodec* codec, QObject* parent) : - QObject(parent), - m_file(openfile), - m_fileStream(0) +File::File(QFile* openfile, QTextCodec* codec, QObject* parent) + : QObject(parent) + , m_file(openfile) + , m_fileStream(0) { if (codec) { m_fileStream = new QTextStream(m_file); @@ -72,7 +72,8 @@ QString File::read(const QVariant& n) const bool isReadAll = 0 > bytesToRead; if (!m_file->isReadable()) { - qDebug() << "File::read - " << "Couldn't read:" << m_file->fileName(); + qDebug() << "File::read - " + << "Couldn't read:" << m_file->fileName(); return QString(); } if (m_file->isWritable()) { @@ -117,7 +118,8 @@ QString File::read(const QVariant& n) bool File::write(const QString& data) { if (!m_file->isWritable()) { - qDebug() << "File::write - " << "Couldn't write:" << m_file->fileName(); + qDebug() << "File::write - " + << "Couldn't write:" << m_file->fileName(); return true; } if (m_fileStream) { @@ -149,7 +151,8 @@ bool File::seek(const qint64 pos) QString File::readLine() { if (!m_file->isReadable()) { - qDebug() << "File::readLine - " << "Couldn't read:" << m_file->fileName(); + qDebug() << "File::readLine - " + << "Couldn't read:" << m_file->fileName(); return QString(); } if (m_file->isWritable()) { @@ -170,7 +173,8 @@ bool File::writeLine(const QString& data) if (write(data) && write("\n")) { return true; } - qDebug() << "File::writeLine - " << "Couldn't write:" << m_file->fileName(); + qDebug() << "File::writeLine - " + << "Couldn't write:" << m_file->fileName(); return false; } @@ -185,7 +189,8 @@ bool File::atEnd() const return m_file->atEnd(); } } - qDebug() << "File::atEnd - " << "Couldn't read:" << m_file->fileName(); + qDebug() << "File::atEnd - " + << "Couldn't read:" << m_file->fileName(); return false; } @@ -267,12 +272,12 @@ bool File::_isUnbuffered() const return m_file->openMode() & QIODevice::Unbuffered; } - // FileSystem // public: FileSystem::FileSystem(QObject* parent) : QObject(parent) -{ } +{ +} // public slots: @@ -354,15 +359,15 @@ bool FileSystem::_copyTree(const QString& source, const QString& destination) co return false; } - foreach(QFileInfo entry, sourceDir.entryInfoList(sourceDirFilter, QDir::DirsFirst)) { + foreach (QFileInfo entry, sourceDir.entryInfoList(sourceDirFilter, QDir::DirsFirst)) { if (entry.isDir()) { if (!FileSystem::_copyTree(entry.absoluteFilePath(), - destination + "/" + entry.fileName())) { //< directory: recursive call + destination + "/" + entry.fileName())) { //< directory: recursive call return false; } } else { if (!FileSystem::_copy(entry.absoluteFilePath(), - destination + "/" + entry.fileName())) { //< file: copy + destination + "/" + entry.fileName())) { //< file: copy return false; } } @@ -393,7 +398,7 @@ bool FileSystem::_removeTree(const QString& path) const QDir::Filters dirFilter = QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files; if (dir.exists()) { - foreach(QFileInfo info, dir.entryInfoList(dirFilter, QDir::DirsFirst)) { + foreach (QFileInfo info, dir.entryInfoList(dirFilter, QDir::DirsFirst)) { if (info.isDir()) { if (!FileSystem::_removeTree(info.absoluteFilePath())) { //< directory: recursive call return false; @@ -456,7 +461,8 @@ QObject* FileSystem::_open(const QString& path, const QVariantMap& opts) const const QVariant modeVar = opts["mode"]; // Ensure only strings if (modeVar.type() != QVariant::String) { - qDebug() << "FileSystem::open - " << "Mode must be a string!" << modeVar; + qDebug() << "FileSystem::open - " + << "Mode must be a string!" << modeVar; return 0; } @@ -464,27 +470,33 @@ QObject* FileSystem::_open(const QString& path, const QVariantMap& opts) const QFile::OpenMode modeCode = QFile::NotOpen; // Determine the OpenMode - foreach(const QChar & c, modeVar.toString()) { + foreach (const QChar& c, modeVar.toString()) { switch (c.toLatin1()) { - case 'r': case 'R': { + case 'r': + case 'R': { modeCode |= QFile::ReadOnly; break; } - case 'a': case 'A': case '+': { + case 'a': + case 'A': + case '+': { modeCode |= QFile::Append; modeCode |= QFile::WriteOnly; break; } - case 'w': case 'W': { + case 'w': + case 'W': { modeCode |= QFile::WriteOnly; break; } - case 'b': case 'B': { + case 'b': + case 'B': { isBinary = true; break; } default: { - qDebug() << "FileSystem::open - " << "Wrong Mode:" << c; + qDebug() << "FileSystem::open - " + << "Wrong Mode:" << c; return 0; } } @@ -493,14 +505,16 @@ QObject* FileSystem::_open(const QString& path, const QVariantMap& opts) const // Make sure the file exists OR it can be created at the required path if (!QFile::exists(path) && modeCode & QFile::WriteOnly) { if (!makeTree(QFileInfo(path).dir().absolutePath())) { - qDebug() << "FileSystem::open - " << "Full path coulnd't be created:" << path; + qDebug() << "FileSystem::open - " + << "Full path coulnd't be created:" << path; return 0; } } // Make sure there is something to read if (!QFile::exists(path) && modeCode & QFile::ReadOnly) { - qDebug() << "FileSystem::open - " << "Trying to read a file that doesn't exist:" << path; + qDebug() << "FileSystem::open - " + << "Trying to read a file that doesn't exist:" << path; return 0; } @@ -510,7 +524,8 @@ QObject* FileSystem::_open(const QString& path, const QVariantMap& opts) const const QString charset = opts.value("charset", "UTF-8").toString(); codec = QTextCodec::codecForName(charset.toLatin1()); if (!codec) { - qDebug() << "FileSystem::open - " << "Unknown charset:" << charset; + qDebug() << "FileSystem::open - " + << "Unknown charset:" << charset; return 0; } } @@ -520,7 +535,8 @@ QObject* FileSystem::_open(const QString& path, const QVariantMap& opts) const if (!file->open(modeCode)) { // Return "NULL" if the file couldn't be opened as requested delete file; - qDebug() << "FileSystem::open - " << "Couldn't be opened:" << path; + qDebug() << "FileSystem::open - " + << "Couldn't be opened:" << path; return 0; } diff --git a/src/filesystem.h b/src/filesystem.h index 7a7c680ee4..95e61fdd7b 100644 --- a/src/filesystem.h +++ b/src/filesystem.h @@ -30,14 +30,13 @@ #ifndef FILESYSTEM_H #define FILESYSTEM_H -#include #include +#include #include #include #include -class File : public QObject -{ +class File : public QObject { Q_OBJECT public: @@ -74,9 +73,7 @@ public slots: QTextStream* m_fileStream; }; - -class FileSystem : public QObject -{ +class FileSystem : public QObject { Q_OBJECT Q_PROPERTY(QString workingDirectory READ workingDirectory) Q_PROPERTY(QString separator READ separator) diff --git a/src/main.cpp b/src/main.cpp index 25519baacb..3cf6aab803 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -27,14 +27,14 @@ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "consts.h" -#include "utils.h" +#include "crashdump.h" #include "env.h" #include "phantom.h" -#include "crashdump.h" +#include "utils.h" #include -#include #include +#include #include #include diff --git a/src/networkaccessmanager.cpp b/src/networkaccessmanager.cpp index 6ca702891e..b5faadd009 100644 --- a/src/networkaccessmanager.cpp +++ b/src/networkaccessmanager.cpp @@ -33,16 +33,16 @@ #include #include #include -#include +#include #include #include #include -#include +#include -#include "phantom.h" #include "config.h" #include "cookiejar.h" #include "networkaccessmanager.h" +#include "phantom.h" // 10 MB const qint64 MAX_REQUEST_POST_BODY_SIZE = 10 * 1000 * 1000; @@ -85,24 +85,22 @@ NoFileAccessReply::NoFileAccessReply(QObject* parent, const QNetworkRequest& req qRegisterMetaType(); QString msg = (QCoreApplication::translate("QNetworkReply", "Protocol \"%1\" is unknown") - .arg(req.url().scheme())); + .arg(req.url().scheme())); setError(ProtocolUnknownError, msg); QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection, - Q_ARG(QNetworkReply::NetworkError, ProtocolUnknownError)); + Q_ARG(QNetworkReply::NetworkError, ProtocolUnknownError)); QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection); } // The destructor must be out-of-line in order to trigger generation of the vtable. NoFileAccessReply::~NoFileAccessReply() {} - TimeoutTimer::TimeoutTimer(QObject* parent) : QTimer(parent) { } - JsNetworkRequest::JsNetworkRequest(QNetworkRequest* request, QObject* parent) : QObject(parent) { @@ -144,10 +142,10 @@ const ssl_protocol_option ssl_protocol_options[] = { { "tlsv1.2", QSsl::TlsV1_2 }, { "tlsv1.1", QSsl::TlsV1_1 }, { "tlsv1.0", QSsl::TlsV1_0 }, - { "tlsv1", QSsl::TlsV1_0 }, - { "sslv3", QSsl::SslV3 }, - { "any", QSsl::AnyProtocol }, - { 0, QSsl::UnknownProtocol } + { "tlsv1", QSsl::TlsV1_0 }, + { "sslv3", QSsl::SslV3 }, + { "any", QSsl::AnyProtocol }, + { 0, QSsl::UnknownProtocol } }; // public: @@ -195,8 +193,8 @@ void NetworkAccessManager::prepareSslConfiguration(const Config* config) bool setProtocol = false; for (const ssl_protocol_option* proto_opt = ssl_protocol_options; - proto_opt->name; - proto_opt++) { + proto_opt->name; + proto_opt++) { if (config->sslProtocol() == proto_opt->name) { m_sslConfiguration.setProtocol(proto_opt->proto); setProtocol = true; @@ -212,9 +210,9 @@ void NetworkAccessManager::prepareSslConfiguration(const Config* config) // That overload isn't available on QSslConfiguration. if (!config->sslCiphers().isEmpty()) { QList cipherList; - foreach(const QString & cipherName, - config->sslCiphers().split(QLatin1String(":"), - QString::SkipEmptyParts)) { + foreach (const QString& cipherName, + config->sslCiphers().split(QLatin1String(":"), + QString::SkipEmptyParts)) { QSslCipher cipher(cipherName); if (!cipher.isNull()) { cipherList << cipher; @@ -227,14 +225,14 @@ void NetworkAccessManager::prepareSslConfiguration(const Config* config) if (!config->sslCertificatesPath().isEmpty()) { QList caCerts = QSslCertificate::fromPath( - config->sslCertificatesPath(), QSsl::Pem, QRegExp::Wildcard); + config->sslCertificatesPath(), QSsl::Pem, QRegExp::Wildcard); m_sslConfiguration.setCaCertificates(caCerts); } if (!config->sslClientCertificateFile().isEmpty()) { QList clientCerts = QSslCertificate::fromPath( - config->sslClientCertificateFile(), QSsl::Pem, QRegExp::Wildcard); + config->sslClientCertificateFile(), QSsl::Pem, QRegExp::Wildcard); if (!clientCerts.isEmpty()) { QSslCertificate clientCert = clientCerts.first(); @@ -323,7 +321,9 @@ QNetworkReply* NetworkAccessManager::createRequest(Operation op, const QNetworkR // http://code.google.com/p/phantomjs/issues/detail?id=337 if (op == QNetworkAccessManager::PostOperation) { - if (outgoingData) { postData = outgoingData->peek(MAX_REQUEST_POST_BODY_SIZE); } + if (outgoingData) { + postData = outgoingData->peek(MAX_REQUEST_POST_BODY_SIZE); + } QString contentType = req.header(QNetworkRequest::ContentTypeHeader).toString(); if (contentType.isEmpty()) { req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); @@ -340,7 +340,7 @@ QNetworkReply* NetworkAccessManager::createRequest(Operation op, const QNetworkR m_idCounter++; QVariantList headers; - foreach(QByteArray headerName, req.rawHeaderList()) { + foreach (QByteArray headerName, req.rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(req.rawHeader(headerName)); @@ -352,7 +352,9 @@ QNetworkReply* NetworkAccessManager::createRequest(Operation op, const QNetworkR data["url"] = url.data(); data["method"] = toString(op); data["headers"] = headers; - if (op == QNetworkAccessManager::PostOperation) { data["postData"] = postData.data(); } + if (op == QNetworkAccessManager::PostOperation) { + data["postData"] = postData.data(); + } data["time"] = QDateTime::currentDateTime(); JsNetworkRequest jsNetworkRequest(&req, this); @@ -362,8 +364,7 @@ QNetworkReply* NetworkAccessManager::createRequest(Operation op, const QNetworkR // The second half of this conditional must match // QNetworkAccessManager's own idea of what a local file URL is. QNetworkReply* reply; - if (!m_localUrlAccessEnabled && - (req.url().isLocalFile() || scheme == QLatin1String("qrc"))) { + if (!m_localUrlAccessEnabled && (req.url().isLocalFile() || scheme == QLatin1String("qrc"))) { reply = new NoFileAccessReply(this, req, op); } else { reply = QNetworkAccessManager::createRequest(op, req, outgoingData); @@ -496,7 +497,7 @@ void NetworkAccessManager::handleFinished(QNetworkReply* reply, const QVariant& void NetworkAccessManager::handleSslErrors(const QList& errors) { QNetworkReply* reply = qobject_cast(sender()); - foreach(QSslError e, errors) { + foreach (QSslError e, errors) { qDebug() << "Network - SSL Error:" << e; } @@ -527,7 +528,7 @@ void NetworkAccessManager::handleNetworkError() QVariantList NetworkAccessManager::getHeadersFromReply(const QNetworkReply* reply) { QVariantList headers; - foreach(QByteArray headerName, reply->rawHeaderList()) { + foreach (QByteArray headerName, reply->rawHeaderList()) { QVariantMap header; header["name"] = QString::fromUtf8(headerName); header["value"] = QString::fromUtf8(reply->rawHeader(headerName)); diff --git a/src/networkaccessmanager.h b/src/networkaccessmanager.h index 0130cb714e..781ab380f3 100644 --- a/src/networkaccessmanager.h +++ b/src/networkaccessmanager.h @@ -34,16 +34,15 @@ #include #include #include -#include #include +#include class Config; class QAuthenticator; class QNetworkDiskCache; class QSslConfiguration; -class TimeoutTimer : public QTimer -{ +class TimeoutTimer : public QTimer { Q_OBJECT public: @@ -52,8 +51,7 @@ class TimeoutTimer : public QTimer QVariantMap data; }; -class JsNetworkRequest : public QObject -{ +class JsNetworkRequest : public QObject { Q_OBJECT public: @@ -66,20 +64,19 @@ class JsNetworkRequest : public QObject QNetworkRequest* m_networkRequest; }; -class NoFileAccessReply : public QNetworkReply -{ +class NoFileAccessReply : public QNetworkReply { Q_OBJECT public: NoFileAccessReply(QObject* parent, const QNetworkRequest& req, const QNetworkAccessManager::Operation op); ~NoFileAccessReply(); void abort() {} + protected: qint64 readData(char*, qint64) { return -1; } }; -class NetworkAccessManager : public QNetworkAccessManager -{ +class NetworkAccessManager : public QNetworkAccessManager { Q_OBJECT public: NetworkAccessManager(QObject* parent, const Config* config); diff --git a/src/phantom.cpp b/src/phantom.cpp index 2a614f40c1..12d5bcb67a 100644 --- a/src/phantom.cpp +++ b/src/phantom.cpp @@ -53,7 +53,7 @@ #include "webpage.h" #include "webserver.h" -#if QTWEBKIT_VERSION < ((5<<16) | (212<<8)) +#if QTWEBKIT_VERSION < ((5 << 16) | (212 << 8)) #error "This version of QtWebKit is not supported. Please use QtWebKit >= 5.212" #endif @@ -136,9 +136,9 @@ void Phantom::init() m_scriptFileEnc.setEncoding(m_config.scriptEncoding()); connect(m_page, SIGNAL(javaScriptConsoleMessageSent(QString)), - SLOT(printConsoleMessage(QString))); + SLOT(printConsoleMessage(QString))); connect(m_page, SIGNAL(initialized()), - SLOT(onInitialized())); + SLOT(onInitialized())); m_defaultPageSettings[PAGE_SETTINGS_LOAD_IMAGES] = QVariant::fromValue(m_config.autoLoadImages()); m_defaultPageSettings[PAGE_SETTINGS_JS_ENABLED] = QVariant::fromValue(true); @@ -198,19 +198,20 @@ bool Phantom::execute() } qDebug() << "Phantom - execute: Script & Arguments"; - qDebug() << " " << "script:" << m_config.scriptFile(); + qDebug() << " " + << "script:" << m_config.scriptFile(); QStringList args = m_config.scriptArgs(); for (int i = 0, ilen = args.length(); i < ilen; ++i) { qDebug() << " " << i << "arg:" << args.at(i); } #endif - if (m_config.scriptFile().isEmpty()) { // REPL mode requested + if (m_config.scriptFile().isEmpty()) { // REPL mode requested qDebug() << "Phantom - execute: Starting REPL mode"; // Create the REPL: it will launch itself, no need to store this variable. REPL::getInstance(m_page->mainFrame(), this); - } else { // Load the User Script + } else { // Load the User Script qDebug() << "Phantom - execute: Starting normal mode"; if (m_config.debug()) { @@ -362,14 +363,7 @@ void Phantom::loadModule(const QString& moduleSource, const QString& filename) return; } - QString scriptSource = - "(function(require, exports, module) {\n" + - moduleSource + - "\n}.call({}," + - "require.cache['" + filename + "']._getRequire()," + - "require.cache['" + filename + "'].exports," + - "require.cache['" + filename + "']" + - "));"; + QString scriptSource = "(function(require, exports, module) {\n" + moduleSource + "\n}.call({}," + "require.cache['" + filename + "']._getRequire()," + "require.cache['" + filename + "'].exports," + "require.cache['" + filename + "']" + "));"; m_page->mainFrame()->evaluateJavaScript(scriptSource); } @@ -461,8 +455,7 @@ void Phantom::onInitialized() // Bootstrap the PhantomJS scope m_page->mainFrame()->evaluateJavaScript( - Utils::readResourceFileUtf8(":/bootstrap.js") - ); + Utils::readResourceFileUtf8(":/bootstrap.js")); } bool Phantom::setCookies(const QVariantList& cookies) @@ -497,7 +490,6 @@ void Phantom::clearCookies() m_defaultCookieJar->clearCookies(); } - // private: void Phantom::doExit(int code) { @@ -508,7 +500,7 @@ void Phantom::doExit(int code) // Iterate in reverse order so the first page is the last one scheduled for deletion. // The first page is the root object, which will be invalidated when it is deleted. // This causes an assertion to go off in BridgeJSC.cpp Instance::createRuntimeObject. - QListIterator > i(m_pages); + QListIterator> i(m_pages); i.toBack(); while (i.hasPrevious()) { const QPointer page = i.previous(); diff --git a/src/phantom.h b/src/phantom.h index 6d144ae244..a509ee2888 100644 --- a/src/phantom.h +++ b/src/phantom.h @@ -33,19 +33,18 @@ #include -#include "filesystem.h" -#include "encoding.h" -#include "config.h" -#include "system.h" #include "childprocess.h" +#include "config.h" #include "cookiejar.h" +#include "encoding.h" +#include "filesystem.h" +#include "system.h" class WebPage; class CustomPage; class WebServer; -class Phantom : public QObject -{ +class Phantom : public QObject { Q_OBJECT Q_PROPERTY(QVariantMap defaultPageSettings READ defaultPageSettings) Q_PROPERTY(QString libraryPath READ libraryPath WRITE setLibraryPath) @@ -230,8 +229,8 @@ private slots: FileSystem* m_filesystem; System* m_system; ChildProcess* m_childprocess; - QList > m_pages; - QList > m_servers; + QList> m_pages; + QList> m_servers; Config m_config; CookieJar* m_defaultCookieJar; qreal m_defaultDpi; diff --git a/src/repl.cpp b/src/repl.cpp index 7f25a22b0e..01474f5e1e 100644 --- a/src/repl.cpp +++ b/src/repl.cpp @@ -29,41 +29,40 @@ #include "repl.h" -#include -#include #include -#include #include #include +#include +#include +#include #include "consts.h" #include "terminal.h" #include "utils.h" -#define PROMPT "phantomjs> " -#define HISTORY_FILENAME "phantom_repl_history" +#define PROMPT "phantomjs> " +#define HISTORY_FILENAME "phantom_repl_history" // Only with word characters, spaces and the dot ('.') // we can still attempt to offer a completion to the user -#define REGEXP_NON_COMPLETABLE_CHARS "[^\\w\\s\\.]" +#define REGEXP_NON_COMPLETABLE_CHARS "[^\\w\\s\\.]" // JS Code to find possible completions #define JS_RETURN_POSSIBLE_COMPLETIONS "REPL._getCompletions(%1, \"%2\");" // JS Code to evaluate User Input and prettify the expression result -#define JS_EVAL_USER_INPUT \ - "try { " \ - "REPL._lastEval = eval(\"%1\");" \ +#define JS_EVAL_USER_INPUT \ + "try { " \ + "REPL._lastEval = eval(\"%1\");" \ "console.log(JSON.stringify(REPL._lastEval, REPL._expResStringifyReplacer, ' ')); " \ - "} catch(e) { " \ - "if (e instanceof TypeError) { " \ - "console.error(\"'%1' is a cyclic structure\"); " \ - "} else { " \ - "console.error(e.message);" \ - "}" \ + "} catch(e) { " \ + "if (e instanceof TypeError) { " \ + "console.error(\"'%1' is a cyclic structure\"); " \ + "} else { " \ + "console.error(e.message);" \ + "}" \ "} " - // public: bool REPL::instanceExists() { @@ -128,14 +127,15 @@ QStringList REPL::_enumerateCompletions(QObject* obj) const // private: REPL::REPL(QWebFrame* webframe, Phantom* parent) - : QObject(parent), - m_looping(true) + : QObject(parent) + , m_looping(true) { m_webframe = webframe; m_parentPhantom = parent; m_historyFilepath = QString("%1/%2").arg( - QStandardPaths::writableLocation(QStandardPaths::DataLocation), - HISTORY_FILENAME).toLocal8Bit(); + QStandardPaths::writableLocation(QStandardPaths::DataLocation), + HISTORY_FILENAME) + .toLocal8Bit(); // Ensure the location for the history file exists QDir().mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation)); @@ -182,12 +182,10 @@ void REPL::offerCompletion(const char* buf, linenoiseCompletions* lc) // This will return an array of String with the possible completions QStringList completions = REPL::getInstance()->m_webframe->evaluateJavaScript( - QString(JS_RETURN_POSSIBLE_COMPLETIONS).arg( - toInspect, - toComplete) - ).toStringList(); + QString(JS_RETURN_POSSIBLE_COMPLETIONS).arg(toInspect, toComplete)) + .toStringList(); - foreach(QString c, completions) { + foreach (QString c, completions) { if (lastIndexOfDot > -1) { // Preserve the "toInspect" portion of the string to complete linenoiseAddCompletion(lc, QString("%1.%2").arg(toInspect, c).toLocal8Bit().data()); @@ -203,13 +201,12 @@ void REPL::startLoop() char* userInput; // Load REPL history - linenoiseHistoryLoad(m_historyFilepath.data()); //< requires "char *" + linenoiseHistoryLoad(m_historyFilepath.data()); //< requires "char *" while (m_looping && (userInput = linenoise(PROMPT)) != NULL) { if (userInput[0] != '\0') { // Send the user input to the main Phantom frame for evaluation m_webframe->evaluateJavaScript( - QString(JS_EVAL_USER_INPUT).arg( - QString(userInput).replace('"', "\\\""))); + QString(JS_EVAL_USER_INPUT).arg(QString(userInput).replace('"', "\\\""))); // Save command in the REPL history linenoiseHistoryAdd(userInput); diff --git a/src/repl.h b/src/repl.h index 2f23a033b2..17d283ac91 100644 --- a/src/repl.h +++ b/src/repl.h @@ -50,8 +50,7 @@ extern "C" { * It's based the Linenoise library (https://github.com/tadmarshall/linenoise). * More info about REPL: http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop */ -class REPL: public QObject -{ +class REPL : public QObject { Q_OBJECT public: diff --git a/src/system.cpp b/src/system.cpp index 623114d994..f83daa18a5 100644 --- a/src/system.cpp +++ b/src/system.cpp @@ -32,8 +32,8 @@ #include #include -#include #include +#include #include "../env.h" #include "terminal.h" @@ -52,8 +52,8 @@ QString getOSRelease() } #endif -System::System(QObject* parent) : - QObject(parent) +System::System(QObject* parent) + : QObject(parent) , m_stdout((File*)NULL) , m_stderr((File*)NULL) , m_stdin((File*)NULL) diff --git a/src/system.h b/src/system.h index 959b79484a..b6405f7a53 100644 --- a/src/system.h +++ b/src/system.h @@ -32,17 +32,16 @@ #define SYSTEM_H #include +#include #include #include -#include #include #include "filesystem.h" // This class implements the CommonJS System/1.0 spec. // See: http://wiki.commonjs.org/wiki/System/1.0 -class System : public QObject -{ +class System : public QObject { Q_OBJECT Q_PROPERTY(qint64 pid READ pid) Q_PROPERTY(QStringList args READ args) diff --git a/src/terminal.h b/src/terminal.h index 0df4afa0f3..b34b24545a 100644 --- a/src/terminal.h +++ b/src/terminal.h @@ -37,8 +37,7 @@ #include "encoding.h" -class Terminal: public QObject -{ +class Terminal : public QObject { Q_OBJECT public: diff --git a/src/utils.cpp b/src/utils.cpp index 543bfb4cff..173e2cddb3 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -32,10 +32,10 @@ #include "consts.h" #include "terminal.h" -#include -#include #include +#include #include +#include #include static QString findScript(const QString& jsFilePath, const QString& libraryPath) @@ -65,7 +65,9 @@ static QString jsFromScriptFile(const QString& scriptPath, const Encoding& enc) // Remove CLI script heading if (scriptBody.startsWith("#!")) { int len = scriptBody.indexOf(QRegExp("[\r\n]")); - if (len == -1) { len = scriptBody.length(); } + if (len == -1) { + len = scriptBody.length(); + } scriptBody.remove(0, len); } @@ -75,8 +77,7 @@ static QString jsFromScriptFile(const QString& scriptPath, const Encoding& enc) } } -namespace Utils -{ +namespace Utils { bool printDebugMessages = false; diff --git a/src/utils.h b/src/utils.h index 251c6c17b7..3774e04b61 100644 --- a/src/utils.h +++ b/src/utils.h @@ -31,8 +31,8 @@ #ifndef UTILS_H #define UTILS_H -#include #include "encoding.h" +#include class QWebFrame; @@ -40,28 +40,26 @@ class QWebFrame; * Aggregate common utility functions. */ -namespace Utils -{ +namespace Utils { void messageHandler(QtMsgType type, - const QMessageLogContext& context, - const QString& msg); + const QMessageLogContext& context, + const QString& msg); extern bool printDebugMessages; bool injectJsInFrame(const QString& jsFilePath, - const Encoding& jsFileEnc, - const QString& libraryPath, - QWebFrame* targetFrame, - const bool startingScript = false); + const Encoding& jsFileEnc, + const QString& libraryPath, + QWebFrame* targetFrame, + const bool startingScript = false); bool loadJSForDebug(const QString& jsFilePath, - const Encoding& jsFileEnc, - const QString& libraryPath, - QWebFrame* targetFrame, - const bool autorun = false); + const Encoding& jsFileEnc, + const QString& libraryPath, + QWebFrame* targetFrame, + const bool autorun = false); QString readResourceFileUtf8(const QString& resourceFilePath); - }; #endif // UTILS_H diff --git a/src/webpage.cpp b/src/webpage.cpp index b5ff679150..31420a25c6 100644 --- a/src/webpage.cpp +++ b/src/webpage.cpp @@ -73,21 +73,19 @@ #endif // Ensure we have at least head and body. -#define BLANK_HTML "" -#define CALLBACKS_OBJECT_NAME "_phantom" -#define INPAGE_CALL_NAME "window.callPhantom" -#define CALLBACKS_OBJECT_INJECTION INPAGE_CALL_NAME " = function() { return window." CALLBACKS_OBJECT_NAME ".call.call(_phantom, Array.prototype.slice.call(arguments, 0)); };" -#define CALLBACKS_OBJECT_PRESENT "typeof(window." CALLBACKS_OBJECT_NAME ") !== \"undefined\";" +#define BLANK_HTML "" +#define CALLBACKS_OBJECT_NAME "_phantom" +#define INPAGE_CALL_NAME "window.callPhantom" +#define CALLBACKS_OBJECT_INJECTION INPAGE_CALL_NAME " = function() { return window." CALLBACKS_OBJECT_NAME ".call.call(_phantom, Array.prototype.slice.call(arguments, 0)); };" +#define CALLBACKS_OBJECT_PRESENT "typeof(window." CALLBACKS_OBJECT_NAME ") !== \"undefined\";" #define STDOUT_FILENAME "/dev/stdout" #define STDERR_FILENAME "/dev/stderr" - /** * @class CustomPage */ -class CustomPage: public QWebPage -{ +class CustomPage : public QWebPage { Q_OBJECT public: @@ -216,10 +214,10 @@ public slots: bool isNavigationLocked = m_webPage->navigationLocked(); emit m_webPage->navigationRequested( - request.url().toEncoded(), //< Requested URL - navigationType, //< Navigation Type - !isNavigationLocked, //< Will navigate (not locked)? - isMainFrame); //< Is main frame? + request.url().toEncoded(), //< Requested URL + navigationType, //< Navigation Type + !isNavigationLocked, //< Will navigate (not locked)? + isMainFrame); //< Is main frame? return !isNavigationLocked; } @@ -256,7 +254,6 @@ public slots: CookieJar* m_cookieJar; }; - /** * Contains the Callback Objects used to regulate callback-traffic from the webpage internal context. * It's directly exposed within the webpage JS context, @@ -264,8 +261,7 @@ public slots: * * @class WebPageCallbacks */ -class WebpageCallbacks : public QObject -{ +class WebpageCallbacks : public QObject { Q_OBJECT public: @@ -348,7 +344,6 @@ public slots: friend class WebPage; }; - WebPage::WebPage(QObject* parent, const QUrl& baseUrl) : QObject(parent) , m_navigationLocked(false) @@ -396,7 +391,6 @@ WebPage::WebPage(QObject* parent, const QUrl& baseUrl) connect(m_customWebPage, SIGNAL(loadProgress(int)), this, SLOT(updateLoadingProgress(int))); connect(m_customWebPage, SIGNAL(repaintRequested(QRect)), this, SLOT(handleRepaintRequested(QRect)), Qt::QueuedConnection); - // Start with transparent background. QPalette palette = m_customWebPage->palette(); palette.setBrush(QPalette::Base, Qt::transparent); @@ -420,8 +414,7 @@ WebPage::WebPage(QObject* parent, const QUrl& baseUrl) if (isLocalStorageEnabled) { if (phantomCfg->localStoragePath().isEmpty()) { pageSettings->setLocalStoragePath(QStandardPaths::writableLocation(QStandardPaths::DataLocation)); - } - else { + } else { pageSettings->setLocalStoragePath(phantomCfg->localStoragePath()); } } @@ -430,13 +423,13 @@ WebPage::WebPage(QObject* parent, const QUrl& baseUrl) m_networkAccessManager = new NetworkAccessManager(this, phantomCfg); m_customWebPage->setNetworkAccessManager(m_networkAccessManager); connect(m_networkAccessManager, SIGNAL(resourceRequested(QVariant, QObject*)), - SIGNAL(resourceRequested(QVariant, QObject*))); + SIGNAL(resourceRequested(QVariant, QObject*))); connect(m_networkAccessManager, SIGNAL(resourceReceived(QVariant)), - SIGNAL(resourceReceived(QVariant))); + SIGNAL(resourceReceived(QVariant))); connect(m_networkAccessManager, SIGNAL(resourceError(QVariant)), - SIGNAL(resourceError(QVariant))); + SIGNAL(resourceError(QVariant))); connect(m_networkAccessManager, SIGNAL(resourceTimeout(QVariant)), - SIGNAL(resourceTimeout(QVariant))); + SIGNAL(resourceTimeout(QVariant))); m_dpi = qRound(QApplication::primaryScreen()->logicalDotsPerInch()); m_customWebPage->setViewportSize(QSize(400, 300)); @@ -580,7 +573,6 @@ void WebPage::stop() m_customWebPage->triggerAction(QWebPage::Stop); } - QString WebPage::plainText() const { return m_mainFrame->toPlainText(); @@ -734,7 +726,6 @@ QVariantMap WebPage::clipRect() const return result; } - void WebPage::setScrollPosition(const QVariantMap& size) { int top = size.value("top").toInt(); @@ -769,7 +760,7 @@ QVariant WebPage::evaluateJavaScript(const QString& code) qDebug() << "WebPage - evaluateJavaScript" << function; evalResult = m_currentFrame->evaluateJavaScript( - function); + function); qDebug() << "WebPage - evaluateJavaScript result" << evalResult; @@ -778,14 +769,16 @@ QVariant WebPage::evaluateJavaScript(const QString& code) QString WebPage::filePicker(const QString& oldFile) { - qDebug() << "WebPage - filePicker" << "- old file:" << oldFile; + qDebug() << "WebPage - filePicker" + << "- old file:" << oldFile; if (m_callbacks->m_filePickerCallback) { QVariant res = m_callbacks->m_filePickerCallback->call(QVariantList() << oldFile); if (res.canConvert()) { QString filePath = res.toString(); - qDebug() << "WebPage - filePicker" << "- new file:" << filePath; + qDebug() << "WebPage - filePicker" + << "- new file:" << filePath; // Return this value only if the file actually exists if (QFile::exists(filePath)) { return filePath; @@ -1206,12 +1199,13 @@ bool WebPage::renderPdf(QPdfWriter& pdfWriter) if (paperSize.contains("width") && paperSize.contains("height")) { const QSizeF sizePt(ceil(stringToPointSize(paperSize.value("width").toString())), - ceil(stringToPointSize(paperSize.value("height").toString()))); + ceil(stringToPointSize(paperSize.value("height").toString()))); pdfWriter.setPageSize(QPageSize(sizePt, QPageSize::Point)); } else if (paperSize.contains("format")) { const QPageLayout::Orientation orientation = paperSize.contains("orientation") - && paperSize.value("orientation").toString().compare("landscape", Qt::CaseInsensitive) == 0 ? - QPageLayout::Portrait : QPageLayout::Landscape; + && paperSize.value("orientation").toString().compare("landscape", Qt::CaseInsensitive) == 0 + ? QPageLayout::Portrait + : QPageLayout::Landscape; pdfWriter.setPageOrientation(orientation); static const struct { QString format; @@ -1480,7 +1474,7 @@ void WebPage::sendEvent(const QString& type, const QVariant& arg1, const QVarian if (arg1.type() == QVariant::String) { // this is the case for e.g. sendEvent("...", 'A') // but also works with sendEvent("...", "ABCD") - foreach(const QChar typeChar, arg1.toString()) { + foreach (const QChar typeChar, arg1.toString()) { sendEvent("keydown", typeChar, QVariant(), QString(), modifierArg); sendEvent("keyup", typeChar, QVariant(), QString(), modifierArg); } @@ -1493,10 +1487,7 @@ void WebPage::sendEvent(const QString& type, const QVariant& arg1, const QVarian } // mouse events - if (eventType == "mousedown" || - eventType == "mouseup" || - eventType == "mousemove" || - eventType == "mousedoubleclick") { + if (eventType == "mousedown" || eventType == "mouseup" || eventType == "mousemove" || eventType == "mousedoubleclick") { QMouseEvent::Type mouseEventType = QEvent::None; // Which mouse button (if it's a click) @@ -1562,7 +1553,6 @@ void WebPage::sendEvent(const QString& type, const QVariant& arg1, const QVarian return; } - // mouse click events: Qt doesn't provide this as a separate events, // so we compose it with a mousedown/mouseup sequence // mouse doubleclick events: It is not enough to simply send a @@ -1595,7 +1585,7 @@ QStringList WebPage::pagesWindowName() const { QStringList pagesWindowName; - foreach(const WebPage * p, this->findChildren()) { + foreach (const WebPage* p, this->findChildren()) { pagesWindowName << p->windowName(); } @@ -1637,7 +1627,7 @@ QStringList WebPage::framesName() const { QStringList framesName; - foreach(const QWebFrame * f, m_currentFrame->childFrames()) { + foreach (const QWebFrame* f, m_currentFrame->childFrames()) { framesName << f->frameName(); } return framesName; @@ -1665,15 +1655,15 @@ void WebPage::changeCurrentFrame(QWebFrame* const frame) if (m_currentFrame != m_mainFrame) { disconnect(m_currentFrame, &QWebFrame::destroyed, - this, &WebPage::handleCurrentFrameDestroyed); + this, &WebPage::handleCurrentFrameDestroyed); } m_currentFrame = frame; if (m_currentFrame != m_mainFrame) { connect(m_currentFrame, &QWebFrame::destroyed, - this, &WebPage::handleCurrentFrameDestroyed, - Qt::DirectConnection); + this, &WebPage::handleCurrentFrameDestroyed, + Qt::DirectConnection); } } } diff --git a/src/webpage.h b/src/webpage.h index 4a3e67efde..3559be83ef 100644 --- a/src/webpage.h +++ b/src/webpage.h @@ -32,10 +32,10 @@ #define WEBPAGE_H #include +#include #include -#include #include -#include +#include #include "cookiejar.h" @@ -46,8 +46,7 @@ class NetworkAccessManager; class QWebInspector; class Phantom; -class WebPage : public QObject -{ +class WebPage : public QObject { Q_OBJECT Q_PROPERTY(QString title READ title) Q_PROPERTY(QString frameTitle READ frameTitle) @@ -515,7 +514,8 @@ private slots: void handleCurrentFrameDestroyed(); private: - enum RenderMode { Content, Viewport }; + enum RenderMode { Content, + Viewport }; QImage renderImage(const RenderMode mode = Content); bool renderPdf(QPdfWriter& pdfWriter); void applySettings(const QVariantMap& defaultSettings); diff --git a/src/webserver.cpp b/src/webserver.cpp index 73b9180f56..d82681b46d 100644 --- a/src/webserver.cpp +++ b/src/webserver.cpp @@ -31,20 +31,19 @@ #include "webserver.h" +#include "consts.h" #include "encoding.h" #include "mongoose/mongoose.h" -#include "consts.h" #include +#include #include #include #include #include #include -#include -namespace UrlEncodedParser -{ +namespace UrlEncodedParser { QString unescape(QByteArray in) { @@ -66,7 +65,7 @@ QVariantMap parse(const QByteArray& data) if (data.isEmpty()) { return ret; } - foreach(const QByteArray & part, data.split('&')) { + foreach (const QByteArray& part, data.split('&')) { const int eqPos = part.indexOf('='); if (eqPos == -1) { ret[unescape(part)] = ""; @@ -79,12 +78,11 @@ QVariantMap parse(const QByteArray& data) return ret; } - } static void* callback(mg_event event, - mg_connection* conn, - const mg_request_info* request) + mg_connection* conn, + const mg_request_info* request) { WebServer* server = static_cast(request->user_data); if (server->handleRequest(event, conn, request)) { @@ -114,10 +112,12 @@ bool WebServer::listenOnPort(const QString& port, const QVariantMap& opts) // Create options vector QVector options; - options << "listening_ports" << qstrdup(qPrintable(port)); - options << "enable_directory_listing" << "no"; + options << "listening_ports" << qstrdup(qPrintable(port)); + options << "enable_directory_listing" + << "no"; if (opts.value("keepAlive", false).toBool()) { - options << "enable_keep_alive" << "yes"; + options << "enable_keep_alive" + << "yes"; } options << NULL; @@ -144,7 +144,7 @@ void WebServer::close() // make sure we wake up all pending responses, such that mg_stop() // can be called without deadlocking QMutexLocker lock(&m_mutex); - foreach(WebServerResponse * response, m_pendingResponses) { + foreach (WebServerResponse* response, m_pendingResponses) { response->close(); } } @@ -203,10 +203,10 @@ bool WebServer::handleRequest(mg_event event, mg_connection* conn, const mg_requ // force-encoded in ->uri, and only '#' should be force-encoded // in ->query_string.) QByteArray uri(request->uri); - uri = uri.toPercentEncoding(/*exclude=*/ "!$&'()*+,;=:/[]@"); + uri = uri.toPercentEncoding(/*exclude=*/"!$&'()*+,;=:/[]@"); if (request->query_string) { QByteArray qs(request->query_string); - qs = qs.toPercentEncoding(/*exclude=*/ "!$&'()*+,;=:/[]@?"); + qs = qs.toPercentEncoding(/*exclude=*/"!$&'()*+,;=:/[]@?"); uri.append('?'); uri.append(qs); } @@ -223,7 +223,7 @@ bool WebServer::handleRequest(mg_event event, mg_connection* conn, const mg_requ #endif QVariantMap headersObject; - QMap ciHeadersObject; //< FIXME: "case-insensitive" Headers. This shows how desperately we need a better HTTP Server + QMap ciHeadersObject; //< FIXME: "case-insensitive" Headers. This shows how desperately we need a better HTTP Server for (int i = 0; i < request->num_headers; ++i) { QString key = QString::fromLocal8Bit(request->http_headers[i].name); QString value = QString::fromLocal8Bit(request->http_headers[i].value); @@ -298,7 +298,6 @@ bool WebServer::handleRequest(mg_event event, mg_connection* conn, const mg_requ return true; } - //BEGIN WebServerResponse WebServerResponse::WebServerResponse(mg_connection* conn, QSemaphore* close) diff --git a/src/webserver.h b/src/webserver.h index 7901814c09..f9a0e5bc74 100644 --- a/src/webserver.h +++ b/src/webserver.h @@ -31,9 +31,9 @@ #ifndef WEBSERVER_H #define WEBSERVER_H -#include #include #include +#include #include "mongoose.h" @@ -46,8 +46,7 @@ class WebServerResponse; * * see also: modules/webserver.js */ -class WebServer : public QObject -{ +class WebServer : public QObject { Q_OBJECT Q_PROPERTY(QString port READ port) @@ -91,12 +90,10 @@ public slots: QAtomicInt m_closing; }; - /** * Outgoing HTTP response to client. */ -class WebServerResponse : public QObject -{ +class WebServerResponse : public QObject { Q_OBJECT Q_PROPERTY(int statusCode READ statusCode WRITE setStatusCode)