Improve coding style

This commit is contained in:
Vladimir Golovnev (Glassez)
2020-11-16 10:02:11 +03:00
parent acad35c5bc
commit c41df9ffbd
147 changed files with 4454 additions and 2227 deletions

View File

@@ -181,12 +181,14 @@ Application::Application(int &argc, char **argv)
m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
Logger::instance()->addMessage(tr("qBittorrent %1 started", "qBittorrent v3.2.0alpha started").arg(QBT_VERSION));
if (portableModeEnabled) {
if (portableModeEnabled)
{
Logger::instance()->addMessage(tr("Running in portable mode. Auto detected profile folder at: %1").arg(profileDir));
if (m_commandLineArgs.relativeFastresumePaths)
Logger::instance()->addMessage(tr("Redundant command line flag detected: \"%1\". Portable mode implies relative fastresume.").arg("--relative-fastresume"), Log::WARNING); // to avoid translating the `--relative-fastresume` string
}
else {
else
{
Logger::instance()->addMessage(tr("Using config directory: %1").arg(Profile::instance()->location(SpecialFolder::Config)));
}
}
@@ -361,11 +363,13 @@ void Application::runExternalProgram(const BitTorrent::TorrentHandle *torrent) c
proc.setArguments(argList);
proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments *args)
{
if (Preferences::instance()->isAutoRunConsoleEnabled()) {
if (Preferences::instance()->isAutoRunConsoleEnabled())
{
args->flags |= CREATE_NEW_CONSOLE;
args->flags &= ~(CREATE_NO_WINDOW | DETACHED_PROCESS);
}
else {
else
{
args->flags |= CREATE_NO_WINDOW;
args->flags &= ~(CREATE_NEW_CONSOLE | DETACHED_PROCESS);
}
@@ -428,7 +432,8 @@ void Application::torrentFinished(BitTorrent::TorrentHandle *const torrent)
runExternalProgram(torrent);
// Mail notification
if (pref->isMailNotificationEnabled()) {
if (pref->isMailNotificationEnabled())
{
Logger::instance()->addMessage(tr("Torrent: %1, sending mail notification").arg(torrent->name()));
sendNotificationEmail(torrent);
}
@@ -455,16 +460,19 @@ void Application::allTorrentsFinished()
#ifndef DISABLE_GUI
// ask confirm
if ((action == ShutdownDialogAction::Exit) && (pref->dontConfirmAutoExit())) {
if ((action == ShutdownDialogAction::Exit) && (pref->dontConfirmAutoExit()))
{
// do nothing & skip confirm
}
else {
else
{
if (!ShutdownConfirmDialog::askForConfirmation(m_window, action)) return;
}
#endif // DISABLE_GUI
// Actually shut down
if (action != ShutdownDialogAction::Exit) {
if (action != ShutdownDialogAction::Exit)
{
qDebug("Preparing for auto-shutdown because all downloads are complete!");
// Disabling it for next time
pref->setShutdownWhenDownloadsComplete(false);
@@ -490,7 +498,8 @@ bool Application::sendParams(const QStringList &params)
void Application::processParams(const QStringList &params)
{
#ifndef DISABLE_GUI
if (params.isEmpty()) {
if (params.isEmpty())
{
m_window->activate(); // show UI
return;
}
@@ -498,42 +507,50 @@ void Application::processParams(const QStringList &params)
BitTorrent::AddTorrentParams torrentParams;
TriStateBool skipTorrentDialog;
for (QString param : params) {
for (QString param : params)
{
param = param.trimmed();
// Process strings indicating options specified by the user.
if (param.startsWith(QLatin1String("@savePath="))) {
if (param.startsWith(QLatin1String("@savePath=")))
{
torrentParams.savePath = param.mid(10);
continue;
}
if (param.startsWith(QLatin1String("@addPaused="))) {
if (param.startsWith(QLatin1String("@addPaused=")))
{
torrentParams.addPaused = param.midRef(11).toInt() ? TriStateBool::True : TriStateBool::False;
continue;
}
if (param == QLatin1String("@skipChecking")) {
if (param == QLatin1String("@skipChecking"))
{
torrentParams.skipChecking = true;
continue;
}
if (param.startsWith(QLatin1String("@category="))) {
if (param.startsWith(QLatin1String("@category=")))
{
torrentParams.category = param.mid(10);
continue;
}
if (param == QLatin1String("@sequential")) {
if (param == QLatin1String("@sequential"))
{
torrentParams.sequential = true;
continue;
}
if (param == QLatin1String("@firstLastPiecePriority")) {
if (param == QLatin1String("@firstLastPiecePriority"))
{
torrentParams.firstLastPiecePriority = true;
continue;
}
if (param.startsWith(QLatin1String("@skipDialog="))) {
if (param.startsWith(QLatin1String("@skipDialog=")))
{
skipTorrentDialog = param.midRef(12).toInt() ? TriStateBool::True : TriStateBool::False;
continue;
}
@@ -561,7 +578,8 @@ int Application::exec(const QStringList &params)
Net::DownloadManager::initInstance();
IconProvider::initInstance();
try {
try
{
BitTorrent::Session::initInstance();
connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentFinished, this, &Application::torrentFinished);
connect(BitTorrent::Session::instance(), &BitTorrent::Session::allTorrentsFinished, this, &Application::allTorrentsFinished, Qt::QueuedConnection);
@@ -581,7 +599,8 @@ int Application::exec(const QStringList &params)
new RSS::Session; // create RSS::Session singleton
new RSS::AutoDownloader; // create RSS::AutoDownloader singleton
}
catch (const RuntimeError &err) {
catch (const RuntimeError &err)
{
#ifdef DISABLE_GUI
fprintf(stderr, "%s", err.what());
#else
@@ -605,7 +624,8 @@ int Application::exec(const QStringList &params)
.arg(QString("http://localhost:") + QString::number(pref->getWebUiPort())) + '\n';
printf("%s", qUtf8Printable(mesg));
if (pref->getWebUIPassword() == "ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ==") {
if (pref->getWebUIPassword() == "ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ==")
{
const QString warning = tr("The Web UI administrator username is: %1").arg(pref->getWebUiUsername()) + '\n'
+ tr("The Web UI administrator password is still the default one: %1").arg("adminadmin") + '\n'
+ tr("This is a security risk, please consider changing your password from program preferences.") + '\n';
@@ -623,7 +643,8 @@ int Application::exec(const QStringList &params)
BitTorrent::Session::instance()->startUpTorrents();
m_paramsQueue = params + m_paramsQueue;
if (!m_paramsQueue.isEmpty()) {
if (!m_paramsQueue.isEmpty())
{
processParams(m_paramsQueue);
m_paramsQueue.clear();
}
@@ -639,7 +660,8 @@ bool Application::isRunning()
#ifdef Q_OS_MACOS
bool Application::event(QEvent *ev)
{
if (ev->type() == QEvent::FileOpen) {
if (ev->type() == QEvent::FileOpen)
{
QString path = static_cast<QFileOpenEvent *>(ev)->file();
if (path.isEmpty())
// Get the url instead
@@ -651,7 +673,8 @@ bool Application::event(QEvent *ev)
m_paramsQueue.append(path);
return true;
}
else {
else
{
return BaseApplication::event(ev);
}
}
@@ -679,11 +702,13 @@ void Application::initializeTranslation()
installTranslator(&m_translator);
#ifndef DISABLE_GUI
if (localeStr.startsWith("ar") || localeStr.startsWith("he")) {
if (localeStr.startsWith("ar") || localeStr.startsWith("he"))
{
qDebug("Right to Left mode");
setLayoutDirection(Qt::RightToLeft);
}
else {
else
{
setLayoutDirection(Qt::LeftToRight);
}
#endif
@@ -725,7 +750,8 @@ void Application::cleanup()
return;
#ifndef DISABLE_GUI
if (m_window) {
if (m_window)
{
// Hide the window and don't leave it on screen as
// unresponsive. Also for Windows take the WinId
// after it's hidden, because hide() may cause a
@@ -769,7 +795,8 @@ void Application::cleanup()
Utils::Fs::removeDirRecursive(Utils::Fs::tempPath());
#ifndef DISABLE_GUI
if (m_window) {
if (m_window)
{
#ifdef Q_OS_WIN
::ShutdownBlockReasonDestroy(reinterpret_cast<HWND>(m_window->effectiveWinId()));
#endif // Q_OS_WIN
@@ -780,7 +807,8 @@ void Application::cleanup()
Profile::freeInstance();
if (m_shutdownAct != ShutdownDialogAction::Exit) {
if (m_shutdownAct != ShutdownDialogAction::Exit)
{
qDebug() << "Sending computer shutdown/suspend/hibernate signal...";
Utils::Misc::shutdownComputer(m_shutdownAct);
}

View File

@@ -46,16 +46,20 @@ ApplicationInstanceManager::ApplicationInstanceManager(const QString &appId, QOb
#ifdef Q_OS_WIN
auto sharedMem = new QSharedMemory {appId + QLatin1String {"-shared-memory-key"}, this};
if (m_isFirstInstance) {
if (m_isFirstInstance)
{
// First instance creates shared memory and store PID
if (sharedMem->create(sizeof(DWORD)) && sharedMem->lock()) {
if (sharedMem->create(sizeof(DWORD)) && sharedMem->lock())
{
*(static_cast<DWORD *>(sharedMem->data())) = ::GetCurrentProcessId();
sharedMem->unlock();
}
}
else {
else
{
// Later instances attach to shared memory and retrieve PID
if (sharedMem->attach() && sharedMem->lock()) {
if (sharedMem->attach() && sharedMem->lock())
{
::AllowSetForegroundWindow(*(static_cast<DWORD *>(sharedMem->data())));
sharedMem->unlock();
}

View File

@@ -217,7 +217,8 @@ namespace
bool ok;
int res = val.toInt(&ok);
if (!ok) {
if (!ok)
{
qDebug() << QObject::tr("Expected integer number in environment variable '%1', but got '%2'")
.arg(envVarName(), val);
return defaultValue;
@@ -257,16 +258,20 @@ namespace
{
QStringList parts = arg.split(QLatin1Char('='));
if (parts.size() == 1) {
if (parts.size() == 1)
{
return TriStateBool(m_defaultValue);
}
if (parts.size() == 2) {
if (parts.size() == 2)
{
QString val = parts[1];
if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) {
if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1")))
{
return TriStateBool::True;
}
if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) {
if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0")))
{
return TriStateBool::False;
}
}
@@ -281,16 +286,20 @@ namespace
{
const QString val = env.value(envVarName(), "-1");
if (val.isEmpty()) {
if (val.isEmpty())
{
return TriStateBool(m_defaultValue);
}
if (val == QLatin1String("-1")) {
if (val == QLatin1String("-1"))
{
return TriStateBool::Undefined;
}
if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1"))) {
if ((val.toUpper() == QLatin1String("TRUE")) || (val == QLatin1String("1")))
{
return TriStateBool::True;
}
if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0"))) {
if ((val.toUpper() == QLatin1String("FALSE")) || (val == QLatin1String("0")))
{
return TriStateBool::False;
}
@@ -365,10 +374,12 @@ QStringList QBtCommandLineParameters::paramList() const
if (!savePath.isEmpty())
result.append(QLatin1String("@savePath=") + savePath);
if (addPaused == TriStateBool::True) {
if (addPaused == TriStateBool::True)
{
result.append(QLatin1String("@addPaused=1"));
}
else if (addPaused == TriStateBool::False) {
else if (addPaused == TriStateBool::False)
{
result.append(QLatin1String("@addPaused=0"));
}
@@ -384,10 +395,12 @@ QStringList QBtCommandLineParameters::paramList() const
if (firstLastPiecePriority)
result.append(QLatin1String("@firstLastPiecePriority"));
if (skipDialog == TriStateBool::True) {
if (skipDialog == TriStateBool::True)
{
result.append(QLatin1String("@skipDialog=1"));
}
else if (skipDialog == TriStateBool::False) {
else if (skipDialog == TriStateBool::False)
{
result.append(QLatin1String("@skipDialog=0"));
}
@@ -399,72 +412,91 @@ QBtCommandLineParameters parseCommandLine(const QStringList &args)
{
QBtCommandLineParameters result {QProcessEnvironment::systemEnvironment()};
for (int i = 1; i < args.count(); ++i) {
for (int i = 1; i < args.count(); ++i)
{
const QString &arg = args[i];
if ((arg.startsWith("--") && !arg.endsWith(".torrent"))
|| (arg.startsWith('-') && (arg.size() == 2))) {
|| (arg.startsWith('-') && (arg.size() == 2)))
{
// Parse known parameters
if (arg == SHOW_HELP_OPTION) {
if (arg == SHOW_HELP_OPTION)
{
result.showHelp = true;
}
#if !defined(Q_OS_WIN) || defined(DISABLE_GUI)
else if (arg == SHOW_VERSION_OPTION) {
else if (arg == SHOW_VERSION_OPTION)
{
result.showVersion = true;
}
#endif
else if (arg == WEBUI_PORT_OPTION) {
else if (arg == WEBUI_PORT_OPTION)
{
result.webUiPort = WEBUI_PORT_OPTION.value(arg);
if ((result.webUiPort < 1) || (result.webUiPort > 65535))
throw CommandLineParameterError(QObject::tr("%1 must specify a valid port (1 to 65535).")
.arg(QLatin1String("--webui-port")));
}
#ifndef DISABLE_GUI
else if (arg == NO_SPLASH_OPTION) {
else if (arg == NO_SPLASH_OPTION)
{
result.noSplash = true;
}
#elif !defined(Q_OS_WIN)
else if (arg == DAEMON_OPTION) {
else if (arg == DAEMON_OPTION)
{
result.shouldDaemonize = true;
}
#endif
else if (arg == PROFILE_OPTION) {
else if (arg == PROFILE_OPTION)
{
result.profileDir = PROFILE_OPTION.value(arg);
}
else if (arg == RELATIVE_FASTRESUME) {
else if (arg == RELATIVE_FASTRESUME)
{
result.relativeFastresumePaths = true;
}
else if (arg == CONFIGURATION_OPTION) {
else if (arg == CONFIGURATION_OPTION)
{
result.configurationName = CONFIGURATION_OPTION.value(arg);
}
else if (arg == SAVE_PATH_OPTION) {
else if (arg == SAVE_PATH_OPTION)
{
result.savePath = SAVE_PATH_OPTION.value(arg);
}
else if (arg == PAUSED_OPTION) {
else if (arg == PAUSED_OPTION)
{
result.addPaused = PAUSED_OPTION.value(arg);
}
else if (arg == SKIP_HASH_CHECK_OPTION) {
else if (arg == SKIP_HASH_CHECK_OPTION)
{
result.skipChecking = true;
}
else if (arg == CATEGORY_OPTION) {
else if (arg == CATEGORY_OPTION)
{
result.category = CATEGORY_OPTION.value(arg);
}
else if (arg == SEQUENTIAL_OPTION) {
else if (arg == SEQUENTIAL_OPTION)
{
result.sequential = true;
}
else if (arg == FIRST_AND_LAST_OPTION) {
else if (arg == FIRST_AND_LAST_OPTION)
{
result.firstLastPiecePriority = true;
}
else if (arg == SKIP_DIALOG_OPTION) {
else if (arg == SKIP_DIALOG_OPTION)
{
result.skipDialog = SKIP_DIALOG_OPTION.value(arg);
}
else {
else
{
// Unknown argument
result.unknownParameter = arg;
break;
}
}
else {
else
{
QFileInfo torrentPath;
torrentPath.setFile(arg);
@@ -495,11 +527,14 @@ QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN
QStringList lines = {words.first()};
int currentLineMaxLength = wrapAtColumn - initialIndentation;
for (const QString &word : asConst(words.mid(1))) {
if (lines.last().length() + word.length() + 1 < currentLineMaxLength) {
for (const QString &word : asConst(words.mid(1)))
{
if (lines.last().length() + word.length() + 1 < currentLineMaxLength)
{
lines.last().append(' ' + word);
}
else {
else
{
lines.append(QString(initialIndentation, ' ') + word);
currentLineMaxLength = wrapAtColumn;
}

View File

@@ -73,7 +73,8 @@ void FileLogger::changePath(const QString &newPath)
dir.mkpath(newPath);
const QString tmpPath = dir.absoluteFilePath("qbittorrent.log");
if (tmpPath != m_path) {
if (tmpPath != m_path)
{
m_path = tmpPath;
closeLogFile();
@@ -89,9 +90,11 @@ void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
const QFileInfoList fileList = dir.entryInfoList(QStringList("qbittorrent.log.bak*")
, (QDir::Files | QDir::Writable), (QDir::Time | QDir::Reversed));
for (const QFileInfo &file : fileList) {
for (const QFileInfo &file : fileList)
{
QDateTime modificationDate = file.lastModified();
switch (ageType) {
switch (ageType)
{
case DAYS:
modificationDate = modificationDate.addDays(age);
break;
@@ -124,7 +127,8 @@ void FileLogger::addLogMessage(const Log::Msg &msg)
QTextStream stream(&m_logFile);
stream.setCodec("UTF-8");
switch (msg.type) {
switch (msg.type)
{
case Log::INFO:
stream << "(I) ";
break;
@@ -140,12 +144,14 @@ void FileLogger::addLogMessage(const Log::Msg &msg)
stream << QDateTime::fromMSecsSinceEpoch(msg.timestamp).toString(Qt::ISODate) << " - " << msg.message << '\n';
if (m_backup && (m_logFile.size() >= m_maxSize)) {
if (m_backup && (m_logFile.size() >= m_maxSize))
{
closeLogFile();
int counter = 0;
QString backupLogFilename = m_path + ".bak";
while (QFile::exists(backupLogFilename)) {
while (QFile::exists(backupLogFilename))
{
++counter;
backupLogFilename = m_path + ".bak" + QString::number(counter);
}
@@ -153,7 +159,8 @@ void FileLogger::addLogMessage(const Log::Msg &msg)
QFile::rename(m_path, backupLogFilename);
openLogFile();
}
else {
else
{
if (!m_flusher.isActive())
m_flusher.start();
}
@@ -168,7 +175,8 @@ void FileLogger::flushLog()
void FileLogger::openLogFile()
{
if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)
|| !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner)) {
|| !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner))
{
m_logFile.close();
LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled."), Log::CRITICAL);
}

View File

@@ -92,7 +92,8 @@ void sigNormalHandler(int signum);
void sigAbnormalHandler(int signum);
#endif
// sys_signame[] is only defined in BSD
const char *const sysSigName[] = {
const char *const sysSigName[] =
{
#if defined(Q_OS_WIN)
"", "", "SIGINT", "", "SIGILL", "", "SIGABRT_COMPAT", "", "SIGFPE", "",
"", "SIGSEGV", "", "", "", "SIGTERM", "", "", "", "",
@@ -141,19 +142,23 @@ int main(int argc, char *argv[])
Application::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
#endif
try {
try
{
// Create Application
auto app = std::make_unique<Application>(argc, argv);
const QBtCommandLineParameters params = app->commandLineArgs();
if (!params.unknownParameter.isEmpty()) {
if (!params.unknownParameter.isEmpty())
{
throw CommandLineParameterError(QObject::tr("%1 is an unknown command line parameter.",
"--random-parameter is an unknown command line parameter.")
.arg(params.unknownParameter));
}
#if !defined(Q_OS_WIN) || defined(DISABLE_GUI)
if (params.showVersion) {
if (isOneArg) {
if (params.showVersion)
{
if (isOneArg)
{
displayVersion();
return EXIT_SUCCESS;
}
@@ -161,8 +166,10 @@ int main(int argc, char *argv[])
.arg(QLatin1String("-v (or --version)")));
}
#endif
if (params.showHelp) {
if (isOneArg) {
if (params.showHelp)
{
if (isOneArg)
{
displayUsage(argv[0]);
return EXIT_SUCCESS;
}
@@ -175,7 +182,8 @@ int main(int argc, char *argv[])
fprintf(stderr, "Couldn't set environment variable...\n");
const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal();
if (firstTimeUser) {
if (firstTimeUser)
{
#ifndef DISABLE_GUI
if (!userAgreesWithLegalNotice())
return EXIT_SUCCESS;
@@ -195,9 +203,11 @@ int main(int argc, char *argv[])
}
// Check if qBittorrent is already running for this user
if (app->isRunning()) {
if (app->isRunning())
{
#if defined(DISABLE_GUI) && !defined(Q_OS_WIN)
if (params.shouldDaemonize) {
if (params.shouldDaemonize)
{
throw CommandLineParameterError(QObject::tr("You cannot use %1: qBittorrent is already running for this user.")
.arg(QLatin1String("-d (or --daemon)")));
}
@@ -242,7 +252,8 @@ int main(int argc, char *argv[])
app->setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
if (!firstTimeUser) {
if (!firstTimeUser)
{
handleChangedDefaults(DefaultPreferencesMode::Legacy);
#ifndef DISABLE_GUI
@@ -256,21 +267,26 @@ int main(int argc, char *argv[])
&& isatty(fileno(stdout)))) return EXIT_FAILURE;
#endif
}
else {
else
{
handleChangedDefaults(DefaultPreferencesMode::Current);
}
#if defined(DISABLE_GUI) && !defined(Q_OS_WIN)
if (params.shouldDaemonize) {
if (params.shouldDaemonize)
{
app.reset(); // Destroy current application
if (daemon(1, 0) == 0) {
if (daemon(1, 0) == 0)
{
app = std::make_unique<Application>(argc, argv);
if (app->isRunning()) {
if (app->isRunning())
{
// Another instance had time to start.
return EXIT_FAILURE;
}
}
else {
else
{
qCritical("Something went wrong while daemonizing, exiting...");
return EXIT_FAILURE;
}
@@ -289,7 +305,8 @@ int main(int argc, char *argv[])
return app->exec(params.paramList());
}
catch (const CommandLineParameterError &er) {
catch (const CommandLineParameterError &er)
{
displayBadArgMessage(er.messageForUser());
return EXIT_FAILURE;
}
@@ -300,10 +317,12 @@ void reportToUser(const char *str)
{
const size_t strLen = strlen(str);
#ifndef Q_OS_WIN
if (write(STDERR_FILENO, str, strLen) < static_cast<ssize_t>(strLen)) {
if (write(STDERR_FILENO, str, strLen) < static_cast<ssize_t>(strLen))
{
const auto dummy = write(STDOUT_FILENO, str, strLen);
#else
if (_write(STDERR_FILENO, str, strLen) < static_cast<ssize_t>(strLen)) {
if (_write(STDERR_FILENO, str, strLen) < static_cast<ssize_t>(strLen))
{
const auto dummy = _write(STDOUT_FILENO, str, strLen);
#endif
Q_UNUSED(dummy);
@@ -405,7 +424,8 @@ bool userAgreesWithLegalNotice()
printf("%s", qUtf8Printable(eula));
const char ret = getchar(); // Read pressed key
if ((ret == 'y') || (ret == 'Y')) {
if ((ret == 'y') || (ret == 'Y'))
{
// Save the answer
pref->setAcceptedLegal(true);
return true;
@@ -419,7 +439,8 @@ bool userAgreesWithLegalNotice()
msgBox.show(); // Need to be shown or to moveToCenter does not work
msgBox.move(Utils::Gui::screenCenter(&msgBox));
msgBox.exec();
if (msgBox.clickedButton() == agreeButton) {
if (msgBox.clickedButton() == agreeButton)
{
// Save the answer
pref->setAcceptedLegal(true);
return true;

View File

@@ -100,7 +100,8 @@ QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
, id(appId)
{
QString prefix = id;
if (id.isEmpty()) {
if (id.isEmpty())
{
id = QCoreApplication::applicationFilePath();
#if defined(Q_OS_WIN)
id = id.toLower();
@@ -143,7 +144,8 @@ bool QtLocalPeer::isClient()
bool res = server->listen(socketName);
#if defined(Q_OS_UNIX)
// ### Workaround
if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
if (!res && server->serverError() == QAbstractSocket::AddressInUseError)
{
QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
res = server->listen(socketName);
}
@@ -161,7 +163,8 @@ bool QtLocalPeer::sendMessage(const QString &message, const int timeout)
QLocalSocket socket;
bool connOk = false;
for(int i = 0; i < 2; i++) {
for(int i = 0; i < 2; i++)
{
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout/2);
@@ -182,7 +185,8 @@ bool QtLocalPeer::sendMessage(const QString &message, const int timeout)
QDataStream ds(&socket);
ds.writeBytes(uMsg.constData(), uMsg.size());
bool res = socket.waitForBytesWritten(timeout);
if (res) {
if (res)
{
res &= socket.waitForReadyRead(timeout); // wait for ack
if (res)
res &= (socket.read(qstrlen(ack)) == ack);
@@ -201,8 +205,10 @@ void QtLocalPeer::receiveConnection()
if (!socket)
return;
while (true) {
if (socket->state() == QLocalSocket::UnconnectedState) {
while (true)
{
if (socket->state() == QLocalSocket::UnconnectedState)
{
qWarning("QtLocalPeer: Peer disconnected");
delete socket;
return;
@@ -216,7 +222,8 @@ void QtLocalPeer::receiveConnection()
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
if (remaining > 65535) {
if (remaining > 65535)
{
// drop suspiciously large data
delete socket;
return;
@@ -225,12 +232,14 @@ void QtLocalPeer::receiveConnection()
uMsg.resize(remaining);
int got = 0;
char* uMsgBuf = uMsg.data();
do {
do
{
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000));
if (got < 0) {
if (got < 0)
{
qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
delete socket;
return;

View File

@@ -22,7 +22,8 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames
// retrieve current stack addresses
int addrlen = backtrace(addrlist.data(), addrlist.size());
if (addrlen == 0) {
if (addrlen == 0)
{
fprintf(out, " <empty, possibly corrupt>\n");
return;
}
@@ -38,27 +39,33 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames
int functionNamesFound = 0;
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (int i = 2; i < addrlen; i++) {
for (int i = 2; i < addrlen; i++)
{
char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
// find parentheses and +address offset surrounding the mangled name:
// ./module(function+0x15c) [0x8048a6d]
// fprintf(out, "%s TT\n", symbollist[i]);
for (char *p = symbollist[i]; *p; ++p) {
if (*p == '(') {
for (char *p = symbollist[i]; *p; ++p)
{
if (*p == '(')
{
begin_name = p;
}
else if (*p == '+') {
else if (*p == '+')
{
begin_offset = p;
}
else if ((*p == ')') && begin_offset) {
else if ((*p == ')') && begin_offset)
{
end_offset = p;
break;
}
}
if (begin_name && begin_offset && end_offset
&& (begin_name < begin_offset)) {
&& (begin_name < begin_offset))
{
*begin_name++ = '\0';
*begin_offset++ = '\0';
*end_offset = '\0';
@@ -70,12 +77,14 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames
int status;
char *ret = abi::__cxa_demangle(begin_name,
funcname, &funcnamesize, &status);
if (status == 0) {
if (status == 0)
{
funcname = ret; // use possibly realloc()-ed string
fprintf(out, " %s : %s+%s %s\n",
symbollist[i], funcname, begin_offset, ++end_offset);
}
else {
else
{
// demangling failed. Output function name as a C function with
// no arguments.
fprintf(out, " %s : %s()+%s %s\n",
@@ -83,17 +92,20 @@ static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames
}
++functionNamesFound;
}
else {
else
{
// couldn't parse the line? print the whole line.
fprintf(out, " %s\n", symbollist[i]);
}
}
if (!functionNamesFound) {
if (!functionNamesFound)
{
fprintf(out, "There were no function names found in the stack trace\n."
"Seems like debug symbols are not installed, and the stack trace is useless.\n");
}
if (functionNamesFound < addrlen - 2) {
if (functionNamesFound < addrlen - 2)
{
fprintf(out, "Consider installing debug symbols for packages containing files with empty"
" function names (i.e. empty braces \"()\") to make your stack trace more useful\n");
}

View File

@@ -54,7 +54,8 @@ void straceWin::demangle(QString& str)
int status = 0;
size_t outSz = 0;
char* demangled_name = abi::__cxa_demangle(inStr, 0, &outSz, &status);
if (status == 0) {
if (status == 0)
{
str = QString::fromLocal8Bit(demangled_name);
if (outSz > 0)
free(demangled_name);
@@ -92,7 +93,8 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO
IMAGEHLP_MODULE64 mod;
EnumModulesContext* context = (EnumModulesContext*)UserContext;
mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if(SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod)) {
if(SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod))
{
QString moduleBase = QString::fromLatin1("0x%1").arg(BaseOfDll, 16, 16, QLatin1Char('0'));
QString line = QString::fromLatin1("%1 %2 Image: %3")
.arg(mod.ModuleName, -25)
@@ -101,7 +103,8 @@ BOOL CALLBACK straceWin::EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVO
context->stream << line << '\n';
QString pdbName(mod.LoadedPdbName);
if(!pdbName.isEmpty()) {
if(!pdbName.isEmpty())
{
QString line2 = QString::fromLatin1("%1 %2")
.arg("", 35)
.arg(pdbName);
@@ -126,7 +129,8 @@ bool straceWin::makeRelativePath(const QString& dir, QString& file)
if (!d.isEmpty() && (d[d.length() - 1] != separator))
d += separator;
if (f.startsWith(d, Qt::CaseInsensitive)) {
if (f.startsWith(d, Qt::CaseInsensitive))
{
f.remove(0, d.length());
file.swap(f);
@@ -142,7 +146,8 @@ QString straceWin::getSourcePathAndLineNumber(HANDLE hProcess, DWORD64 addr)
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
DWORD dwDisplacement = 0;
if (SymGetLineFromAddr64(hProcess, addr, &dwDisplacement, &line)) {
if (SymGetLineFromAddr64(hProcess, addr, &dwDisplacement, &line))
{
QString path(line.FileName);
#if defined STACKTRACE_WIN_PROJECT_PATH || defined STACKTRACE_WIN_MAKEFILE_PATH
@@ -159,7 +164,8 @@ QString straceWin::getSourcePathAndLineNumber(HANDLE hProcess, DWORD64 addr)
#endif
#ifdef STACKTRACE_WIN_MAKEFILE_PATH
if (!success) {
if (!success)
{
QString targetPath(STACKTRACE_WIN_STRING(STACKTRACE_WIN_MAKEFILE_PATH));
makeRelativePath(targetPath, path);
}
@@ -201,7 +207,8 @@ const QString straceWin::getBacktrace()
: //no input
: "eax");
#else
_asm {
_asm
{
Label:
mov [Context.Ebp], ebp;
mov [Context.Esp], esp;
@@ -269,15 +276,18 @@ const QString straceWin::getBacktrace()
int i = 0;
while(StackWalk64(MachineType, hProcess, hThread, &StackFrame, &Context, NULL, NULL, NULL, NULL)) {
while(StackWalk64(MachineType, hProcess, hThread, &StackFrame, &Context, NULL, NULL, NULL, NULL))
{
if(i == 128)
break;
loadHelpStackFrame(ihsf, StackFrame);
if(StackFrame.AddrPC.Offset != 0) { // Valid frame.
if(StackFrame.AddrPC.Offset != 0)
{ // Valid frame.
QString fileName("???");
if(SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod)) {
if(SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod))
{
fileName = QString(mod.ImageName);
int slashPos = fileName.lastIndexOf('\\');
if(slashPos != -1)
@@ -285,7 +295,8 @@ const QString straceWin::getBacktrace()
}
QString funcName;
QString sourceFile;
if(SymFromAddr(hProcess, ihsf.InstructionOffset, &dwDisplacement, pSymbol)) {
if(SymFromAddr(hProcess, ihsf.InstructionOffset, &dwDisplacement, pSymbol))
{
funcName = QString(pSymbol->Name);
#ifdef __MINGW32__
demangle(funcName);
@@ -295,7 +306,8 @@ const QString straceWin::getBacktrace()
// decrease the query address by one byte to point somewhere in the CALL instruction byte sequence
sourceFile = getSourcePathAndLineNumber(hProcess, ihsf.InstructionOffset - 1);
}
else {
else
{
funcName = QString::fromLatin1("0x%1").arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0'));
}
SymSetContext(hProcess, &ihsf, NULL);
@@ -325,7 +337,8 @@ const QString straceWin::getBacktrace()
logStream << debugLine << '\n';
i++;
}
else {
else
{
break; // we're at the end.
}
}

View File

@@ -39,7 +39,8 @@ namespace
{
void exportWebUIHttpsFiles()
{
const auto migrate = [](const QString &oldKey, const QString &newKey, const QString &savePath) {
const auto migrate = [](const QString &oldKey, const QString &newKey, const QString &savePath)
{
SettingsStorage *settingsStorage {SettingsStorage::instance()};
const QByteArray oldData {settingsStorage->loadValue(oldKey).toByteArray()};
const QString newData {settingsStorage->loadValue(newKey).toString()};
@@ -49,11 +50,13 @@ namespace
return;
QFile file(savePath);
if (!file.open(QIODevice::WriteOnly)) {
if (!file.open(QIODevice::WriteOnly))
{
LogMsg(errorMsgFormat.arg(savePath, file.errorString()) , Log::WARNING);
return;
}
if (file.write(oldData) != oldData.size()) {
if (file.write(oldData) != oldData.size())
{
file.close();
Utils::Fs::forceRemove(savePath);
LogMsg(errorMsgFormat.arg(savePath, QLatin1String("Write incomplete.")) , Log::WARNING);
@@ -92,12 +95,14 @@ void handleChangedDefaults(const DefaultPreferencesMode mode)
QVariant current;
};
const QVector<DefaultValue> changedDefaults {
const QVector<DefaultValue> changedDefaults
{
{QLatin1String {"BitTorrent/Session/QueueingSystemEnabled"}, true, false}
};
SettingsStorage *settingsStorage {SettingsStorage::instance()};
for (auto it = changedDefaults.cbegin(); it != changedDefaults.cend(); ++it) {
for (auto it = changedDefaults.cbegin(); it != changedDefaults.cend(); ++it)
{
if (settingsStorage->loadValue(it->name).isNull())
settingsStorage->storeValue(it->name, (mode == DefaultPreferencesMode::Legacy ? it->legacy : it->current));
}