From c8d0f788e00bdae125a26d9159ce9efdd6325cd2 Mon Sep 17 00:00:00 2001 From: Christian Kamm Date: Wed, 17 May 2017 10:55:42 +0200 Subject: [PATCH] Apply clang-format --- src/cmd/cmd.cpp | 184 ++--- src/cmd/cmd.h | 11 +- src/cmd/netrcparser.cpp | 17 +- src/cmd/simplesslerrorhandler.cpp | 9 +- src/cmd/simplesslerrorhandler.h | 4 +- src/crashreporter/main.cpp | 77 ++- src/gui/accountmanager.cpp | 81 +-- src/gui/accountmanager.h | 18 +- src/gui/accountsettings.cpp | 253 +++---- src/gui/accountsettings.h | 20 +- src/gui/accountstate.cpp | 51 +- src/gui/accountstate.h | 16 +- src/gui/activitydata.cpp | 18 +- src/gui/activitydata.h | 26 +- src/gui/activityitemdelegate.cpp | 88 +-- src/gui/activityitemdelegate.h | 26 +- src/gui/activitylistmodel.cpp | 68 +- src/gui/activitylistmodel.h | 24 +- src/gui/activitywidget.cpp | 240 ++++--- src/gui/activitywidget.h | 40 +- src/gui/addcertificatedialog.cpp | 7 +- src/gui/addcertificatedialog.h | 5 +- src/gui/application.cpp | 200 +++--- src/gui/application.h | 18 +- src/gui/authenticationdialog.cpp | 2 +- src/gui/authenticationdialog.h | 4 +- src/gui/cocoainitializer.h | 20 +- src/gui/creds/credentialsfactory.cpp | 32 +- src/gui/creds/credentialsfactory.h | 8 +- src/gui/creds/httpcredentialsgui.cpp | 16 +- src/gui/creds/httpcredentialsgui.h | 17 +- .../creds/shibboleth/shibbolethuserjob.cpp | 7 +- src/gui/creds/shibboleth/shibbolethuserjob.h | 9 +- .../creds/shibboleth/shibbolethwebview.cpp | 38 +- src/gui/creds/shibboleth/shibbolethwebview.h | 33 +- src/gui/creds/shibbolethcredentials.cpp | 75 +- src/gui/creds/shibbolethcredentials.h | 21 +- src/gui/folder.cpp | 296 ++++---- src/gui/folder.h | 146 ++-- src/gui/folderman.cpp | 575 ++++++++-------- src/gui/folderman.h | 89 ++- src/gui/folderstatusdelegate.cpp | 195 +++--- src/gui/folderstatusdelegate.h | 38 +- src/gui/folderstatusmodel.cpp | 434 ++++++------ src/gui/folderstatusmodel.h | 78 ++- src/gui/folderwatcher.cpp | 30 +- src/gui/folderwatcher.h | 17 +- src/gui/folderwatcher_linux.cpp | 80 +-- src/gui/folderwatcher_linux.h | 12 +- src/gui/folderwatcher_mac.cpp | 56 +- src/gui/folderwatcher_mac.h | 5 +- src/gui/folderwatcher_win.cpp | 58 +- src/gui/folderwatcher_win.h | 28 +- src/gui/folderwizard.cpp | 154 ++--- src/gui/folderwizard.h | 37 +- src/gui/generalsettings.cpp | 27 +- src/gui/generalsettings.h | 3 +- src/gui/ignorelisteditor.cpp | 26 +- src/gui/ignorelisteditor.h | 6 +- src/gui/lockwatcher.cpp | 8 +- src/gui/lockwatcher.h | 7 +- src/gui/logbrowser.cpp | 74 +- src/gui/logbrowser.h | 14 +- src/gui/main.cpp | 50 +- src/gui/networksettings.cpp | 31 +- src/gui/networksettings.h | 2 +- src/gui/notificationconfirmjob.cpp | 24 +- src/gui/notificationconfirmjob.h | 9 +- src/gui/notificationwidget.cpp | 41 +- src/gui/notificationwidget.h | 13 +- src/gui/ocsjob.cpp | 29 +- src/gui/ocsjob.h | 13 +- src/gui/ocsshareejob.cpp | 10 +- src/gui/ocsshareejob.h | 8 +- src/gui/ocssharejob.cpp | 19 +- src/gui/ocssharejob.h | 29 +- src/gui/openfilemanager.cpp | 28 +- src/gui/owncloudgui.cpp | 345 +++++----- src/gui/owncloudgui.h | 22 +- src/gui/owncloudsetupwizard.cpp | 210 +++--- src/gui/owncloudsetupwizard.h | 31 +- src/gui/protocolwidget.cpp | 111 ++- src/gui/protocolwidget.h | 19 +- src/gui/proxyauthdialog.cpp | 6 +- src/gui/proxyauthdialog.h | 4 +- src/gui/proxyauthhandler.cpp | 31 +- src/gui/proxyauthhandler.h | 10 +- src/gui/quotainfo.cpp | 16 +- src/gui/quotainfo.h | 6 +- src/gui/selectivesyncdialog.cpp | 127 ++-- src/gui/selectivesyncdialog.h | 25 +- src/gui/servernotificationhandler.cpp | 53 +- src/gui/servernotificationhandler.h | 8 +- src/gui/settingsdialog.cpp | 100 +-- src/gui/settingsdialog.h | 19 +- src/gui/settingsdialogmac.cpp | 35 +- src/gui/settingsdialogmac.h | 8 +- src/gui/sharedialog.cpp | 52 +- src/gui/sharedialog.h | 14 +- src/gui/sharee.cpp | 62 +- src/gui/sharee.h | 14 +- src/gui/sharelinkwidget.cpp | 86 ++- src/gui/sharelinkwidget.h | 21 +- src/gui/sharemanager.cpp | 129 ++-- src/gui/sharemanager.h | 77 ++- src/gui/sharepermissions.h | 10 +- src/gui/shareusergroupwidget.cpp | 101 ++- src/gui/shareusergroupwidget.h | 28 +- src/gui/socketapi.cpp | 167 ++--- src/gui/socketapi.h | 29 +- src/gui/sslbutton.cpp | 41 +- src/gui/sslbutton.h | 6 +- src/gui/sslerrordialog.cpp | 110 +-- src/gui/sslerrordialog.h | 18 +- src/gui/synclogdialog.cpp | 14 +- src/gui/synclogdialog.h | 4 +- src/gui/syncrunfilelog.cpp | 38 +- src/gui/syncrunfilelog.h | 13 +- src/gui/systray.cpp | 9 +- src/gui/systray.h | 2 +- src/gui/thumbnailjob.cpp | 5 +- src/gui/thumbnailjob.h | 6 +- src/gui/tooltipupdater.cpp | 18 +- src/gui/tooltipupdater.h | 8 +- src/gui/updater/ocupdater.cpp | 92 ++- src/gui/updater/ocupdater.h | 39 +- src/gui/updater/sparkleupdater.h | 6 +- src/gui/updater/updateinfo.cpp | 216 +++--- src/gui/updater/updateinfo.h | 22 +- src/gui/updater/updater.cpp | 32 +- src/gui/updater/updater.h | 13 +- src/gui/wizard/abstractcredswizardpage.cpp | 3 +- src/gui/wizard/abstractcredswizardpage.h | 5 +- src/gui/wizard/owncloudadvancedsetuppage.cpp | 65 +- src/gui/wizard/owncloudadvancedsetuppage.h | 62 +- .../wizard/owncloudconnectionmethoddialog.cpp | 11 +- .../wizard/owncloudconnectionmethoddialog.h | 5 +- src/gui/wizard/owncloudhttpcredspage.cpp | 51 +- src/gui/wizard/owncloudhttpcredspage.h | 36 +- src/gui/wizard/owncloudsetuppage.cpp | 111 ++- src/gui/wizard/owncloudsetuppage.h | 78 +-- .../wizard/owncloudshibbolethcredspage.cpp | 24 +- src/gui/wizard/owncloudshibbolethcredspage.h | 28 +- src/gui/wizard/owncloudwizard.cpp | 101 +-- src/gui/wizard/owncloudwizard.h | 39 +- src/gui/wizard/owncloudwizardcommon.cpp | 69 +- src/gui/wizard/owncloudwizardcommon.h | 54 +- src/gui/wizard/owncloudwizardresultpage.cpp | 30 +- src/gui/wizard/owncloudwizardresultpage.h | 28 +- src/gui/wizard/postfixlineedit.cpp | 11 +- src/gui/wizard/postfixlineedit.h | 3 +- src/libsync/abstractnetworkjob.cpp | 63 +- src/libsync/abstractnetworkjob.h | 48 +- src/libsync/accessmanager.cpp | 15 +- src/libsync/accessmanager.h | 9 +- src/libsync/account.cpp | 58 +- src/libsync/account.h | 41 +- src/libsync/asserts.h | 35 +- src/libsync/bandwidthmanager.cpp | 121 ++-- src/libsync/bandwidthmanager.h | 22 +- src/libsync/capabilities.cpp | 13 +- src/libsync/capabilities.h | 7 +- src/libsync/checksums.cpp | 57 +- src/libsync/checksums.h | 31 +- src/libsync/clientproxy.cpp | 27 +- src/libsync/clientproxy.h | 8 +- src/libsync/configfile.cpp | 249 +++---- src/libsync/configfile.h | 56 +- src/libsync/connectionvalidator.cpp | 77 ++- src/libsync/connectionvalidator.h | 15 +- src/libsync/cookiejar.cpp | 23 +- src/libsync/cookiejar.h | 3 +- src/libsync/creds/abstractcredentials.cpp | 11 +- src/libsync/creds/abstractcredentials.h | 9 +- src/libsync/creds/credentialscommon.cpp | 3 +- src/libsync/creds/credentialscommon.h | 3 +- src/libsync/creds/dummycredentials.cpp | 8 +- src/libsync/creds/dummycredentials.h | 8 +- src/libsync/creds/httpcredentials.cpp | 103 +-- src/libsync/creds/httpcredentials.h | 24 +- src/libsync/creds/tokencredentials.cpp | 57 +- src/libsync/creds/tokencredentials.h | 9 +- src/libsync/discoveryphase.cpp | 233 ++++--- src/libsync/discoveryphase.h | 105 +-- src/libsync/excludedfiles.cpp | 20 +- src/libsync/excludedfiles.h | 14 +- src/libsync/filesystem.cpp | 192 +++--- src/libsync/filesystem.h | 110 ++- src/libsync/logger.cpp | 92 +-- src/libsync/logger.h | 89 ++- src/libsync/networkjobs.cpp | 160 +++-- src/libsync/networkjobs.h | 53 +- src/libsync/owncloudpropagator.cpp | 251 ++++--- src/libsync/owncloudpropagator.h | 161 +++-- src/libsync/owncloudpropagator_p.h | 17 +- src/libsync/owncloudtheme.cpp | 35 +- src/libsync/owncloudtheme.h | 11 +- src/libsync/ownsql.cpp | 124 ++-- src/libsync/ownsql.h | 19 +- src/libsync/progressdispatcher.cpp | 117 ++-- src/libsync/progressdispatcher.h | 35 +- src/libsync/propagatedownload.cpp | 265 ++++---- src/libsync/propagatedownload.h | 52 +- src/libsync/propagateremotedelete.cpp | 41 +- src/libsync/propagateremotedelete.h | 19 +- src/libsync/propagateremotemkdir.cpp | 25 +- src/libsync/propagateremotemkdir.h | 11 +- src/libsync/propagateremotemove.cpp | 62 +- src/libsync/propagateremotemove.h | 21 +- src/libsync/propagateupload.cpp | 149 ++-- src/libsync/propagateupload.h | 132 ++-- src/libsync/propagateuploadng.cpp | 95 ++- src/libsync/propagateuploadv1.cpp | 63 +- src/libsync/propagatorjobs.cpp | 48 +- src/libsync/propagatorjobs.h | 28 +- src/libsync/syncengine.cpp | 607 +++++++++-------- src/libsync/syncengine.h | 38 +- src/libsync/syncfileitem.h | 129 ++-- src/libsync/syncfilestatus.cpp | 12 +- src/libsync/syncfilestatus.h | 10 +- src/libsync/syncfilestatustracker.cpp | 41 +- src/libsync/syncfilestatustracker.h | 26 +- src/libsync/syncjournaldb.cpp | 643 +++++++++--------- src/libsync/syncjournaldb.h | 88 ++- src/libsync/syncjournalfilerecord.cpp | 61 +- src/libsync/syncjournalfilerecord.h | 39 +- src/libsync/syncresult.cpp | 35 +- src/libsync/syncresult.h | 55 +- src/libsync/theme.cpp | 131 ++-- src/libsync/theme.h | 31 +- src/libsync/utility.cpp | 151 ++-- src/libsync/utility.h | 44 +- src/libsync/utility_mac.cpp | 30 +- src/libsync/utility_unix.cpp | 18 +- src/libsync/utility_win.cpp | 21 +- 235 files changed, 7276 insertions(+), 7080 deletions(-) diff --git a/src/cmd/cmd.cpp b/src/cmd/cmd.cpp index 32fa03b49..0535875cd 100644 --- a/src/cmd/cmd.cpp +++ b/src/cmd/cmd.cpp @@ -51,9 +51,12 @@ using namespace OCC; -static void nullMessageHandler(QtMsgType, const char *) {} +static void nullMessageHandler(QtMsgType, const char *) +{ +} -struct CmdOptions { +struct CmdOptions +{ QString source_dir; QString target_url; QString config_directory; @@ -78,7 +81,7 @@ struct CmdOptions { // So we have to use a global variable CmdOptions *opts = 0; -const qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5*1000); +const qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5 * 1000); class EchoDisabler { @@ -105,6 +108,7 @@ public: tcsetattr(STDIN_FILENO, TCSANOW, &tios); #endif } + private: #ifdef Q_OS_WIN DWORD mode = 0; @@ -123,25 +127,31 @@ QString queryPassword(const QString &user) return QString::fromStdString(s); } -class HttpCredentialsText : public HttpCredentials { +class HttpCredentialsText : public HttpCredentials +{ public: - HttpCredentialsText(const QString& user, const QString& password) - : HttpCredentials(user, password), // FIXME: not working with client certs yet (qknight) - _sslTrusted(false) - {} + HttpCredentialsText(const QString &user, const QString &password) + : HttpCredentials(user, password) + , // FIXME: not working with client certs yet (qknight) + _sslTrusted(false) + { + } - void askFromUser() Q_DECL_OVERRIDE { + void askFromUser() Q_DECL_OVERRIDE + { _password = ::queryPassword(user()); _ready = true; persist(); emit asked(); } - void setSSLTrusted( bool isTrusted ) { + void setSSLTrusted(bool isTrusted) + { _sslTrusted = isTrusted; } - bool sslIsTrusted() Q_DECL_OVERRIDE { + bool sslIsTrusted() Q_DECL_OVERRIDE + { return _sslTrusted; } @@ -180,22 +190,22 @@ void help() std::cout << " --version, -v Display version and exit" << std::endl; std::cout << "" << std::endl; exit(0); - } -void showVersion() { +void showVersion() +{ const char *binaryName = APPLICATION_EXECUTABLE "cmd"; std::cout << binaryName << " version " << qPrintable(Theme::instance()->version()) << std::endl; exit(0); } -void parseOptions( const QStringList& app_args, CmdOptions *options ) +void parseOptions(const QStringList &app_args, CmdOptions *options) { QStringList args(app_args); int argCount = args.count(); - if( argCount < 3 ) { + if (argCount < 3) { if (argCount >= 2) { const QString option = args.at(1); if (option == "-v" || option == "--version") { @@ -212,7 +222,7 @@ void parseOptions( const QStringList& app_args, CmdOptions *options ) options->source_dir.append('/'); } QFileInfo fi(options->source_dir); - if( !fi.exists() ) { + if (!fi.exists()) { std::cerr << "Source dir '" << qPrintable(options->source_dir) << "' does not exist." << std::endl; exit(1); } @@ -220,47 +230,48 @@ void parseOptions( const QStringList& app_args, CmdOptions *options ) QStringListIterator it(args); // skip file name; - if (it.hasNext()) it.next(); + if (it.hasNext()) + it.next(); - while(it.hasNext()) { + while (it.hasNext()) { const QString option = it.next(); - if( option == "--httpproxy" && !it.peekNext().startsWith("-")) { + if (option == "--httpproxy" && !it.peekNext().startsWith("-")) { options->proxy = it.next(); - } else if( option == "-s" || option == "--silent") { + } else if (option == "-s" || option == "--silent") { options->silent = true; - } else if( option == "--trust") { + } else if (option == "--trust") { options->trustSSL = true; - } else if( option == "-n") { + } else if (option == "-n") { options->useNetrc = true; - } else if( option == "-h") { + } else if (option == "-h") { options->ignoreHiddenFiles = false; - } else if( option == "--non-interactive") { + } else if (option == "--non-interactive") { options->interactive = false; - } else if( (option == "-u" || option == "--user") && !it.peekNext().startsWith("-") ) { - options->user = it.next(); - } else if( (option == "-p" || option == "--password") && !it.peekNext().startsWith("-") ) { - options->password = it.next(); - } else if( option == "--exclude" && !it.peekNext().startsWith("-") ) { - options->exclude = it.next(); - } else if( option == "--unsyncedfolders" && !it.peekNext().startsWith("-") ) { + } else if ((option == "-u" || option == "--user") && !it.peekNext().startsWith("-")) { + options->user = it.next(); + } else if ((option == "-p" || option == "--password") && !it.peekNext().startsWith("-")) { + options->password = it.next(); + } else if (option == "--exclude" && !it.peekNext().startsWith("-")) { + options->exclude = it.next(); + } else if (option == "--unsyncedfolders" && !it.peekNext().startsWith("-")) { options->unsyncedfolders = it.next(); - } else if( option == "--nonshib" ) { + } else if (option == "--nonshib") { options->nonShib = true; - } else if( option == "--davpath" && !it.peekNext().startsWith("-") ) { + } else if (option == "--davpath" && !it.peekNext().startsWith("-")) { options->davPath = it.next(); - } else if( option == "--max-sync-retries" && !it.peekNext().startsWith("-") ) { + } else if (option == "--max-sync-retries" && !it.peekNext().startsWith("-")) { options->restartTimes = it.next().toInt(); - } else if( option == "--uplimit" && !it.peekNext().startsWith("-") ) { + } else if (option == "--uplimit" && !it.peekNext().startsWith("-")) { options->uplimit = it.next().toInt() * 1000; - } else if( option == "--downlimit" && !it.peekNext().startsWith("-") ) { + } else if (option == "--downlimit" && !it.peekNext().startsWith("-")) { options->downlimit = it.next().toInt() * 1000; } else { help(); } } - if( options->target_url.isEmpty() || options->source_dir.isEmpty() ) { + if (options->target_url.isEmpty() || options->source_dir.isEmpty()) { help(); } } @@ -278,10 +289,10 @@ void selectiveSyncFixup(OCC::SyncJournalDb *journal, const QStringList &newList) bool ok; auto oldBlackListSet = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok).toSet(); - if( ok ) { + if (ok) { auto blackListSet = newList.toSet(); auto changes = (oldBlackListSet - blackListSet) + (blackListSet - oldBlackListSet); - foreach(const auto &it, changes) { + foreach (const auto &it, changes) { journal->avoidReadFromDbOnNextSync(it); } @@ -289,12 +300,13 @@ void selectiveSyncFixup(OCC::SyncJournalDb *journal, const QStringList &newList) } } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ QCoreApplication app(argc, argv); #ifdef Q_OS_WIN // Ensure OpenSSL config file is only loaded from app directory - QString opensslConf = QCoreApplication::applicationDirPath()+QString("/openssl.cnf"); + QString opensslConf = QCoreApplication::applicationDirPath() + QString("/openssl.cnf"); qputenv("OPENSSL_CONF", opensslConf.toLocal8Bit()); #endif @@ -312,7 +324,7 @@ int main(int argc, char **argv) { options.downlimit = 0; ClientProxy clientProxy; - parseOptions( app.arguments(), &options ); + parseOptions(app.arguments(), &options); csync_set_log_level(options.silent ? 1 : 11); if (options.silent) { @@ -321,24 +333,24 @@ int main(int argc, char **argv) { AccountPtr account = Account::create(); - if( !account ) { + if (!account) { qFatal("Could not initialize account!"); return EXIT_FAILURE; } // check if the webDAV path was added to the url and append if not. - if(!options.target_url.endsWith("/")) { + if (!options.target_url.endsWith("/")) { options.target_url.append("/"); } - if( options.nonShib ) { + if (options.nonShib) { account->setNonShib(true); } - if(!options.davPath.isEmpty()) { - account->setDavPath( options.davPath ); + if (!options.davPath.isEmpty()) { + account->setDavPath(options.davPath); } - if( !options.target_url.contains( account->davPath() )) { + if (!options.target_url.contains(account->davPath())) { options.target_url.append(account->davPath()); } @@ -353,34 +365,34 @@ int main(int argc, char **argv) { QString user = url.userName(); QString password = url.password(); - if (!options.user.isEmpty()) { - user = options.user; - } - - if (!options.password.isEmpty()) { - password = options.password; - } - - if (options.useNetrc) { - NetrcParser parser; - if (parser.parse()) { - NetrcParser::LoginPair pair = parser.find(url.host()); - user = pair.first; - password = pair.second; - } - } - - if (options.interactive) { - if (user.isEmpty()) { - std::cout << "Please enter user name: "; - std::string s; - std::getline(std::cin, s); - user = QString::fromStdString(s); - } - if (password.isEmpty()) { - password = queryPassword(user); - } - } + if (!options.user.isEmpty()) { + user = options.user; + } + + if (!options.password.isEmpty()) { + password = options.password; + } + + if (options.useNetrc) { + NetrcParser parser; + if (parser.parse()) { + NetrcParser::LoginPair pair = parser.find(url.host()); + user = pair.first; + password = pair.second; + } + } + + if (options.interactive) { + if (user.isEmpty()) { + std::cout << "Please enter user name: "; + std::string s; + std::getline(std::cin, s); + user = QString::fromStdString(s); + } + if (password.isEmpty()) { + password = queryPassword(user); + } + } // take the unmodified url to pass to csync_create() QByteArray remUrl = options.target_url.toUtf8(); @@ -405,7 +417,7 @@ int main(int argc, char **argv) { HttpCredentialsText *cred = new HttpCredentialsText(user, password); - if( options.trustSSL ) { + if (options.trustSSL) { cred->setSSLTrusted(true); } account->setUrl(url); @@ -438,17 +450,18 @@ restart_sync: opts = &options; - if( !options.proxy.isNull() ) { + if (!options.proxy.isNull()) { QString host; int port = 0; bool ok; QStringList pList = options.proxy.split(':'); - if(pList.count() == 3) { + if (pList.count() == 3) { // http: //192.168.178.23 : 8080 // 0 1 2 host = pList.at(1); - if( host.startsWith("//") ) host.remove(0, 2); + if (host.startsWith("//")) + host.remove(0, 2); port = pList.at(2).toInt(&ok); @@ -457,8 +470,8 @@ restart_sync: } } else { clientProxy.setupQtProxyFromConfig(); - QString url( options.target_url ); - if( url.startsWith("owncloud")) { + QString url(options.target_url); + if (url.startsWith("owncloud")) { url.remove(0, 8); url = QString("http%1").arg(url); } @@ -494,7 +507,7 @@ restart_sync: engine.setNetworkLimits(options.uplimit, options.downlimit); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QObject::connect(&engine, &SyncEngine::finished, - [&app](bool result) { app.exit(result ? EXIT_SUCCESS : EXIT_FAILURE); }); + [&app](bool result) { app.exit(result ? EXIT_SUCCESS : EXIT_FAILURE); }); #else QObject::connect(&engine, SIGNAL(finished(bool)), &app, SLOT(quit())); #endif @@ -507,11 +520,11 @@ restart_sync: QString systemExcludeFile = ConfigFile::excludeFileFromSystem(); // Always try to load the user-provided exclude list if one is specified - if ( hasUserExcludeFile ) { + if (hasUserExcludeFile) { engine.excludedFiles().addExcludeFilePath(options.exclude); } // Load the system list if available, or if there's no user-provided list - if ( !hasUserExcludeFile || QFile::exists(systemExcludeFile) ) { + if (!hasUserExcludeFile || QFile::exists(systemExcludeFile)) { engine.excludedFiles().addExcludeFilePath(systemExcludeFile); } @@ -537,4 +550,3 @@ restart_sync: return resultCode; } - diff --git a/src/cmd/cmd.h b/src/cmd/cmd.h index 06ae2fa6c..34b4a15ad 100644 --- a/src/cmd/cmd.h +++ b/src/cmd/cmd.h @@ -22,12 +22,17 @@ * @brief Helper class for command line client * @ingroup cmd */ -class Cmd : public QObject { +class Cmd : public QObject +{ Q_OBJECT public: - Cmd() : QObject() { } + Cmd() + : QObject() + { + } public slots: - void transmissionProgressSlot() { + void transmissionProgressSlot() + { } }; diff --git a/src/cmd/netrcparser.cpp b/src/cmd/netrcparser.cpp index 9e831305c..a89eb7622 100644 --- a/src/cmd/netrcparser.cpp +++ b/src/cmd/netrcparser.cpp @@ -25,25 +25,25 @@ namespace OCC { namespace { -QString defaultKeyword = QLatin1String("default"); -QString machineKeyword = QLatin1String("machine"); -QString loginKeyword = QLatin1String("login"); -QString passwordKeyword = QLatin1String("password"); - + QString defaultKeyword = QLatin1String("default"); + QString machineKeyword = QLatin1String("machine"); + QString loginKeyword = QLatin1String("login"); + QString passwordKeyword = QLatin1String("password"); } NetrcParser::NetrcParser(const QString &file) { _netrcLocation = file; if (_netrcLocation.isEmpty()) { - _netrcLocation = QDir::homePath()+QLatin1String("/.netrc"); + _netrcLocation = QDir::homePath() + QLatin1String("/.netrc"); } } -void NetrcParser::tryAddEntryAndClear(QString& machine, LoginPair& pair, bool& isDefault) { +void NetrcParser::tryAddEntryAndClear(QString &machine, LoginPair &pair, bool &isDefault) +{ if (isDefault) { _default = pair; - } else if (!machine.isEmpty() && !pair.first.isEmpty()){ + } else if (!machine.isEmpty() && !pair.first.isEmpty()) { _entries.insert(machine, pair); } pair = qMakePair(QString(), QString()); @@ -87,7 +87,6 @@ bool NetrcParser::parse() } else if (key == passwordKeyword) { pair.second = value; } // ignore unsupported tokens - } tryAddEntryAndClear(machine, pair, isDefault); diff --git a/src/cmd/simplesslerrorhandler.cpp b/src/cmd/simplesslerrorhandler.cpp index a9d760532..18a03293a 100644 --- a/src/cmd/simplesslerrorhandler.cpp +++ b/src/cmd/simplesslerrorhandler.cpp @@ -20,18 +20,17 @@ namespace OCC { bool SimpleSslErrorHandler::handleErrors(QList errors, const QSslConfiguration &conf, QList *certs, OCC::AccountPtr account) { - (void) account; - (void) conf; + (void)account; + (void)conf; if (!certs) { qDebug() << "Certs parameter required but is NULL!"; return false; } - foreach( QSslError error, errors ) { - certs->append( error.certificate() ); + foreach (QSslError error, errors) { + certs->append(error.certificate()); } return true; } - } diff --git a/src/cmd/simplesslerrorhandler.h b/src/cmd/simplesslerrorhandler.h index 05ee5ed42..33376b820 100644 --- a/src/cmd/simplesslerrorhandler.h +++ b/src/cmd/simplesslerrorhandler.h @@ -25,11 +25,11 @@ namespace OCC { * @brief The SimpleSslErrorHandler class * @ingroup cmd */ -class SimpleSslErrorHandler : public OCC::AbstractSslErrorHandler { +class SimpleSslErrorHandler : public OCC::AbstractSslErrorHandler +{ public: bool handleErrors(QList errors, const QSslConfiguration &conf, QList *certs, OCC::AccountPtr) Q_DECL_OVERRIDE; }; - } #endif // SIMPLESSLERRORHANDLER_H diff --git a/src/crashreporter/main.cpp b/src/crashreporter/main.cpp index 048b9ff0b..631c211b5 100644 --- a/src/crashreporter/main.cpp +++ b/src/crashreporter/main.cpp @@ -20,18 +20,17 @@ #include #include -int main( int argc, char* argv[] ) +int main(int argc, char *argv[]) { - QApplication app( argc, argv ); + QApplication app(argc, argv); - if ( app.arguments().size() != 2 ) - { + if (app.arguments().size() != 2) { qDebug() << "You need to pass the .dmp file path as only argument"; return 1; } // TODO: install socorro .... - CrashReporter reporter( QUrl( CRASHREPORTER_SUBMIT_URL ), app.arguments() ); + CrashReporter reporter(QUrl(CRASHREPORTER_SUBMIT_URL), app.arguments()); #ifdef CRASHREPORTER_ICON reporter.setLogo(QPixmap(CRASHREPORTER_ICON)); @@ -39,47 +38,47 @@ int main( int argc, char* argv[] ) reporter.setWindowTitle(CRASHREPORTER_PRODUCT_NAME); reporter.setText("

Sorry! " CRASHREPORTER_PRODUCT_NAME " crashed. Please tell us about it! " CRASHREPORTER_PRODUCT_NAME " has created an error report for you that can help improve the stability in the future. You can now send this report directly to the " CRASHREPORTER_PRODUCT_NAME " developers.

"); - reporter.setReportData( "BuildID", CRASHREPORTER_BUILD_ID ); - reporter.setReportData( "ProductName", CRASHREPORTER_PRODUCT_NAME ); - reporter.setReportData( "Version", CRASHREPORTER_VERSION_STRING ); - reporter.setReportData( "ReleaseChannel", CRASHREPORTER_RELEASE_CHANNEL); + reporter.setReportData("BuildID", CRASHREPORTER_BUILD_ID); + reporter.setReportData("ProductName", CRASHREPORTER_PRODUCT_NAME); + reporter.setReportData("Version", CRASHREPORTER_VERSION_STRING); + reporter.setReportData("ReleaseChannel", CRASHREPORTER_RELEASE_CHANNEL); //reporter.setReportData( "timestamp", QByteArray::number( QDateTime::currentDateTime().toTime_t() ) ); - // add parameters - - // << Pair("InstallTime", "1357622062") - // << Pair("Theme", "classic/1.0") - // << Pair("Version", "30") - // << Pair("id", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") - // << Pair("Vendor", "Mozilla") - // << Pair("EMCheckCompatibility", "true") - // << Pair("Throttleable", "0") - // << Pair("URL", "http://code.google.com/p/crashme/") - // << Pair("version", "20.0a1") - // << Pair("CrashTime", "1357770042") - // << Pair("submitted_timestamp", "2013-01-09T22:21:18.646733+00:00") - // << Pair("buildid", "20130107030932") - // << Pair("timestamp", "1357770078.646789") - // << Pair("Notes", "OpenGL: NVIDIA Corporation -- GeForce 8600M GT/PCIe/SSE2 -- 3.3.0 NVIDIA 313.09 -- texture_from_pixmap\r\n") - // << Pair("StartupTime", "1357769913") - // << Pair("FramePoisonSize", "4096") - // << Pair("FramePoisonBase", "7ffffffff0dea000") - // << Pair("Add-ons", "%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:20.0a1,crashme%40ted.mielczarek.org:0.4") - // << Pair("SecondsSinceLastCrash", "1831736") - // << Pair("ProductName", "WaterWolf") - // << Pair("legacy_processing", "0") - // << Pair("ProductID", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") - - ; + // add parameters + + // << Pair("InstallTime", "1357622062") + // << Pair("Theme", "classic/1.0") + // << Pair("Version", "30") + // << Pair("id", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") + // << Pair("Vendor", "Mozilla") + // << Pair("EMCheckCompatibility", "true") + // << Pair("Throttleable", "0") + // << Pair("URL", "http://code.google.com/p/crashme/") + // << Pair("version", "20.0a1") + // << Pair("CrashTime", "1357770042") + // << Pair("submitted_timestamp", "2013-01-09T22:21:18.646733+00:00") + // << Pair("buildid", "20130107030932") + // << Pair("timestamp", "1357770078.646789") + // << Pair("Notes", "OpenGL: NVIDIA Corporation -- GeForce 8600M GT/PCIe/SSE2 -- 3.3.0 NVIDIA 313.09 -- texture_from_pixmap\r\n") + // << Pair("StartupTime", "1357769913") + // << Pair("FramePoisonSize", "4096") + // << Pair("FramePoisonBase", "7ffffffff0dea000") + // << Pair("Add-ons", "%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:20.0a1,crashme%40ted.mielczarek.org:0.4") + // << Pair("SecondsSinceLastCrash", "1831736") + // << Pair("ProductName", "WaterWolf") + // << Pair("legacy_processing", "0") + // << Pair("ProductID", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") + + ; // TODO: // send log -// QFile logFile( INSERT_FILE_PATH_HERE ); -// logFile.open( QFile::ReadOnly ); -// reporter.setReportData( "upload_file_miralllog", qCompress( logFile.readAll() ), "application/x-gzip", QFileInfo( INSERT_FILE_PATH_HERE ).fileName().toUtf8()); -// logFile.close(); + // QFile logFile( INSERT_FILE_PATH_HERE ); + // logFile.open( QFile::ReadOnly ); + // reporter.setReportData( "upload_file_miralllog", qCompress( logFile.readAll() ), "application/x-gzip", QFileInfo( INSERT_FILE_PATH_HERE ).fileName().toUtf8()); + // logFile.close(); reporter.show(); diff --git a/src/gui/accountmanager.cpp b/src/gui/accountmanager.cpp index 1c1ab1754..a54a1b6c8 100644 --- a/src/gui/accountmanager.cpp +++ b/src/gui/accountmanager.cpp @@ -50,18 +50,18 @@ bool AccountManager::restore() auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); if (settings->status() != QSettings::NoError) { qCWarning(lcAccountManager) << "Could not read settings from" << settings->fileName() - << settings->status(); + << settings->status(); return false; } // If there are no accounts, check the old format. if (settings->childGroups().isEmpty() - && !settings->contains(QLatin1String(versionC))) { + && !settings->contains(QLatin1String(versionC))) { restoreFromLegacySettings(); return true; } - foreach (const auto& accountId, settings->childGroups()) { + foreach (const auto &accountId, settings->childGroups()) { settings->beginGroup(accountId); if (auto acc = loadAccountHelper(*settings)) { acc->_id = accountId; @@ -78,40 +78,44 @@ bool AccountManager::restore() bool AccountManager::restoreFromLegacySettings() { qCInfo(lcAccountManager) << "Migrate: restoreFromLegacySettings, checking settings group" - << Theme::instance()->appName(); + << Theme::instance()->appName(); // try to open the correctly themed settings auto settings = Utility::settingsWithGroup(Theme::instance()->appName()); // if the settings file could not be opened, the childKeys list is empty // then try to load settings from a very old place - if( settings->childKeys().isEmpty() ) { + if (settings->childKeys().isEmpty()) { // Now try to open the original ownCloud settings to see if they exist. - QString oCCfgFile = QDir::fromNativeSeparators( settings->fileName() ); + QString oCCfgFile = QDir::fromNativeSeparators(settings->fileName()); // replace the last two segments with ownCloud/owncloud.cfg - oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/')); - oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/')); + oCCfgFile = oCCfgFile.left(oCCfgFile.lastIndexOf('/')); + oCCfgFile = oCCfgFile.left(oCCfgFile.lastIndexOf('/')); oCCfgFile += QLatin1String("/ownCloud/owncloud.cfg"); qCInfo(lcAccountManager) << "Migrate: checking old config " << oCCfgFile; - QFileInfo fi( oCCfgFile ); - if( fi.isReadable() ) { + QFileInfo fi(oCCfgFile); + if (fi.isReadable()) { std::unique_ptr oCSettings(new QSettings(oCCfgFile, QSettings::IniFormat)); oCSettings->beginGroup(QLatin1String("ownCloud")); // Check the theme url to see if it is the same url that the oC config was for QString overrideUrl = Theme::instance()->overrideServerUrl(); - if( !overrideUrl.isEmpty() ) { - if (overrideUrl.endsWith('/')) { overrideUrl.chop(1); } + if (!overrideUrl.isEmpty()) { + if (overrideUrl.endsWith('/')) { + overrideUrl.chop(1); + } QString oCUrl = oCSettings->value(QLatin1String(urlC)).toString(); - if (oCUrl.endsWith('/')) { oCUrl.chop(1); } + if (oCUrl.endsWith('/')) { + oCUrl.chop(1); + } // in case the urls are equal reset the settings object to read from // the ownCloud settings object qCInfo(lcAccountManager) << "Migrate oC config if " << oCUrl << " == " << overrideUrl << ":" - << (oCUrl == overrideUrl ? "Yes" : "No"); - if( oCUrl == overrideUrl ) { + << (oCUrl == overrideUrl ? "Yes" : "No"); + if (oCUrl == overrideUrl) { settings = std::move(oCSettings); } } @@ -143,7 +147,7 @@ void AccountManager::save(bool saveCredentials) qCInfo(lcAccountManager) << "Saved all account settings, status:" << settings->status(); } -void AccountManager::saveAccount(Account* a) +void AccountManager::saveAccount(Account *a) { qCInfo(lcAccountManager) << "Saving account" << a->url().toString(); auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); @@ -155,7 +159,7 @@ void AccountManager::saveAccount(Account* a) qCInfo(lcAccountManager) << "Saved account settings, status:" << settings->status(); } -void AccountManager::saveAccountState(AccountState* a) +void AccountManager::saveAccountState(AccountState *a) { qCInfo(lcAccountManager) << "Saving account state" << a->account()->url().toString(); auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); @@ -167,7 +171,7 @@ void AccountManager::saveAccountState(AccountState* a) qCInfo(lcAccountManager) << "Saved account state settings, status:" << settings->status(); } -void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool saveCredentials) +void AccountManager::saveAccountHelper(Account *acc, QSettings &settings, bool saveCredentials) { settings.setValue(QLatin1String(urlC), acc->_url.toString()); settings.setValue(QLatin1String(serverVersionC), acc->_serverVersion); @@ -179,7 +183,7 @@ void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool s // re-persisting them) acc->_credentials->persist(); } - Q_FOREACH(QString key, acc->_settingsMap.keys()) { + Q_FOREACH (QString key, acc->_settingsMap.keys()) { settings.setValue(key, acc->_settingsMap.value(key)); } settings.setValue(QLatin1String(authTypeC), acc->_credentials->authType()); @@ -193,17 +197,17 @@ void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool s settings.beginGroup(QLatin1String("General")); qCInfo(lcAccountManager) << "Saving " << acc->approvedCerts().count() << " unknown certs."; QByteArray certs; - Q_FOREACH( const QSslCertificate& cert, acc->approvedCerts() ) { + Q_FOREACH (const QSslCertificate &cert, acc->approvedCerts()) { certs += cert.toPem() + '\n'; } if (!certs.isEmpty()) { - settings.setValue( QLatin1String(caCertsKeyC), certs ); + settings.setValue(QLatin1String(caCertsKeyC), certs); } settings.endGroup(); // Save cookies. if (acc->_am) { - CookieJar* jar = qobject_cast(acc->_am->cookieJar()); + CookieJar *jar = qobject_cast(acc->_am->cookieJar()); if (jar) { qCInfo(lcAccountManager) << "Saving cookies." << acc->cookieJarPath(); jar->save(acc->cookieJarPath()); @@ -211,7 +215,7 @@ void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool s } } -AccountPtr AccountManager::loadAccountHelper(QSettings& settings) +AccountPtr AccountManager::loadAccountHelper(QSettings &settings) { auto urlConfig = settings.value(QLatin1String(urlC)); if (!urlConfig.isValid()) { @@ -236,7 +240,7 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings) QString overrideUrl = Theme::instance()->overrideServerUrl(); QString forceAuth = Theme::instance()->forceConfigAuthType(); - if(!forceAuth.isEmpty() && !overrideUrl.isEmpty() ) { + if (!forceAuth.isEmpty() && !overrideUrl.isEmpty()) { // If forceAuth is set, this might also mean the overrideURL has changed. // See enterprise issues #1126 acc->setUrl(overrideUrl); @@ -252,7 +256,7 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings) // We want to only restore settings for that auth type and the user value acc->_settingsMap.insert(QLatin1String(userC), settings.value(userC)); QString authTypePrefix = authType + "_"; - Q_FOREACH(QString key, settings.childKeys()) { + Q_FOREACH (QString key, settings.childKeys()) { if (!key.startsWith(authTypePrefix)) continue; acc->_settingsMap.insert(key, settings.value(key)); @@ -268,9 +272,9 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings) return acc; } -AccountStatePtr AccountManager::account(const QString& name) +AccountStatePtr AccountManager::account(const QString &name) { - foreach (const auto& acc, _accounts) { + foreach (const auto &acc, _accounts) { if (acc->account()->displayName() == name) { return acc; } @@ -278,7 +282,7 @@ AccountStatePtr AccountManager::account(const QString& name) return AccountStatePtr(); } -AccountState *AccountManager::addAccount(const AccountPtr& newAccount) +AccountState *AccountManager::addAccount(const AccountPtr &newAccount) { auto id = newAccount->id(); if (id.isEmpty() || !isAccountIdAvailable(id)) { @@ -291,10 +295,12 @@ AccountState *AccountManager::addAccount(const AccountPtr& newAccount) return newAccountState; } -void AccountManager::deleteAccount(AccountState* account) +void AccountManager::deleteAccount(AccountState *account) { auto it = std::find(_accounts.begin(), _accounts.end(), account); - if (it == _accounts.end()) { return; } + if (it == _accounts.end()) { + return; + } auto copy = *it; // keep a reference to the shared pointer so it does not delete it just yet _accounts.erase(it); @@ -310,8 +316,8 @@ AccountPtr AccountManager::createAccount() { AccountPtr acc = Account::create(); acc->setSslErrorHandler(new SslDialogErrorHandler); - connect(acc.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator*)), - ProxyAuthHandler::instance(), SLOT(handleProxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); + connect(acc.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)), + ProxyAuthHandler::instance(), SLOT(handleProxyAuthenticationRequired(QNetworkProxy, QAuthenticator *))); return acc; } @@ -325,9 +331,9 @@ void AccountManager::shutdown() } } -bool AccountManager::isAccountIdAvailable(const QString& id) const +bool AccountManager::isAccountIdAvailable(const QString &id) const { - foreach (const auto& acc, _accounts) { + foreach (const auto &acc, _accounts) { if (acc->account()->id() == id) { return false; } @@ -347,15 +353,14 @@ QString AccountManager::generateFreeAccountId() const } } -void AccountManager::addAccountState(AccountState* accountState) +void AccountManager::addAccountState(AccountState *accountState) { QObject::connect(accountState->account().data(), - SIGNAL(wantsAccountSaved(Account*)), - SLOT(saveAccount(Account*))); + SIGNAL(wantsAccountSaved(Account *)), + SLOT(saveAccount(Account *))); AccountStatePtr ptr(accountState); _accounts << ptr; emit accountAdded(accountState); } - } diff --git a/src/gui/accountmanager.h b/src/gui/accountmanager.h index 2dcb9c88d..a2c13bec2 100644 --- a/src/gui/accountmanager.h +++ b/src/gui/accountmanager.h @@ -23,7 +23,8 @@ namespace OCC { @brief The AccountManager class @ingroup gui */ -class AccountManager : public QObject { +class AccountManager : public QObject +{ Q_OBJECT public: static AccountManager *instance(); @@ -62,7 +63,7 @@ public: /** * Return the account state pointer for an account identified by its display name */ - AccountStatePtr account(const QString& name); + AccountStatePtr account(const QString &name); /** * Delete the AccountState @@ -78,23 +79,23 @@ public: private: // saving and loading Account to settings - void saveAccountHelper(Account* account, QSettings& settings, bool saveCredentials = true); - AccountPtr loadAccountHelper(QSettings& settings); + void saveAccountHelper(Account *account, QSettings &settings, bool saveCredentials = true); + AccountPtr loadAccountHelper(QSettings &settings); bool restoreFromLegacySettings(); - bool isAccountIdAvailable(const QString& id) const; + bool isAccountIdAvailable(const QString &id) const; QString generateFreeAccountId() const; // Adds an account to the tracked list, emitting accountAdded() - void addAccountState(AccountState* accountState); + void addAccountState(AccountState *accountState); public slots: /// Saves account data, not including the credentials - void saveAccount(Account* a); + void saveAccount(Account *a); /// Saves account state data, not including the account - void saveAccountState(AccountState* a); + void saveAccountState(AccountState *a); Q_SIGNALS: @@ -105,5 +106,4 @@ private: AccountManager() {} QList _accounts; }; - } diff --git a/src/gui/accountsettings.cpp b/src/gui/accountsettings.cpp index b12d245f7..9eb3a53d2 100644 --- a/src/gui/accountsettings.cpp +++ b/src/gui/accountsettings.cpp @@ -60,21 +60,21 @@ namespace OCC { Q_LOGGING_CATEGORY(lcAccountSettings, "gui.account.settings", QtInfoMsg) static const char progressBarStyleC[] = - "QProgressBar {" - "border: 1px solid grey;" - "border-radius: 5px;" - "text-align: center;" - "}" - "QProgressBar::chunk {" - "background-color: %1; width: 1px;" - "}"; - -AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent) : - QWidget(parent), - ui(new Ui::AccountSettings), - _wasDisabledBefore(false), - _accountState(accountState), - _quotaInfo(accountState) + "QProgressBar {" + "border: 1px solid grey;" + "border-radius: 5px;" + "text-align: center;" + "}" + "QProgressBar::chunk {" + "background-color: %1; width: 1px;" + "}"; + +AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent) + : QWidget(parent) + , ui(new Ui::AccountSettings) + , _wasDisabledBefore(false) + , _accountState(accountState) + , _quotaInfo(accountState) { ui->setupUi(this); @@ -85,31 +85,31 @@ AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent) : delegate->setParent(this); ui->_folderList->header()->hide(); - ui->_folderList->setItemDelegate( delegate ); - ui->_folderList->setModel( _model ); + ui->_folderList->setItemDelegate(delegate); + ui->_folderList->setModel(_model); #if defined(Q_OS_MAC) - ui->_folderList->setMinimumWidth( 400 ); + ui->_folderList->setMinimumWidth(400); #else - ui->_folderList->setMinimumWidth( 300 ); + ui->_folderList->setMinimumWidth(300); #endif new ToolTipUpdater(ui->_folderList); createAccountToolbox(); - connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)), - SLOT(slotAccountAdded(AccountState*))); + connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)), + SLOT(slotAccountAdded(AccountState *))); connect(ui->_folderList, SIGNAL(customContextMenuRequested(QPoint)), - this, SLOT(slotCustomContextMenuRequested(QPoint))); + this, SLOT(slotCustomContextMenuRequested(QPoint))); connect(ui->_folderList, SIGNAL(clicked(const QModelIndex &)), - this, SLOT(slotFolderListClicked(const QModelIndex&))); - connect(ui->_folderList, SIGNAL(expanded(QModelIndex)) , this, SLOT(refreshSelectiveSyncStatus())); - connect(ui->_folderList, SIGNAL(collapsed(QModelIndex)) , this, SLOT(refreshSelectiveSyncStatus())); + this, SLOT(slotFolderListClicked(const QModelIndex &))); + connect(ui->_folderList, SIGNAL(expanded(QModelIndex)), this, SLOT(refreshSelectiveSyncStatus())); + connect(ui->_folderList, SIGNAL(collapsed(QModelIndex)), this, SLOT(refreshSelectiveSyncStatus())); connect(ui->selectiveSyncNotification, SIGNAL(linkActivated(QString)), - this, SLOT(slotLinkActivated(QString))); + this, SLOT(slotLinkActivated(QString))); connect(_model, SIGNAL(suggestExpand(QModelIndex)), ui->_folderList, SLOT(expand(QModelIndex))); connect(_model, SIGNAL(dirtyChanged()), this, SLOT(refreshSelectiveSyncStatus())); refreshSelectiveSyncStatus(); - connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), - this, SLOT(refreshSelectiveSyncStatus())); + connect(_model, SIGNAL(rowsInserted(QModelIndex, int, int)), + this, SLOT(refreshSelectiveSyncStatus())); QAction *syncNowAction = new QAction(this); syncNowAction->setShortcut(QKeySequence(Qt::Key_F6)); @@ -122,7 +122,6 @@ AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent) : addAction(syncNowWithRemoteDiscovery); - connect(ui->selectiveSyncApply, SIGNAL(clicked()), _model, SLOT(slotApplySelectiveSync())); connect(ui->selectiveSyncCancel, SIGNAL(clicked()), _model, SLOT(resetFolders())); connect(ui->bigFolderApply, SIGNAL(clicked(bool)), _model, SLOT(slotApplySelectiveSync())); @@ -141,9 +140,8 @@ AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent) : connect(_accountState, SIGNAL(stateChanged(int)), SLOT(slotAccountStateChanged(int))); slotAccountStateChanged(_accountState->state()); - connect( &_quotaInfo, SIGNAL(quotaUpdated(qint64,qint64)), - this, SLOT(slotUpdateQuota(qint64,qint64))); - + connect(&_quotaInfo, SIGNAL(quotaUpdated(qint64, qint64)), + this, SLOT(slotUpdateQuota(qint64, qint64))); } @@ -160,7 +158,7 @@ void AccountSettings::createAccountToolbox() QAction *action = new QAction(tr("Remove"), this); menu->addAction(action); - connect( action, SIGNAL(triggered(bool)), SLOT(slotDeleteAccount())); + connect(action, SIGNAL(triggered(bool)), SLOT(slotDeleteAccount())); ui->_accountToolbox->setText(tr("Account") + QLatin1Char(' ')); ui->_accountToolbox->setMenu(menu); @@ -172,25 +170,25 @@ void AccountSettings::createAccountToolbox() QString AccountSettings::selectedFolderAlias() const { QModelIndex selected = ui->_folderList->selectionModel()->currentIndex(); - if( !selected.isValid() ) + if (!selected.isValid()) return ""; - return _model->data( selected, FolderStatusDelegate::FolderAliasRole ).toString(); + return _model->data(selected, FolderStatusDelegate::FolderAliasRole).toString(); } void AccountSettings::slotOpenAccountWizard() { if ( #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0) - qgetenv("QT_QPA_PLATFORMTHEME") == "appmenu-qt5" || - // We can't call isSystemTrayAvailable with appmenu-qt5 because it breaks the systemtray - // (issue #4693, #4944) + qgetenv("QT_QPA_PLATFORMTHEME") == "appmenu-qt5" || +// We can't call isSystemTrayAvailable with appmenu-qt5 because it breaks the systemtray +// (issue #4693, #4944) #endif - QSystemTrayIcon::isSystemTrayAvailable()) { + QSystemTrayIcon::isSystemTrayAvailable()) { topLevelWidget()->close(); } #ifdef Q_OS_MAC qCDebug(lcAccountSettings) << parent() << topLevelWidget(); - SettingsDialogMac *sd = qobject_cast(topLevelWidget()); + SettingsDialogMac *sd = qobject_cast(topLevelWidget()); if (sd) { sd->showActivityPage(); @@ -231,7 +229,7 @@ void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos) QAction *ac = menu->addAction(tr("Open folder")); connect(ac, SIGNAL(triggered(bool)), this, SLOT(slotOpenCurrentLocalSubFolder())); - QString fileName = _model->data( index, FolderStatusDelegate::FolderPathRole ).toString(); + QString fileName = _model->data(index, FolderStatusDelegate::FolderPathRole).toString(); if (!QFile::exists(fileName)) { ac->setEnabled(false); } @@ -246,9 +244,9 @@ void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos) } tv->setCurrentIndex(index); - QString alias = _model->data( index, FolderStatusDelegate::FolderAliasRole ).toString(); - bool folderPaused = _model->data( index, FolderStatusDelegate::FolderSyncPaused).toBool(); - bool folderConnected = _model->data( index, FolderStatusDelegate::FolderAccountConnected ).toBool(); + QString alias = _model->data(index, FolderStatusDelegate::FolderAliasRole).toString(); + bool folderPaused = _model->data(index, FolderStatusDelegate::FolderSyncPaused).toBool(); + bool folderConnected = _model->data(index, FolderStatusDelegate::FolderAccountConnected).toBool(); auto folderMan = FolderMan::instance(); QMenu *menu = new QMenu(tv); @@ -280,7 +278,7 @@ void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos) menu->exec(tv->mapToGlobal(pos)); } -void AccountSettings::slotFolderListClicked(const QModelIndex& indx) +void AccountSettings::slotFolderListClicked(const QModelIndex &indx) { if (indx.data(FolderStatusDelegate::AddButton).toBool()) { // "Add Folder Sync Connection" @@ -288,9 +286,9 @@ void AccountSettings::slotFolderListClicked(const QModelIndex& indx) slotAddFolder(); } else { QToolTip::showText( - QCursor::pos(), - _model->data(indx, Qt::ToolTipRole).toString(), - this); + QCursor::pos(), + _model->data(indx, Qt::ToolTipRole).toString(), + this); } return; } @@ -304,8 +302,8 @@ void AccountSettings::slotFolderListClicked(const QModelIndex& indx) } // Expand root items on single click - if(_accountState && _accountState->state() == AccountState::Connected ) { - bool expanded = ! (ui->_folderList->isExpanded(indx)); + if (_accountState && _accountState->state() == AccountState::Connected) { + bool expanded = !(ui->_folderList->isExpanded(indx)); ui->_folderList->setExpanded(indx, expanded); } } @@ -326,16 +324,16 @@ void AccountSettings::slotAddFolder() void AccountSettings::slotFolderWizardAccepted() { - FolderWizard *folderWizard = qobject_cast(sender()); + FolderWizard *folderWizard = qobject_cast(sender()); FolderMan *folderMan = FolderMan::instance(); qCInfo(lcAccountSettings) << "Folder wizard completed"; FolderDefinition definition; - definition.localPath = FolderDefinition::prepareLocalPath( - folderWizard->field(QLatin1String("sourceFolder")).toString()); - definition.targetPath = FolderDefinition::prepareTargetPath( - folderWizard->property("targetPath").toString()); + definition.localPath = FolderDefinition::prepareLocalPath( + folderWizard->field(QLatin1String("sourceFolder")).toString()); + definition.targetPath = FolderDefinition::prepareTargetPath( + folderWizard->property("targetPath").toString()); { QDir dir(definition.localPath); @@ -343,8 +341,8 @@ void AccountSettings::slotFolderWizardAccepted() qCInfo(lcAccountSettings) << "Creating folder" << definition.localPath; if (!dir.mkpath(".")) { QMessageBox::warning(this, tr("Folder creation failed"), - tr("

Could not create local folder %1.") - .arg(QDir::toNativeSeparators(definition.localPath))); + tr("

Could not create local folder %1.") + .arg(QDir::toNativeSeparators(definition.localPath))); return; } } @@ -362,12 +360,12 @@ void AccountSettings::slotFolderWizardAccepted() folderMan->setSyncEnabled(true); Folder *f = folderMan->addFolder(_accountState, definition); - if( f ) { + if (f) { f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, selectiveSyncBlackList); // The user already accepted the selective sync dialog. everything is in the white list f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, - QStringList() << QLatin1String("/")); + QStringList() << QLatin1String("/")); folderMan->scheduleAllFolders(); emit folderChanged(); } @@ -385,20 +383,21 @@ void AccountSettings::slotRemoveCurrentFolder() FolderMan *folderMan = FolderMan::instance(); auto folder = folderMan->folder(selectedFolderAlias()); QModelIndex selected = ui->_folderList->selectionModel()->currentIndex(); - if( selected.isValid() && folder ) { + if (selected.isValid() && folder) { int row = selected.row(); qCInfo(lcAccountSettings) << "Remove Folder alias " << folder->alias(); QString shortGuiLocalPath = folder->shortGuiLocalPath(); QMessageBox messageBox(QMessageBox::Question, - tr("Confirm Folder Sync Connection Removal"), - tr("

Do you really want to stop syncing the folder %1?

" - "

Note: This will not delete any files.

").arg(shortGuiLocalPath), - QMessageBox::NoButton, - this); - QPushButton* yesButton = - messageBox.addButton(tr("Remove Folder Sync Connection"), QMessageBox::YesRole); + tr("Confirm Folder Sync Connection Removal"), + tr("

Do you really want to stop syncing the folder %1?

" + "

Note: This will not delete any files.

") + .arg(shortGuiLocalPath), + QMessageBox::NoButton, + this); + QPushButton *yesButton = + messageBox.addButton(tr("Remove Folder Sync Connection"), QMessageBox::YesRole); messageBox.addButton(tr("Cancel"), QMessageBox::NoRole); messageBox.exec(); @@ -406,7 +405,7 @@ void AccountSettings::slotRemoveCurrentFolder() return; } - folderMan->removeFolder( folder ); + folderMan->removeFolder(folder); _model->removeRow(row); // single folder fix to show add-button and hide remove-button @@ -418,7 +417,7 @@ void AccountSettings::slotRemoveCurrentFolder() void AccountSettings::slotOpenCurrentFolder() { auto alias = selectedFolderAlias(); - if( !alias.isEmpty() ) { + if (!alias.isEmpty()) { emit openFolderAlias(alias); } } @@ -426,27 +425,27 @@ void AccountSettings::slotOpenCurrentFolder() void AccountSettings::slotOpenCurrentLocalSubFolder() { QModelIndex selected = ui->_folderList->selectionModel()->currentIndex(); - if( !selected.isValid() || _model->classify(selected) != FolderStatusModel::SubFolder) + if (!selected.isValid() || _model->classify(selected) != FolderStatusModel::SubFolder) return; - QString fileName = _model->data( selected, FolderStatusDelegate::FolderPathRole ).toString(); + QString fileName = _model->data(selected, FolderStatusDelegate::FolderPathRole).toString(); QUrl url = QUrl::fromLocalFile(fileName); QDesktopServices::openUrl(url); } -void AccountSettings::showConnectionLabel( const QString& message, QStringList errors ) +void AccountSettings::showConnectionLabel(const QString &message, QStringList errors) { const QString errStyle = QLatin1String("color:#ffffff; background-color:#bb4d4d;padding:5px;" "border-width: 1px; border-style: solid; border-color: #aaaaaa;" "border-radius:5px;"); - if( errors.isEmpty() ) { - ui->connectLabel->setText( message ); + if (errors.isEmpty()) { + ui->connectLabel->setText(message); ui->connectLabel->setToolTip(QString()); ui->connectLabel->setStyleSheet(QString()); } else { errors.prepend(message); const QString msg = errors.join(QLatin1String("\n")); qCDebug(lcAccountSettings) << msg; - ui->connectLabel->setText( msg ); + ui->connectLabel->setText(msg); ui->connectLabel->setToolTip(QString()); ui->connectLabel->setStyleSheet(errStyle); } @@ -457,7 +456,7 @@ void AccountSettings::slotEnableCurrentFolder() { auto alias = selectedFolderAlias(); - if( !alias.isEmpty() ) { + if (!alias.isEmpty()) { FolderMan *folderMan = FolderMan::instance(); qCInfo(lcAccountSettings) << "Application: enable folder with alias " << alias; @@ -465,14 +464,14 @@ void AccountSettings::slotEnableCurrentFolder() bool currentlyPaused = false; // this sets the folder status to disabled but does not interrupt it. - Folder *f = folderMan->folder( alias ); + Folder *f = folderMan->folder(alias); if (!f) { return; } currentlyPaused = f->syncPaused(); - if( ! currentlyPaused ) { + if (!currentlyPaused) { // check if a sync is still running and if so, ask if we should terminate. - if( f->isBusy() ) { // its still running + if (f->isBusy()) { // its still running #if defined(Q_OS_MAC) QWidget *parent = this; Qt::WindowFlags flags = Qt::Sheet; @@ -481,11 +480,11 @@ void AccountSettings::slotEnableCurrentFolder() Qt::WindowFlags flags = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint; // default flags #endif QMessageBox msgbox(QMessageBox::Question, tr("Sync Running"), - tr("The syncing operation is running.
Do you want to terminate it?"), - QMessageBox::Yes | QMessageBox::No, parent, flags); + tr("The syncing operation is running.
Do you want to terminate it?"), + QMessageBox::Yes | QMessageBox::No, parent, flags); msgbox.setDefaultButton(QMessageBox::Yes); int reply = msgbox.exec(); - if ( reply == QMessageBox::Yes ) + if (reply == QMessageBox::Yes) terminate = true; else return; // do nothing @@ -494,15 +493,16 @@ void AccountSettings::slotEnableCurrentFolder() // message box can return at any time while the thread keeps running, // so better check again after the user has responded. - if ( f->isBusy() && terminate ) { + if (f->isBusy() && terminate) { f->slotTerminateSync(); } f->setSyncPaused(!currentlyPaused); // keep state for the icon setting. - if( currentlyPaused ) _wasDisabledBefore = true; + if (currentlyPaused) + _wasDisabledBefore = true; - _model->slotUpdateFolderState (f); + _model->slotUpdateFolderState(f); } } @@ -528,7 +528,7 @@ void AccountSettings::slotForceSyncCurrentFolder() FolderMan *folderMan = FolderMan::instance(); if (auto selectedFolder = folderMan->folder(selectedFolderAlias())) { // Terminate and reschedule any running sync - if (Folder* current = folderMan->currentSyncFolder()) { + if (Folder *current = folderMan->currentSyncFolder()) { folderMan->terminateSyncProcess(); folderMan->scheduleFolder(current); } @@ -540,17 +540,17 @@ void AccountSettings::slotForceSyncCurrentFolder() void AccountSettings::slotOpenOC() { - if( _OCUrl.isValid() ) - QDesktopServices::openUrl( _OCUrl ); + if (_OCUrl.isValid()) + QDesktopServices::openUrl(_OCUrl); } void AccountSettings::slotUpdateQuota(qint64 total, qint64 used) { - if( total > 0 ) { + if (total > 0) { ui->quotaProgressBar->setVisible(true); ui->quotaProgressBar->setEnabled(true); // workaround the label only accepting ints (which may be only 32 bit wide) - const double percent = used/(double)total*100; + const double percent = used / (double)total * 100; const int percentInt = qMin(qRound(percent), 100); ui->quotaProgressBar->setValue(percentInt); QString usedStr = Utility::octetsToString(used); @@ -588,7 +588,7 @@ void AccountSettings::slotAccountStateChanged(int state) QString server = QString::fromLatin1("%2") .arg(Utility::escape(account->url().toString()), - Utility::escape(safeUrl.toString())); + Utility::escape(safeUrl.toString())); QString serverWithUser = server; if (AbstractCredentials *cred = account->credentials()) { serverWithUser = tr("%1 as %2").arg(server, Utility::escape(cred->user())); @@ -599,17 +599,17 @@ void AccountSettings::slotAccountStateChanged(int state) if (account->serverVersionUnsupported()) { errors << tr("The server version %1 is old and unsupported! Proceed at your own risk.").arg(account->serverVersion()); } - showConnectionLabel( tr("Connected to %1.").arg(serverWithUser), errors ); + showConnectionLabel(tr("Connected to %1.").arg(serverWithUser), errors); } else if (state == AccountState::ServiceUnavailable) { - showConnectionLabel( tr("Server %1 is temporarily unavailable.").arg(server) ); + showConnectionLabel(tr("Server %1 is temporarily unavailable.").arg(server)); } else if (state == AccountState::MaintenanceMode) { - showConnectionLabel( tr("Server %1 is currently in maintenance mode.").arg(server) ); + showConnectionLabel(tr("Server %1 is currently in maintenance mode.").arg(server)); } else if (state == AccountState::SignedOut) { - showConnectionLabel( tr("Signed out from %1.").arg(serverWithUser) ); + showConnectionLabel(tr("Signed out from %1.").arg(serverWithUser)); } else { showConnectionLabel(tr("No connection to %1 at %2.") .arg(Utility::escape(Theme::instance()->appNameGUI()), server), - _accountState->connectionErrors()); + _accountState->connectionErrors()); } } else { // ownCloud is not yet configured. @@ -618,10 +618,10 @@ void AccountSettings::slotAccountStateChanged(int state) } /* Allow to expand the item if the account is connected. */ - ui->_folderList->setItemsExpandable( state == AccountState::Connected ); + ui->_folderList->setItemsExpandable(state == AccountState::Connected); /* check if there are expanded root items, if so, close them, if the state is different from being Connected. */ - if( state != AccountState::Connected ) { + if (state != AccountState::Connected) { int i; for (i = 0; i < _model->rowCount(); ++i) { if (ui->_folderList->isExpanded(_model->index(i))) @@ -629,8 +629,8 @@ void AccountSettings::slotAccountStateChanged(int state) } } /* set the correct label for the Account toolbox button */ - if( _accountState ) { - if( _accountState->isSignedOut() ) { + if (_accountState) { + if (_accountState->isSignedOut()) { _toggleSignInOutAction->setText(tr("Log in")); } else { _toggleSignInOutAction->setText(tr("Log out")); @@ -638,28 +638,29 @@ void AccountSettings::slotAccountStateChanged(int state) } } -void AccountSettings::slotLinkActivated(const QString& link) +void AccountSettings::slotLinkActivated(const QString &link) { // Parse folder alias and filename from the link, calculate the index // and select it if it exists. const QStringList li = link.split(QLatin1String("?folder=")); - if( li.count() > 1) { + if (li.count() > 1) { QString myFolder = li[0]; const QString alias = li[1]; - if(myFolder.endsWith(QLatin1Char('/'))) myFolder.chop(1); + if (myFolder.endsWith(QLatin1Char('/'))) + myFolder.chop(1); // Make sure the folder itself is expanded Folder *f = FolderMan::instance()->folder(alias); QModelIndex folderIndx = _model->indexForPath(f, QString()); - if( !ui->_folderList->isExpanded(folderIndx)) { + if (!ui->_folderList->isExpanded(folderIndx)) { ui->_folderList->setExpanded(folderIndx, true); } QModelIndex indx = _model->indexForPath(f, myFolder); - if( indx.isValid() ) { + if (indx.isValid()) { // make sure all the parents are expanded for (auto i = indx.parent(); i.isValid(); i = i.parent()) { - if( !ui->_folderList->isExpanded(i)) { + if (!ui->_folderList->isExpanded(i)) { ui->_folderList->setExpanded(i, true); } } @@ -689,20 +690,20 @@ void AccountSettings::refreshSelectiveSyncStatus() } bool ok; - auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok); + auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok); QString p; - foreach(const auto &it, undecidedList) { + foreach (const auto &it, undecidedList) { // FIXME: add the folder alias in a hoover hint. // folder->alias() + QLatin1String("/") - if( cnt++ ) { + if (cnt++) { msg += QLatin1String(", "); } QString myFolder = (it); - if( myFolder.endsWith('/')) { + if (myFolder.endsWith('/')) { myFolder.chop(1); } QModelIndex theIndx = _model->indexForPath(folder, myFolder); - if(theIndx.isValid()) { + if (theIndx.isValid()) { msg += QString::fromLatin1("%1") .arg(Utility::escape(myFolder), Utility::escape(folder->alias())); } else { @@ -717,10 +718,10 @@ void AccountSettings::refreshSelectiveSyncStatus() } else { ConfigFile cfg; QString info = !cfg.confirmExternalStorage() - ? tr("There are folders that were not synchronized because they are too big: ") - : !cfg.newBigFolderSizeLimit().first - ? tr("There are folders that were not synchronized because they are external storages: ") - : tr("There are folders that were not synchronized because they are too big or external storages: "); + ? tr("There are folders that were not synchronized because they are too big: ") + : !cfg.newBigFolderSizeLimit().first + ? tr("There are folders that were not synchronized because they are external storages: ") + : tr("There are folders that were not synchronized because they are too big or external storages: "); ui->selectiveSyncNotification->setText(info + msg); ui->selectiveSyncButtons->setVisible(false); @@ -745,12 +746,12 @@ void AccountSettings::refreshSelectiveSyncStatus() } } -void AccountSettings::slotAccountAdded(AccountState*) +void AccountSettings::slotAccountAdded(AccountState *) { // if the theme is limited to single account, the button must hide if // there is already one account. int s = AccountManager::instance()->accounts().size(); - if( s > 0 && !Theme::instance()->multiAccount() ) { + if (s > 0 && !Theme::instance()->multiAccount()) { _addAccountAction->setVisible(false); } else { _addAccountAction->setVisible(true); @@ -763,14 +764,14 @@ void AccountSettings::slotDeleteAccount() // the QMessageBox should be destroyed before that happens. { QMessageBox messageBox(QMessageBox::Question, - tr("Confirm Account Removal"), - tr("

Do you really want to remove the connection to the account %1?

" - "

Note: This will not delete any files.

") - .arg(_accountState->account()->displayName()), - QMessageBox::NoButton, - this); - QPushButton* yesButton = - messageBox.addButton(tr("Remove connection"), QMessageBox::YesRole); + tr("Confirm Account Removal"), + tr("

Do you really want to remove the connection to the account %1?

" + "

Note: This will not delete any files.

") + .arg(_accountState->account()->displayName()), + QMessageBox::NoButton, + this); + QPushButton *yesButton = + messageBox.addButton(tr("Remove connection"), QMessageBox::YesRole); messageBox.addButton(tr("Cancel"), QMessageBox::NoRole); messageBox.exec(); @@ -790,7 +791,7 @@ void AccountSettings::slotDeleteAccount() // .exec() QMessageBox magic above as it recurses into the event loop. } -bool AccountSettings::event(QEvent* e) +bool AccountSettings::event(QEvent *e) { if (e->type() == QEvent::Hide || e->type() == QEvent::Show) { _quotaInfo.setActive(isVisible()); diff --git a/src/gui/accountsettings.h b/src/gui/accountsettings.h index 5ad472397..9c4a1fc56 100644 --- a/src/gui/accountsettings.h +++ b/src/gui/accountsettings.h @@ -34,7 +34,7 @@ class QLabel; namespace OCC { namespace Ui { -class AccountSettings; + class AccountSettings; } class FolderMan; @@ -59,14 +59,14 @@ public: signals: void folderChanged(); - void openFolderAlias( const QString& ); + void openFolderAlias(const QString &); public slots: void slotOpenOC(); - void slotUpdateQuota( qint64,qint64 ); + void slotUpdateQuota(qint64, qint64); void slotAccountStateChanged(int state); - AccountState* accountsState() { return _accountState; } + AccountState *accountsState() { return _accountState; } protected slots: void slotAddFolder(); @@ -84,15 +84,15 @@ protected slots: void slotOpenAccountWizard(); void slotAccountAdded(AccountState *); void refreshSelectiveSyncStatus(); - void slotCustomContextMenuRequested(const QPoint&); - void slotFolderListClicked( const QModelIndex& indx ); + void slotCustomContextMenuRequested(const QPoint &); + void slotFolderListClicked(const QModelIndex &indx); void doExpand(); void slotLinkActivated(const QString &link); private: - void showConnectionLabel(const QString& message, - QStringList errors = QStringList()); - bool event(QEvent*) Q_DECL_OVERRIDE; + void showConnectionLabel(const QString &message, + QStringList errors = QStringList()); + bool event(QEvent *) Q_DECL_OVERRIDE; void createAccountToolbox(); /// Returns the alias of the selected folder, empty string if none @@ -101,7 +101,7 @@ private: Ui::AccountSettings *ui; FolderStatusModel *_model; - QUrl _OCUrl; + QUrl _OCUrl; bool _wasDisabledBefore; AccountState *_accountState; QuotaInfo _quotaInfo; diff --git a/src/gui/accountstate.cpp b/src/gui/accountstate.cpp index b14197467..90dfa5e62 100644 --- a/src/gui/accountstate.cpp +++ b/src/gui/accountstate.cpp @@ -33,14 +33,14 @@ AccountState::AccountState(AccountPtr account) , _connectionStatus(ConnectionValidator::Undefined) , _waitingForNewCredentials(false) { - qRegisterMetaType("AccountState*"); + qRegisterMetaType("AccountState*"); connect(account.data(), SIGNAL(invalidCredentials()), - SLOT(slotInvalidCredentials())); - connect(account.data(), SIGNAL(credentialsFetched(AbstractCredentials*)), - SLOT(slotCredentialsFetched(AbstractCredentials*))); - connect(account.data(), SIGNAL(credentialsAsked(AbstractCredentials*)), - SLOT(slotCredentialsAsked(AbstractCredentials*))); + SLOT(slotInvalidCredentials())); + connect(account.data(), SIGNAL(credentialsFetched(AbstractCredentials *)), + SLOT(slotCredentialsFetched(AbstractCredentials *))); + connect(account.data(), SIGNAL(credentialsAsked(AbstractCredentials *)), + SLOT(slotCredentialsAsked(AbstractCredentials *))); _timeSinceLastETagCheck.invalidate(); } @@ -48,13 +48,13 @@ AccountState::~AccountState() { } -AccountState *AccountState::loadFromSettings(AccountPtr account, QSettings& /*settings*/) +AccountState *AccountState::loadFromSettings(AccountPtr account, QSettings & /*settings*/) { auto accountState = new AccountState(account); return accountState; } -void AccountState::writeToSettings(QSettings& /*settings*/) +void AccountState::writeToSettings(QSettings & /*settings*/) { } @@ -87,7 +87,7 @@ void AccountState::setState(State state) { if (_state != state) { qCInfo(lcAccountState) << "AccountState state change: " - << stateString(_state) << "->" << stateString(state); + << stateString(_state) << "->" << stateString(state); State oldState = _state; _state = state; @@ -116,8 +116,7 @@ void AccountState::setState(State state) QString AccountState::stateString(State state) { - switch (state) - { + switch (state) { case SignedOut: return tr("Signed out"); case Disconnected: @@ -181,15 +180,15 @@ void AccountState::checkConnectivity() int polltime = cfg.remotePollInterval(); if (isConnected() && _timeSinceLastETagCheck.isValid() - && _timeSinceLastETagCheck.elapsed() < polltime) { - qCDebug(lcAccountState) << account()->displayName() << "The last ETag check succeeded within the last " << polltime/1000 << " secs. No connection check needed!"; + && _timeSinceLastETagCheck.elapsed() < polltime) { + qCDebug(lcAccountState) << account()->displayName() << "The last ETag check succeeded within the last " << polltime / 1000 << " secs. No connection check needed!"; return; } - ConnectionValidator * conValidator = new ConnectionValidator(account()); + ConnectionValidator *conValidator = new ConnectionValidator(account()); _connectionValidator = conValidator; - connect(conValidator, SIGNAL(connectionResult(ConnectionValidator::Status,QStringList)), - SLOT(slotConnectionValidatorResult(ConnectionValidator::Status,QStringList))); + connect(conValidator, SIGNAL(connectionResult(ConnectionValidator::Status, QStringList)), + SLOT(slotConnectionValidatorResult(ConnectionValidator::Status, QStringList))); if (isConnected()) { // Use a small authed propfind as a minimal ping when we're // already connected. @@ -197,8 +196,8 @@ void AccountState::checkConnectivity() } else { // Check the server and then the auth. -// Let's try this for all OS and see if it fixes the Qt issues we have on Linux #4720 #3888 #4051 -//#ifdef Q_OS_WIN + // Let's try this for all OS and see if it fixes the Qt issues we have on Linux #4720 #3888 #4051 + //#ifdef Q_OS_WIN // There seems to be a bug in Qt on Windows where QNAM sometimes stops // working correctly after the computer woke up from sleep. See #2895 #2899 // and #2973. @@ -209,12 +208,12 @@ void AccountState::checkConnectivity() // If we don't reset the ssl config a second CheckServerJob can produce a // ssl config that does not have a sensible certificate chain. account()->setSslConfiguration(QSslConfiguration()); -//#endif + //#endif conValidator->checkServerAndAuth(); } } -void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList& errors) +void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList &errors) { if (isSignedOut()) { qCWarning(lcAccountState) << "Signed out, ignoring" << connectionStatusString(status) << _account->url().toString(); @@ -223,14 +222,13 @@ void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status sta if (_connectionStatus != status) { qCInfo(lcAccountState) << "AccountState connection status change: " - << connectionStatusString(_connectionStatus) << "->" - << connectionStatusString(status); + << connectionStatusString(_connectionStatus) << "->" + << connectionStatusString(status); _connectionStatus = status; } _connectionErrors = errors; - switch (status) - { + switch (status) { case ConnectionValidator::Connected: if (_state != Connected) { setState(Connected); @@ -280,7 +278,7 @@ void AccountState::slotInvalidCredentials() _waitingForNewCredentials = true; } -void AccountState::slotCredentialsFetched(AbstractCredentials* credentials) +void AccountState::slotCredentialsFetched(AbstractCredentials *credentials) { if (!credentials->ready()) { // No exiting credentials found in the keychain @@ -300,7 +298,7 @@ void AccountState::slotCredentialsFetched(AbstractCredentials* credentials) checkConnectivity(); } -void AccountState::slotCredentialsAsked(AbstractCredentials* credentials) +void AccountState::slotCredentialsAsked(AbstractCredentials *credentials) { _waitingForNewCredentials = false; @@ -346,5 +344,4 @@ QString AccountState::shortDisplayNameForSettings(int width) const } - } // namespace OCC diff --git a/src/gui/accountstate.h b/src/gui/accountstate.h index ef81bb39f..450766bf8 100644 --- a/src/gui/accountstate.h +++ b/src/gui/accountstate.h @@ -36,7 +36,8 @@ typedef QExplicitlySharedDataPointer AccountStatePtr; * @brief Extra info about an ownCloud server account. * @ingroup gui */ -class AccountState : public QObject, public QSharedData { +class AccountState : public QObject, public QSharedData +{ Q_OBJECT public: enum State { @@ -78,13 +79,13 @@ public: * * Use from AccountManager with a prepared QSettings object only. */ - static AccountState* loadFromSettings(AccountPtr account, QSettings& settings); + static AccountState *loadFromSettings(AccountPtr account, QSettings &settings); /** Writes account state information to settings. * * It does not write the Account data. */ - void writeToSettings(QSettings& settings); + void writeToSettings(QSettings &settings); AccountPtr account() const; @@ -134,10 +135,10 @@ signals: void isConnectedChanged(); protected Q_SLOTS: - void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList& errors); + void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList &errors); void slotInvalidCredentials(); - void slotCredentialsFetched(AbstractCredentials* creds); - void slotCredentialsAsked(AbstractCredentials* creds); + void slotCredentialsFetched(AbstractCredentials *creds); + void slotCredentialsAsked(AbstractCredentials *creds); private: AccountPtr _account; @@ -148,10 +149,9 @@ private: QElapsedTimer _timeSinceLastETagCheck; QPointer _connectionValidator; }; - } -Q_DECLARE_METATYPE(OCC::AccountState*) +Q_DECLARE_METATYPE(OCC::AccountState *) Q_DECLARE_METATYPE(OCC::AccountStatePtr) #endif //ACCOUNTINFO_H diff --git a/src/gui/activitydata.cpp b/src/gui/activitydata.cpp index cd67c9494..b0236658e 100644 --- a/src/gui/activitydata.cpp +++ b/src/gui/activitydata.cpp @@ -17,20 +17,20 @@ #include "activitydata.h" -namespace OCC -{ +namespace OCC { -bool operator<( const Activity& rhs, const Activity& lhs ) { +bool operator<(const Activity &rhs, const Activity &lhs) +{ return rhs._dateTime.toMSecsSinceEpoch() > lhs._dateTime.toMSecsSinceEpoch(); } -bool operator==( const Activity& rhs, const Activity& lhs ) { - return (rhs._type == lhs._type && rhs._id== lhs._id && rhs._accName == lhs._accName); +bool operator==(const Activity &rhs, const Activity &lhs) +{ + return (rhs._type == lhs._type && rhs._id == lhs._id && rhs._accName == lhs._accName); } -Activity::Identifier Activity::ident() const { - return Identifier( _id, _accName ); +Activity::Identifier Activity::ident() const +{ + return Identifier(_id, _accName); } - - } diff --git a/src/gui/activitydata.h b/src/gui/activitydata.h index 7817f5672..40cd35e05 100644 --- a/src/gui/activitydata.h +++ b/src/gui/activitydata.h @@ -27,10 +27,10 @@ namespace OCC { class ActivityLink { public: - QString _label; - QString _link; + QString _label; + QString _link; QByteArray _verb; - bool _isPrimary; + bool _isPrimary; }; /* ==================================================================== */ @@ -51,16 +51,16 @@ public: NotificationType }; - Type _type; + Type _type; qlonglong _id; - QString _subject; - QString _message; - QString _file; - QUrl _link; + QString _subject; + QString _message; + QString _file; + QUrl _link; QDateTime _dateTime; - QString _accName; + QString _accName; - QVector _links; + QVector _links; /** * @brief Sort operator to sort the list youngest first. * @param val @@ -71,8 +71,8 @@ public: Identifier ident() const; }; -bool operator==( const Activity& rhs, const Activity& lhs ); -bool operator<( const Activity& rhs, const Activity& lhs ); +bool operator==(const Activity &rhs, const Activity &lhs); +bool operator<(const Activity &rhs, const Activity &lhs); /* ==================================================================== */ /** @@ -83,8 +83,6 @@ bool operator<( const Activity& rhs, const Activity& lhs ); */ typedef QList ActivityList; - - } #endif // ACTIVITYDATA_H diff --git a/src/gui/activityitemdelegate.cpp b/src/gui/activityitemdelegate.cpp index 171b5895e..8de739eb7 100644 --- a/src/gui/activityitemdelegate.cpp +++ b/src/gui/activityitemdelegate.cpp @@ -33,7 +33,7 @@ int ActivityItemDelegate::_margin = 0; int ActivityItemDelegate::iconHeight() { - if( _iconHeight == 0 ) { + if (_iconHeight == 0) { QStyleOptionViewItem option; QFont font = option.font; @@ -46,74 +46,74 @@ int ActivityItemDelegate::iconHeight() int ActivityItemDelegate::rowHeight() { - if( _margin == 0 ) { - QStyleOptionViewItem opt; + if (_margin == 0) { + QStyleOptionViewItem opt; - QFont f = opt.font; - QFontMetrics fm(f); + QFont f = opt.font; + QFontMetrics fm(f); - _margin = fm.height()/4; + _margin = fm.height() / 4; } return iconHeight() + 2 * _margin; } -QSize ActivityItemDelegate::sizeHint(const QStyleOptionViewItem & option , - const QModelIndex & /* index */) const +QSize ActivityItemDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex & /* index */) const { QFont font = option.font; - return QSize( 0, rowHeight() ); + return QSize(0, rowHeight()); } void ActivityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const + const QModelIndex &index) const { - QStyledItemDelegate::paint(painter,option,index); + QStyledItemDelegate::paint(painter, option, index); QFont font = option.font; - QFontMetrics fm( font ); - int margin = fm.height()/4; + QFontMetrics fm(font); + int margin = fm.height() / 4; painter->save(); - QIcon actionIcon = qvariant_cast(index.data(ActionIconRole)); - QIcon userIcon = qvariant_cast(index.data(UserIconRole)); - QString actionText = qvariant_cast(index.data(ActionTextRole)); - QString pathText = qvariant_cast(index.data(PathRole)); + QIcon actionIcon = qvariant_cast(index.data(ActionIconRole)); + QIcon userIcon = qvariant_cast(index.data(UserIconRole)); + QString actionText = qvariant_cast(index.data(ActionTextRole)); + QString pathText = qvariant_cast(index.data(PathRole)); - QString remoteLink = qvariant_cast(index.data(LinkRole)); - QString timeText = qvariant_cast(index.data(PointInTimeRole)); - QString accountRole = qvariant_cast(index.data(AccountRole)); - bool accountOnline = qvariant_cast (index.data(AccountConnectedRole)); + QString remoteLink = qvariant_cast(index.data(LinkRole)); + QString timeText = qvariant_cast(index.data(PointInTimeRole)); + QString accountRole = qvariant_cast(index.data(AccountRole)); + bool accountOnline = qvariant_cast(index.data(AccountConnectedRole)); QRect actionIconRect = option.rect; - QRect userIconRect = option.rect; + QRect userIconRect = option.rect; int iconHeight = qRound(fm.height() / 5.0 * 8.0); int iconWidth = iconHeight; - actionIconRect.setLeft( option.rect.left() + margin ); - actionIconRect.setWidth( iconWidth ); - actionIconRect.setHeight( iconHeight ); - actionIconRect.setTop( actionIconRect.top() + margin ); - userIconRect.setLeft( actionIconRect.right() + margin ); - userIconRect.setWidth( iconWidth ); - userIconRect.setHeight( iconHeight ); - userIconRect.setTop( actionIconRect.top() ); + actionIconRect.setLeft(option.rect.left() + margin); + actionIconRect.setWidth(iconWidth); + actionIconRect.setHeight(iconHeight); + actionIconRect.setTop(actionIconRect.top() + margin); + userIconRect.setLeft(actionIconRect.right() + margin); + userIconRect.setWidth(iconWidth); + userIconRect.setHeight(iconHeight); + userIconRect.setTop(actionIconRect.top()); - int textTopOffset = qRound( (iconHeight - fm.height())/ 2.0 ); + int textTopOffset = qRound((iconHeight - fm.height()) / 2.0); // time rect QRect timeBox; int timeBoxWidth = fm.boundingRect(QLatin1String("4 hour(s) ago on longlongdomain.org")).width(); // FIXME. - timeBox.setTop( actionIconRect.top()+textTopOffset); - timeBox.setLeft( option.rect.right() - timeBoxWidth- margin ); - timeBox.setWidth( timeBoxWidth); - timeBox.setHeight( fm.height() ); + timeBox.setTop(actionIconRect.top() + textTopOffset); + timeBox.setLeft(option.rect.right() - timeBoxWidth - margin); + timeBox.setWidth(timeBoxWidth); + timeBox.setHeight(fm.height()); QRect actionTextBox = timeBox; - actionTextBox.setLeft( userIconRect.right()+margin ); - actionTextBox.setRight( timeBox.left()-margin ); + actionTextBox.setLeft(userIconRect.right() + margin); + actionTextBox.setRight(timeBox.left() - margin); /* === start drawing === */ QPixmap pm = actionIcon.pixmap(iconWidth, iconHeight, QIcon::Normal); @@ -123,7 +123,8 @@ void ActivityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & painter->drawPixmap(QPoint(userIconRect.left(), userIconRect.top()), pm); QPalette::ColorGroup cg = option.state & QStyle::State_Enabled - ? QPalette::Normal : QPalette::Disabled; + ? QPalette::Normal + : QPalette::Disabled; if (cg == QPalette::Normal && !(option.state & QStyle::State_Active)) cg = QPalette::Inactive; if (option.state & QStyle::State_Selected) { @@ -136,12 +137,12 @@ void ActivityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & painter->drawText(actionTextBox, elidedAction); int atPos = accountRole.indexOf(QLatin1Char('@')); - if( atPos > -1 ) { - accountRole.remove(0, atPos+1); + if (atPos > -1) { + accountRole.remove(0, atPos + 1); } QString timeStr; - if ( accountOnline ) { + if (accountOnline) { timeStr = tr("%1 on %2").arg(timeText, accountRole); } else { timeStr = tr("%1 on %2 (disconnected)").arg(timeText, accountRole); @@ -152,11 +153,10 @@ void ActivityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & painter->drawText(timeBox, elidedTime); painter->restore(); - } -bool ActivityItemDelegate::editorEvent ( QEvent * event, QAbstractItemModel * model, - const QStyleOptionViewItem & option, const QModelIndex & index ) +bool ActivityItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, + const QStyleOptionViewItem &option, const QModelIndex &index) { return QStyledItemDelegate::editorEvent(event, model, option, index); } diff --git a/src/gui/activityitemdelegate.h b/src/gui/activityitemdelegate.h index 82919ee24..193e15da9 100644 --- a/src/gui/activityitemdelegate.h +++ b/src/gui/activityitemdelegate.h @@ -26,20 +26,19 @@ class ActivityItemDelegate : public QStyledItemDelegate { Q_OBJECT public: - enum datarole { ActionIconRole = Qt::UserRole + 1, - UserIconRole, - AccountRole, - ActionTextRole, - PathRole, - LinkRole, - PointInTimeRole, - AccountConnectedRole }; - - void paint( QPainter*, const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE; - QSize sizeHint( const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE; - bool editorEvent( QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, - const QModelIndex& index ) Q_DECL_OVERRIDE; + UserIconRole, + AccountRole, + ActionTextRole, + PathRole, + LinkRole, + PointInTimeRole, + AccountConnectedRole }; + + void paint(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE; + QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE; + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, + const QModelIndex &index) Q_DECL_OVERRIDE; static int rowHeight(); static int iconHeight(); @@ -50,4 +49,3 @@ private: }; } // namespace OCC - diff --git a/src/gui/activitylistmodel.cpp b/src/gui/activitylistmodel.cpp index fb1201ef3..05af4a8e3 100644 --- a/src/gui/activitylistmodel.cpp +++ b/src/gui/activitylistmodel.cpp @@ -38,7 +38,7 @@ namespace OCC { Q_LOGGING_CATEGORY(lcActivity, "gui.activity", QtInfoMsg) ActivityListModel::ActivityListModel(QWidget *parent) - :QAbstractListModel(parent) + : QAbstractListModel(parent) { } @@ -58,12 +58,12 @@ QVariant ActivityListModel::data(const QModelIndex &index, int role) const switch (role) { case ActivityItemDelegate::PathRole: list = FolderMan::instance()->findFileInLocalFolders(a._file, ast->account()); - if( list.count() > 0 ) { + if (list.count() > 0) { return QVariant(list.at(0)); } // File does not exist anymore? Let's try to open its path list = FolderMan::instance()->findFileInLocalFolders(QFileInfo(a._file).path(), ast->account()); - if( list.count() > 0 ) { + if (list.count() > 0) { return QVariant(list.at(0)); } return QVariant(); @@ -92,13 +92,11 @@ QVariant ActivityListModel::data(const QModelIndex &index, int role) const break; default: return QVariant(); - } return QVariant(); - } -int ActivityListModel::rowCount(const QModelIndex&) const +int ActivityListModel::rowCount(const QModelIndex &) const { return _finalList.count(); } @@ -106,16 +104,16 @@ int ActivityListModel::rowCount(const QModelIndex&) const // current strategy: Fetch 100 items per Account // ATTENTION: This method is const and thus it is not possible to modify // the _activityLists hash or so. Doesn't make it easier... -bool ActivityListModel::canFetchMore(const QModelIndex& ) const +bool ActivityListModel::canFetchMore(const QModelIndex &) const { - if( _activityLists.count() == 0 ) return true; + if (_activityLists.count() == 0) + return true; - for(auto i = _activityLists.begin() ; i != _activityLists.end(); ++i) { + for (auto i = _activityLists.begin(); i != _activityLists.end(); ++i) { AccountState *ast = i.key(); - if( ast && ast->isConnected() ) { + if (ast && ast->isConnected()) { ActivityList activities = i.value(); - if( activities.count() == 0 && - ! _currentlyFetching.contains(ast) ) { + if (activities.count() == 0 && !_currentlyFetching.contains(ast)) { return true; } } @@ -124,18 +122,18 @@ bool ActivityListModel::canFetchMore(const QModelIndex& ) const return false; } -void ActivityListModel::startFetchJob(AccountState* s) +void ActivityListModel::startFetchJob(AccountState *s) { - if( !s->isConnected() ) { + if (!s->isConnected()) { return; } JsonApiJob *job = new JsonApiJob(s->account(), QLatin1String("ocs/v1.php/cloud/activity"), this); QObject::connect(job, SIGNAL(jsonReceived(QJsonDocument, int)), - this, SLOT(slotActivitiesReceived(QJsonDocument, int))); + this, SLOT(slotActivitiesReceived(QJsonDocument, int))); job->setProperty("AccountStatePtr", QVariant::fromValue>(s)); - QList< QPair > params; - params.append(qMakePair(QString::fromLatin1("page"), QString::fromLatin1("0"))); + QList> params; + params.append(qMakePair(QString::fromLatin1("page"), QString::fromLatin1("0"))); params.append(qMakePair(QString::fromLatin1("pagesize"), QString::fromLatin1("100"))); job->addQueryParams(params); @@ -144,7 +142,7 @@ void ActivityListModel::startFetchJob(AccountState* s) job->start(); } -void ActivityListModel::slotActivitiesReceived(const QJsonDocument& json, int statusCode) +void ActivityListModel::slotActivitiesReceived(const QJsonDocument &json, int statusCode) { auto activities = json.object().value("ocs").toObject().value("data").toArray(); @@ -155,17 +153,17 @@ void ActivityListModel::slotActivitiesReceived(const QJsonDocument& json, int st _currentlyFetching.remove(ast); - foreach( auto activ, activities ) { + foreach (auto activ, activities) { auto json = activ.toObject(); Activity a; a._type = Activity::ActivityType; - a._accName = ast->account()->displayName(); - a._id = json.value("id").toInt(); - a._subject = json.value("subject").toString(); - a._message = json.value("message").toString(); - a._file = json.value("file").toString(); - a._link = QUrl(json.value("link").toString()); + a._accName = ast->account()->displayName(); + a._id = json.value("id").toInt(); + a._subject = json.value("subject").toString(); + a._message = json.value("message").toString(); + a._file = json.value("file").toString(); + a._link = QUrl(json.value("link").toString()); a._dateTime = QDateTime::fromString(json.value("date").toString(), Qt::ISODate); list.append(a); } @@ -182,11 +180,11 @@ void ActivityListModel::combineActivityLists() { ActivityList resultList; - foreach( ActivityList list, _activityLists.values() ) { + foreach (ActivityList list, _activityLists.values()) { resultList.append(list); } - std::sort( resultList.begin(), resultList.end() ); + std::sort(resultList.begin(), resultList.end()); beginResetModel(); _finalList.clear(); @@ -201,9 +199,8 @@ void ActivityListModel::fetchMore(const QModelIndex &) { QList accounts = AccountManager::instance()->accounts(); - foreach (const AccountStatePtr& asp, accounts) { - - if( !_activityLists.contains(asp.data()) && asp->isConnected() ) { + foreach (const AccountStatePtr &asp, accounts) { + if (!_activityLists.contains(asp.data()) && asp->isConnected()) { _activityLists[asp.data()] = ActivityList(); startFetchJob(asp.data()); } @@ -212,15 +209,15 @@ void ActivityListModel::fetchMore(const QModelIndex &) void ActivityListModel::slotRefreshActivity(AccountState *ast) { - if(ast && _activityLists.contains(ast)) { + if (ast && _activityLists.contains(ast)) { _activityLists.remove(ast); } startFetchJob(ast); } -void ActivityListModel::slotRemoveAccount(AccountState *ast ) +void ActivityListModel::slotRemoveAccount(AccountState *ast) { - if( _activityLists.contains(ast) ) { + if (_activityLists.contains(ast)) { int i = 0; const QString accountToRemove = ast->account()->displayName(); @@ -228,8 +225,8 @@ void ActivityListModel::slotRemoveAccount(AccountState *ast ) while (it.hasNext()) { Activity activity = it.next(); - if( activity._accName == accountToRemove ) { - beginRemoveRows(QModelIndex(), i, i+1); + if (activity._accName == accountToRemove) { + beginRemoveRows(QModelIndex(), i, i + 1); it.remove(); endRemoveRows(); } @@ -238,5 +235,4 @@ void ActivityListModel::slotRemoveAccount(AccountState *ast ) _currentlyFetching.remove(ast); } } - } diff --git a/src/gui/activitylistmodel.h b/src/gui/activitylistmodel.h index ed3a9e270..ad5574d27 100644 --- a/src/gui/activitylistmodel.h +++ b/src/gui/activitylistmodel.h @@ -38,35 +38,33 @@ class ActivityListModel : public QAbstractListModel { Q_OBJECT public: - explicit ActivityListModel(QWidget *parent=0); + explicit ActivityListModel(QWidget *parent = 0); QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - int rowCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - bool canFetchMore(const QModelIndex& ) const Q_DECL_OVERRIDE; - void fetchMore(const QModelIndex&) Q_DECL_OVERRIDE; + bool canFetchMore(const QModelIndex &) const Q_DECL_OVERRIDE; + void fetchMore(const QModelIndex &) Q_DECL_OVERRIDE; ActivityList activityList() { return _finalList; } public slots: - void slotRefreshActivity(AccountState* ast); - void slotRemoveAccount( AccountState *ast ); + void slotRefreshActivity(AccountState *ast); + void slotRemoveAccount(AccountState *ast); private slots: - void slotActivitiesReceived(const QJsonDocument& json, int statusCode); + void slotActivitiesReceived(const QJsonDocument &json, int statusCode); signals: - void activityJobStatusCode(AccountState* ast, int statusCode); + void activityJobStatusCode(AccountState *ast, int statusCode); private: - void startFetchJob(AccountState* s); + void startFetchJob(AccountState *s); void combineActivityLists(); - QMap _activityLists; + QMap _activityLists; ActivityList _finalList; - QSet _currentlyFetching; + QSet _currentlyFetching; }; - - } #endif // ACTIVITYLISTMODEL_H diff --git a/src/gui/activitywidget.cpp b/src/gui/activitywidget.cpp index 176679316..6a55001c0 100644 --- a/src/gui/activitywidget.cpp +++ b/src/gui/activitywidget.cpp @@ -50,14 +50,14 @@ namespace OCC { -ActivityWidget::ActivityWidget(QWidget *parent) : - QWidget(parent), - _ui(new Ui::ActivityWidget), - _notificationRequestsRunning(0) +ActivityWidget::ActivityWidget(QWidget *parent) + : QWidget(parent) + , _ui(new Ui::ActivityWidget) + , _notificationRequestsRunning(0) { _ui->setupUi(this); - // Adjust copyToClipboard() when making changes here! +// Adjust copyToClipboard() when making changes here! #if defined(Q_OS_MAC) _ui->_activityList->setMinimumWidth(400); #endif @@ -83,19 +83,19 @@ ActivityWidget::ActivityWidget(QWidget *parent) : showLabels(); - connect(_model, SIGNAL(activityJobStatusCode(AccountState*,int)), - this, SLOT(slotAccountActivityStatus(AccountState*,int))); + connect(_model, SIGNAL(activityJobStatusCode(AccountState *, int)), + this, SLOT(slotAccountActivityStatus(AccountState *, int))); _copyBtn = _ui->_dialogButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole); - _copyBtn->setToolTip( tr("Copy the activity list to the clipboard.")); + _copyBtn->setToolTip(tr("Copy the activity list to the clipboard.")); connect(_copyBtn, SIGNAL(clicked()), SIGNAL(copyToClipboard())); - connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(rowsInserted())); + connect(_model, SIGNAL(rowsInserted(QModelIndex, int, int)), SIGNAL(rowsInserted())); - connect( _ui->_activityList, SIGNAL(activated(QModelIndex)), this, - SLOT(slotOpenFile(QModelIndex))); + connect(_ui->_activityList, SIGNAL(activated(QModelIndex)), this, + SLOT(slotOpenFile(QModelIndex))); - connect( &_removeTimer, SIGNAL(timeout()), this, SLOT(slotCheckToCleanWidgets()) ); + connect(&_removeTimer, SIGNAL(timeout()), this, SLOT(slotCheckToCleanWidgets())); _removeTimer.setInterval(1000); } @@ -113,10 +113,10 @@ void ActivityWidget::slotRefreshNotifications(AccountState *ptr) { // start a server notification handler if no notification requests // are running - if( _notificationRequestsRunning == 0 ) { + if (_notificationRequestsRunning == 0) { ServerNotificationHandler *snh = new ServerNotificationHandler; connect(snh, SIGNAL(newNotificationList(ActivityList)), this, - SLOT(slotBuildNotificationDisplay(ActivityList))); + SLOT(slotBuildNotificationDisplay(ActivityList))); snh->slotFetchNotifications(ptr); } else { @@ -124,7 +124,7 @@ void ActivityWidget::slotRefreshNotifications(AccountState *ptr) } } -void ActivityWidget::slotRemoveAccount( AccountState *ptr ) +void ActivityWidget::slotRemoveAccount(AccountState *ptr) { _model->slotRemoveAccount(ptr); } @@ -139,8 +139,8 @@ void ActivityWidget::showLabels() t.clear(); QSetIterator i(_accountsWithoutActivities); - while (i.hasNext() ) { - t.append( tr("
Account %1 does not have activities enabled.").arg(i.next())); + while (i.hasNext()) { + t.append(tr("
Account %1 does not have activities enabled.").arg(i.next())); } _ui->_bottomLabel->setTextFormat(Qt::RichText); _ui->_bottomLabel->setText(t); @@ -148,10 +148,10 @@ void ActivityWidget::showLabels() void ActivityWidget::slotAccountActivityStatus(AccountState *ast, int statusCode) { - if( !(ast && ast->account()) ) { + if (!(ast && ast->account())) { return; } - if( statusCode == 999 ) { + if (statusCode == 999) { _accountsWithoutActivities.insert(ast->account()->displayName()); } else { _accountsWithoutActivities.remove(ast->account()->displayName()); @@ -171,40 +171,40 @@ QString ActivityWidget::timeString(QDateTime dt, QLocale::FormatType format) con return loc.toString(dt, dtFormat); } -void ActivityWidget::storeActivityList( QTextStream& ts ) +void ActivityWidget::storeActivityList(QTextStream &ts) { ActivityList activities = _model->activityList(); - foreach( Activity activity, activities ) { + foreach (Activity activity, activities) { ts << right - // account name + // account name << qSetFieldWidth(30) << activity._accName - // separator + // separator << qSetFieldWidth(0) << "," - // date and time + // date and time << qSetFieldWidth(34) << activity._dateTime.toString() - // separator + // separator << qSetFieldWidth(0) << "," - // file + // file << qSetFieldWidth(30) << activity._file - // separator + // separator << qSetFieldWidth(0) << "," - // subject + // subject << qSetFieldWidth(100) << activity._subject - // separator + // separator << qSetFieldWidth(0) << "," - // message (mostly empty) + // message (mostly empty) << qSetFieldWidth(55) << activity._message - // + // << qSetFieldWidth(0) << endl; } @@ -214,14 +214,14 @@ void ActivityWidget::checkActivityTabVisibility() { int accountCount = AccountManager::instance()->accounts().count(); bool hasAccountsWithActivity = - _accountsWithoutActivities.count() != accountCount; + _accountsWithoutActivities.count() != accountCount; bool hasNotifications = !_widgetForNotifId.isEmpty(); - _ui->_headerLabel->setVisible( hasAccountsWithActivity ); - _ui->_activityList->setVisible( hasAccountsWithActivity ); + _ui->_headerLabel->setVisible(hasAccountsWithActivity); + _ui->_activityList->setVisible(hasAccountsWithActivity); - _ui->_notifyLabel->setVisible( hasNotifications ); - _ui->_notifyScroll->setVisible( hasNotifications ); + _ui->_notifyLabel->setVisible(hasNotifications); + _ui->_notifyScroll->setVisible(hasNotifications); emit hideActivityTab(!hasAccountsWithActivity && !hasNotifications); } @@ -229,7 +229,7 @@ void ActivityWidget::checkActivityTabVisibility() void ActivityWidget::slotOpenFile(QModelIndex indx) { qCDebug(lcActivity) << indx.isValid() << indx.data(ActivityItemDelegate::PathRole).toString() << QFile::exists(indx.data(ActivityItemDelegate::PathRole).toString()); - if( indx.isValid() ) { + if (indx.isValid()) { QString fullPath = indx.data(ActivityItemDelegate::PathRole).toString(); if (QFile::exists(fullPath)) { @@ -242,7 +242,7 @@ void ActivityWidget::slotOpenFile(QModelIndex indx) // All notifications in list are coming from the same account // but in the _widgetForNotifId hash widgets for all accounts are // collected. -void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) +void ActivityWidget::slotBuildNotificationDisplay(const ActivityList &list) { QHash accNotified; QString listAccountName; @@ -250,25 +250,25 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) // Whether a new notification widget was added to the notificationLayout. bool newNotificationShown = false; - foreach( auto activity, list ) { - if( _blacklistedNotifications.contains(activity)) { + foreach (auto activity, list) { + if (_blacklistedNotifications.contains(activity)) { qCInfo(lcActivity) << "Activity in blacklist, skip"; continue; } NotificationWidget *widget = 0; - if( _widgetForNotifId.contains( activity.ident()) ) { + if (_widgetForNotifId.contains(activity.ident())) { widget = _widgetForNotifId[activity.ident()]; } else { widget = new NotificationWidget(this); connect(widget, SIGNAL(sendNotificationRequest(QString, QString, QByteArray)), - this, SLOT(slotSendNotificationRequest(QString, QString, QByteArray))); + this, SLOT(slotSendNotificationRequest(QString, QString, QByteArray))); connect(widget, SIGNAL(requestCleanupAndBlacklist(Activity)), - this, SLOT(slotRequestCleanupAndBlacklist(Activity))); + this, SLOT(slotRequestCleanupAndBlacklist(Activity))); _notificationsLayout->addWidget(widget); - // _ui->_notifyScroll->setMinimumHeight( widget->height()); +// _ui->_notifyScroll->setMinimumHeight( widget->height()); #if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) _ui->_notifyScroll->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContentsOnFirstShow); #endif @@ -276,7 +276,7 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) newNotificationShown = true; } - widget->setActivity( activity ); + widget->setActivity(activity); // remember the list account name for the strayCat handling below. listAccountName = activity._accName; @@ -288,21 +288,21 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) // will repeat the gui log. // after one hour, clear the gui log notification store - if( _guiLogTimer.elapsed() > 60*60*1000 ) { + if (_guiLogTimer.elapsed() > 60 * 60 * 1000) { _guiLoggedNotifications.clear(); } - if( !_guiLoggedNotifications.contains(activity._id)) { + if (!_guiLoggedNotifications.contains(activity._id)) { QString host = activity._accName; // store the name of the account that sends the notification to be // able to add it to the tray notification // remove the user name from the account as that is not accurate here. int indx = host.indexOf(QChar('@')); - if( indx>-1 ) { - host.remove(0, 1+indx); + if (indx > -1) { + host.remove(0, 1 + indx); } - if( !host.isEmpty() ) { - if( accNotified.contains(host)) { - accNotified[host] = accNotified[host]+1; + if (!host.isEmpty()) { + if (accNotified.contains(host)) { + accNotified[host] = accNotified[host] + 1; } else { accNotified[host] = 1; } @@ -313,31 +313,31 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) // check if there are widgets that have no corresponding activity from // the server any more. Collect them in a list - QList< Activity::Identifier > strayCats; - foreach( auto id, _widgetForNotifId.keys() ) { + QList strayCats; + foreach (auto id, _widgetForNotifId.keys()) { NotificationWidget *widget = _widgetForNotifId[id]; bool found = false; // do not mark widgets of other accounts to delete. - if( widget->activity()._accName != listAccountName ) { + if (widget->activity()._accName != listAccountName) { continue; } - foreach( auto activity, list ) { - if( activity.ident() == id ) { + foreach (auto activity, list) { + if (activity.ident() == id) { // found an activity found = true; break; } } - if( ! found ) { + if (!found) { // the activity does not exist any more. strayCats.append(id); } } // .. and now delete all these stray cat widgets. - foreach( auto strayCatId, strayCats ) { + foreach (auto strayCatId, strayCats) { NotificationWidget *widgetToGo = _widgetForNotifId[strayCatId]; scheduleWidgetToRemove(widgetToGo, 0); } @@ -346,19 +346,18 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) int newGuiLogCount = accNotified.count(); - if( newGuiLogCount > 0 ) { + if (newGuiLogCount > 0) { // restart the gui log timer now that we show a notification _guiLogTimer.restart(); // Assemble a tray notification - QString msg = tr("You received %n new notification(s) from %2.", "", accNotified[accNotified.keys().at(0)]). - arg(accNotified.keys().at(0)); + QString msg = tr("You received %n new notification(s) from %2.", "", accNotified[accNotified.keys().at(0)]).arg(accNotified.keys().at(0)); - if( newGuiLogCount >= 2 ) { + if (newGuiLogCount >= 2) { QString acc1 = accNotified.keys().at(0); QString acc2 = accNotified.keys().at(1); - if( newGuiLogCount == 2 ) { - int notiCount = accNotified[ acc1 ] + accNotified[ acc2 ]; + if (newGuiLogCount == 2) { + int notiCount = accNotified[acc1] + accNotified[acc2]; msg = tr("You received %n new notification(s) from %1 and %2.", "", notiCount).arg(acc1, acc2); } else { msg = tr("You received new notifications from %1, %2 and other accounts.").arg(acc1, acc2); @@ -366,7 +365,7 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) } const QString log = tr("%1 Notifications - Action Required").arg(Theme::instance()->appNameGUI()); - emit guiLog( log, msg); + emit guiLog(log, msg); } if (newNotificationShown) { @@ -374,24 +373,27 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list) } } -void ActivityWidget::slotSendNotificationRequest(const QString& accountName, const QString& link, const QByteArray& verb) +void ActivityWidget::slotSendNotificationRequest(const QString &accountName, const QString &link, const QByteArray &verb) { qCInfo(lcActivity) << "Server Notification Request " << verb << link << "on account" << accountName; - NotificationWidget *theSender = qobject_cast(sender()); + NotificationWidget *theSender = qobject_cast(sender()); - const QStringList validVerbs = QStringList() << "GET" << "PUT" << "POST" << "DELETE"; + const QStringList validVerbs = QStringList() << "GET" + << "PUT" + << "POST" + << "DELETE"; - if( validVerbs.contains(verb)) { + if (validVerbs.contains(verb)) { AccountStatePtr acc = AccountManager::instance()->account(accountName); - if( acc ) { + if (acc) { NotificationConfirmJob *job = new NotificationConfirmJob(acc->account()); QUrl l(link); job->setLinkAndVerb(l, verb); job->setWidget(theSender); - connect( job, SIGNAL( networkError(QNetworkReply*)), - this, SLOT(slotNotifyNetworkError(QNetworkReply*))); - connect( job, SIGNAL( jobFinished(QString, int)), - this, SLOT(slotNotifyServerFinished(QString, int)) ); + connect(job, SIGNAL(networkError(QNetworkReply *)), + this, SLOT(slotNotifyNetworkError(QNetworkReply *))); + connect(job, SIGNAL(jobFinished(QString, int)), + this, SLOT(slotNotifyServerFinished(QString, int))); job->start(); // count the number of running notification requests. If this member var @@ -403,18 +405,18 @@ void ActivityWidget::slotSendNotificationRequest(const QString& accountName, con } } -void ActivityWidget::endNotificationRequest( NotificationWidget *widget, int replyCode ) +void ActivityWidget::endNotificationRequest(NotificationWidget *widget, int replyCode) { _notificationRequestsRunning--; - if( widget ) { + if (widget) { widget->slotNotificationRequestFinished(replyCode); } } -void ActivityWidget::slotNotifyNetworkError( QNetworkReply *reply) +void ActivityWidget::slotNotifyNetworkError(QNetworkReply *reply) { - NotificationConfirmJob *job = qobject_cast(sender()); - if( !job ) { + NotificationConfirmJob *job = qobject_cast(sender()); + if (!job) { return; } @@ -422,43 +424,42 @@ void ActivityWidget::slotNotifyNetworkError( QNetworkReply *reply) endNotificationRequest(job->widget(), resultCode); qCWarning(lcActivity) << "Server notify job failed with code " << resultCode; - } -void ActivityWidget::slotNotifyServerFinished( const QString& reply, int replyCode ) +void ActivityWidget::slotNotifyServerFinished(const QString &reply, int replyCode) { - NotificationConfirmJob *job = qobject_cast(sender()); - if( !job ) { + NotificationConfirmJob *job = qobject_cast(sender()); + if (!job) { return; } endNotificationRequest(job->widget(), replyCode); // FIXME: remove the widget after a couple of seconds - qCInfo(lcActivity) << "Server Notification reply code"<< replyCode << reply; + qCInfo(lcActivity) << "Server Notification reply code" << replyCode << reply; // if the notification was successful start a timer that triggers // removal of the done widgets in a few seconds // Add 200 millisecs to the predefined value to make sure that the timer in // widget's method readyToClose() has elapsed. - if( replyCode == OCS_SUCCESS_STATUS_CODE ) { - scheduleWidgetToRemove( job->widget() ); + if (replyCode == OCS_SUCCESS_STATUS_CODE) { + scheduleWidgetToRemove(job->widget()); } } // blacklist the activity coming in here. -void ActivityWidget::slotRequestCleanupAndBlacklist(const Activity& blacklistActivity) +void ActivityWidget::slotRequestCleanupAndBlacklist(const Activity &blacklistActivity) { - if ( ! _blacklistedNotifications.contains(blacklistActivity) ) { + if (!_blacklistedNotifications.contains(blacklistActivity)) { _blacklistedNotifications.append(blacklistActivity); } - NotificationWidget *widget = _widgetForNotifId[ blacklistActivity.ident() ]; + NotificationWidget *widget = _widgetForNotifId[blacklistActivity.ident()]; scheduleWidgetToRemove(widget); } void ActivityWidget::scheduleWidgetToRemove(NotificationWidget *widget, int milliseconds) { - if( !widget ) { + if (!widget) { return; } // in five seconds from now, remove the widget. @@ -467,7 +468,7 @@ void ActivityWidget::scheduleWidgetToRemove(NotificationWidget *widget, int mill if (!it.isValid() || it > removeTime) { it = removeTime; } - if( !_removeTimer.isActive() ) { + if (!_removeTimer.isActive()) { _removeTimer.start(); } } @@ -482,7 +483,7 @@ void ActivityWidget::slotCheckToCleanWidgets() QDateTime t = it.value(); NotificationWidget *widget = it.key(); - if( currentTime > t ) { + if (currentTime > t) { // found one to remove! Activity::Identifier id = widget->activity().ident(); _widgetForNotifId.remove(id); @@ -493,12 +494,12 @@ void ActivityWidget::slotCheckToCleanWidgets() } } - if( _widgetsToRemove.isEmpty() ) { + if (_widgetsToRemove.isEmpty()) { _removeTimer.stop(); } // check to see if the whole notification pane should be hidden - if( _widgetForNotifId.isEmpty() ) { + if (_widgetForNotifId.isEmpty()) { _ui->_notifyLabel->setHidden(true); _ui->_notifyScroll->setHidden(true); } @@ -508,7 +509,7 @@ void ActivityWidget::slotCheckToCleanWidgets() /* ==================================================================== */ ActivitySettings::ActivitySettings(QWidget *parent) - :QWidget(parent) + : QWidget(parent) { QHBoxLayout *hbox = new QHBoxLayout(this); setLayout(hbox); @@ -520,14 +521,14 @@ ActivitySettings::ActivitySettings(QWidget *parent) _activityTabId = _tab->insertTab(0, _activityWidget, Theme::instance()->applicationIcon(), tr("Server Activity")); connect(_activityWidget, SIGNAL(copyToClipboard()), this, SLOT(slotCopyToClipboard())); connect(_activityWidget, SIGNAL(hideActivityTab(bool)), this, SLOT(setActivityTabHidden(bool))); - connect(_activityWidget, SIGNAL(guiLog(QString,QString)), this, SIGNAL(guiLog(QString,QString))); + connect(_activityWidget, SIGNAL(guiLog(QString, QString)), this, SIGNAL(guiLog(QString, QString))); connect(_activityWidget, SIGNAL(newNotification()), SLOT(slotShowActivityTab())); _protocolWidget = new ProtocolWidget(this); _tab->insertTab(1, _protocolWidget, Theme::instance()->syncStateIcon(SyncResult::Success), tr("Sync Protocol")); connect(_protocolWidget, SIGNAL(copyToClipboard()), this, SLOT(slotCopyToClipboard())); connect(_protocolWidget, SIGNAL(issueItemCountUpdated(int)), - this, SLOT(slotShowIssueItemCount(int))); + this, SLOT(slotShowIssueItemCount(int))); // Add the not-synced list into the tab QWidget *w = new QWidget; @@ -537,7 +538,7 @@ ActivitySettings::ActivitySettings(QWidget *parent) QDialogButtonBox *dlgButtonBox = new QDialogButtonBox(this); vbox2->addWidget(dlgButtonBox); QPushButton *_copyBtn = dlgButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole); - _copyBtn->setToolTip( tr("Copy the activity list to the clipboard.")); + _copyBtn->setToolTip(tr("Copy the activity list to the clipboard.")); _copyBtn->setEnabled(true); connect(_copyBtn, SIGNAL(clicked()), this, SLOT(slotCopyToClipboard())); @@ -550,7 +551,7 @@ ActivitySettings::ActivitySettings(QWidget *parent) _tab->setCornerWidget(_progressIndicator); connect(&_notificationCheckTimer, SIGNAL(timeout()), - this, SLOT(slotRegularNotificationCheck())); + this, SLOT(slotRegularNotificationCheck())); // connect a model signal to stop the animation. connect(_activityWidget, SIGNAL(rowsInserted()), _progressIndicator, SLOT(stopAnimation())); @@ -559,20 +560,20 @@ ActivitySettings::ActivitySettings(QWidget *parent) _tab->setCurrentIndex(1); } -void ActivitySettings::setNotificationRefreshInterval( quint64 interval ) +void ActivitySettings::setNotificationRefreshInterval(quint64 interval) { - qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval/1000 << " sec interval"; + qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval / 1000 << " sec interval"; _notificationCheckTimer.start(interval); } void ActivitySettings::setActivityTabHidden(bool hidden) { - if( hidden && _activityTabId > -1 ) { + if (hidden && _activityTabId > -1) { _tab->removeTab(_activityTabId); _activityTabId = -1; } - if( !hidden && _activityTabId == -1 ) { + if (!hidden && _activityTabId == -1) { _activityTabId = _tab->insertTab(0, _activityWidget, Theme::instance()->applicationIcon(), tr("Server Activity")); } } @@ -580,7 +581,7 @@ void ActivitySettings::setActivityTabHidden(bool hidden) void ActivitySettings::slotShowIssueItemCount(int cnt) { QString cntText = tr("Not Synced"); - if( cnt ) { + if (cnt) { //: %1 is the number of not synced files. cntText = tr("Not Synced (%1)").arg(cnt); } @@ -602,46 +603,46 @@ void ActivitySettings::slotCopyToClipboard() int idx = _tab->currentIndex(); QString message; - if( idx == 0 ) { + if (idx == 0) { // the activity widget _activityWidget->storeActivityList(ts); message = tr("The server activity list has been copied to the clipboard."); - } else if(idx == 1 ) { + } else if (idx == 1) { // the protocol widget _protocolWidget->storeSyncActivity(ts); message = tr("The sync activity list has been copied to the clipboard."); - } else if(idx == 2 ) { + } else if (idx == 2) { // issues Widget message = tr("The list of unsynced items has been copied to the clipboard."); - _protocolWidget->storeSyncIssues(ts); + _protocolWidget->storeSyncIssues(ts); } QApplication::clipboard()->setText(text); emit guiLog(tr("Copied to clipboard"), message); } -void ActivitySettings::slotRemoveAccount( AccountState *ptr ) +void ActivitySettings::slotRemoveAccount(AccountState *ptr) { _activityWidget->slotRemoveAccount(ptr); } -void ActivitySettings::slotRefresh( AccountState* ptr ) +void ActivitySettings::slotRefresh(AccountState *ptr) { // QElapsedTimer isn't actually constructed as invalid. - if ( !_timeSinceLastCheck.contains(ptr) ) { + if (!_timeSinceLastCheck.contains(ptr)) { _timeSinceLastCheck[ptr].invalidate(); } - QElapsedTimer & timer = _timeSinceLastCheck[ptr]; + QElapsedTimer &timer = _timeSinceLastCheck[ptr]; // Fetch Activities only if visible and if last check is longer than 15 secs ago - if( timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD ) { + if (timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD) { qCDebug(lcActivity) << "Do not check as last check is only secs ago: " << timer.elapsed() / 1000; return; } - if( ptr && ptr->isConnected() ) { - if( isVisible() || !timer.isValid() ) { + if (ptr && ptr->isConnected()) { + if (isVisible() || !timer.isValid()) { _progressIndicator->startAnimation(); - _activityWidget->slotRefreshActivities( ptr); + _activityWidget->slotRefreshActivities(ptr); } _activityWidget->slotRefreshNotifications(ptr); timer.start(); @@ -656,7 +657,7 @@ void ActivitySettings::slotRegularNotificationCheck() } } -bool ActivitySettings::event(QEvent* e) +bool ActivitySettings::event(QEvent *e) { if (e->type() == QEvent::Show) { AccountManager *am = AccountManager::instance(); @@ -669,8 +670,5 @@ bool ActivitySettings::event(QEvent* e) ActivitySettings::~ActivitySettings() { - } - - } diff --git a/src/gui/activitywidget.h b/src/gui/activitywidget.h index a60f51d4f..bae9b6ff9 100644 --- a/src/gui/activitywidget.h +++ b/src/gui/activitywidget.h @@ -40,7 +40,7 @@ class NotificationWidget; class ActivityListModel; namespace Ui { - class ActivityWidget; + class ActivityWidget; } class Application; @@ -71,25 +71,25 @@ public: public slots: void slotOpenFile(QModelIndex indx); - void slotRefreshActivities(AccountState* ptr); + void slotRefreshActivities(AccountState *ptr); void slotRefreshNotifications(AccountState *ptr); - void slotRemoveAccount( AccountState *ptr ); + void slotRemoveAccount(AccountState *ptr); void slotAccountActivityStatus(AccountState *ast, int statusCode); - void slotRequestCleanupAndBlacklist(const Activity& blacklistActivity); + void slotRequestCleanupAndBlacklist(const Activity &blacklistActivity); signals: - void guiLog(const QString&, const QString&); + void guiLog(const QString &, const QString &); void copyToClipboard(); void rowsInserted(); void hideActivityTab(bool); void newNotification(); private slots: - void slotBuildNotificationDisplay(const ActivityList& list); - void slotSendNotificationRequest(const QString &accountName, const QString& link, const QByteArray &verb); - void slotNotifyNetworkError( QNetworkReply* ); - void slotNotifyServerFinished( const QString& reply, int replyCode ); - void endNotificationRequest(NotificationWidget *widget , int replyCode); + void slotBuildNotificationDisplay(const ActivityList &list); + void slotSendNotificationRequest(const QString &accountName, const QString &link, const QByteArray &verb); + void slotNotifyNetworkError(QNetworkReply *); + void slotNotifyServerFinished(const QString &reply, int replyCode); + void endNotificationRequest(NotificationWidget *widget, int replyCode); void scheduleWidgetToRemove(NotificationWidget *widget, int milliseconds = 4500); void slotCheckToCleanWidgets(); @@ -100,12 +100,12 @@ private: QPushButton *_copyBtn; QSet _accountsWithoutActivities; - QMap _widgetForNotifId; + QMap _widgetForNotifId; QElapsedTimer _guiLogTimer; QSet _guiLoggedNotifications; ActivityList _blacklistedNotifications; - QHash _widgetsToRemove; + QHash _widgetsToRemove; QTimer _removeTimer; // number of currently running notification requests. If non zero, @@ -114,7 +114,6 @@ private: ActivityListModel *_model; QVBoxLayout *_notificationsLayout; - }; @@ -134,10 +133,10 @@ public: QSize sizeHint() const Q_DECL_OVERRIDE { return ownCloudGui::settingsDialogSize(); } public slots: - void slotRefresh( AccountState* ptr ); - void slotRemoveAccount( AccountState *ptr ); + void slotRefresh(AccountState *ptr); + void slotRemoveAccount(AccountState *ptr); - void setNotificationRefreshInterval( quint64 interval ); + void setNotificationRefreshInterval(quint64 interval); private slots: void slotCopyToClipboard(); @@ -147,10 +146,10 @@ private slots: void slotShowActivityTab(); signals: - void guiLog(const QString&, const QString&); + void guiLog(const QString &, const QString &); private: - bool event(QEvent* e) Q_DECL_OVERRIDE; + bool event(QEvent *e) Q_DECL_OVERRIDE; QTabWidget *_tab; int _activityTabId; @@ -159,9 +158,8 @@ private: ActivityWidget *_activityWidget; ProtocolWidget *_protocolWidget; QProgressIndicator *_progressIndicator; - QTimer _notificationCheckTimer; - QHash _timeSinceLastCheck; + QTimer _notificationCheckTimer; + QHash _timeSinceLastCheck; }; - } #endif // ActivityWIDGET_H diff --git a/src/gui/addcertificatedialog.cpp b/src/gui/addcertificatedialog.cpp index 34e0fc242..fabaeec5b 100644 --- a/src/gui/addcertificatedialog.cpp +++ b/src/gui/addcertificatedialog.cpp @@ -20,9 +20,9 @@ namespace OCC { -AddCertificateDialog::AddCertificateDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::AddCertificateDialog) +AddCertificateDialog::AddCertificateDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::AddCertificateDialog) { ui->setupUi(this); ui->labelErrorCertif->setText(""); @@ -60,5 +60,4 @@ void AddCertificateDialog::reinit() ui->lineEditCertificatePath->clear(); ui->lineEditPWDCertificate->clear(); } - } diff --git a/src/gui/addcertificatedialog.h b/src/gui/addcertificatedialog.h index 1840f5007..c9e6826c2 100644 --- a/src/gui/addcertificatedialog.h +++ b/src/gui/addcertificatedialog.h @@ -22,7 +22,7 @@ namespace OCC { namespace Ui { -class AddCertificateDialog; + class AddCertificateDialog; } /** @@ -46,9 +46,8 @@ private slots: private: Ui::AddCertificateDialog *ui; - }; -}//End namespace OCC +} //End namespace OCC #endif // ADDCERTIFICATEDIALOG_H diff --git a/src/gui/application.cpp b/src/gui/application.cpp index 04e817634..4991aac56 100644 --- a/src/gui/application.cpp +++ b/src/gui/application.cpp @@ -63,7 +63,7 @@ Q_LOGGING_CATEGORY(lcApplication, "gui.application", QtInfoMsg) namespace { -static const char optionsC[] = + static const char optionsC[] = "Options:\n" " -h --help : show this help screen.\n" " --logwindow : open a window to show log output.\n" @@ -74,62 +74,62 @@ static const char optionsC[] = " (to be used with --logdir)\n" " --logflush : flush the log file after every write.\n" " --logdebug : also output debug-level messages in the log (equivalent to setting the env var QT_LOGGING_RULES=\"qt.*=true;*.debug=true\").\n" - " --confdir : Use the given configuration folder.\n" - ; + " --confdir : Use the given configuration folder.\n"; -QString applicationTrPath() -{ - QString devTrPath = qApp->applicationDirPath() + QString::fromLatin1("/../src/gui/"); - if (QDir(devTrPath).exists()) { - // might miss Qt, QtKeyChain, etc. - qCWarning(lcApplication) << "Running from build location! Translations may be incomplete!"; - return devTrPath; - } + QString applicationTrPath() + { + QString devTrPath = qApp->applicationDirPath() + QString::fromLatin1("/../src/gui/"); + if (QDir(devTrPath).exists()) { + // might miss Qt, QtKeyChain, etc. + qCWarning(lcApplication) << "Running from build location! Translations may be incomplete!"; + return devTrPath; + } #if defined(Q_OS_WIN) - return QApplication::applicationDirPath(); + return QApplication::applicationDirPath(); #elif defined(Q_OS_MAC) - return QApplication::applicationDirPath()+QLatin1String("/../Resources/Translations"); // path defaults to app dir. + return QApplication::applicationDirPath() + QLatin1String("/../Resources/Translations"); // path defaults to app dir. #elif defined(Q_OS_UNIX) - return QString::fromLatin1(SHAREDIR "/" APPLICATION_EXECUTABLE "/i18n/"); + return QString::fromLatin1(SHAREDIR "/" APPLICATION_EXECUTABLE "/i18n/"); #endif -} + } } // ---------------------------------------------------------------------------------- -Application::Application(int &argc, char **argv) : - SharedTools::QtSingleApplication(Theme::instance()->appName() ,argc, argv), - _gui(0), - _theme(Theme::instance()), - _helpOnly(false), - _versionOnly(false), - _showLogWindow(false), - _logExpire(0), - _logFlush(false), - _logDebug(false), - _userTriggeredConnect(false), - _debugMode(false) +Application::Application(int &argc, char **argv) + : SharedTools::QtSingleApplication(Theme::instance()->appName(), argc, argv) + , _gui(0) + , _theme(Theme::instance()) + , _helpOnly(false) + , _versionOnly(false) + , _showLogWindow(false) + , _logExpire(0) + , _logFlush(false) + , _logDebug(false) + , _userTriggeredConnect(false) + , _debugMode(false) { _startedAt.start(); #ifdef Q_OS_WIN // Ensure OpenSSL config file is only loaded from app directory - QString opensslConf = QCoreApplication::applicationDirPath()+QString("/openssl.cnf"); + QString opensslConf = QCoreApplication::applicationDirPath() + QString("/openssl.cnf"); qputenv("OPENSSL_CONF", opensslConf.toLocal8Bit()); #endif -// TODO: Can't set this without breaking current config paths -// setOrganizationName(QLatin1String(APPLICATION_VENDOR)); + // TODO: Can't set this without breaking current config paths + // setOrganizationName(QLatin1String(APPLICATION_VENDOR)); setOrganizationDomain(QLatin1String(APPLICATION_REV_DOMAIN)); - setApplicationName( _theme->appNameGUI() ); - setWindowIcon( _theme->applicationIcon() ); + setApplicationName(_theme->appNameGUI()); + setWindowIcon(_theme->applicationIcon()); #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0) setAttribute(Qt::AA_UseHighDpiPixmaps, true); #endif parseOptions(arguments()); //no need to waste time; - if ( _helpOnly || _versionOnly ) return; + if (_helpOnly || _versionOnly) + return; if (isRunning()) return; @@ -145,7 +145,7 @@ Application::Application(int &argc, char **argv) : #if defined(WITH_CRASHREPORTER) if (ConfigFile().crashReporter()) - _crashHandler.reset(new CrashReporter::Handler( QDir::tempPath(), true, CRASHREPORTER_EXECUTABLE )); + _crashHandler.reset(new CrashReporter::Handler(QDir::tempPath(), true, CRASHREPORTER_EXECUTABLE)); #endif setupLogging(); @@ -154,14 +154,14 @@ Application::Application(int &argc, char **argv) : // Setup global excludes qCInfo(lcApplication) << "Loading global exclude list"; ConfigFile cfg; - ExcludedFiles& excludes = ExcludedFiles::instance(); - excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::SystemScope) ); - excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::UserScope) ); + ExcludedFiles &excludes = ExcludedFiles::instance(); + excludes.addExcludeFilePath(cfg.excludeFile(ConfigFile::SystemScope)); + excludes.addExcludeFilePath(cfg.excludeFile(ConfigFile::UserScope)); excludes.reloadExcludes(); _folderManager.reset(new FolderMan); - connect(this, SIGNAL(messageReceived(QString, QObject*)), SLOT(slotParseMessage(QString, QObject*))); + connect(this, SIGNAL(messageReceived(QString, QObject *)), SLOT(slotParseMessage(QString, QObject *))); if (!AccountManager::instance()->restore()) { // If there is an error reading the account settings, try again @@ -171,11 +171,12 @@ Application::Application(int &argc, char **argv) : if (!AccountManager::instance()->restore()) { qCCritical(lcApplication) << "Could not read the account settings, quitting"; QMessageBox::critical( - 0, - tr("Error accessing the configuration file"), - tr("There was an error while accessing the configuration " - "file at %1.").arg(ConfigFile().configFile()), - tr("Quit ownCloud")); + 0, + tr("Error accessing the configuration file"), + tr("There was an error while accessing the configuration " + "file at %1.") + .arg(ConfigFile().configFile()), + tr("Quit ownCloud")); QTimer::singleShot(0, qApp, SLOT(quit())); return; } @@ -186,50 +187,50 @@ Application::Application(int &argc, char **argv) : setQuitOnLastWindowClosed(false); _theme->setSystrayUseMonoIcons(cfg.monoIcons()); - connect (_theme, SIGNAL(systrayUseMonoIconsChanged(bool)), SLOT(slotUseMonoIconsChanged(bool))); + connect(_theme, SIGNAL(systrayUseMonoIconsChanged(bool)), SLOT(slotUseMonoIconsChanged(bool))); FolderMan::instance()->setupFolders(); _proxy.setupQtProxyFromConfig(); // folders have to be defined first, than we set up the Qt proxy. _gui = new ownCloudGui(this); - if( _showLogWindow ) { + if (_showLogWindow) { _gui->slotToggleLogBrowser(); // _showLogWindow is set in parseOptions. } // Enable word wrapping of QInputDialog (#4197) setStyleSheet("QInputDialog QLabel { qproperty-wordWrap:1; }"); - connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)), - SLOT(slotAccountStateAdded(AccountState*))); - connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)), - SLOT(slotAccountStateRemoved(AccountState*))); - foreach (auto ai , AccountManager::instance()->accounts()) { + connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)), + SLOT(slotAccountStateAdded(AccountState *))); + connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)), + SLOT(slotAccountStateRemoved(AccountState *))); + foreach (auto ai, AccountManager::instance()->accounts()) { slotAccountStateAdded(ai.data()); } connect(FolderMan::instance()->socketApi(), SIGNAL(shareCommandReceived(QString, QString, bool)), - _gui, SLOT(slotShowShareDialog(QString, QString, bool))); + _gui, SLOT(slotShowShareDialog(QString, QString, bool))); // startup procedure. connect(&_checkConnectionTimer, SIGNAL(timeout()), this, SLOT(slotCheckConnection())); _checkConnectionTimer.setInterval(ConnectionValidator::DefaultCallingIntervalMsec); // check for connection every 32 seconds. _checkConnectionTimer.start(); // Also check immediately - QTimer::singleShot( 0, this, SLOT( slotCheckConnection() )); + QTimer::singleShot(0, this, SLOT(slotCheckConnection())); // Can't use onlineStateChanged because it is always true on modern systems because of many interfaces connect(&_networkConfigurationManager, SIGNAL(configurationChanged(QNetworkConfiguration)), - this, SLOT(slotSystemOnlineConfigurationChanged(QNetworkConfiguration))); + this, SLOT(slotSystemOnlineConfigurationChanged(QNetworkConfiguration))); // Update checks UpdaterScheduler *updaterScheduler = new UpdaterScheduler(this); connect(updaterScheduler, SIGNAL(updaterAnnouncement(QString, QString)), - _gui, SLOT(slotShowTrayMessage(QString, QString))); + _gui, SLOT(slotShowTrayMessage(QString, QString))); connect(updaterScheduler, SIGNAL(requestRestart()), - _folderManager.data(), SLOT(slotScheduleAppRestart())); + _folderManager.data(), SLOT(slotScheduleAppRestart())); // Cleanup at Quit. - connect (this, SIGNAL(aboutToQuit()), SLOT(slotCleanup())); + connect(this, SIGNAL(aboutToQuit()), SLOT(slotCleanup())); } Application::~Application() @@ -248,19 +249,19 @@ void Application::slotAccountStateRemoved(AccountState *accountState) { if (_gui) { disconnect(accountState, SIGNAL(stateChanged(int)), - _gui, SLOT(slotAccountStateChanged())); - disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)), - _gui, SLOT(slotTrayMessageIfServerUnsupported(Account*))); + _gui, SLOT(slotAccountStateChanged())); + disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)), + _gui, SLOT(slotTrayMessageIfServerUnsupported(Account *))); } if (_folderManager) { disconnect(accountState, SIGNAL(stateChanged(int)), - _folderManager.data(), SLOT(slotAccountStateChanged())); - disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)), - _folderManager.data(), SLOT(slotServerVersionChanged(Account*))); + _folderManager.data(), SLOT(slotAccountStateChanged())); + disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)), + _folderManager.data(), SLOT(slotServerVersionChanged(Account *))); } // if there is no more account, show the wizard. - if( AccountManager::instance()->accounts().isEmpty() ) { + if (AccountManager::instance()->accounts().isEmpty()) { // allow to add a new account if there is non any more. Always think // about single account theming! OwncloudSetupWizard::runWizard(this, SLOT(slotownCloudWizardDone(int))); @@ -270,13 +271,13 @@ void Application::slotAccountStateRemoved(AccountState *accountState) void Application::slotAccountStateAdded(AccountState *accountState) { connect(accountState, SIGNAL(stateChanged(int)), - _gui, SLOT(slotAccountStateChanged())); - connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)), - _gui, SLOT(slotTrayMessageIfServerUnsupported(Account*))); + _gui, SLOT(slotAccountStateChanged())); + connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)), + _gui, SLOT(slotTrayMessageIfServerUnsupported(Account *))); connect(accountState, SIGNAL(stateChanged(int)), - _folderManager.data(), SLOT(slotAccountStateChanged())); - connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)), - _folderManager.data(), SLOT(slotServerVersionChanged(Account*))); + _folderManager.data(), SLOT(slotAccountStateChanged())); + connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)), + _folderManager.data(), SLOT(slotServerVersionChanged(Account *))); _gui->slotTrayMessageIfServerUnsupported(accountState->account().data()); } @@ -303,13 +304,13 @@ void Application::slotSystemOnlineConfigurationChanged(QNetworkConfiguration cnf void Application::slotCheckConnection() { auto list = AccountManager::instance()->accounts(); - foreach (const auto &accountState , list) { + foreach (const auto &accountState, list) { AccountState::State state = accountState->state(); // Don't check if we're manually signed out or // when the error is permanent. if (state != AccountState::SignedOut - && state != AccountState::ConfigurationError) { + && state != AccountState::ConfigurationError) { accountState->checkConnectivity(); } } @@ -327,7 +328,7 @@ void Application::slotCrash() Utility::crash(); } -void Application::slotownCloudWizardDone( int res ) +void Application::slotownCloudWizardDone(int res) { AccountManager *accountMan = AccountManager::instance(); FolderMan *folderMan = FolderMan::instance(); @@ -335,7 +336,7 @@ void Application::slotownCloudWizardDone( int res ) // During the wizard, scheduling of new syncs is disabled folderMan->setSyncEnabled(true); - if( res == QDialog::Accepted ) { + if (res == QDialog::Accepted) { // Check connectivity of the newly created account _checkConnectionTimer.start(); slotCheckConnection(); @@ -345,7 +346,7 @@ void Application::slotownCloudWizardDone( int res ) #ifdef Q_OS_MAC // Don't auto start when not being 'installed' shouldSetAutoStart = shouldSetAutoStart - && QCoreApplication::applicationDirPath().startsWith("/Applications/"); + && QCoreApplication::applicationDirPath().startsWith("/Applications/"); #endif Utility::setLaunchOnStartup(_theme->appName(), _theme->appNameGUI(), shouldSetAutoStart); @@ -364,11 +365,7 @@ void Application::setupLogging() Logger::instance()->enterNextLogFile(); - qCInfo(lcApplication) << QString::fromLatin1( "################## %1 locale:[%2] ui_lang:[%3] version:[%4] os:[%5]").arg(_theme->appName()) - .arg( QLocale::system().name() ) - .arg(property("ui_lang").toString()) - .arg(_theme->version()) - .arg(Utility::platformName()); + qCInfo(lcApplication) << QString::fromLatin1("################## %1 locale:[%2] ui_lang:[%3] version:[%4] os:[%5]").arg(_theme->appName()).arg(QLocale::system().name()).arg(property("ui_lang").toString()).arg(_theme->version()).arg(Utility::platformName()); } void Application::slotUseMonoIconsChanged(bool) @@ -376,7 +373,7 @@ void Application::slotUseMonoIconsChanged(bool) _gui->slotComputeOverallSyncStatus(); } -void Application::slotParseMessage(const QString &msg, QObject*) +void Application::slotParseMessage(const QString &msg, QObject *) { if (msg.startsWith(QLatin1String("MSG_PARSEOPTIONS:"))) { const int lengthOfMsgPrefix = 17; @@ -384,8 +381,8 @@ void Application::slotParseMessage(const QString &msg, QObject*) parseOptions(options); setupLogging(); } else if (msg.startsWith(QLatin1String("MSG_SHOWSETTINGS"))) { - qCInfo(lcApplication) << "Running for" << _startedAt.elapsed()/1000.0 << "sec"; - if (_startedAt.elapsed() < 10*1000) { + qCInfo(lcApplication) << "Running for" << _startedAt.elapsed() / 1000.0 << "sec"; + if (_startedAt.elapsed() < 10 * 1000) { // This call is mirrored with the one in int main() qCWarning(lcApplication) << "Ignoring MSG_SHOWSETTINGS, possibly double-invocation of client via session restore and auto start"; return; @@ -398,7 +395,8 @@ void Application::parseOptions(const QStringList &options) { QStringListIterator it(options); // skip file name; - if (it.hasNext()) it.next(); + if (it.hasNext()) + it.next(); //parse options; if help or bad option exit while (it.hasNext()) { @@ -406,18 +404,17 @@ void Application::parseOptions(const QStringList &options) if (option == QLatin1String("--help") || option == QLatin1String("-h")) { setHelp(); break; - } else if (option == QLatin1String("--logwindow") || - option == QLatin1String("-l")) { + } else if (option == QLatin1String("--logwindow") || option == QLatin1String("-l")) { _showLogWindow = true; } else if (option == QLatin1String("--logfile")) { if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) { - _logFile = it.next(); + _logFile = it.next(); } else { showHint("Log file not specified"); } } else if (option == QLatin1String("--logdir")) { if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) { - _logDir = it.next(); + _logDir = it.next(); } else { showHint("Log dir not specified"); } @@ -434,7 +431,7 @@ void Application::parseOptions(const QStringList &options) } else if (option == QLatin1String("--confdir")) { if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) { QString confDir = it.next(); - if (!ConfigFile::setConfDir( confDir )) { + if (!ConfigFile::setConfDir(confDir)) { showHint("Invalid path passed to --confdir"); } } else { @@ -485,11 +482,14 @@ void Application::showHelp() << QLatin1String(" version ") << _theme->version().toLatin1().constData() << endl; - stream << QLatin1String("File synchronisation desktop utility.") << endl << endl + stream << QLatin1String("File synchronisation desktop utility.") << endl + << endl << QLatin1String(optionsC); if (_theme->appName() == QLatin1String("ownCloud")) - stream << endl << "For more information, see http://www.owncloud.org" << endl << endl; + stream << endl + << "For more information, see http://www.owncloud.org" << endl + << endl; displayHelpText(helpText); } @@ -548,13 +548,13 @@ QString substLang(const QString &lang) void Application::setupTranslations() { QStringList uiLanguages; - // uiLanguages crashes on Windows with 4.8.0 release builds - #if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN)) - uiLanguages = QLocale::system().uiLanguages(); - #else - // older versions need to fall back to the systems locale - uiLanguages << QLocale::system().name(); - #endif +// uiLanguages crashes on Windows with 4.8.0 release builds +#if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN)) + uiLanguages = QLocale::system().uiLanguages(); +#else + // older versions need to fall back to the systems locale + uiLanguages << QLocale::system().name(); +#endif QString enforcedLocale = Theme::instance()->enforcedLocale(); if (!enforcedLocale.isEmpty()) @@ -564,13 +564,12 @@ void Application::setupTranslations() QTranslator *qtTranslator = new QTranslator(this); QTranslator *qtkeychainTranslator = new QTranslator(this); - foreach(QString lang, uiLanguages) { + foreach (QString lang, uiLanguages) { lang.replace(QLatin1Char('-'), QLatin1Char('_')); // work around QTBUG-25973 lang = substLang(lang); const QString trPath = applicationTrPath(); const QString trFile = QLatin1String("client_") + lang; - if (translator->load(trFile, trPath) || - lang.startsWith(QLatin1String("en"))) { + if (translator->load(trFile, trPath) || lang.startsWith(QLatin1String("en"))) { // Permissive approach: Qt and keychain translations // may be missing, but Qt translations must be there in order // for us to accept the language. Otherwise, we try with the next. @@ -626,4 +625,3 @@ void Application::showSettingsDialog() } // namespace OCC - diff --git a/src/gui/application.h b/src/gui/application.h index 0228ecafc..099053def 100644 --- a/src/gui/application.h +++ b/src/gui/application.h @@ -73,7 +73,7 @@ public slots: void slotownCloudWizardDone(int); protected: - void parseOptions(const QStringList& ); + void parseOptions(const QStringList &); void setupTranslations(); void setupLogging(); void enterNextLogFile(); @@ -81,12 +81,12 @@ protected: signals: void folderRemoved(); - void folderStateChanged(Folder*); + void folderStateChanged(Folder *); protected slots: - void slotParseMessage(const QString&, QObject*); + void slotParseMessage(const QString &, QObject *); void slotCheckConnection(); - void slotUseMonoIconsChanged( bool ); + void slotUseMonoIconsChanged(bool); void slotCleanup(); void slotAccountStateAdded(AccountState *accountState); void slotAccountStateRemoved(AccountState *accountState); @@ -109,11 +109,11 @@ private: bool _showLogWindow; QString _logFile; QString _logDir; - int _logExpire; - bool _logFlush; - bool _logDebug; - bool _userTriggeredConnect; - bool _debugMode; + int _logExpire; + bool _logFlush; + bool _logDebug; + bool _userTriggeredConnect; + bool _debugMode; ClientProxy _proxy; diff --git a/src/gui/authenticationdialog.cpp b/src/gui/authenticationdialog.cpp index 1d05e7264..bae0bcd13 100644 --- a/src/gui/authenticationdialog.cpp +++ b/src/gui/authenticationdialog.cpp @@ -39,7 +39,7 @@ AuthenticationDialog::AuthenticationDialog(const QString &realm, const QString & lay->addLayout(form); _password->setEchoMode(QLineEdit::Password); - QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, Qt::Horizontal); + QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); connect(box, SIGNAL(accepted()), this, SLOT(accept())); connect(box, SIGNAL(rejected()), this, SLOT(reject())); lay->addWidget(box); diff --git a/src/gui/authenticationdialog.h b/src/gui/authenticationdialog.h index 4dc23987d..3983e20a3 100644 --- a/src/gui/authenticationdialog.h +++ b/src/gui/authenticationdialog.h @@ -25,7 +25,8 @@ namespace OCC { * @brief Authenticate a user for a specific credential given his credentials * @ingroup gui */ -class AuthenticationDialog : public QDialog { +class AuthenticationDialog : public QDialog +{ Q_OBJECT public: AuthenticationDialog(const QString &realm, const QString &domain, QWidget *parent = 0); @@ -36,7 +37,6 @@ public: private: QLineEdit *_user; QLineEdit *_password; - }; diff --git a/src/gui/cocoainitializer.h b/src/gui/cocoainitializer.h index bdeb54091..7919a1698 100644 --- a/src/gui/cocoainitializer.h +++ b/src/gui/cocoainitializer.h @@ -15,18 +15,20 @@ namespace OCC { namespace Mac { -/** + /** * @brief CocoaInitializer provides an AutoRelease Pool via RIIA for use in main() * @ingroup gui */ -class CocoaInitializer { -public: - CocoaInitializer(); - ~CocoaInitializer(); -private: - class Private; - Private *d; -}; + class CocoaInitializer + { + public: + CocoaInitializer(); + ~CocoaInitializer(); + + private: + class Private; + Private *d; + }; } // namespace Mac } // namespace OCC diff --git a/src/gui/creds/credentialsfactory.cpp b/src/gui/creds/credentialsfactory.cpp index 9a60209c7..f9574f096 100644 --- a/src/gui/creds/credentialsfactory.cpp +++ b/src/gui/creds/credentialsfactory.cpp @@ -22,30 +22,28 @@ #include "creds/shibbolethcredentials.h" #endif -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcGuiCredentials, "gui.credentials", QtInfoMsg) -namespace CredentialsFactory -{ +namespace CredentialsFactory { -AbstractCredentials* create(const QString& type) -{ - // empty string might happen for old version of configuration - if (type == "http" || type == "") { - return new HttpCredentialsGui; - } else if (type == "dummy") { - return new DummyCredentials; + AbstractCredentials *create(const QString &type) + { + // empty string might happen for old version of configuration + if (type == "http" || type == "") { + return new HttpCredentialsGui; + } else if (type == "dummy") { + return new DummyCredentials; #ifndef NO_SHIBBOLETH - } else if (type == "shibboleth") { - return new ShibbolethCredentials; + } else if (type == "shibboleth") { + return new ShibbolethCredentials; #endif - } else { - qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type)); - return new DummyCredentials; + } else { + qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type)); + return new DummyCredentials; + } } -} } // ns CredentialsFactory diff --git a/src/gui/creds/credentialsfactory.h b/src/gui/creds/credentialsfactory.h index 5dcb5197b..d346a2f71 100644 --- a/src/gui/creds/credentialsfactory.h +++ b/src/gui/creds/credentialsfactory.h @@ -19,8 +19,7 @@ class QString; -namespace OCC -{ +namespace OCC { class AbstractCredentials; @@ -28,10 +27,9 @@ class AbstractCredentials; * @brief The HttpCredentialsGui namespace * @ingroup gui */ -namespace CredentialsFactory -{ +namespace CredentialsFactory { -AbstractCredentials* create(const QString& type); + AbstractCredentials *create(const QString &type); } // ns CredentialsFactory diff --git a/src/gui/creds/httpcredentialsgui.cpp b/src/gui/creds/httpcredentialsgui.cpp index d157f4c57..50d2a2367 100644 --- a/src/gui/creds/httpcredentialsgui.cpp +++ b/src/gui/creds/httpcredentialsgui.cpp @@ -21,8 +21,7 @@ using namespace QKeychain; -namespace OCC -{ +namespace OCC { void HttpCredentialsGui::askFromUser() { @@ -36,9 +35,9 @@ void HttpCredentialsGui::askFromUserAsync() "
" "User: %2
" "Account: %3
") - .arg(Utility::escape(Theme::instance()->appNameGUI()), - Utility::escape(_user), - Utility::escape(_account->displayName())); + .arg(Utility::escape(Theme::instance()->appNameGUI()), + Utility::escape(_user), + Utility::escape(_account->displayName())); QString reqTxt = requestAppPasswordText(_account); if (!reqTxt.isEmpty()) { @@ -46,8 +45,9 @@ void HttpCredentialsGui::askFromUserAsync() } if (!_fetchErrorString.isEmpty()) { msg += QLatin1String("
") - + tr("Reading from keychain failed with error: '%1'") - .arg(Utility::escape(_fetchErrorString)) + QLatin1String("
"); + + tr("Reading from keychain failed with error: '%1'") + .arg(Utility::escape(_fetchErrorString)) + + QLatin1String("
"); } QInputDialog dialog; @@ -69,7 +69,7 @@ void HttpCredentialsGui::askFromUserAsync() emit asked(); } -QString HttpCredentialsGui::requestAppPasswordText(const Account* account) +QString HttpCredentialsGui::requestAppPasswordText(const Account *account) { int version = account->serverVersionInt(); QString path; diff --git a/src/gui/creds/httpcredentialsgui.h b/src/gui/creds/httpcredentialsgui.h index 4e80ae77a..235fd523e 100644 --- a/src/gui/creds/httpcredentialsgui.h +++ b/src/gui/creds/httpcredentialsgui.h @@ -16,18 +16,24 @@ #pragma once #include "creds/httpcredentials.h" -namespace OCC -{ +namespace OCC { /** * @brief The HttpCredentialsGui class * @ingroup gui */ -class HttpCredentialsGui : public HttpCredentials { +class HttpCredentialsGui : public HttpCredentials +{ Q_OBJECT public: - explicit HttpCredentialsGui() : HttpCredentials() {} - HttpCredentialsGui(const QString& user, const QString& password, const QSslCertificate& certificate, const QSslKey& key) : HttpCredentials(user, password, certificate, key) {} + explicit HttpCredentialsGui() + : HttpCredentials() + { + } + HttpCredentialsGui(const QString &user, const QString &password, const QSslCertificate &certificate, const QSslKey &key) + : HttpCredentials(user, password, certificate, key) + { + } void askFromUser() Q_DECL_OVERRIDE; Q_INVOKABLE void askFromUserAsync(); @@ -35,4 +41,3 @@ public: }; } // namespace OCC - diff --git a/src/gui/creds/shibboleth/shibbolethuserjob.cpp b/src/gui/creds/shibboleth/shibbolethuserjob.cpp index 02d4d22f4..743643692 100644 --- a/src/gui/creds/shibboleth/shibbolethuserjob.cpp +++ b/src/gui/creds/shibboleth/shibbolethuserjob.cpp @@ -23,7 +23,7 @@ namespace OCC { Q_DECLARE_LOGGING_CATEGORY(lcShibboleth) -ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent) +ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject *parent) : JsonApiJob(account, QLatin1String("ocs/v1.php/cloud/user"), parent) { setIgnoreCredentialFailure(true); @@ -32,11 +32,10 @@ ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent) void ShibbolethUserJob::slotJsonReceived(const QJsonDocument &json, int statusCode) { - if( statusCode != 100 ) { + if (statusCode != 100) { qCWarning(lcShibboleth) << "JSON Api call resulted in status code != 100"; } - QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString(); + QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString(); emit userFetched(user); } - } diff --git a/src/gui/creds/shibboleth/shibbolethuserjob.h b/src/gui/creds/shibboleth/shibbolethuserjob.h index feb59014a..22706b1c1 100644 --- a/src/gui/creds/shibboleth/shibbolethuserjob.h +++ b/src/gui/creds/shibboleth/shibbolethuserjob.h @@ -18,17 +18,17 @@ class QJsonDocument; -namespace OCC -{ +namespace OCC { /** * @brief Fetch the user name of the shibboleth connection * @ingroup gui */ -class ShibbolethUserJob : public JsonApiJob { +class ShibbolethUserJob : public JsonApiJob +{ Q_OBJECT public: - explicit ShibbolethUserJob(AccountPtr account, QObject* parent = 0); + explicit ShibbolethUserJob(AccountPtr account, QObject *parent = 0); signals: // is always emitted when the job is finished. user is empty in case of error. @@ -40,4 +40,3 @@ private slots: } // namespace OCC - diff --git a/src/gui/creds/shibboleth/shibbolethwebview.cpp b/src/gui/creds/shibboleth/shibbolethwebview.cpp index fb5709bb7..64a1f7c35 100644 --- a/src/gui/creds/shibboleth/shibbolethwebview.cpp +++ b/src/gui/creds/shibboleth/shibbolethwebview.cpp @@ -31,26 +31,28 @@ #include "configfile.h" namespace { - const char ShibbolethWebViewGeometryC[] = "ShibbolethWebView/Geometry"; +const char ShibbolethWebViewGeometryC[] = "ShibbolethWebView/Geometry"; } -namespace OCC -{ +namespace OCC { -class UserAgentWebPage : public QWebPage { - public: - UserAgentWebPage(QObject *parent) : QWebPage(parent) +class UserAgentWebPage : public QWebPage +{ +public: + UserAgentWebPage(QObject *parent) + : QWebPage(parent) { if (!qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty()) { settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); } } - QString userAgentForUrl(const QUrl &url ) const { + QString userAgentForUrl(const QUrl &url) const + { return QWebPage::userAgentForUrl(url) + " " + Utility::userAgentString(); } }; -ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget* parent) +ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget *parent) : QWebView(parent) , _account(account) , _accepted(false) @@ -60,31 +62,31 @@ ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget* parent) setWindowFlags(Qt::Dialog); setAttribute(Qt::WA_DeleteOnClose); - QWebPage* page = new UserAgentWebPage(this); + QWebPage *page = new UserAgentWebPage(this); connect(page, SIGNAL(loadStarted()), - this, SLOT(slotLoadStarted())); + this, SLOT(slotLoadStarted())); connect(page, SIGNAL(loadFinished(bool)), - this, SLOT(slotLoadFinished(bool))); + this, SLOT(slotLoadFinished(bool))); // Make sure to accept the same SSL certificate issues as the regular QNAM we use for syncing - QObject::connect(page->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*,QList)), - _account.data(), SLOT(slotHandleSslErrors(QNetworkReply*,QList))); + QObject::connect(page->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply *, QList)), + _account.data(), SLOT(slotHandleSslErrors(QNetworkReply *, QList))); // The Account keeps ownership of the cookie jar, it must outlive this webview. account->lendCookieJarTo(page->networkAccessManager()); connect(page->networkAccessManager()->cookieJar(), - SIGNAL(newCookiesForUrl (QList, QUrl)), - this, SLOT(onNewCookiesForUrl (QList, QUrl))); + SIGNAL(newCookiesForUrl(QList, QUrl)), + this, SLOT(onNewCookiesForUrl(QList, QUrl))); page->mainFrame()->load(account->url()); this->setPage(page); setWindowTitle(tr("%1 - Authenticate").arg(Theme::instance()->appNameGUI())); // Debug view to display the cipher suite - if( !qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty() ) { + if (!qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty()) { // open an additional window to display some cipher debug info QWebPage *debugPage = new UserAgentWebPage(this); - debugPage->mainFrame()->load( QUrl("https://cc.dcsec.uni-hannover.de/")); + debugPage->mainFrame()->load(QUrl("https://cc.dcsec.uni-hannover.de/")); QWebView *debugView = new QWebView(this); debugView->setPage(debugPage); QMainWindow *window = new QMainWindow(this); @@ -112,7 +114,7 @@ ShibbolethWebView::~ShibbolethWebView() settings.setValue(ShibbolethWebViewGeometryC, saveGeometry()); } -void ShibbolethWebView::onNewCookiesForUrl (const QList& cookieList, const QUrl& url) +void ShibbolethWebView::onNewCookiesForUrl(const QList &cookieList, const QUrl &url) { if (url.host() == _account->url().host()) { QNetworkCookie shibCookie = ShibbolethCredentials::findShibCookie(_account.data(), cookieList); diff --git a/src/gui/creds/shibboleth/shibbolethwebview.h b/src/gui/creds/shibboleth/shibbolethwebview.h index 9005c17b0..b2b45c1ab 100644 --- a/src/gui/creds/shibboleth/shibbolethwebview.h +++ b/src/gui/creds/shibboleth/shibbolethwebview.h @@ -24,8 +24,7 @@ class QNetworkCookie; class QUrl; -namespace OCC -{ +namespace OCC { class ShibbolethCookieJar; @@ -35,32 +34,32 @@ class ShibbolethCookieJar; */ class ShibbolethWebView : public QWebView { - Q_OBJECT + Q_OBJECT public: - ShibbolethWebView(AccountPtr account, QWidget* parent = 0); - ShibbolethWebView(AccountPtr account, ShibbolethCookieJar* jar, QWidget* parent = 0); - ~ShibbolethWebView(); + ShibbolethWebView(AccountPtr account, QWidget *parent = 0); + ShibbolethWebView(AccountPtr account, ShibbolethCookieJar *jar, QWidget *parent = 0); + ~ShibbolethWebView(); - void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE; + void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE; Q_SIGNALS: - void shibbolethCookieReceived(const QNetworkCookie &cookie); - void rejected(); + void shibbolethCookieReceived(const QNetworkCookie &cookie); + void rejected(); private Q_SLOTS: - void onNewCookiesForUrl(const QList& cookieList, const QUrl& url); - void slotLoadStarted(); - void slotLoadFinished(bool success); + void onNewCookiesForUrl(const QList &cookieList, const QUrl &url); + void slotLoadStarted(); + void slotLoadFinished(bool success); protected: - void accept(); + void accept(); private: - void setup(AccountPtr account, ShibbolethCookieJar* jar); - AccountPtr _account; - bool _accepted; - bool _cursorOverriden; + void setup(AccountPtr account, ShibbolethCookieJar *jar); + AccountPtr _account; + bool _accepted; + bool _cursorOverriden; }; } // namespace OCC diff --git a/src/gui/creds/shibbolethcredentials.cpp b/src/gui/creds/shibbolethcredentials.cpp index a8cae2eb6..a827106df 100644 --- a/src/gui/creds/shibbolethcredentials.cpp +++ b/src/gui/creds/shibbolethcredentials.cpp @@ -35,37 +35,36 @@ using namespace QKeychain; -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcShibboleth, "gui.credentials.shibboleth", QtInfoMsg) -namespace -{ +namespace { -// Not "user" because it has a special meaning for http -const char userC[] = "shib_user"; -const char shibCookieNameC[] = "_shibsession_"; + // Not "user" because it has a special meaning for http + const char userC[] = "shib_user"; + const char shibCookieNameC[] = "_shibsession_"; } // ns ShibbolethCredentials::ShibbolethCredentials() - : AbstractCredentials(), - _url(), - _ready(false), - _stillValid(false), - _browser(0) -{} - -ShibbolethCredentials::ShibbolethCredentials(const QNetworkCookie& cookie) - : _ready(true), - _stillValid(true), - _browser(0), - _shibCookie(cookie) + : AbstractCredentials() + , _url() + , _ready(false) + , _stillValid(false) + , _browser(0) +{ +} + +ShibbolethCredentials::ShibbolethCredentials(const QNetworkCookie &cookie) + : _ready(true) + , _stillValid(true) + , _browser(0) + , _shibCookie(cookie) { } -void ShibbolethCredentials::setAccount(Account* account) +void ShibbolethCredentials::setAccount(Account *account) { AbstractCredentials::setAccount(account); @@ -91,15 +90,15 @@ QString ShibbolethCredentials::user() const return _user; } -QNetworkAccessManager* ShibbolethCredentials::getQNAM() const +QNetworkAccessManager *ShibbolethCredentials::getQNAM() const { - QNetworkAccessManager* qnam(new AccessManager); - connect(qnam, SIGNAL(finished(QNetworkReply*)), - this, SLOT(slotReplyFinished(QNetworkReply*))); + QNetworkAccessManager *qnam(new AccessManager); + connect(qnam, SIGNAL(finished(QNetworkReply *)), + this, SLOT(slotReplyFinished(QNetworkReply *))); return qnam; } -void ShibbolethCredentials::slotReplyFinished(QNetworkReply* r) +void ShibbolethCredentials::slotReplyFinished(QNetworkReply *r) { if (!_browser.isNull()) { return; @@ -133,7 +132,7 @@ void ShibbolethCredentials::fetchFromKeychain() job->setSettings(Utility::settingsWithGroup(Theme::instance()->appName(), job).release()); job->setInsecureFallback(false); job->setKey(keychainKey(_account->url().toString(), user())); - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadJobDone(QKeychain::Job*))); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadJobDone(QKeychain::Job *))); job->start(); } } @@ -161,11 +160,11 @@ void ShibbolethCredentials::invalidateToken() { _ready = false; - CookieJar *jar = static_cast(_account->networkAccessManager()->cookieJar()); + CookieJar *jar = static_cast(_account->networkAccessManager()->cookieJar()); // Remove the _shibCookie auto cookies = jar->allCookies(); - for (auto it = cookies.begin(); it != cookies.end(); ) { + for (auto it = cookies.begin(); it != cookies.end();) { if (it->name() == _shibCookie.name()) { it = cookies.erase(it); } else { @@ -185,7 +184,7 @@ void ShibbolethCredentials::forgetSensitiveData() invalidateToken(); } -void ShibbolethCredentials::onShibbolethCookieReceived(const QNetworkCookie& shibCookie) +void ShibbolethCredentials::onShibbolethCookieReceived(const QNetworkCookie &shibCookie) { storeShibCookie(shibCookie); _shibCookie = shibCookie; @@ -198,8 +197,8 @@ void ShibbolethCredentials::slotFetchUser() { // We must first do a request to webdav so the session is enabled. // (because for some reason we can't access the API without that.. a bug in the server maybe?) - EntityExistsJob* job = new EntityExistsJob(_account->sharedFromThis(), _account->davPath(), this); - connect(job, SIGNAL(exists(QNetworkReply*)), this, SLOT(slotFetchUserHelper())); + EntityExistsJob *job = new EntityExistsJob(_account->sharedFromThis(), _account->davPath(), this); + connect(job, SIGNAL(exists(QNetworkReply *)), this, SLOT(slotFetchUserHelper())); job->setIgnoreCredentialFailure(true); job->start(); } @@ -241,7 +240,7 @@ void ShibbolethCredentials::slotBrowserRejected() void ShibbolethCredentials::slotReadJobDone(QKeychain::Job *job) { if (job->error() == QKeychain::NoError) { - ReadPasswordJob *readJob = static_cast(job); + ReadPasswordJob *readJob = static_cast(job); delete readJob->settings(); QList cookies = QNetworkCookie::parseCookies(readJob->textData().toUtf8()); if (cookies.count() > 0) { @@ -267,7 +266,7 @@ void ShibbolethCredentials::showLoginWindow() return; } - CookieJar *jar = static_cast(_account->networkAccessManager()->cookieJar()); + CookieJar *jar = static_cast(_account->networkAccessManager()->cookieJar()); // When opening a new window clear all the session cookie that might keep the user from logging in // (or the session may already be open in the server, and there will not be redirect asking for the // real long term cookie we want to store) @@ -275,24 +274,24 @@ void ShibbolethCredentials::showLoginWindow() _browser = new ShibbolethWebView(_account->sharedFromThis()); connect(_browser, SIGNAL(shibbolethCookieReceived(QNetworkCookie)), - this, SLOT(onShibbolethCookieReceived(QNetworkCookie)), Qt::QueuedConnection); + this, SLOT(onShibbolethCookieReceived(QNetworkCookie)), Qt::QueuedConnection); connect(_browser, SIGNAL(rejected()), this, SLOT(slotBrowserRejected())); ownCloudGui::raiseDialog(_browser); } -QList ShibbolethCredentials::accountCookies(Account* account) +QList ShibbolethCredentials::accountCookies(Account *account) { return account->networkAccessManager()->cookieJar()->cookiesForUrl(account->davUrl()); } -QNetworkCookie ShibbolethCredentials::findShibCookie(Account* account, QList cookies) +QNetworkCookie ShibbolethCredentials::findShibCookie(Account *account, QList cookies) { - if(cookies.isEmpty()) { + if (cookies.isEmpty()) { cookies = accountCookies(account); } - Q_FOREACH(QNetworkCookie cookie, cookies) { + Q_FOREACH (QNetworkCookie cookie, cookies) { if (cookie.name().startsWith(shibCookieNameC)) { return cookie; } diff --git a/src/gui/creds/shibbolethcredentials.h b/src/gui/creds/shibbolethcredentials.h index 1114b4d6c..46b6bc08d 100644 --- a/src/gui/creds/shibbolethcredentials.h +++ b/src/gui/creds/shibbolethcredentials.h @@ -25,13 +25,12 @@ #include "creds/abstractcredentials.h" namespace QKeychain { - class Job; +class Job; } class QAuthenticator; -namespace OCC -{ +namespace OCC { Q_DECLARE_LOGGING_CATEGORY(lcShibboleth) @@ -43,7 +42,7 @@ class ShibbolethWebView; */ class ShibbolethCredentials : public AbstractCredentials { -Q_OBJECT + Q_OBJECT public: ShibbolethCredentials(); @@ -51,10 +50,10 @@ public: /* create credentials for an already connected account */ ShibbolethCredentials(const QNetworkCookie &cookie); - void setAccount(Account* account) Q_DECL_OVERRIDE; + void setAccount(Account *account) Q_DECL_OVERRIDE; QString authType() const Q_DECL_OVERRIDE; QString user() const Q_DECL_OVERRIDE; - QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE; + QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE; bool ready() const Q_DECL_OVERRIDE; void fetchFromKeychain() Q_DECL_OVERRIDE; void askFromUser() Q_DECL_OVERRIDE; @@ -70,16 +69,16 @@ public: static QByteArray shibCookieName(); private Q_SLOTS: - void onShibbolethCookieReceived(const QNetworkCookie&); + void onShibbolethCookieReceived(const QNetworkCookie &); void slotBrowserRejected(); - void slotReadJobDone(QKeychain::Job*); - void slotReplyFinished(QNetworkReply*); - void slotUserFetched(const QString& user); + void slotReadJobDone(QKeychain::Job *); + void slotReplyFinished(QNetworkReply *); + void slotUserFetched(const QString &user); void slotFetchUser(); void slotFetchUserHelper(); Q_SIGNALS: - void newCookie(const QNetworkCookie& cookie); + void newCookie(const QNetworkCookie &cookie); private: void storeShibCookie(const QNetworkCookie &cookie); diff --git a/src/gui/folder.cpp b/src/gui/folder.cpp index f9ef2caeb..b17a87d0d 100644 --- a/src/gui/folder.cpp +++ b/src/gui/folder.cpp @@ -47,20 +47,20 @@ namespace OCC { Q_LOGGING_CATEGORY(lcFolder, "gui.folder", QtInfoMsg) -Folder::Folder(const FolderDefinition& definition, - AccountState* accountState, - QObject* parent) +Folder::Folder(const FolderDefinition &definition, + AccountState *accountState, + QObject *parent) : QObject(parent) - , _accountState(accountState) - , _definition(definition) - , _csyncUnavail(false) - , _proxyDirty(true) - , _lastSyncDuration(0) - , _consecutiveFailingSyncs(0) - , _consecutiveFollowUpSyncs(0) - , _journal(_definition.absoluteJournalPath()) - , _fileLog(new SyncRunFileLog) - , _saveBackwardsCompatible(false) + , _accountState(accountState) + , _definition(definition) + , _csyncUnavail(false) + , _proxyDirty(true) + , _lastSyncDuration(0) + , _consecutiveFailingSyncs(0) + , _consecutiveFollowUpSyncs(0) + , _journal(_definition.absoluteJournalPath()) + , _fileLog(new SyncRunFileLog) + , _saveBackwardsCompatible(false) { qsrand(QTime::currentTime().msec()); _timeSinceLastSyncStart.start(); @@ -87,30 +87,30 @@ Folder::Folder(const FolderDefinition& definition, connect(_accountState.data(), SIGNAL(isConnectedChanged()), this, SIGNAL(canSyncChanged())); connect(_engine.data(), SIGNAL(rootEtag(QString)), this, SLOT(etagRetreivedFromSyncEngine(QString))); - connect(_engine.data(), SIGNAL(started()), SLOT(slotSyncStarted()), Qt::QueuedConnection); + connect(_engine.data(), SIGNAL(started()), SLOT(slotSyncStarted()), Qt::QueuedConnection); connect(_engine.data(), SIGNAL(finished(bool)), SLOT(slotSyncFinished(bool)), Qt::QueuedConnection); connect(_engine.data(), SIGNAL(csyncError(QString)), SLOT(slotSyncError(QString)), Qt::QueuedConnection); connect(_engine.data(), SIGNAL(csyncUnavailable()), SLOT(slotCsyncUnavailable()), Qt::QueuedConnection); //direct connection so the message box is blocking the sync. - connect(_engine.data(), SIGNAL(aboutToRemoveAllFiles(SyncFileItem::Direction,bool*)), - SLOT(slotAboutToRemoveAllFiles(SyncFileItem::Direction,bool*))); - connect(_engine.data(), SIGNAL(aboutToRestoreBackup(bool*)), - SLOT(slotAboutToRestoreBackup(bool*))); - connect(_engine.data(), SIGNAL(folderDiscovered(bool,QString)), this, SLOT(slotFolderDiscovered(bool,QString))); + connect(_engine.data(), SIGNAL(aboutToRemoveAllFiles(SyncFileItem::Direction, bool *)), + SLOT(slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool *))); + connect(_engine.data(), SIGNAL(aboutToRestoreBackup(bool *)), + SLOT(slotAboutToRestoreBackup(bool *))); + connect(_engine.data(), SIGNAL(folderDiscovered(bool, QString)), this, SLOT(slotFolderDiscovered(bool, QString))); connect(_engine.data(), SIGNAL(transmissionProgress(ProgressInfo)), this, SLOT(slotTransmissionProgress(ProgressInfo))); connect(_engine.data(), SIGNAL(itemCompleted(const SyncFileItemPtr &)), - this, SLOT(slotItemCompleted(const SyncFileItemPtr &))); - connect(_engine.data(), SIGNAL(newBigFolder(QString,bool)), - this, SLOT(slotNewBigFolderDiscovered(QString,bool))); + this, SLOT(slotItemCompleted(const SyncFileItemPtr &))); + connect(_engine.data(), SIGNAL(newBigFolder(QString, bool)), + this, SLOT(slotNewBigFolderDiscovered(QString, bool))); connect(_engine.data(), SIGNAL(seenLockedFile(QString)), FolderMan::instance(), SLOT(slotSyncOnceFileUnlocks(QString))); - connect(_engine.data(), SIGNAL(aboutToPropagate(SyncFileItemVector&)), - SLOT(slotLogPropagationStart())); + connect(_engine.data(), SIGNAL(aboutToPropagate(SyncFileItemVector &)), + SLOT(slotLogPropagationStart())); _scheduleSelfTimer.setSingleShot(true); _scheduleSelfTimer.setInterval(SyncEngine::minimumFileAgeForUpload); connect(&_scheduleSelfTimer, SIGNAL(timeout()), - SLOT(slotScheduleThisFolder())); + SLOT(slotScheduleThisFolder())); } Folder::~Folder() @@ -127,23 +127,23 @@ void Folder::checkLocalPath() if (_canonicalLocalPath.isEmpty()) { qCWarning(lcFolder) << "Broken symlink:" << _definition.localPath; _canonicalLocalPath = _definition.localPath; - } else if( !_canonicalLocalPath.endsWith('/') ) { + } else if (!_canonicalLocalPath.endsWith('/')) { _canonicalLocalPath.append('/'); } - if( fi.isDir() && fi.isReadable() ) { + if (fi.isDir() && fi.isReadable()) { qCDebug(lcFolder) << "Checked local path ok"; } else { // Check directory again - if( !FileSystem::fileExists(_definition.localPath, fi) ) { + if (!FileSystem::fileExists(_definition.localPath, fi)) { _syncResult.appendErrorString(tr("Local folder %1 does not exist.").arg(_definition.localPath)); - _syncResult.setStatus( SyncResult::SetupError ); - } else if( !fi.isDir() ) { + _syncResult.setStatus(SyncResult::SetupError); + } else if (!fi.isDir()) { _syncResult.appendErrorString(tr("%1 should be a folder but is not.").arg(_definition.localPath)); - _syncResult.setStatus( SyncResult::SetupError ); - } else if( !fi.isReadable() ) { + _syncResult.setStatus(SyncResult::SetupError); + } else if (!fi.isReadable()) { _syncResult.appendErrorString(tr("%1 is not readable.").arg(_definition.localPath)); - _syncResult.setStatus( SyncResult::SetupError ); + _syncResult.setStatus(SyncResult::SetupError); } } } @@ -175,7 +175,7 @@ QString Folder::shortGuiLocalPath() const { QString p = _definition.localPath; QString home = QDir::homePath(); - if( ! home.endsWith('/') ) { + if (!home.endsWith('/')) { home.append('/'); } if (p.startsWith(home)) { @@ -203,8 +203,8 @@ QString Folder::cleanPath() const { QString cleanedPath = QDir::cleanPath(_canonicalLocalPath); - if(cleanedPath.length() == 3 && cleanedPath.endsWith(":/")) - cleanedPath.remove(2,1); + if (cleanedPath.length() == 3 && cleanedPath.endsWith(":/")) + cleanedPath.remove(2, 1); return cleanedPath; } @@ -226,7 +226,7 @@ QUrl Folder::remoteUrl() const bool Folder::syncPaused() const { - return _definition.paused; + return _definition.paused; } bool Folder::canSync() const @@ -234,7 +234,7 @@ bool Folder::canSync() const return !syncPaused() && accountState()->isConnected(); } -void Folder::setSyncPaused( bool paused ) +void Folder::setSyncPaused(bool paused) { if (paused == _definition.paused) { return; @@ -243,7 +243,7 @@ void Folder::setSyncPaused( bool paused ) _definition.paused = paused; saveToSettings(); - if( !paused ) { + if (!paused) { setSyncState(SyncResult::NotYetStarted); } else { setSyncState(SyncResult::Paused); @@ -260,13 +260,13 @@ void Folder::setSyncState(SyncResult::Status state) SyncResult Folder::syncResult() const { - return _syncResult; + return _syncResult; } void Folder::prepareToSync() { _syncResult.reset(); - _syncResult.setStatus( SyncResult::NotYetStarted ); + _syncResult.setStatus(SyncResult::NotYetStarted); } void Folder::slotRunEtagJob() @@ -281,7 +281,7 @@ void Folder::slotRunEtagJob() } if (!canSync()) { - qCInfo(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state()); + qCInfo(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state()); return; } @@ -289,14 +289,14 @@ void Folder::slotRunEtagJob() // sync if it's different. _requestEtagJob = new RequestEtagJob(account, remotePath(), this); - _requestEtagJob->setTimeout(60*1000); + _requestEtagJob->setTimeout(60 * 1000); // check if the etag is different when retrieved QObject::connect(_requestEtagJob, SIGNAL(etagRetreived(QString)), this, SLOT(etagRetreived(QString))); FolderMan::instance()->slotScheduleETagJob(alias(), _requestEtagJob); // The _requestEtagJob is auto deleting itself on finish. Our guard pointer _requestEtagJob will then be null. } -void Folder::etagRetreived(const QString& etag) +void Folder::etagRetreived(const QString &etag) { // re-enable sync if it was disabled because network was down FolderMan::instance()->setSyncEnabled(true); @@ -310,7 +310,7 @@ void Folder::etagRetreived(const QString& etag) _accountState->tagLastSuccessfullETagRequest(); } -void Folder::etagRetreivedFromSyncEngine(const QString& etag) +void Folder::etagRetreivedFromSyncEngine(const QString &etag) { qCInfo(lcFolder) << "Root etag from during sync:" << etag; accountState()->tagLastSuccessfullETagRequest(); @@ -320,42 +320,42 @@ void Folder::etagRetreivedFromSyncEngine(const QString& etag) void Folder::showSyncResultPopup() { - if( _syncResult.firstItemNew() ) { - createGuiLog( _syncResult.firstItemNew()->_file, LogStatusNew, _syncResult.numNewItems() ); + if (_syncResult.firstItemNew()) { + createGuiLog(_syncResult.firstItemNew()->_file, LogStatusNew, _syncResult.numNewItems()); } - if( _syncResult.firstItemDeleted() ) { - createGuiLog( _syncResult.firstItemDeleted()->_file, LogStatusRemove, _syncResult.numRemovedItems() ); + if (_syncResult.firstItemDeleted()) { + createGuiLog(_syncResult.firstItemDeleted()->_file, LogStatusRemove, _syncResult.numRemovedItems()); } - if( _syncResult.firstItemUpdated() ) { - createGuiLog( _syncResult.firstItemUpdated()->_file, LogStatusUpdated, _syncResult.numUpdatedItems() ); + if (_syncResult.firstItemUpdated()) { + createGuiLog(_syncResult.firstItemUpdated()->_file, LogStatusUpdated, _syncResult.numUpdatedItems()); } - if( _syncResult.firstItemRenamed() ) { + if (_syncResult.firstItemRenamed()) { LogStatus status(LogStatusRename); // if the path changes it's rather a move QDir renTarget = QFileInfo(_syncResult.firstItemRenamed()->_renameTarget).dir(); QDir renSource = QFileInfo(_syncResult.firstItemRenamed()->_file).dir(); - if(renTarget != renSource) { + if (renTarget != renSource) { status = LogStatusMove; } - createGuiLog( _syncResult.firstItemRenamed()->_originalFile, status, - _syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget ); + createGuiLog(_syncResult.firstItemRenamed()->_originalFile, status, + _syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget); } - if( _syncResult.firstConflictItem() ) { - createGuiLog( _syncResult.firstConflictItem()->_file, LogStatusConflict, _syncResult.numConflictItems() ); + if (_syncResult.firstConflictItem()) { + createGuiLog(_syncResult.firstConflictItem()->_file, LogStatusConflict, _syncResult.numConflictItems()); } if (int errorCount = _syncResult.numErrorItems()) { - createGuiLog( _syncResult.firstItemError()->_file, LogStatusError, errorCount ); + createGuiLog(_syncResult.firstItemError()->_file, LogStatusError, errorCount); } qCInfo(lcFolder) << "Folder sync result: " << int(_syncResult.status()); } -void Folder::createGuiLog( const QString& filename, LogStatus status, int count, - const QString& renameTarget ) +void Folder::createGuiLog(const QString &filename, LogStatus status, int count, + const QString &renameTarget) { - if(count > 0) { + if (count > 0) { Logger *logger = Logger::instance(); QString file = QDir::toNativeSeparators(filename); @@ -363,58 +363,58 @@ void Folder::createGuiLog( const QString& filename, LogStatus status, int count, switch (status) { case LogStatusRemove: - if( count > 1 ) { - text = tr("%1 and %n other file(s) have been removed.", "", count-1).arg(file); + if (count > 1) { + text = tr("%1 and %n other file(s) have been removed.", "", count - 1).arg(file); } else { text = tr("%1 has been removed.", "%1 names a file.").arg(file); } break; case LogStatusNew: - if( count > 1 ) { - text = tr("%1 and %n other file(s) have been downloaded.", "", count-1).arg(file); + if (count > 1) { + text = tr("%1 and %n other file(s) have been downloaded.", "", count - 1).arg(file); } else { text = tr("%1 has been downloaded.", "%1 names a file.").arg(file); } break; case LogStatusUpdated: - if( count > 1 ) { - text = tr("%1 and %n other file(s) have been updated.", "", count-1).arg(file); + if (count > 1) { + text = tr("%1 and %n other file(s) have been updated.", "", count - 1).arg(file); } else { text = tr("%1 has been updated.", "%1 names a file.").arg(file); } break; case LogStatusRename: - if( count > 1 ) { - text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count-1).arg(file, renameTarget); + if (count > 1) { + text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count - 1).arg(file, renameTarget); } else { text = tr("%1 has been renamed to %2.", "%1 and %2 name files.").arg(file, renameTarget); } break; case LogStatusMove: - if( count > 1 ) { - text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count-1).arg(file, renameTarget); + if (count > 1) { + text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count - 1).arg(file, renameTarget); } else { text = tr("%1 has been moved to %2.").arg(file, renameTarget); } break; case LogStatusConflict: - if( count > 1 ) { - text = tr("%1 has and %n other file(s) have sync conflicts.", "", count-1).arg(file); + if (count > 1) { + text = tr("%1 has and %n other file(s) have sync conflicts.", "", count - 1).arg(file); } else { text = tr("%1 has a sync conflict. Please check the conflict file!").arg(file); } break; case LogStatusError: - if( count > 1 ) { - text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count-1).arg(file); + if (count > 1) { + text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count - 1).arg(file); } else { text = tr("%1 could not be synced due to an error. See the log for details.").arg(file); } break; } - if( !text.isEmpty() ) { - logger->postOptionalGuiLog( tr("Sync Activity"), text ); + if (!text.isEmpty()) { + logger->postOptionalGuiLog(tr("Sync Activity"), text); } } } @@ -425,8 +425,8 @@ int Folder::slotDiscardDownloadProgress() QDir folderpath(_definition.localPath); QSet keep_nothing; const QVector deleted_infos = - _journal.getAndDeleteStaleDownloadInfos(keep_nothing); - foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) { + _journal.getAndDeleteStaleDownloadInfos(keep_nothing); + foreach (const SyncJournalDb::DownloadInfo &deleted_info, deleted_infos) { const QString tmppath = folderpath.filePath(deleted_info._tmpfile); qCInfo(lcFolder) << "Deleting temporary file: " << tmppath; FileSystem::remove(tmppath); @@ -449,19 +449,19 @@ int Folder::slotWipeErrorBlacklist() return _journal.wipeErrorBlacklist(); } -void Folder::slotWatchedPathChanged(const QString& path) +void Folder::slotWatchedPathChanged(const QString &path) { - // The folder watcher fires a lot of bogus notifications during - // a sync operation, both for actual user files and the database - // and log. Therefore we check notifications against operations - // the sync is doing to filter out our own changes. +// The folder watcher fires a lot of bogus notifications during +// a sync operation, both for actual user files and the database +// and log. Therefore we check notifications against operations +// the sync is doing to filter out our own changes. #ifdef Q_OS_MAC Q_UNUSED(path) - // On OSX the folder watcher does not report changes done by our - // own process. Therefore nothing needs to be done here! +// On OSX the folder watcher does not report changes done by our +// own process. Therefore nothing needs to be done here! #else // Use the path to figure out whether it was our own change - const auto maxNotificationDelay = 15*1000; + const auto maxNotificationDelay = 15 * 1000; qint64 time = _engine->timeSinceFileTouched(path); if (time != -1 && time < maxNotificationDelay) { return; @@ -472,10 +472,9 @@ void Folder::slotWatchedPathChanged(const QString& path) if (path.startsWith(this->path())) { auto relativePath = path.mid(this->path().size()); auto record = _journal.getFileRecord(relativePath); - if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize, - Utility::qDateTimeToTime_t(record._modtime))) { + if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize, Utility::qDateTimeToTime_t(record._modtime))) { qCInfo(lcFolder) << "Ignoring spurious notification for file" << relativePath; - return; // probably a spurious notification + return; // probably a spurious notification } } @@ -501,7 +500,7 @@ void Folder::saveToSettings() const // where two folders for different accounts point at the same // local folders. bool oneAccountOnly = true; - foreach (Folder* other, FolderMan::instance()->map()) { + foreach (Folder *other, FolderMan::instance()->map()) { if (other != this && other->cleanPath() == this->cleanPath()) { oneAccountOnly = false; break; @@ -531,12 +530,12 @@ void Folder::removeFromSettings() const settings->remove(FolderMan::escapeAlias(_definition.alias)); } -bool Folder::isFileExcludedAbsolute(const QString& fullPath) const +bool Folder::isFileExcludedAbsolute(const QString &fullPath) const { return _engine->excludedFiles().isExcluded(fullPath, path(), _definition.ignoreHiddenFiles); } -bool Folder::isFileExcludedRelative(const QString& relativePath) const +bool Folder::isFileExcludedRelative(const QString &relativePath) const { return _engine->excludedFiles().isExcluded(path() + relativePath, path(), _definition.ignoreHiddenFiles); } @@ -545,7 +544,7 @@ void Folder::slotTerminateSync() { qCInfo(lcFolder) << "folder " << alias() << " Terminating!"; - if( _engine->isSyncRunning() ) { + if (_engine->isSyncRunning()) { _engine->abort(); setSyncState(SyncResult::SyncAbortRequested); @@ -567,8 +566,8 @@ void Folder::wipe() _journal.close(); // close the sync journal QFile file(stateDbFile); - if( file.exists() ) { - if( !file.remove()) { + if (file.exists()) { + if (!file.remove()) { qCWarning(lcFolder) << "Failed to remove existing csync StateDB " << stateDbFile; } else { qCInfo(lcFolder) << "wipe: Removed csync StateDB " << stateDbFile; @@ -578,10 +577,10 @@ void Folder::wipe() } // Also remove other db related files - QFile::remove( stateDbFile + ".ctmp" ); - QFile::remove( stateDbFile + "-shm" ); - QFile::remove( stateDbFile + "-wal" ); - QFile::remove( stateDbFile + "-journal" ); + QFile::remove(stateDbFile + ".ctmp"); + QFile::remove(stateDbFile + "-shm"); + QFile::remove(stateDbFile + "-wal"); + QFile::remove(stateDbFile + "-journal"); if (canSync()) FolderMan::instance()->socketApi()->slotRegisterPath(alias()); @@ -599,7 +598,7 @@ bool Folder::setIgnoredFiles() _engine->excludedFiles().addExcludeFilePath(systemList); QString userList = cfg.excludeFile(ConfigFile::UserScope); - if( QFile::exists(userList) ) { + if (QFile::exists(userList)) { qCInfo(lcFolder) << "Adding user defined ignore list to csync:" << userList; _engine->excludedFiles().addExcludeFilePath(userList); } @@ -631,16 +630,15 @@ void Folder::startSync(const QStringList &pathList) _csyncUnavail = false; _timeSinceLastSyncStart.restart(); - _syncResult.setStatus( SyncResult::SyncPrepare ); + _syncResult.setStatus(SyncResult::SyncPrepare); emit syncStateChange(); qCInfo(lcFolder) << "*** Start syncing " << remoteUrl().toString() << " - client version" - << qPrintable(Theme::instance()->version()); + << qPrintable(Theme::instance()->version()); _fileLog->start(path()); - if (!setIgnoredFiles()) - { + if (!setIgnoredFiles()) { slotSyncError(tr("Could not read system exclude file")); QMetaObject::invokeMethod(this, "slotSyncFinished", Qt::QueuedConnection, Q_ARG(bool, false)); return; @@ -714,7 +712,7 @@ void Folder::setDirtyNetworkLimits() int uploadLimit = -75; // 75% int useUpLimit = cfg.useUploadLimit(); - if ( useUpLimit >= 1) { + if (useUpLimit >= 1) { uploadLimit = cfg.uploadLimit() * 1000; } else if (useUpLimit == 0) { uploadLimit = 0; @@ -724,7 +722,7 @@ void Folder::setDirtyNetworkLimits() } -void Folder::slotSyncError(const QString& err) +void Folder::slotSyncError(const QString &err) { _syncResult.appendErrorString(err); } @@ -744,14 +742,14 @@ void Folder::slotCsyncUnavailable() void Folder::slotSyncFinished(bool success) { qCInfo(lcFolder) << "Client version" << qPrintable(Theme::instance()->version()) - << " Qt" << qVersion() -#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - << " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data() + << " Qt" << qVersion() +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + << " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data() #endif - ; + ; bool syncError = !_syncResult.errorStrings().isEmpty(); - if( syncError ) { + if (syncError) { qCWarning(lcFolder) << "SyncEngine finished with ERROR"; } else { qCInfo(lcFolder) << "SyncEngine finished without problem."; @@ -766,9 +764,9 @@ void Folder::slotSyncFinished(bool success) } else if (_csyncUnavail) { _syncResult.setStatus(SyncResult::Error); qCWarning(lcFolder) << "csync not available."; - } else if( _syncResult.foundFilesNotSynced() ) { + } else if (_syncResult.foundFilesNotSynced()) { _syncResult.setStatus(SyncResult::Problem); - } else if( _definition.paused ) { + } else if (_definition.paused) { // Maybe the sync was terminated because the user paused the folder _syncResult.setStatus(SyncResult::Paused); } else { @@ -777,12 +775,9 @@ void Folder::slotSyncFinished(bool success) // Count the number of syncs that have failed in a row. if (_syncResult.status() == SyncResult::Success - || _syncResult.status() == SyncResult::Problem) - { + || _syncResult.status() == SyncResult::Problem) { _consecutiveFailingSyncs = 0; - } - else - { + } else { _consecutiveFailingSyncs++; qCInfo(lcFolder) << "the last" << _consecutiveFailingSyncs << "syncs failed"; } @@ -800,7 +795,7 @@ void Folder::slotSyncFinished(bool success) // file system change notifications are ignored for that folder. And it takes // some time under certain conditions to make the file system notifications // all come in. - QTimer::singleShot(200, this, SLOT(slotEmitFinishedDelayed() )); + QTimer::singleShot(200, this, SLOT(slotEmitFinishedDelayed())); _lastSyncDuration = _timeSinceLastSyncStart.elapsed(); _timeSinceLastSyncDone.restart(); @@ -809,14 +804,13 @@ void Folder::slotSyncFinished(bool success) if (anotherSyncNeeded == ImmediateFollowUp) { _consecutiveFollowUpSyncs++; qCInfo(lcFolder) << "another sync was requested by the finished sync, this has" - << "happened" << _consecutiveFollowUpSyncs << "times"; + << "happened" << _consecutiveFollowUpSyncs << "times"; } else { _consecutiveFollowUpSyncs = 0; } // Maybe force a follow-up sync to take place, but only a couple of times. - if (anotherSyncNeeded == ImmediateFollowUp && _consecutiveFollowUpSyncs <= 3) - { + if (anotherSyncNeeded == ImmediateFollowUp && _consecutiveFollowUpSyncs <= 3) { // Sometimes another sync is requested because a local file is still // changing, so wait at least a small amount of time before syncing // the folder again. @@ -826,7 +820,7 @@ void Folder::slotSyncFinished(bool success) void Folder::slotEmitFinishedDelayed() { - emit syncFinished( _syncResult ); + emit syncFinished(_syncResult); } @@ -851,11 +845,11 @@ void Folder::slotTransmissionProgress(const ProgressInfo &pi) void Folder::slotItemCompleted(const SyncFileItemPtr &item) { // add new directories or remove gone away dirs to the watcher - if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NEW ) { - FolderMan::instance()->addMonitorPath( alias(), path()+item->_file ); + if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NEW) { + FolderMan::instance()->addMonitorPath(alias(), path() + item->_file); } - if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_REMOVE ) { - FolderMan::instance()->removeMonitorPath( alias(), path()+item->_file ); + if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_REMOVE) { + FolderMan::instance()->removeMonitorPath(alias(), path() + item->_file); } _syncResult.processCompletedItem(item); @@ -883,16 +877,16 @@ void Folder::slotNewBigFolderDiscovered(const QString &newF, bool isExternal) // And add the entry to the undecided list and signal the UI auto undecidedList = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok1); - if( ok1 ) { + if (ok1) { if (!undecidedList.contains(newFolder)) { undecidedList.append(newFolder); journal->setSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, undecidedList); emit newBigFolderDiscovered(newFolder); } - QString message = !isExternal ? - (tr("A new folder larger than %1 MB has been added: %2.\n") - .arg(ConfigFile().newBigFolderSizeLimit().second).arg(newF)) - : (tr("A folder from an external storage has been added.\n")); + QString message = !isExternal ? (tr("A new folder larger than %1 MB has been added: %2.\n") + .arg(ConfigFile().newBigFolderSizeLimit().second) + .arg(newF)) + : (tr("A folder from an external storage has been added.\n")); message += tr("Please go in the settings to select it if you wish to download it."); auto logger = Logger::instance(); @@ -928,21 +922,20 @@ void Folder::slotAboutToRemoveAllFiles(SyncFileItem::Direction dir, bool *cancel if (!cfgFile.promptDeleteFiles()) return; - QString msg = dir == SyncFileItem::Down ? - tr("All files in the sync folder '%1' folder were deleted on the server.\n" - "These deletes will be synchronized to your local sync folder, making such files " - "unavailable unless you have a right to restore. \n" - "If you decide to keep the files, they will be re-synced with the server if you have rights to do so.\n" - "If you decide to delete the files, they will be unavailable to you, unless you are the owner.") : - tr("All the files in your local sync folder '%1' were deleted. These deletes will be " - "synchronized with your server, making such files unavailable unless restored.\n" - "Are you sure you want to sync those actions with the server?\n" - "If this was an accident and you decide to keep your files, they will be re-synced from the server."); + QString msg = dir == SyncFileItem::Down ? tr("All files in the sync folder '%1' folder were deleted on the server.\n" + "These deletes will be synchronized to your local sync folder, making such files " + "unavailable unless you have a right to restore. \n" + "If you decide to keep the files, they will be re-synced with the server if you have rights to do so.\n" + "If you decide to delete the files, they will be unavailable to you, unless you are the owner.") + : tr("All the files in your local sync folder '%1' were deleted. These deletes will be " + "synchronized with your server, making such files unavailable unless restored.\n" + "Are you sure you want to sync those actions with the server?\n" + "If this was an accident and you decide to keep your files, they will be re-synced from the server."); QMessageBox msgBox(QMessageBox::Warning, tr("Remove All Files?"), - msg.arg(shortGuiLocalPath())); + msg.arg(shortGuiLocalPath())); msgBox.setWindowFlags(msgBox.windowFlags() | Qt::WindowStaysOnTopHint); msgBox.addButton(tr("Remove all files"), QMessageBox::DestructiveRole); - QPushButton* keepBtn = msgBox.addButton(tr("Keep files"), QMessageBox::AcceptRole); + QPushButton *keepBtn = msgBox.addButton(tr("Keep files"), QMessageBox::AcceptRole); if (msgBox.exec() == -1) { *cancel = true; return; @@ -965,10 +958,10 @@ void Folder::slotAboutToRestoreBackup(bool *restore) "file in an earlier state. " "Do you want to keep your local most recent files as conflict files?"); QMessageBox msgBox(QMessageBox::Warning, tr("Backup detected"), - msg.arg(shortGuiLocalPath())); + msg.arg(shortGuiLocalPath())); msgBox.setWindowFlags(msgBox.windowFlags() | Qt::WindowStaysOnTopHint); msgBox.addButton(tr("Normal Synchronisation"), QMessageBox::DestructiveRole); - QPushButton* keepBtn = msgBox.addButton(tr("Keep Local Files as Conflict"), QMessageBox::AcceptRole); + QPushButton *keepBtn = msgBox.addButton(tr("Keep Local Files as Conflict"), QMessageBox::AcceptRole); if (msgBox.exec() == -1) { *restore = true; @@ -978,7 +971,7 @@ void Folder::slotAboutToRestoreBackup(bool *restore) } -void FolderDefinition::save(QSettings& settings, const FolderDefinition& folder) +void FolderDefinition::save(QSettings &settings, const FolderDefinition &folder) { settings.beginGroup(FolderMan::escapeAlias(folder.alias)); settings.setValue(QLatin1String("localPath"), folder.localPath); @@ -989,8 +982,8 @@ void FolderDefinition::save(QSettings& settings, const FolderDefinition& folder) settings.endGroup(); } -bool FolderDefinition::load(QSettings& settings, const QString& alias, - FolderDefinition* folder) +bool FolderDefinition::load(QSettings &settings, const QString &alias, + FolderDefinition *folder) { settings.beginGroup(alias); folder->alias = FolderMan::unescapeAlias(alias); @@ -1011,7 +1004,7 @@ bool FolderDefinition::load(QSettings& settings, const QString& alias, return true; } -QString FolderDefinition::prepareLocalPath(const QString& path) +QString FolderDefinition::prepareLocalPath(const QString &path) { QString p = QDir::fromNativeSeparators(path); if (!p.endsWith(QLatin1Char('/'))) { @@ -1045,4 +1038,3 @@ QString FolderDefinition::defaultJournalPath(AccountPtr account) } } // namespace OCC - diff --git a/src/gui/folder.h b/src/gui/folder.h index 591f2de9e..ce1b3a7d9 100644 --- a/src/gui/folder.h +++ b/src/gui/folder.h @@ -47,7 +47,8 @@ public: FolderDefinition() : paused(false) , ignoreHiddenFiles(true) - {} + { + } /// The name of the folder in the ui and internally QString alias; @@ -63,17 +64,17 @@ public: bool ignoreHiddenFiles; /// Saves the folder definition, creating a new settings group. - static void save(QSettings& settings, const FolderDefinition& folder); + static void save(QSettings &settings, const FolderDefinition &folder); /// Reads a folder definition from a settings group with the name 'alias'. - static bool load(QSettings& settings, const QString& alias, - FolderDefinition* folder); + static bool load(QSettings &settings, const QString &alias, + FolderDefinition *folder); /// Ensure / as separator and trailing /. - static QString prepareLocalPath(const QString& path); + static QString prepareLocalPath(const QString &path); /// Ensure starting / and no ending /. - static QString prepareTargetPath(const QString& path); + static QString prepareTargetPath(const QString &path); /// journalPath relative to localPath. QString absoluteJournalPath() const; @@ -91,17 +92,17 @@ class Folder : public QObject Q_OBJECT public: - Folder(const FolderDefinition& definition, AccountState* accountState, QObject* parent = 0L); + Folder(const FolderDefinition &definition, AccountState *accountState, QObject *parent = 0L); ~Folder(); - typedef QMap Map; - typedef QMapIterator MapIterator; + typedef QMap Map; + typedef QMapIterator MapIterator; /** * The account the folder is configured on. */ - AccountState* accountState() const { return _accountState.data(); } + AccountState *accountState() const { return _accountState.data(); } /** * alias or nickname @@ -140,7 +141,7 @@ public: /** * switch sync on or off */ - void setSyncPaused( bool ); + void setSyncPaused(bool); bool syncPaused() const; @@ -160,56 +161,56 @@ public: /** * return the last sync result with error message and status */ - SyncResult syncResult() const; + SyncResult syncResult() const; - /** + /** * set the config file name. */ - void setConfigFile( const QString& ); - QString configFile(); + void setConfigFile(const QString &); + QString configFile(); - /** + /** * This is called if the sync folder definition is removed. Do cleanups here. */ - virtual void wipe(); + virtual void wipe(); - void setSyncState(SyncResult::Status state); + void setSyncState(SyncResult::Status state); - void setDirtyNetworkLimits(); + void setDirtyNetworkLimits(); - /** + /** * Ignore syncing of hidden files or not. This is defined in the * folder definition */ - bool ignoreHiddenFiles(); - void setIgnoreHiddenFiles(bool ignore); + bool ignoreHiddenFiles(); + void setIgnoreHiddenFiles(bool ignore); - // Used by the Socket API - SyncJournalDb *journalDb() { return &_journal; } - SyncEngine &syncEngine() { return *_engine; } + // Used by the Socket API + SyncJournalDb *journalDb() { return &_journal; } + SyncEngine &syncEngine() { return *_engine; } - RequestEtagJob *etagJob() { return _requestEtagJob; } - qint64 msecSinceLastSync() const { return _timeSinceLastSyncDone.elapsed(); } - qint64 msecLastSyncDuration() const { return _lastSyncDuration; } - int consecutiveFollowUpSyncs() const { return _consecutiveFollowUpSyncs; } - int consecutiveFailingSyncs() const { return _consecutiveFailingSyncs; } + RequestEtagJob *etagJob() { return _requestEtagJob; } + qint64 msecSinceLastSync() const { return _timeSinceLastSyncDone.elapsed(); } + qint64 msecLastSyncDuration() const { return _lastSyncDuration; } + int consecutiveFollowUpSyncs() const { return _consecutiveFollowUpSyncs; } + int consecutiveFailingSyncs() const { return _consecutiveFailingSyncs; } - /// Saves the folder data in the account's settings. - void saveToSettings() const; - /// Removes the folder from the account's settings. - void removeFromSettings() const; + /// Saves the folder data in the account's settings. + void saveToSettings() const; + /// Removes the folder from the account's settings. + void removeFromSettings() const; - /** + /** * Returns whether a file inside this folder should be excluded. */ - bool isFileExcludedAbsolute(const QString& fullPath) const; + bool isFileExcludedAbsolute(const QString &fullPath) const; - /** + /** * Returns whether a file inside this folder should be excluded. */ - bool isFileExcludedRelative(const QString& relativePath) const; + bool isFileExcludedRelative(const QString &relativePath) const; - /** Calls schedules this folder on the FolderMan after a short delay. + /** Calls schedules this folder on the FolderMan after a short delay. * * This should be used in situations where a sync should be triggered * because a local file was modified. Syncs don't upload files that were @@ -218,72 +219,72 @@ public: * * The delay doesn't reset with subsequent calls. */ - void scheduleThisFolderSoon(); + void scheduleThisFolderSoon(); - /** + /** * Migration: When this flag is true, this folder will save to * the backwards-compatible 'Folders' section in the config file. */ - void setSaveBackwardsCompatible(bool save); + void setSaveBackwardsCompatible(bool save); signals: void syncStateChange(); void syncStarted(); void syncFinished(const SyncResult &result); - void progressInfo(const ProgressInfo& progress); + void progressInfo(const ProgressInfo &progress); void newBigFolderDiscovered(const QString &); // A new folder bigger than the threshold was discovered - void syncPausedChanged(Folder*, bool paused); + void syncPausedChanged(Folder *, bool paused); void canSyncChanged(); /** * Fires for each change inside this folder that wasn't caused * by sync activity. */ - void watchedFileChangedExternally(const QString& path); + void watchedFileChangedExternally(const QString &path); public slots: - /** + /** * terminate the current sync run */ - void slotTerminateSync(); + void slotTerminateSync(); - // connected to the corresponding signals in the SyncEngine - void slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool*); - void slotAboutToRestoreBackup(bool*); + // connected to the corresponding signals in the SyncEngine + void slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool *); + void slotAboutToRestoreBackup(bool *); - /** + /** * Starts a sync operation * * If the list of changed files is known, it is passed. */ - void startSync(const QStringList &pathList = QStringList()); + void startSync(const QStringList &pathList = QStringList()); - void setProxyDirty(bool value); - bool proxyDirty(); + void setProxyDirty(bool value); + bool proxyDirty(); - int slotDiscardDownloadProgress(); - int downloadInfoCount(); - int slotWipeErrorBlacklist(); - int errorBlackListEntryCount(); + int slotDiscardDownloadProgress(); + int downloadInfoCount(); + int slotWipeErrorBlacklist(); + int errorBlackListEntryCount(); - /** + /** * Triggered by the folder watcher when a file/dir in this folder * changes. Needs to check whether this change should trigger a new * sync run to be scheduled. */ - void slotWatchedPathChanged(const QString& path); + void slotWatchedPathChanged(const QString &path); private slots: void slotSyncStarted(); - void slotSyncError(const QString& ); + void slotSyncError(const QString &); void slotCsyncUnavailable(); void slotSyncFinished(bool); void slotFolderDiscovered(bool local, QString folderName); - void slotTransmissionProgress(const ProgressInfo& pi); - void slotItemCompleted(const SyncFileItemPtr&); + void slotTransmissionProgress(const ProgressInfo &pi); + void slotItemCompleted(const SyncFileItemPtr &); void slotRunEtagJob(); void etagRetreived(const QString &); @@ -319,8 +320,8 @@ private: LogStatusUpdated }; - void createGuiLog(const QString& filename, LogStatus status, int count, - const QString& renameTarget = QString::null ); + void createGuiLog(const QString &filename, LogStatus status, int count, + const QString &renameTarget = QString::null); AccountStatePtr _accountState; FolderDefinition _definition; @@ -328,25 +329,25 @@ private: SyncResult _syncResult; QScopedPointer _engine; - bool _csyncUnavail; - bool _proxyDirty; + bool _csyncUnavail; + bool _proxyDirty; QPointer _requestEtagJob; - QString _lastEtag; + QString _lastEtag; QElapsedTimer _timeSinceLastSyncDone; QElapsedTimer _timeSinceLastSyncStart; - qint64 _lastSyncDuration; + qint64 _lastSyncDuration; /// The number of syncs that failed in a row. /// Reset when a sync is successful. - int _consecutiveFailingSyncs; + int _consecutiveFailingSyncs; /// The number of requested follow-up syncs. /// Reset when no follow-up is requested. - int _consecutiveFollowUpSyncs; + int _consecutiveFollowUpSyncs; SyncJournalDb _journal; - ClientProxy _clientProxy; + ClientProxy _clientProxy; QScopedPointer _fileLog; @@ -362,7 +363,6 @@ private: */ bool _saveBackwardsCompatible; }; - } #endif diff --git a/src/gui/folderman.cpp b/src/gui/folderman.cpp index 367e9072f..b1d5d3a92 100644 --- a/src/gui/folderman.cpp +++ b/src/gui/folderman.cpp @@ -42,14 +42,14 @@ namespace OCC { Q_LOGGING_CATEGORY(lcFolderMan, "gui.folder.manager", QtInfoMsg) -FolderMan* FolderMan::_instance = 0; - -FolderMan::FolderMan(QObject *parent) : - QObject(parent), - _currentSyncFolder(0), - _syncEnabled( true ), - _lockWatcher(new LockWatcher), - _appRestartRequired(false) +FolderMan *FolderMan::_instance = 0; + +FolderMan::FolderMan(QObject *parent) + : QObject(parent) + , _currentSyncFolder(0) + , _syncEnabled(true) + , _lockWatcher(new LockWatcher) + , _appRestartRequired(false) { ASSERT(!_instance); _instance = this; @@ -59,25 +59,25 @@ FolderMan::FolderMan(QObject *parent) : ConfigFile cfg; int polltime = cfg.remotePollInterval(); qCInfo(lcFolderMan) << "setting remote poll timer interval to" << polltime << "msec"; - _etagPollTimer.setInterval( polltime ); + _etagPollTimer.setInterval(polltime); QObject::connect(&_etagPollTimer, SIGNAL(timeout()), this, SLOT(slotEtagPollTimerTimeout())); _etagPollTimer.start(); _startScheduledSyncTimer.setSingleShot(true); connect(&_startScheduledSyncTimer, SIGNAL(timeout()), - SLOT(slotStartScheduledFolderSync())); + SLOT(slotStartScheduledFolderSync())); _timeScheduler.setInterval(5000); _timeScheduler.setSingleShot(false); connect(&_timeScheduler, SIGNAL(timeout()), - SLOT(slotScheduleFolderByTime())); + SLOT(slotScheduleFolderByTime())); _timeScheduler.start(); - connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)), - SLOT(slotRemoveFoldersForAccount(AccountState*))); + connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)), + SLOT(slotRemoveFoldersForAccount(AccountState *))); connect(_lockWatcher.data(), SIGNAL(fileUnlocked(QString)), - SLOT(slotWatchedFileUnlocked(QString))); + SLOT(slotWatchedFileUnlocked(QString))); } FolderMan *FolderMan::instance() @@ -96,31 +96,31 @@ OCC::Folder::Map FolderMan::map() return _folderMap; } -void FolderMan::unloadFolder( Folder *f ) +void FolderMan::unloadFolder(Folder *f) { - if( !f ) { + if (!f) { return; } _socketApi->slotUnregisterPath(f->alias()); - if( _folderWatchers.contains(f->alias())) { + if (_folderWatchers.contains(f->alias())) { _folderWatchers.remove(f->alias()); } - _folderMap.remove( f->alias() ); + _folderMap.remove(f->alias()); disconnect(f, SIGNAL(syncStarted()), - this, SLOT(slotFolderSyncStarted())); + this, SLOT(slotFolderSyncStarted())); disconnect(f, SIGNAL(syncFinished(SyncResult)), - this, SLOT(slotFolderSyncFinished(SyncResult))); + this, SLOT(slotFolderSyncFinished(SyncResult))); disconnect(f, SIGNAL(syncStateChange()), - this, SLOT(slotForwardFolderSyncStateChange())); - disconnect(f, SIGNAL(syncPausedChanged(Folder*,bool)), - this, SLOT(slotFolderSyncPaused(Folder*,bool))); + this, SLOT(slotForwardFolderSyncStateChange())); + disconnect(f, SIGNAL(syncPausedChanged(Folder *, bool)), + this, SLOT(slotFolderSyncPaused(Folder *, bool))); disconnect(&f->syncEngine().syncFileStatusTracker(), SIGNAL(fileStatusChanged(const QString &, SyncFileStatus)), - _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus))); + _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus))); disconnect(f, SIGNAL(watchedFileChangedExternally(QString)), - &f->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString))); + &f->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString))); } int FolderMan::unloadAndDeleteAllFolders() @@ -131,7 +131,7 @@ int FolderMan::unloadAndDeleteAllFolders() Folder::MapIterator i(_folderMap); while (i.hasNext()) { i.next(); - Folder* f = i.value(); + Folder *f = i.value(); unloadFolder(f); delete f; cnt++; @@ -149,12 +149,14 @@ int FolderMan::unloadAndDeleteAllFolders() // add a monitor to the local file system. If there is a change in the // file system, the method slotFolderMonitorFired is triggered through // the SignalMapper -void FolderMan::registerFolderMonitor( Folder *folder ) +void FolderMan::registerFolderMonitor(Folder *folder) { - if( !folder ) return; - if( !QDir(folder->path()).exists() ) return; + if (!folder) + return; + if (!QDir(folder->path()).exists()) + return; - if( !_folderWatchers.contains(folder->alias() ) ) { + if (!_folderWatchers.contains(folder->alias())) { FolderWatcher *fw = new FolderWatcher(folder->path(), folder); // Connect the pathChanged signal, which comes with the changed path, @@ -170,23 +172,23 @@ void FolderMan::registerFolderMonitor( Folder *folder ) _socketApi->slotRegisterPath(folder->alias()); } -void FolderMan::addMonitorPath( const QString& alias, const QString& path ) +void FolderMan::addMonitorPath(const QString &alias, const QString &path) { - if( !alias.isEmpty() && _folderWatchers.contains(alias) ) { + if (!alias.isEmpty() && _folderWatchers.contains(alias)) { FolderWatcher *fw = _folderWatchers[alias]; - if( fw ) { + if (fw) { fw->addPath(path); } } } -void FolderMan::removeMonitorPath( const QString& alias, const QString& path ) +void FolderMan::removeMonitorPath(const QString &alias, const QString &path) { - if( !alias.isEmpty() && _folderWatchers.contains(alias) ) { + if (!alias.isEmpty() && _folderWatchers.contains(alias)) { FolderWatcher *fw = _folderWatchers[alias]; - if( fw ) { + if (fw) { fw->removePath(path); } } @@ -208,7 +210,7 @@ int FolderMan::setupFolders() qCInfo(lcFolderMan) << "Setup folders from settings file"; - foreach (const auto& account, AccountManager::instance()->accounts()) { + foreach (const auto &account, AccountManager::instance()->accounts()) { const auto id = account->account()->id(); if (!accountsWithSettings.contains(id)) { continue; @@ -234,7 +236,7 @@ int FolderMan::setupFolders() void FolderMan::setupFoldersHelper(QSettings &settings, AccountStatePtr account, bool backwardsCompatible) { - foreach (const auto& folderAlias, settings.childGroups()) { + foreach (const auto &folderAlias, settings.childGroups()) { FolderDefinition folderDefinition; if (FolderDefinition::load(settings, folderAlias, &folderDefinition)) { // Migration: Old settings don't have journalPath @@ -247,7 +249,7 @@ void FolderMan::setupFoldersHelper(QSettings &settings, AccountStatePtr account, SyncJournalDb::maybeMigrateDb(folderDefinition.localPath, folderDefinition.absoluteJournalPath()); } - Folder* f = addFolderInternal(std::move(folderDefinition), account.data()); + Folder *f = addFolderInternal(std::move(folderDefinition), account.data()); if (f) { // Migration: Mark folders that shall be saved in a backwards-compatible way if (backwardsCompatible) { @@ -268,16 +270,16 @@ int FolderMan::setupFoldersMigration() qCInfo(lcFolderMan) << "Setup folders from " << _folderConfigPath << "(migration)"; - QDir dir( _folderConfigPath ); + QDir dir(_folderConfigPath); //We need to include hidden files just in case the alias starts with '.' dir.setFilter(QDir::Files | QDir::Hidden); QStringList list = dir.entryList(); // Normally there should be only one account when migrating. - AccountState* accountState = AccountManager::instance()->accounts().value(0).data(); - foreach ( const QString& alias, list ) { - Folder *f = setupFolderFromOldConfigFile( alias, accountState ); - if( f ) { + AccountState *accountState = AccountManager::instance()->accounts().value(0).data(); + foreach (const QString &alias, list) { + Folder *f = setupFolderFromOldConfigFile(alias, accountState); + if (f) { scheduleFolder(f); emit folderSyncStateChange(f); } @@ -289,17 +291,17 @@ int FolderMan::setupFoldersMigration() return _folderMap.size(); } -bool FolderMan::ensureJournalGone( const QString& journalDbFile ) +bool FolderMan::ensureJournalGone(const QString &journalDbFile) { // remove the old journal file while (QFile::exists(journalDbFile) && !QFile::remove(journalDbFile)) { qCWarning(lcFolderMan) << "Could not remove old db file at" << journalDbFile; int ret = QMessageBox::warning(0, tr("Could not reset folder state"), - tr("An old sync journal '%1' was found, " - "but could not be removed. Please make sure " - "that no application is currently using it.") - .arg(QDir::fromNativeSeparators(QDir::cleanPath(journalDbFile))), - QMessageBox::Retry|QMessageBox::Abort); + tr("An old sync journal '%1' was found, " + "but could not be removed. Please make sure " + "that no application is currently using it.") + .arg(QDir::fromNativeSeparators(QDir::cleanPath(journalDbFile))), + QMessageBox::Retry | QMessageBox::Abort); if (ret == QMessageBox::Abort) { return false; } @@ -307,35 +309,35 @@ bool FolderMan::ensureJournalGone( const QString& journalDbFile ) return true; } -#define SLASH_TAG QLatin1String("__SLASH__") -#define BSLASH_TAG QLatin1String("__BSLASH__") -#define QMARK_TAG QLatin1String("__QMARK__") +#define SLASH_TAG QLatin1String("__SLASH__") +#define BSLASH_TAG QLatin1String("__BSLASH__") +#define QMARK_TAG QLatin1String("__QMARK__") #define PERCENT_TAG QLatin1String("__PERCENT__") -#define STAR_TAG QLatin1String("__STAR__") -#define COLON_TAG QLatin1String("__COLON__") -#define PIPE_TAG QLatin1String("__PIPE__") -#define QUOTE_TAG QLatin1String("__QUOTE__") -#define LT_TAG QLatin1String("__LESS_THAN__") -#define GT_TAG QLatin1String("__GREATER_THAN__") -#define PAR_O_TAG QLatin1String("__PAR_OPEN__") -#define PAR_C_TAG QLatin1String("__PAR_CLOSE__") - -QString FolderMan::escapeAlias( const QString& alias ) +#define STAR_TAG QLatin1String("__STAR__") +#define COLON_TAG QLatin1String("__COLON__") +#define PIPE_TAG QLatin1String("__PIPE__") +#define QUOTE_TAG QLatin1String("__QUOTE__") +#define LT_TAG QLatin1String("__LESS_THAN__") +#define GT_TAG QLatin1String("__GREATER_THAN__") +#define PAR_O_TAG QLatin1String("__PAR_OPEN__") +#define PAR_C_TAG QLatin1String("__PAR_CLOSE__") + +QString FolderMan::escapeAlias(const QString &alias) { QString a(alias); - a.replace( QLatin1Char('/'), SLASH_TAG ); - a.replace( QLatin1Char('\\'), BSLASH_TAG ); - a.replace( QLatin1Char('?'), QMARK_TAG ); - a.replace( QLatin1Char('%'), PERCENT_TAG ); - a.replace( QLatin1Char('*'), STAR_TAG ); - a.replace( QLatin1Char(':'), COLON_TAG ); - a.replace( QLatin1Char('|'), PIPE_TAG ); - a.replace( QLatin1Char('"'), QUOTE_TAG ); - a.replace( QLatin1Char('<'), LT_TAG ); - a.replace( QLatin1Char('>'), GT_TAG ); - a.replace( QLatin1Char('['), PAR_O_TAG ); - a.replace( QLatin1Char(']'), PAR_C_TAG ); + a.replace(QLatin1Char('/'), SLASH_TAG); + a.replace(QLatin1Char('\\'), BSLASH_TAG); + a.replace(QLatin1Char('?'), QMARK_TAG); + a.replace(QLatin1Char('%'), PERCENT_TAG); + a.replace(QLatin1Char('*'), STAR_TAG); + a.replace(QLatin1Char(':'), COLON_TAG); + a.replace(QLatin1Char('|'), PIPE_TAG); + a.replace(QLatin1Char('"'), QUOTE_TAG); + a.replace(QLatin1Char('<'), LT_TAG); + a.replace(QLatin1Char('>'), GT_TAG); + a.replace(QLatin1Char('['), PAR_O_TAG); + a.replace(QLatin1Char(']'), PAR_C_TAG); return a; } @@ -344,22 +346,22 @@ SocketApi *FolderMan::socketApi() return this->_socketApi.data(); } -QString FolderMan::unescapeAlias( const QString& alias ) +QString FolderMan::unescapeAlias(const QString &alias) { QString a(alias); - a.replace( SLASH_TAG, QLatin1String("/") ); - a.replace( BSLASH_TAG, QLatin1String("\\") ); - a.replace( QMARK_TAG, QLatin1String("?") ); - a.replace( PERCENT_TAG, QLatin1String("%") ); - a.replace( STAR_TAG, QLatin1String("*") ); - a.replace( COLON_TAG, QLatin1String(":") ); - a.replace( PIPE_TAG, QLatin1String("|") ); - a.replace( QUOTE_TAG, QLatin1String("\"") ); - a.replace( LT_TAG, QLatin1String("<") ); - a.replace( GT_TAG, QLatin1String(">") ); - a.replace( PAR_O_TAG, QLatin1String("[") ); - a.replace( PAR_C_TAG, QLatin1String("]") ); + a.replace(SLASH_TAG, QLatin1String("/")); + a.replace(BSLASH_TAG, QLatin1String("\\")); + a.replace(QMARK_TAG, QLatin1String("?")); + a.replace(PERCENT_TAG, QLatin1String("%")); + a.replace(STAR_TAG, QLatin1String("*")); + a.replace(COLON_TAG, QLatin1String(":")); + a.replace(PIPE_TAG, QLatin1String("|")); + a.replace(QUOTE_TAG, QLatin1String("\"")); + a.replace(LT_TAG, QLatin1String("<")); + a.replace(GT_TAG, QLatin1String(">")); + a.replace(PAR_O_TAG, QLatin1String("[")); + a.replace(PAR_C_TAG, QLatin1String("]")); return a; } @@ -367,7 +369,7 @@ QString FolderMan::unescapeAlias( const QString& alias ) // filename is the name of the file only, it does not include // the configuration directory path // WARNING: Do not remove this code, it is used for predefined/automated deployments (2016) -Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountState *accountState ) +Folder *FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountState *accountState) { Folder *folder = 0; @@ -376,37 +378,37 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat // check the unescaped variant (for the case when the filename comes out // of the directory listing). If the file does not exist, escape the // file and try again. - QFileInfo cfgFile( _folderConfigPath, file); + QFileInfo cfgFile(_folderConfigPath, file); - if( !cfgFile.exists() ) { + if (!cfgFile.exists()) { // try the escaped variant. escapedAlias = escapeAlias(file); - cfgFile.setFile( _folderConfigPath, escapedAlias ); + cfgFile.setFile(_folderConfigPath, escapedAlias); } - if( !cfgFile.isReadable() ) { + if (!cfgFile.isReadable()) { qCWarning(lcFolderMan) << "Cannot read folder definition for alias " << cfgFile.filePath(); return folder; } - QSettings settings( _folderConfigPath + QLatin1Char('/') + escapedAlias, QSettings::IniFormat); + QSettings settings(_folderConfigPath + QLatin1Char('/') + escapedAlias, QSettings::IniFormat); qCInfo(lcFolderMan) << " -> file path: " << settings.fileName(); // Check if the filename is equal to the group setting. If not, use the group // name as an alias. QStringList groups = settings.childGroups(); - if( ! groups.contains(escapedAlias) && groups.count() > 0 ) { + if (!groups.contains(escapedAlias) && groups.count() > 0) { escapedAlias = groups.first(); } - settings.beginGroup( escapedAlias ); // read the group with the same name as the file which is the folder alias + settings.beginGroup(escapedAlias); // read the group with the same name as the file which is the folder alias QString path = settings.value(QLatin1String("localPath")).toString(); QString backend = settings.value(QLatin1String("backend")).toString(); - QString targetPath = settings.value( QLatin1String("targetPath")).toString(); - bool paused = settings.value( QLatin1String("paused"), false).toBool(); + QString targetPath = settings.value(QLatin1String("targetPath")).toString(); + bool paused = settings.value(QLatin1String("paused"), false).toBool(); // QString connection = settings.value( QLatin1String("connection") ).toString(); - QString alias = unescapeAlias( escapedAlias ); + QString alias = unescapeAlias(escapedAlias); if (backend.isEmpty() || backend != QLatin1String("owncloud")) { qCWarning(lcFolderMan) << "obsolete configuration of type" << backend; @@ -414,8 +416,8 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat } // cut off the leading slash, oCUrl always has a trailing. - if( targetPath.startsWith(QLatin1Char('/')) ) { - targetPath.remove(0,1); + if (targetPath.startsWith(QLatin1Char('/'))) { + targetPath.remove(0, 1); } if (!accountState) { @@ -432,7 +434,7 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat folder = addFolderInternal(folderDefinition, accountState); if (folder) { - QStringList blackList = settings.value( QLatin1String("blackList")).toStringList(); + QStringList blackList = settings.value(QLatin1String("blackList")).toStringList(); if (!blackList.empty()) { //migrate settings folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, blackList); @@ -448,9 +450,9 @@ Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountStat return folder; } -void FolderMan::slotFolderSyncPaused( Folder *f, bool paused ) +void FolderMan::slotFolderSyncPaused(Folder *f, bool paused) { - if( !f ) { + if (!f) { qCCritical(lcFolderMan) << "slotFolderSyncPaused called with empty folder"; return; } @@ -465,7 +467,7 @@ void FolderMan::slotFolderSyncPaused( Folder *f, bool paused ) void FolderMan::slotFolderCanSyncChanged() { - Folder *f = qobject_cast(sender()); + Folder *f = qobject_cast(sender()); ASSERT(f); if (f->canSync()) { _socketApi->slotRegisterPath(f->alias()); @@ -480,17 +482,17 @@ void FolderMan::slotFolderCanSyncChanged() void FolderMan::terminateSyncProcess() { Folder *f = _currentSyncFolder; - if( f ) { + if (f) { // This will, indirectly and eventually, call slotFolderSyncFinished // and thereby clear _currentSyncFolder. f->slotTerminateSync(); } } -Folder *FolderMan::folder( const QString& alias ) +Folder *FolderMan::folder(const QString &alias) { - if( !alias.isEmpty() ) { - if( _folderMap.contains( alias )) { + if (!alias.isEmpty()) { + if (_folderMap.contains(alias)) { return _folderMap[alias]; } } @@ -499,9 +501,9 @@ Folder *FolderMan::folder( const QString& alias ) void FolderMan::scheduleAllFolders() { - foreach( Folder *f, _folderMap.values() ) { + foreach (Folder *f, _folderMap.values()) { if (f && f->canSync()) { - scheduleFolder( f ); + scheduleFolder(f); } } } @@ -512,7 +514,7 @@ void FolderMan::slotScheduleAppRestart() qCInfo(lcFolderMan) << "Application restart requested!"; } -void FolderMan::slotSyncOnceFileUnlocks(const QString& path) +void FolderMan::slotSyncOnceFileUnlocks(const QString &path) { _lockWatcher->addFile(path); } @@ -521,9 +523,9 @@ void FolderMan::slotSyncOnceFileUnlocks(const QString& path) * if a folder wants to be synced, it calls this slot and is added * to the queue. The slot to actually start a sync is called afterwards. */ -void FolderMan::scheduleFolder( Folder *f ) +void FolderMan::scheduleFolder(Folder *f) { - if( !f ) { + if (!f) { qCCritical(lcFolderMan) << "slotScheduleSync called with null folder"; return; } @@ -531,8 +533,8 @@ void FolderMan::scheduleFolder( Folder *f ) qCInfo(lcFolderMan) << "Schedule folder " << alias << " to sync!"; - if( ! _scheduledFolders.contains(f) ) { - if( !f->canSync() ) { + if (!_scheduledFolders.contains(f)) { + if (!f->canSync()) { qCInfo(lcFolderMan) << "Folder is not ready to sync, not scheduled!"; _socketApi->slotUpdateFolderView(f); return; @@ -548,12 +550,12 @@ void FolderMan::scheduleFolder( Folder *f ) startScheduledSyncSoon(); } -void FolderMan::scheduleFolderNext(Folder* f) +void FolderMan::scheduleFolderNext(Folder *f) { auto alias = f->alias(); qCInfo(lcFolderMan) << "Schedule folder " << alias << " to sync! Front-of-queue."; - if( !f->canSync() ) { + if (!f->canSync()) { qCInfo(lcFolderMan) << "Folder is not ready to sync, not scheduled!"; return; } @@ -568,14 +570,14 @@ void FolderMan::scheduleFolderNext(Folder* f) startScheduledSyncSoon(); } -void FolderMan::slotScheduleETagJob(const QString &/*alias*/, RequestEtagJob *job) +void FolderMan::slotScheduleETagJob(const QString & /*alias*/, RequestEtagJob *job) { - QObject::connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotEtagJobDestroyed(QObject*))); + QObject::connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotEtagJobDestroyed(QObject *))); QMetaObject::invokeMethod(this, "slotRunOneEtagJob", Qt::QueuedConnection); // maybe: add to queue } -void FolderMan::slotEtagJobDestroyed(QObject* /*o*/) +void FolderMan::slotEtagJobDestroyed(QObject * /*o*/) { // _currentEtagJob is automatically cleared // maybe: remove from queue @@ -586,7 +588,7 @@ void FolderMan::slotRunOneEtagJob() { if (_currentEtagJob.isNull()) { Folder *folder; - foreach(Folder *f, _folderMap) { + foreach (Folder *f, _folderMap) { if (f->etagJob()) { // Caveat: always grabs the first folder with a job, but we think this is Ok for now and avoids us having a seperate queue. _currentEtagJob = f->etagJob(); @@ -598,7 +600,7 @@ void FolderMan::slotRunOneEtagJob() //qCDebug(lcFolderMan) << "No more remote ETag check jobs to schedule."; /* now it might be a good time to check for restarting... */ - if( _currentSyncFolder == NULL && _appRestartRequired ) { + if (_currentSyncFolder == NULL && _appRestartRequired) { restartApplication(); } } else { @@ -610,8 +612,8 @@ void FolderMan::slotRunOneEtagJob() void FolderMan::slotAccountStateChanged() { - AccountState * accountState = qobject_cast(sender()); - if (! accountState) { + AccountState *accountState = qobject_cast(sender()); + if (!accountState) { return; } QString accountName = accountState->account()->displayName(); @@ -621,23 +623,23 @@ void FolderMan::slotAccountStateChanged() foreach (Folder *f, _folderMap.values()) { if (f - && f->canSync() - && f->accountState() == accountState) { + && f->canSync() + && f->accountState() == accountState) { scheduleFolder(f); } } } else { qCInfo(lcFolderMan) << "Account" << accountName << "disconnected or paused, " - "terminating or descheduling sync folders"; + "terminating or descheduling sync folders"; if (_currentSyncFolder - && _currentSyncFolder->accountState() == accountState) { + && _currentSyncFolder->accountState() == accountState) { _currentSyncFolder->slotTerminateSync(); } - QMutableListIterator it(_scheduledFolders); + QMutableListIterator it(_scheduledFolders); while (it.hasNext()) { - Folder* f = it.next(); + Folder *f = it.next(); if (f->accountState() == accountState) { it.remove(); } @@ -648,7 +650,7 @@ void FolderMan::slotAccountStateChanged() // only enable or disable foldermans will schedule and do syncs. // this is not the same as Pause and Resume of folders. -void FolderMan::setSyncEnabled( bool enabled ) +void FolderMan::setSyncEnabled(bool enabled) { if (!_syncEnabled && enabled && !_scheduledFolders.isEmpty()) { // We have things in our queue that were waiting for the connection to come back on. @@ -656,7 +658,7 @@ void FolderMan::setSyncEnabled( bool enabled ) } _syncEnabled = enabled; // force a redraw in case the network connect status changed - emit( folderSyncStateChange(0) ); + emit(folderSyncStateChange(0)); } void FolderMan::startScheduledSyncSoon() @@ -675,7 +677,7 @@ void FolderMan::startScheduledSyncSoon() qint64 msSinceLastSync = 0; // Require a pause based on the duration of the last sync run. - if (Folder* lastFolder = _lastSyncFolder) { + if (Folder *lastFolder = _lastSyncFolder) { msSinceLastSync = lastFolder->msecSinceLastSync(); // 1s -> 1.5s pause @@ -689,12 +691,12 @@ void FolderMan::startScheduledSyncSoon() // Delays beyond one minute seem too big, particularly since there // could be things later in the queue that shouldn't be punished by a // long delay! - msDelay = qMin(msDelay, 60*1000ll); + msDelay = qMin(msDelay, 60 * 1000ll); // Time since the last sync run counts against the delay msDelay = qMax(1ll, msDelay - msSinceLastSync); - qCInfo(lcFolderMan) << "Starting the next scheduled sync in" << (msDelay/1000) << "seconds"; + qCInfo(lcFolderMan) << "Starting the next scheduled sync in" << (msDelay / 1000) << "seconds"; _startScheduledSyncTimer.start(msDelay); } @@ -705,26 +707,26 @@ void FolderMan::startScheduledSyncSoon() */ void FolderMan::slotStartScheduledFolderSync() { - if( _currentSyncFolder ) { + if (_currentSyncFolder) { qCInfo(lcFolderMan) << "Currently folder " << _currentSyncFolder->remoteUrl().toString() << " is running, wait for finish!"; return; } - if( ! _syncEnabled ) { + if (!_syncEnabled) { qCInfo(lcFolderMan) << "FolderMan: Syncing is disabled, no scheduling."; return; } qCDebug(lcFolderMan) << "folderQueue size: " << _scheduledFolders.count(); - if( _scheduledFolders.isEmpty() ) { + if (_scheduledFolders.isEmpty()) { return; } // Find the first folder in the queue that can be synced. - Folder* folder = 0; - while( !_scheduledFolders.isEmpty() ) { - Folder* g = _scheduledFolders.dequeue(); - if( g->canSync() ) { + Folder *folder = 0; + while (!_scheduledFolders.isEmpty()) { + Folder *g = _scheduledFolders.dequeue(); + if (g->canSync()) { folder = g; break; } @@ -733,13 +735,13 @@ void FolderMan::slotStartScheduledFolderSync() emit scheduleQueueChanged(); // Start syncing this folder! - if( folder ) { + if (folder) { // Safe to call several times, and necessary to try again if // the folder path didn't exist previously. registerFolderMonitor(folder); _currentSyncFolder = folder; - folder->startSync( QStringList() ); + folder->startSync(QStringList()); } } @@ -771,13 +773,13 @@ void FolderMan::slotEtagPollTimerTimeout() } } -void FolderMan::slotRemoveFoldersForAccount(AccountState* accountState) +void FolderMan::slotRemoveFoldersForAccount(AccountState *accountState) { QVarLengthArray foldersToRemove; Folder::MapIterator i(_folderMap); while (i.hasNext()) { i.next(); - Folder* folder = i.value(); + Folder *folder = i.value(); if (folder->accountState() == accountState) { foldersToRemove.append(folder); } @@ -790,7 +792,7 @@ void FolderMan::slotRemoveFoldersForAccount(AccountState* accountState) void FolderMan::slotForwardFolderSyncStateChange() { - if (Folder* f = qobject_cast(sender())) { + if (Folder *f = qobject_cast(sender())) { emit folderSyncStateChange(f); } } @@ -800,9 +802,9 @@ void FolderMan::slotServerVersionChanged(Account *account) // Pause folders if the server version is unsupported if (account->serverVersionUnsupported()) { qCWarning(lcFolderMan) << "The server version is unsupported:" << account->serverVersion() - << "pausing all folders on the account"; + << "pausing all folders on the account"; - foreach (auto& f, _folderMap) { + foreach (auto &f, _folderMap) { if (f->accountState()->account().data() == account) { f->setSyncPaused(true); } @@ -810,16 +812,16 @@ void FolderMan::slotServerVersionChanged(Account *account) } } -void FolderMan::slotWatchedFileUnlocked(const QString& path) +void FolderMan::slotWatchedFileUnlocked(const QString &path) { - if (Folder* f = folderForPath(path)) { + if (Folder *f = folderForPath(path)) { f->scheduleThisFolderSoon(); } } void FolderMan::slotScheduleFolderByTime() { - foreach (auto& f, _folderMap) { + foreach (auto &f, _folderMap) { // Never schedule if syncing is disabled or when we're currently // querying the server for etags if (!f->canSync() || f->etagJob()) { @@ -830,11 +832,11 @@ void FolderMan::slotScheduleFolderByTime() // Possibly it's just time for a new sync run bool forceSyncIntervalExpired = - quint64(msecsSinceSync) > ConfigFile().forceSyncInterval(); + quint64(msecsSinceSync) > ConfigFile().forceSyncInterval(); if (forceSyncIntervalExpired) { qCInfo(lcFolderMan) << "Scheduling folder" << f->alias() - << "because it has been" << msecsSinceSync << "ms " - << "since the last sync"; + << "because it has been" << msecsSinceSync << "ms " + << "since the last sync"; scheduleFolder(f); continue; @@ -842,18 +844,18 @@ void FolderMan::slotScheduleFolderByTime() // Retry a couple of times after failure; or regularly if requested bool syncAgain = - (f->consecutiveFailingSyncs() > 0 && f->consecutiveFailingSyncs() < 3) - || f->syncEngine().isAnotherSyncNeeded() == DelayedFollowUp; + (f->consecutiveFailingSyncs() > 0 && f->consecutiveFailingSyncs() < 3) + || f->syncEngine().isAnotherSyncNeeded() == DelayedFollowUp; qint64 syncAgainDelay = 10 * 1000; // 10s for the first retry-after-fail if (f->consecutiveFailingSyncs() > 1) syncAgainDelay = 60 * 1000; // 60s for each further attempt if (syncAgain - && msecsSinceSync > syncAgainDelay) { + && msecsSinceSync > syncAgainDelay) { qCInfo(lcFolderMan) << "Scheduling folder" << f->alias() - << ", the last" << f->consecutiveFailingSyncs() << "syncs failed" - << ", anotherSyncNeeded" << f->syncEngine().isAnotherSyncNeeded() - << ", last status:" << f->syncResult().statusString() - << ", time since last sync:" << msecsSinceSync; + << ", the last" << f->consecutiveFailingSyncs() << "syncs failed" + << ", anotherSyncNeeded" << f->syncEngine().isAnotherSyncNeeded() + << ", last status:" << f->syncResult().statusString() + << ", time since last sync:" << msecsSinceSync; scheduleFolder(f); continue; @@ -863,7 +865,7 @@ void FolderMan::slotScheduleFolderByTime() } } -void FolderMan::slotFolderSyncStarted( ) +void FolderMan::slotFolderSyncStarted() { qCInfo(lcFolderMan) << ">===================================== sync started for " << _currentSyncFolder->remoteUrl().toString(); } @@ -874,7 +876,7 @@ void FolderMan::slotFolderSyncStarted( ) * This delay is particularly useful to avoid late file change notifications * (that we caused ourselves by syncing) from triggering another spurious sync. */ -void FolderMan::slotFolderSyncFinished( const SyncResult& ) +void FolderMan::slotFolderSyncFinished(const SyncResult &) { qCInfo(lcFolderMan) << "<===================================== sync finished for " << _currentSyncFolder->remoteUrl().toString(); @@ -884,7 +886,7 @@ void FolderMan::slotFolderSyncFinished( const SyncResult& ) startScheduledSyncSoon(); } -Folder* FolderMan::addFolder(AccountState* accountState, const FolderDefinition& folderDefinition) +Folder *FolderMan::addFolder(AccountState *accountState, const FolderDefinition &folderDefinition) { // Choose a db filename auto definition = folderDefinition; @@ -899,7 +901,7 @@ Folder* FolderMan::addFolder(AccountState* accountState, const FolderDefinition& // Migration: The first account that's configured for a local folder shall // be saved in a backwards-compatible way. bool oneAccountOnly = true; - foreach (Folder* other, FolderMan::instance()->map()) { + foreach (Folder *other, FolderMan::instance()->map()) { if (other != folder && other->cleanPath() == folder->cleanPath()) { oneAccountOnly = false; break; @@ -907,7 +909,7 @@ Folder* FolderMan::addFolder(AccountState* accountState, const FolderDefinition& } folder->setSaveBackwardsCompatible(oneAccountOnly); - if(folder) { + if (folder) { folder->saveToSettings(); emit folderSyncStateChange(folder); emit folderListChanged(_folderMap); @@ -915,8 +917,8 @@ Folder* FolderMan::addFolder(AccountState* accountState, const FolderDefinition& return folder; } -Folder* FolderMan::addFolderInternal(FolderDefinition folderDefinition, - AccountState* accountState) +Folder *FolderMan::addFolderInternal(FolderDefinition folderDefinition, + AccountState *accountState) { auto alias = folderDefinition.alias; int count = 0; @@ -925,7 +927,7 @@ Folder* FolderMan::addFolderInternal(FolderDefinition folderDefinition, folderDefinition.alias = alias + QString::number(++count); } - auto folder = new Folder(folderDefinition, accountState, this ); + auto folder = new Folder(folderDefinition, accountState, this); qCInfo(lcFolderMan) << "Adding folder to Folder Map " << folder << folder->alias(); _folderMap[folder->alias()] = folder; @@ -937,12 +939,12 @@ Folder* FolderMan::addFolderInternal(FolderDefinition folderDefinition, connect(folder, SIGNAL(syncStarted()), SLOT(slotFolderSyncStarted())); connect(folder, SIGNAL(syncFinished(SyncResult)), SLOT(slotFolderSyncFinished(SyncResult))); connect(folder, SIGNAL(syncStateChange()), SLOT(slotForwardFolderSyncStateChange())); - connect(folder, SIGNAL(syncPausedChanged(Folder*,bool)), SLOT(slotFolderSyncPaused(Folder*,bool))); + connect(folder, SIGNAL(syncPausedChanged(Folder *, bool)), SLOT(slotFolderSyncPaused(Folder *, bool))); connect(folder, SIGNAL(canSyncChanged()), SLOT(slotFolderCanSyncChanged())); connect(&folder->syncEngine().syncFileStatusTracker(), SIGNAL(fileStatusChanged(const QString &, SyncFileStatus)), - _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus))); + _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus))); connect(folder, SIGNAL(watchedFileChangedExternally(QString)), - &folder->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString))); + &folder->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString))); registerFolderMonitor(folder); return folder; @@ -950,13 +952,12 @@ Folder* FolderMan::addFolderInternal(FolderDefinition folderDefinition, Folder *FolderMan::folderForPath(const QString &path) { - QString absolutePath = QDir::cleanPath(path)+QLatin1Char('/'); + QString absolutePath = QDir::cleanPath(path) + QLatin1Char('/'); - foreach(Folder* folder, this->map().values()) { - const QString folderPath = folder->cleanPath()+QLatin1Char('/'); + foreach (Folder *folder, this->map().values()) { + const QString folderPath = folder->cleanPath() + QLatin1Char('/'); - if(absolutePath.startsWith(folderPath, (Utility::isWindows() || Utility::isMac())? - Qt::CaseInsensitive : Qt::CaseSensitive)) { + if (absolutePath.startsWith(folderPath, (Utility::isWindows() || Utility::isMac()) ? Qt::CaseInsensitive : Qt::CaseSensitive)) { return folder; } } @@ -964,11 +965,11 @@ Folder *FolderMan::folderForPath(const QString &path) return 0; } -QStringList FolderMan::findFileInLocalFolders( const QString& relPath, const AccountPtr acc ) +QStringList FolderMan::findFileInLocalFolders(const QString &relPath, const AccountPtr acc) { QStringList re; - foreach(Folder* folder, this->map().values()) { + foreach (Folder *folder, this->map().values()) { if (acc != 0 && folder->accountState()->account() != acc) { continue; } @@ -978,16 +979,16 @@ QStringList FolderMan::findFileInLocalFolders( const QString& relPath, const Acc remRelPath = relPath.mid(folder->remotePath().length()); path += "/"; path += remRelPath; - if( QFile::exists(path) ) { - re.append( path ); + if (QFile::exists(path)) { + re.append(path); } } return re; } -void FolderMan::removeFolder( Folder *f ) +void FolderMan::removeFolder(Folder *f) { - if( !f ) { + if (!f) { qCCritical(lcFolderMan) << "Can not remove null folder"; return; } @@ -995,7 +996,7 @@ void FolderMan::removeFolder( Folder *f ) qCInfo(lcFolderMan) << "Removing " << f->alias(); const bool currentlyRunning = (_currentSyncFolder == f); - if( currentlyRunning ) { + if (currentlyRunning) { // abort the sync now terminateSyncProcess(); } @@ -1010,11 +1011,11 @@ void FolderMan::removeFolder( Folder *f ) // remove the folder configuration f->removeFromSettings(); - unloadFolder( f); - if( currentlyRunning ) { + unloadFolder(f); + if (currentlyRunning) { // We want to schedule the next folder once this is done connect(f, SIGNAL(syncFinished(SyncResult)), - SLOT(slotFolderSyncFinished(SyncResult))); + SLOT(slotFolderSyncFinished(SyncResult))); // Let the folder delete itself when done. connect(f, SIGNAL(syncFinished(SyncResult)), f, SLOT(deleteLater())); } else { @@ -1022,53 +1023,54 @@ void FolderMan::removeFolder( Folder *f ) } } -QString FolderMan::getBackupName( QString fullPathName ) const +QString FolderMan::getBackupName(QString fullPathName) const { if (fullPathName.endsWith("/")) fullPathName.chop(1); - if( fullPathName.isEmpty() ) return QString::null; + if (fullPathName.isEmpty()) + return QString::null; - QString newName = fullPathName + tr(" (backup)"); - QFileInfo fi( newName ); - int cnt = 2; - do { - if( fi.exists() ) { - newName = fullPathName + tr(" (backup %1)").arg(cnt++); - fi.setFile(newName); - } - } while( fi.exists() ); + QString newName = fullPathName + tr(" (backup)"); + QFileInfo fi(newName); + int cnt = 2; + do { + if (fi.exists()) { + newName = fullPathName + tr(" (backup %1)").arg(cnt++); + fi.setFile(newName); + } + } while (fi.exists()); - return newName; + return newName; } -bool FolderMan::startFromScratch( const QString& localFolder ) +bool FolderMan::startFromScratch(const QString &localFolder) { - if( localFolder.isEmpty() ) { + if (localFolder.isEmpty()) { return false; } - QFileInfo fi( localFolder ); - QDir parentDir( fi.dir() ); + QFileInfo fi(localFolder); + QDir parentDir(fi.dir()); QString folderName = fi.fileName(); // Adjust for case where localFolder ends with a / - if ( fi.isDir() ) { + if (fi.isDir()) { folderName = parentDir.dirName(); parentDir.cdUp(); } - if( fi.exists() ) { + if (fi.exists()) { // It exists, but is empty -> just reuse it. - if( fi.isDir() && fi.dir().count() == 0 ) { + if (fi.isDir() && fi.dir().count() == 0) { qCDebug(lcFolderMan) << "startFromScratch: Directory is empty!"; return true; } // Disconnect the socket api from the database to avoid that locking of the // db file does not allow to move this dir. Folder *f = folderForPath(localFolder); - if(f) { - if( localFolder.startsWith(f->path()) ) { + if (f) { + if (localFolder.startsWith(f->path())) { _socketApi->slotUnregisterPath(f->alias()); } f->journalDb()->close(); @@ -1076,16 +1078,16 @@ bool FolderMan::startFromScratch( const QString& localFolder ) } // Make a backup of the folder/file. - QString newName = getBackupName( parentDir.absoluteFilePath( folderName ) ); + QString newName = getBackupName(parentDir.absoluteFilePath(folderName)); QString renameError; - if( !FileSystem::rename( fi.absoluteFilePath(), newName, &renameError ) ) { + if (!FileSystem::rename(fi.absoluteFilePath(), newName, &renameError)) { qCWarning(lcFolderMan) << "startFromScratch: Could not rename" << fi.absoluteFilePath() - << "to" << newName << "error:" << renameError; + << "to" << newName << "error:" << renameError; return false; } } - if( !parentDir.mkdir( fi.absoluteFilePath() ) ) { + if (!parentDir.mkdir(fi.absoluteFilePath())) { qCWarning(lcFolderMan) << "startFromScratch: Could not mkdir" << fi.absoluteFilePath(); return false; } @@ -1095,15 +1097,15 @@ bool FolderMan::startFromScratch( const QString& localFolder ) void FolderMan::setDirtyProxy(bool value) { - foreach( Folder *f, _folderMap.values() ) { - if(f) { + foreach (Folder *f, _folderMap.values()) { + if (f) { f->setProxyDirty(value); if (f->accountState() && f->accountState()->account() - && f->accountState()->account()->networkAccessManager()) { + && f->accountState()->account()->networkAccessManager()) { // Need to do this so we do not use the old determined system proxy f->accountState()->account()->networkAccessManager()->setProxy( - QNetworkProxy(QNetworkProxy::DefaultProxy)); + QNetworkProxy(QNetworkProxy::DefaultProxy)); } } } @@ -1111,16 +1113,15 @@ void FolderMan::setDirtyProxy(bool value) void FolderMan::setDirtyNetworkLimits() { - foreach( Folder *f, _folderMap.values() ) { + foreach (Folder *f, _folderMap.values()) { // set only in busy folders. Otherwise they read the config anyway. - if(f && f->isBusy()) { + if (f && f->isBusy()) { f->setDirtyNetworkLimits(); } } - } -SyncResult FolderMan::accountStatus(const QList &folders) +SyncResult FolderMan::accountStatus(const QList &folders) { SyncResult overallResult; @@ -1132,45 +1133,45 @@ SyncResult FolderMan::accountStatus(const QList &folders) // if one is paused, but others ok, show ok // do not show "problem" in the tray // - if( cnt == 1 ) { + if (cnt == 1) { Folder *folder = folders.at(0); - if( folder ) { - if( folder->syncPaused() ) { + if (folder) { + if (folder->syncPaused()) { overallResult.setStatus(SyncResult::Paused); } else { SyncResult::Status syncStatus = folder->syncResult().status(); - switch( syncStatus ) { + switch (syncStatus) { case SyncResult::Undefined: overallResult.setStatus(SyncResult::Error); break; case SyncResult::NotYetStarted: - overallResult.setStatus( SyncResult::NotYetStarted ); + overallResult.setStatus(SyncResult::NotYetStarted); break; case SyncResult::SyncPrepare: - overallResult.setStatus( SyncResult::SyncPrepare ); + overallResult.setStatus(SyncResult::SyncPrepare); break; case SyncResult::SyncRunning: - overallResult.setStatus( SyncResult::SyncRunning ); + overallResult.setStatus(SyncResult::SyncRunning); break; case SyncResult::Problem: // don't show the problem icon in tray. case SyncResult::Success: - if( overallResult.status() == SyncResult::Undefined ) - overallResult.setStatus( SyncResult::Success ); + if (overallResult.status() == SyncResult::Undefined) + overallResult.setStatus(SyncResult::Success); break; case SyncResult::Error: - overallResult.setStatus( SyncResult::Error ); + overallResult.setStatus(SyncResult::Error); break; case SyncResult::SetupError: - if ( overallResult.status() != SyncResult::Error ) - overallResult.setStatus( SyncResult::SetupError ); + if (overallResult.status() != SyncResult::Error) + overallResult.setStatus(SyncResult::SetupError); break; case SyncResult::SyncAbortRequested: - overallResult.setStatus( SyncResult::SyncAbortRequested); + overallResult.setStatus(SyncResult::SyncAbortRequested); break; case SyncResult::Paused: - overallResult.setStatus( SyncResult::Paused); + overallResult.setStatus(SyncResult::Paused); break; } } @@ -1182,14 +1183,14 @@ SyncResult FolderMan::accountStatus(const QList &folders) int runSeen = 0; int various = 0; - foreach ( Folder *folder, folders ) { - if( folder->syncPaused() ) { + foreach (Folder *folder, folders) { + if (folder->syncPaused()) { abortOrPausedSeen++; } else { SyncResult folderResult = folder->syncResult(); SyncResult::Status syncStatus = folderResult.status(); - switch( syncStatus ) { + switch (syncStatus) { case SyncResult::Undefined: case SyncResult::NotYetStarted: various++; @@ -1214,20 +1215,20 @@ SyncResult FolderMan::accountStatus(const QList &folders) } } bool set = false; - if( errorsSeen > 0 ) { + if (errorsSeen > 0) { overallResult.setStatus(SyncResult::Error); set = true; } - if( !set && abortOrPausedSeen > 0 && abortOrPausedSeen == cnt ) { + if (!set && abortOrPausedSeen > 0 && abortOrPausedSeen == cnt) { // only if all folders are paused overallResult.setStatus(SyncResult::Paused); set = true; } - if( !set && runSeen > 0 ) { + if (!set && runSeen > 0) { overallResult.setStatus(SyncResult::SyncRunning); set = true; } - if( !set && goodSeen > 0 ) { + if (!set && goodSeen > 0) { overallResult.setStatus(SyncResult::Success); set = true; } @@ -1236,131 +1237,130 @@ SyncResult FolderMan::accountStatus(const QList &folders) return overallResult; } -QString FolderMan::statusToString( SyncResult::Status syncStatus, bool paused ) const +QString FolderMan::statusToString(SyncResult::Status syncStatus, bool paused) const { QString folderMessage; - switch( syncStatus ) { + switch (syncStatus) { case SyncResult::Undefined: - folderMessage = tr( "Undefined State." ); + folderMessage = tr("Undefined State."); break; case SyncResult::NotYetStarted: - folderMessage = tr( "Waiting to start syncing." ); + folderMessage = tr("Waiting to start syncing."); break; case SyncResult::SyncPrepare: - folderMessage = tr( "Preparing for sync." ); + folderMessage = tr("Preparing for sync."); break; case SyncResult::SyncRunning: - folderMessage = tr( "Sync is running." ); + folderMessage = tr("Sync is running."); break; case SyncResult::Success: - folderMessage = tr( "Last Sync was successful." ); + folderMessage = tr("Last Sync was successful."); break; case SyncResult::Error: break; case SyncResult::Problem: - folderMessage = tr( "Last Sync was successful, but with warnings on individual files."); + folderMessage = tr("Last Sync was successful, but with warnings on individual files."); break; case SyncResult::SetupError: - folderMessage = tr( "Setup Error." ); + folderMessage = tr("Setup Error."); break; case SyncResult::SyncAbortRequested: - folderMessage = tr( "User Abort." ); + folderMessage = tr("User Abort."); break; case SyncResult::Paused: folderMessage = tr("Sync is paused."); break; - // no default case on purpose, check compiler warnings + // no default case on purpose, check compiler warnings } - if( paused ) { + if (paused) { // sync is disabled. - folderMessage = tr( "%1 (Sync is paused)" ).arg(folderMessage); + folderMessage = tr("%1 (Sync is paused)").arg(folderMessage); } return folderMessage; } -QString FolderMan::checkPathValidityForNewFolder(const QString& path, const QUrl &serverUrl, bool forNewDirectory) const +QString FolderMan::checkPathValidityForNewFolder(const QString &path, const QUrl &serverUrl, bool forNewDirectory) const { if (path.isEmpty()) { return tr("No valid folder selected!"); } - QFileInfo selFile( path ); + QFileInfo selFile(path); if (!selFile.exists()) { return checkPathValidityForNewFolder(selFile.dir().path(), serverUrl, true); } - if( !selFile.isDir() ) { + if (!selFile.isDir()) { return tr("The selected path is not a folder!"); } - if ( !selFile.isWritable() ) { + if (!selFile.isWritable()) { return tr("You have no permission to write to the selected folder!"); } // check if the local directory isn't used yet in another ownCloud sync Qt::CaseSensitivity cs = Qt::CaseSensitive; - if( Utility::fsCasePreserving() ) { + if (Utility::fsCasePreserving()) { cs = Qt::CaseInsensitive; } - for (auto i = _folderMap.constBegin(); i != _folderMap.constEnd(); ++i ) { - Folder *f = static_cast(i.value()); - QString folderDir = QDir( f->path() ).canonicalPath(); - if( folderDir.isEmpty() ) { + for (auto i = _folderMap.constBegin(); i != _folderMap.constEnd(); ++i) { + Folder *f = static_cast(i.value()); + QString folderDir = QDir(f->path()).canonicalPath(); + if (folderDir.isEmpty()) { continue; } - if( ! folderDir.endsWith(QLatin1Char('/'), cs) ) folderDir.append(QLatin1Char('/')); + if (!folderDir.endsWith(QLatin1Char('/'), cs)) + folderDir.append(QLatin1Char('/')); - const QString folderDirClean = QDir::cleanPath(folderDir)+'/'; - const QString userDirClean = QDir::cleanPath(path)+'/'; + const QString folderDirClean = QDir::cleanPath(folderDir) + '/'; + const QString userDirClean = QDir::cleanPath(path) + '/'; // folderDir follows sym links, path not. bool differentPathes = !Utility::fileNamesEqual(QDir::cleanPath(folderDir), QDir::cleanPath(path)); - if (!forNewDirectory && differentPathes && folderDirClean.startsWith(userDirClean,cs)) { + if (!forNewDirectory && differentPathes && folderDirClean.startsWith(userDirClean, cs)) { return tr("The local folder %1 already contains a folder used in a folder sync connection. " "Please pick another one!") - .arg(QDir::toNativeSeparators(path)); + .arg(QDir::toNativeSeparators(path)); } // QDir::cleanPath keeps links // canonicalPath() remove symlinks and uses the symlink targets. - QString absCleanUserFolder = QDir::cleanPath(QDir(path).canonicalPath())+'/'; + QString absCleanUserFolder = QDir::cleanPath(QDir(path).canonicalPath()) + '/'; - if ( (forNewDirectory || differentPathes) && userDirClean.startsWith( folderDirClean, cs )) { + if ((forNewDirectory || differentPathes) && userDirClean.startsWith(folderDirClean, cs)) { return tr("The local folder %1 is already contained in a folder used in a folder sync connection. " "Please pick another one!") - .arg(QDir::toNativeSeparators(path)); + .arg(QDir::toNativeSeparators(path)); } // both follow symlinks. - bool cleanUserEqualsCleanFolder = Utility::fileNamesEqual(absCleanUserFolder, folderDirClean ); - if (differentPathes && absCleanUserFolder.startsWith( folderDirClean, cs ) && - ! cleanUserEqualsCleanFolder ) { + bool cleanUserEqualsCleanFolder = Utility::fileNamesEqual(absCleanUserFolder, folderDirClean); + if (differentPathes && absCleanUserFolder.startsWith(folderDirClean, cs) && !cleanUserEqualsCleanFolder) { return tr("The local folder %1 is a symbolic link. " "The link target is already contained in a folder used in a folder sync connection. " "Please pick another one!") - .arg(QDir::toNativeSeparators(path)); + .arg(QDir::toNativeSeparators(path)); } - if (differentPathes && folderDirClean.startsWith(absCleanUserFolder, cs) && - !cleanUserEqualsCleanFolder && !forNewDirectory ) { + if (differentPathes && folderDirClean.startsWith(absCleanUserFolder, cs) && !cleanUserEqualsCleanFolder && !forNewDirectory) { return tr("The local folder %1 contains a symbolic link. " "The link target contains an already synced folder " "Please pick another one!") - .arg(QDir::toNativeSeparators(path)); + .arg(QDir::toNativeSeparators(path)); } // if both pathes are equal, the server url needs to be different // otherwise it would mean that a new connection from the same local folder // to the same account is added which is not wanted. The account must differ. - if( serverUrl.isValid() && Utility::fileNamesEqual(absCleanUserFolder,folderDir ) ) { + if (serverUrl.isValid() && Utility::fileNamesEqual(absCleanUserFolder, folderDir)) { QUrl folderUrl = f->accountState()->account()->url(); QString user = f->accountState()->account()->credentials()->user(); folderUrl.setUserName(user); - if( serverUrl == folderUrl ) { + if (serverUrl == folderUrl) { return tr("There is already a sync from the server to this local folder. " "Please pick another local folder!"); } @@ -1368,7 +1368,6 @@ QString FolderMan::checkPathValidityForNewFolder(const QString& path, const QUrl } return QString(); - } QString FolderMan::findGoodPathForNewSyncFolder(const QString &basePath, const QUrl &serverUrl) const @@ -1389,8 +1388,8 @@ QString FolderMan::findGoodPathForNewSyncFolder(const QString &basePath, const Q int attempt = 1; forever { const bool isGood = - !QFileInfo(folder).exists() - && FolderMan::instance()->checkPathValidityForNewFolder(folder, serverUrl).isEmpty(); + !QFileInfo(folder).exists() + && FolderMan::instance()->checkPathValidityForNewFolder(folder, serverUrl).isEmpty(); if (isGood) { break; } @@ -1419,13 +1418,13 @@ void FolderMan::setIgnoreHiddenFiles(bool ignore) { // Note that the setting will revert to 'true' if all folders // are deleted... - foreach (Folder* folder, _folderMap) { + foreach (Folder *folder, _folderMap) { folder->setIgnoreHiddenFiles(ignore); folder->saveToSettings(); } } -QQueue FolderMan::scheduleQueue() const +QQueue FolderMan::scheduleQueue() const { return _scheduledFolders; } @@ -1437,7 +1436,7 @@ Folder *FolderMan::currentSyncFolder() const void FolderMan::restartApplication() { - if( Utility::isLinux() ) { + if (Utility::isLinux()) { // restart: qCInfo(lcFolderMan) << "Restarting application NOW, PID" << qApp->applicationPid() << "is ending."; qApp->quit(); diff --git a/src/gui/folderman.h b/src/gui/folderman.h index 2545c8838..a504cc99b 100644 --- a/src/gui/folderman.h +++ b/src/gui/folderman.h @@ -63,7 +63,7 @@ class FolderMan : public QObject Q_OBJECT public: ~FolderMan(); - static FolderMan* instance(); + static FolderMan *instance(); int setupFolders(); int setupFoldersMigration(); @@ -72,51 +72,51 @@ public: /** Adds a folder for an account, ensures the journal is gone and saves it in the settings. */ - Folder* addFolder(AccountState* accountState, const FolderDefinition& folderDefinition); + Folder *addFolder(AccountState *accountState, const FolderDefinition &folderDefinition); /** Removes a folder */ - void removeFolder( Folder* ); + void removeFolder(Folder *); /** Returns the folder which the file or directory stored in path is in */ - Folder* folderForPath(const QString& path); + Folder *folderForPath(const QString &path); /** * returns a list of local files that exist on the local harddisk for an * incoming relative server path. The method checks with all existing sync * folders. */ - QStringList findFileInLocalFolders( const QString& relPath, const AccountPtr acc ); + QStringList findFileInLocalFolders(const QString &relPath, const AccountPtr acc); /** Returns the folder by alias or NULL if no folder with the alias exists. */ - Folder *folder( const QString& ); + Folder *folder(const QString &); /** * Migrate accounts from owncloud < 2.0 * Creates a folder for a specific configuration, identified by alias. */ - Folder* setupFolderFromOldConfigFile(const QString &, AccountState *account ); + Folder *setupFolderFromOldConfigFile(const QString &, AccountState *account); /** * Ensures that a given directory does not contain a sync journal file. * * @returns false if the journal could not be removed, true otherwise. */ - static bool ensureJournalGone(const QString& journalDbFile); + static bool ensureJournalGone(const QString &journalDbFile); /** Creates a new and empty local directory. */ - bool startFromScratch( const QString& ); + bool startFromScratch(const QString &); - QString statusToString(SyncResult::Status, bool paused ) const; + QString statusToString(SyncResult::Status, bool paused) const; - static SyncResult accountStatus( const QList &folders ); + static SyncResult accountStatus(const QList &folders); - void removeMonitorPath( const QString& alias, const QString& path ); - void addMonitorPath( const QString& alias, const QString& path ); + void removeMonitorPath(const QString &alias, const QString &path); + void addMonitorPath(const QString &alias, const QString &path); // Escaping of the alias which is used in QSettings AND the file // system, thus need to be escaped. - static QString escapeAlias( const QString& ); - static QString unescapeAlias( const QString& ); + static QString escapeAlias(const QString &); + static QString unescapeAlias(const QString &); SocketApi *socketApi(); @@ -130,7 +130,7 @@ public: * * @returns an empty string if it is allowed, or an error if it is not allowed */ - QString checkPathValidityForNewFolder(const QString &path, const QUrl& serverUrl = QUrl(), bool forNewDirectory = false) const; + QString checkPathValidityForNewFolder(const QString &path, const QUrl &serverUrl = QUrl(), bool forNewDirectory = false) const; /** * Attempts to find a non-existing, acceptable path for creating a new sync folder. @@ -155,12 +155,12 @@ public: /** * Access to the current queue of scheduled folders. */ - QQueue scheduleQueue() const; + QQueue scheduleQueue() const; /** * Access to the currently syncing folder. */ - Folder* currentSyncFolder() const; + Folder *currentSyncFolder() const; /** Removes all folders */ int unloadAndDeleteAllFolders(); @@ -169,13 +169,13 @@ public: * If enabled is set to false, no new folders will start to sync. * The current one will finish. */ - void setSyncEnabled( bool ); + void setSyncEnabled(bool); /** Queues a folder for syncing. */ - void scheduleFolder(Folder*); + void scheduleFolder(Folder *); /** Puts a folder in the very front of the queue. */ - void scheduleFolderNext(Folder*); + void scheduleFolderNext(Folder *); /** Queues all folders for syncing. */ void scheduleAllFolders(); @@ -196,7 +196,7 @@ signals: * * Attention: The folder may be zero. Do a general update of the state then. */ - void folderSyncStateChange(Folder*); + void folderSyncStateChange(Folder *); /** * Indicates when the schedule queue changes. @@ -227,31 +227,31 @@ public slots: * Automatically detemines the folder that's responsible for the file. * See slotWatchedFileUnlocked(). */ - void slotSyncOnceFileUnlocks(const QString& path); + void slotSyncOnceFileUnlocks(const QString &path); // slot to schedule an ETag job (from Folder only) - void slotScheduleETagJob ( const QString &alias, RequestEtagJob *job); + void slotScheduleETagJob(const QString &alias, RequestEtagJob *job); private slots: void slotFolderSyncPaused(Folder *, bool paused); void slotFolderCanSyncChanged(); void slotFolderSyncStarted(); - void slotFolderSyncFinished( const SyncResult& ); + void slotFolderSyncFinished(const SyncResult &); void slotRunOneEtagJob(); - void slotEtagJobDestroyed (QObject*); + void slotEtagJobDestroyed(QObject *); // slot to take the next folder from queue and start syncing. void slotStartScheduledFolderSync(); void slotEtagPollTimerTimeout(); - void slotRemoveFoldersForAccount(AccountState* accountState); + void slotRemoveFoldersForAccount(AccountState *accountState); // Wraps the Folder::syncStateChange() signal into the // FolderMan::folderSyncStateChange(Folder*) signal. void slotForwardFolderSyncStateChange(); - void slotServerVersionChanged(Account* account); + void slotServerVersionChanged(Account *account); /** * A file whose locks were being monitored has become unlocked. @@ -259,7 +259,7 @@ private slots: * This schedules the folder for synchronization that contains * the file with the given path. */ - void slotWatchedFileUnlocked(const QString& path); + void slotWatchedFileUnlocked(const QString &path); /** * Schedules folders whose time to sync has come. @@ -270,38 +270,37 @@ private slots: void slotScheduleFolderByTime(); private: - /** Adds a new folder, does not add it to the account settings and * does not set an account on the new folder. */ - Folder* addFolderInternal(FolderDefinition folderDefinition, - AccountState* accountState); + Folder *addFolderInternal(FolderDefinition folderDefinition, + AccountState *accountState); /* unloads a folder object, does not delete it */ - void unloadFolder( Folder * ); + void unloadFolder(Folder *); /** Will start a sync after a bit of delay. */ void startScheduledSyncSoon(); // finds all folder configuration files // and create the folders - QString getBackupName( QString fullPathName ) const; - void registerFolderMonitor( Folder *folder ); + QString getBackupName(QString fullPathName) const; + void registerFolderMonitor(Folder *folder); // restarts the application (Linux only) void restartApplication(); - void setupFoldersHelper(QSettings& settings, AccountStatePtr account, bool backwardsCompatible); + void setupFoldersHelper(QSettings &settings, AccountStatePtr account, bool backwardsCompatible); - QSet _disabledFolders; - Folder::Map _folderMap; - QString _folderConfigPath; - Folder *_currentSyncFolder; + QSet _disabledFolders; + Folder::Map _folderMap; + QString _folderConfigPath; + Folder *_currentSyncFolder; QPointer _lastSyncFolder; - bool _syncEnabled; + bool _syncEnabled; /// Watching for file changes in folders - QMap _folderWatchers; + QMap _folderWatchers; /// Starts regular etag query jobs QTimer _etagPollTimer; @@ -315,14 +314,14 @@ private: QTimer _timeScheduler; /// Scheduled folders that should be synced as soon as possible - QQueue _scheduledFolders; + QQueue _scheduledFolders; /// Picks the next scheduled folder and starts the sync - QTimer _startScheduledSyncTimer; + QTimer _startScheduledSyncTimer; QScopedPointer _socketApi; - bool _appRestartRequired; + bool _appRestartRequired; static FolderMan *_instance; explicit FolderMan(QObject *parent = 0); diff --git a/src/gui/folderstatusdelegate.cpp b/src/gui/folderstatusdelegate.cpp index 628fc893e..ddb503867 100644 --- a/src/gui/folderstatusdelegate.cpp +++ b/src/gui/folderstatusdelegate.cpp @@ -30,13 +30,15 @@ inline static QFont makeAliasFont(const QFont &normalFont) { QFont aliasFont = normalFont; aliasFont.setBold(true); - aliasFont.setPointSize(normalFont.pointSize()+2); + aliasFont.setPointSize(normalFont.pointSize() + 2); return aliasFont; } namespace OCC { -FolderStatusDelegate::FolderStatusDelegate() : QStyledItemDelegate() { +FolderStatusDelegate::FolderStatusDelegate() + : QStyledItemDelegate() +{ m_moreIcon = QIcon(QLatin1String(":/client/resources/more.png")); } @@ -46,8 +48,8 @@ QString FolderStatusDelegate::addFolderText() } // allocate each item size in listview. -QSize FolderStatusDelegate::sizeHint(const QStyleOptionViewItem & option , - const QModelIndex & index) const +QSize FolderStatusDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const { QFont aliasFont = makeAliasFont(option.font); QFont font = option.font; @@ -57,14 +59,14 @@ QSize FolderStatusDelegate::sizeHint(const QStyleOptionViewItem & option , auto classif = static_cast(index.model())->classify(index); if (classif == FolderStatusModel::AddButton) { - const int margins = aliasFm.height(); // same as 2*aliasMargin of paint + const int margins = aliasFm.height(); // same as 2*aliasMargin of paint QFontMetrics fm(option.font); QStyleOptionButton opt; - static_cast(opt) = option; + static_cast(opt) = option; opt.text = addFolderText(); return QApplication::style()->sizeFromContents( - QStyle::CT_PushButton, &opt, fm.size(Qt::TextSingleLine, opt.text)). - expandedTo(QApplication::globalStrut()) + QStyle::CT_PushButton, &opt, fm.size(Qt::TextSingleLine, opt.text)) + .expandedTo(QApplication::globalStrut()) + QSize(0, margins); } @@ -76,55 +78,55 @@ QSize FolderStatusDelegate::sizeHint(const QStyleOptionViewItem & option , int h = rootFolderHeightWithoutErrors(fm, aliasFm); // add some space to show an error condition. - if( ! qvariant_cast(index.data(FolderErrorMsg)).isEmpty() ) { - int margin = fm.height()/4; + if (!qvariant_cast(index.data(FolderErrorMsg)).isEmpty()) { + int margin = fm.height() / 4; QStringList errMsgs = qvariant_cast(index.data(FolderErrorMsg)); - h += margin + errMsgs.count()*fm.height(); + h += margin + errMsgs.count() * fm.height(); } - return QSize( 0, h); + return QSize(0, h); } int FolderStatusDelegate::rootFolderHeightWithoutErrors(const QFontMetrics &fm, const QFontMetrics &aliasFm) { - const int aliasMargin = aliasFm.height()/2; - const int margin = fm.height()/4; - - int h = aliasMargin; // margin to top - h += aliasFm.height(); // alias - h += margin; // between alias and local path - h += fm.height(); // local path - h += margin; // between local and remote path - h += fm.height(); // remote path - h += aliasMargin; // bottom margin + const int aliasMargin = aliasFm.height() / 2; + const int margin = fm.height() / 4; + + int h = aliasMargin; // margin to top + h += aliasFm.height(); // alias + h += margin; // between alias and local path + h += fm.height(); // local path + h += margin; // between local and remote path + h += fm.height(); // remote path + h += aliasMargin; // bottom margin return h; } void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const + const QModelIndex &index) const { - QStyledItemDelegate::paint(painter,option,index); + QStyledItemDelegate::paint(painter, option, index); auto textAlign = Qt::AlignLeft; QFont aliasFont = makeAliasFont(option.font); - QFont subFont = option.font; + QFont subFont = option.font; QFont errorFont = subFont; QFont progressFont = subFont; - progressFont.setPointSize( subFont.pointSize()-2); + progressFont.setPointSize(subFont.pointSize() - 2); - QFontMetrics subFm( subFont ); - QFontMetrics aliasFm( aliasFont ); - QFontMetrics progressFm( progressFont ); + QFontMetrics subFm(subFont); + QFontMetrics aliasFm(aliasFont); + QFontMetrics progressFm(progressFont); - int aliasMargin = aliasFm.height()/2; - int margin = subFm.height()/4; + int aliasMargin = aliasFm.height() / 2; + int margin = subFm.height() / 4; if (index.data(AddButton).toBool()) { QSize hint = sizeHint(option, index); QStyleOptionButton opt; - static_cast(opt) = option; + static_cast(opt) = option; opt.state &= ~QStyle::State_Selected; opt.state |= QStyle::State_Raised; opt.text = addFolderText(); @@ -132,8 +134,9 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem & opt.rect.adjust(0, aliasMargin, 0, -aliasMargin); opt.rect = QStyle::visualRect(option.direction, option.rect, opt.rect); QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter -#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - , option.widget +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + , + option.widget #endif ); return; @@ -144,44 +147,44 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem & } painter->save(); - QIcon statusIcon = qvariant_cast(index.data(FolderStatusIconRole)); - QString aliasText = qvariant_cast(index.data(HeaderRole)); - QString pathText = qvariant_cast(index.data(FolderPathRole)); - QString remotePath = qvariant_cast(index.data(FolderSecondPathRole)); - QStringList errorTexts= qvariant_cast(index.data(FolderErrorMsg)); + QIcon statusIcon = qvariant_cast(index.data(FolderStatusIconRole)); + QString aliasText = qvariant_cast(index.data(HeaderRole)); + QString pathText = qvariant_cast(index.data(FolderPathRole)); + QString remotePath = qvariant_cast(index.data(FolderSecondPathRole)); + QStringList errorTexts = qvariant_cast(index.data(FolderErrorMsg)); - int overallPercent = qvariant_cast(index.data(SyncProgressOverallPercent)); + int overallPercent = qvariant_cast(index.data(SyncProgressOverallPercent)); QString overallString = qvariant_cast(index.data(SyncProgressOverallString)); - QString itemString = qvariant_cast(index.data(SyncProgressItemString)); - int warningCount = qvariant_cast(index.data(WarningCount)); - bool syncOngoing = qvariant_cast(index.data(SyncRunning)); - bool syncEnabled = qvariant_cast(index.data(FolderAccountConnected)); + QString itemString = qvariant_cast(index.data(SyncProgressItemString)); + int warningCount = qvariant_cast(index.data(WarningCount)); + bool syncOngoing = qvariant_cast(index.data(SyncRunning)); + bool syncEnabled = qvariant_cast(index.data(FolderAccountConnected)); QRect iconRect = option.rect; QRect aliasRect = option.rect; - iconRect.setLeft( option.rect.left() + aliasMargin ); - iconRect.setTop( iconRect.top() + aliasMargin ); // (iconRect.height()-iconsize.height())/2); + iconRect.setLeft(option.rect.left() + aliasMargin); + iconRect.setTop(iconRect.top() + aliasMargin); // (iconRect.height()-iconsize.height())/2); // alias box - aliasRect.setTop(aliasRect.top() + aliasMargin ); + aliasRect.setTop(aliasRect.top() + aliasMargin); aliasRect.setBottom(aliasRect.top() + aliasFm.height()); - aliasRect.setRight(aliasRect.right() - aliasMargin ); + aliasRect.setRight(aliasRect.right() - aliasMargin); // remote directory box QRect remotePathRect = aliasRect; - remotePathRect.setTop(aliasRect.bottom() + margin ); + remotePathRect.setTop(aliasRect.bottom() + margin); remotePathRect.setBottom(remotePathRect.top() + subFm.height()); // local directory box QRect localPathRect = remotePathRect; - localPathRect.setTop( remotePathRect.bottom() + margin ); - localPathRect.setBottom( localPathRect.top() + subFm.height()); + localPathRect.setTop(remotePathRect.bottom() + margin); + localPathRect.setBottom(localPathRect.top() + subFm.height()); iconRect.setBottom(localPathRect.bottom()); iconRect.setWidth(iconRect.height()); - int nextToIcon = iconRect.right()+aliasMargin; + int nextToIcon = iconRect.right() + aliasMargin; aliasRect.setLeft(nextToIcon); localPathRect.setLeft(nextToIcon); remotePathRect.setLeft(nextToIcon); @@ -190,23 +193,23 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem & auto optionsButtonVisualRect = optionsButtonRect(option.rect, option.direction); - QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled ); + QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled); painter->drawPixmap(QStyle::visualRect(option.direction, option.rect, iconRect).left(), - iconRect.top(), pm); + iconRect.top(), pm); // only show the warning icon if the sync is running. Otherwise its // encoded in the status icon. - if( warningCount > 0 && syncOngoing) { + if (warningCount > 0 && syncOngoing) { QRect warnRect; warnRect.setLeft(iconRect.left()); - warnRect.setTop(iconRect.bottom()-17); + warnRect.setTop(iconRect.bottom() - 17); warnRect.setWidth(16); warnRect.setHeight(16); QIcon warnIcon(":/client/resources/warning"); - QPixmap pm = warnIcon.pixmap(16,16, syncEnabled ? QIcon::Normal : QIcon::Disabled ); + QPixmap pm = warnIcon.pixmap(16, 16, syncEnabled ? QIcon::Normal : QIcon::Disabled); warnRect = QStyle::visualRect(option.direction, option.rect, warnRect); - painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()),pm ); + painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()), pm); } auto palette = option.palette; @@ -221,7 +224,8 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem & QPalette::ColorGroup cg = option.state & QStyle::State_Enabled - ? QPalette::Normal : QPalette::Disabled; + ? QPalette::Normal + : QPalette::Disabled; if (cg == QPalette::Normal && !(option.state & QStyle::State_Active)) cg = QPalette::Inactive; @@ -235,44 +239,44 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem & painter->drawText(QStyle::visualRect(option.direction, option.rect, aliasRect), textAlign, elidedAlias); const bool showProgess = !overallString.isEmpty() || !itemString.isEmpty(); - if(!showProgess) { + if (!showProgess) { painter->setFont(subFont); QString elidedRemotePathText = subFm.elidedText( - tr("Synchronizing with local folder"), - Qt::ElideRight, remotePathRect.width()); + tr("Synchronizing with local folder"), + Qt::ElideRight, remotePathRect.width()); painter->drawText(QStyle::visualRect(option.direction, option.rect, remotePathRect), - textAlign, elidedRemotePathText); + textAlign, elidedRemotePathText); QString elidedPathText = subFm.elidedText(pathText, Qt::ElideMiddle, localPathRect.width()); painter->drawText(QStyle::visualRect(option.direction, option.rect, localPathRect), - textAlign, elidedPathText); + textAlign, elidedPathText); } // paint an error overlay if there is an error string int h = iconRect.bottom(); - if( !errorTexts.isEmpty() ) { + if (!errorTexts.isEmpty()) { h += margin; QRect errorRect = localPathRect; - errorRect.setLeft( iconRect.left()); - errorRect.setTop( h ); + errorRect.setLeft(iconRect.left()); + errorRect.setTop(h); errorRect.setHeight(errorTexts.count() * subFm.height() + 2 * margin); - errorRect.setRight( option.rect.right() - margin ); + errorRect.setRight(option.rect.right() - margin); - painter->setBrush( QColor(0xbb, 0x4d, 0x4d) ); - painter->setPen( QColor(0xaa, 0xaa, 0xaa)); + painter->setBrush(QColor(0xbb, 0x4d, 0x4d)); + painter->setPen(QColor(0xaa, 0xaa, 0xaa)); painter->drawRoundedRect(QStyle::visualRect(option.direction, option.rect, errorRect), - 4, 4); - painter->setPen( Qt::white ); + 4, 4); + painter->setPen(Qt::white); painter->setFont(errorFont); - QRect errorTextRect( errorRect.left() + margin, + QRect errorTextRect(errorRect.left() + margin, errorRect.top() + margin, errorRect.width() - 2 * margin, - subFm.height() ); + subFm.height()); - foreach( QString eText, errorTexts ) { + foreach (QString eText, errorTexts) { painter->drawText(QStyle::visualRect(option.direction, option.rect, errorTextRect), textAlign, - subFm.elidedText( eText, Qt::ElideLeft, errorTextRect.width())); + subFm.elidedText(eText, Qt::ElideLeft, errorTextRect.width())); errorTextRect.translate(0, errorTextRect.height()); } @@ -290,36 +294,36 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem & // Overall Progress Bar. QRect pBRect; - pBRect.setTop( remotePathRect.top() ); - pBRect.setLeft( nextToIcon ); + pBRect.setTop(remotePathRect.top()); + pBRect.setLeft(nextToIcon); pBRect.setHeight(barHeight); - pBRect.setWidth( overallWidth - 2 * margin ); + pBRect.setWidth(overallWidth - 2 * margin); -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QStyleOptionProgressBarV2 pBarOpt; #else QStyleOptionProgressBar pBarOpt; #endif - pBarOpt.state = option.state | QStyle::State_Horizontal; - pBarOpt.minimum = 0; - pBarOpt.maximum = 100; + pBarOpt.state = option.state | QStyle::State_Horizontal; + pBarOpt.minimum = 0; + pBarOpt.maximum = 100; pBarOpt.progress = overallPercent; pBarOpt.orientation = Qt::Horizontal; pBarOpt.rect = QStyle::visualRect(option.direction, option.rect, pBRect); - QApplication::style()->drawControl( QStyle::CE_ProgressBar, &pBarOpt, painter ); + QApplication::style()->drawControl(QStyle::CE_ProgressBar, &pBarOpt, painter); // Overall Progress Text QRect overallProgressRect; - overallProgressRect.setTop( pBRect.bottom() + margin ); - overallProgressRect.setHeight( fileNameTextHeight ); - overallProgressRect.setLeft( pBRect.left() ); - overallProgressRect.setWidth( pBRect.width() ); + overallProgressRect.setTop(pBRect.bottom() + margin); + overallProgressRect.setHeight(fileNameTextHeight); + overallProgressRect.setLeft(pBRect.left()); + overallProgressRect.setWidth(pBRect.width()); painter->setFont(progressFont); painter->drawText(QStyle::visualRect(option.direction, option.rect, overallProgressRect), - Qt::AlignLeft | Qt::AlignVCenter, overallString); + Qt::AlignLeft | Qt::AlignVCenter, overallString); // painter->drawRect(overallProgressRect); painter->restore(); @@ -338,12 +342,12 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem & btnOpt.rect = optionsButtonVisualRect; btnOpt.icon = m_moreIcon; btnOpt.iconSize = btnOpt.rect.size(); - QApplication::style()->drawComplexControl( QStyle::CC_ToolButton, &btnOpt, painter ); + QApplication::style()->drawComplexControl(QStyle::CC_ToolButton, &btnOpt, painter); } } -bool FolderStatusDelegate::editorEvent ( QEvent * event, QAbstractItemModel * model, - const QStyleOptionViewItem & option, const QModelIndex & index ) +bool FolderStatusDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, + const QStyleOptionViewItem &option, const QModelIndex &index) { return QStyledItemDelegate::editorEvent(event, model, option, index); } @@ -360,13 +364,12 @@ QRect FolderStatusDelegate::optionsButtonRect(QRect within, Qt::LayoutDirection opt.text = QLatin1String("..."); QSize textSize = fm.size(Qt::TextShowMnemonic, opt.text); opt.rect.setSize(textSize); - QSize size = QApplication::style()->sizeFromContents(QStyle::CT_ToolButton, &opt, textSize). - expandedTo(QApplication::globalStrut()); + QSize size = QApplication::style()->sizeFromContents(QStyle::CT_ToolButton, &opt, textSize).expandedTo(QApplication::globalStrut()); int margin = QApplication::style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing); QRect r(QPoint(within.right() - size.width() - margin, - within.top() + within.height()/2 - size.height()/2), - size); + within.top() + within.height() / 2 - size.height() / 2), + size); return QStyle::visualRect(direction, within, r); } diff --git a/src/gui/folderstatusdelegate.h b/src/gui/folderstatusdelegate.h index 6d533258d..b42ae134d 100644 --- a/src/gui/folderstatusdelegate.h +++ b/src/gui/folderstatusdelegate.h @@ -30,26 +30,26 @@ public: FolderStatusDelegate(); enum datarole { FolderAliasRole = Qt::UserRole + 100, - HeaderRole, - FolderPathRole, // for a SubFolder it's the complete path - FolderSecondPathRole, - FolderErrorMsg, - FolderSyncPaused, - FolderStatusIconRole, - FolderAccountConnected, + HeaderRole, + FolderPathRole, // for a SubFolder it's the complete path + FolderSecondPathRole, + FolderErrorMsg, + FolderSyncPaused, + FolderStatusIconRole, + FolderAccountConnected, - SyncProgressOverallPercent, - SyncProgressOverallString, - SyncProgressItemString, - WarningCount, - SyncRunning, + SyncProgressOverallPercent, + SyncProgressOverallString, + SyncProgressItemString, + WarningCount, + SyncRunning, - AddButton // 1 = enabled; 2 = disabled - }; - void paint( QPainter*, const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE; - QSize sizeHint( const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE; - bool editorEvent( QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, - const QModelIndex& index ) Q_DECL_OVERRIDE; + AddButton // 1 = enabled; 2 = disabled + }; + void paint(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE; + QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE; + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, + const QModelIndex &index) Q_DECL_OVERRIDE; /** @@ -57,9 +57,9 @@ public: */ static QRect optionsButtonRect(QRect within, Qt::LayoutDirection direction); static int rootFolderHeightWithoutErrors(const QFontMetrics &fm, const QFontMetrics &aliasFm); + private: static QString addFolderText(); }; } // namespace OCC - diff --git a/src/gui/folderstatusmodel.cpp b/src/gui/folderstatusmodel.cpp index bb8edb746..037285b53 100644 --- a/src/gui/folderstatusmodel.cpp +++ b/src/gui/folderstatusmodel.cpp @@ -34,7 +34,8 @@ Q_LOGGING_CATEGORY(lcFolderStatus, "gui.folder.model", QtInfoMsg) static const char propertyParentIndexC[] = "oc_parentIndex"; static const char propertyPermissionMap[] = "oc_permissionMap"; -static QString removeTrailingSlash(const QString &s) { +static QString removeTrailingSlash(const QString &s) +{ if (s.endsWith('/')) { return s.left(s.size() - 1); } @@ -42,36 +43,40 @@ static QString removeTrailingSlash(const QString &s) { } FolderStatusModel::FolderStatusModel(QObject *parent) - :QAbstractItemModel(parent), _accountState(0), _dirty(false) + : QAbstractItemModel(parent) + , _accountState(0) + , _dirty(false) { } FolderStatusModel::~FolderStatusModel() -{ } +{ +} -static bool sortByFolderHeader(const FolderStatusModel::SubFolderInfo& lhs, const FolderStatusModel::SubFolderInfo& rhs) +static bool sortByFolderHeader(const FolderStatusModel::SubFolderInfo &lhs, const FolderStatusModel::SubFolderInfo &rhs) { return QString::compare(lhs._folder->shortGuiRemotePathOrAppName(), - rhs._folder->shortGuiRemotePathOrAppName(), - Qt::CaseInsensitive) < 0; + rhs._folder->shortGuiRemotePathOrAppName(), + Qt::CaseInsensitive) + < 0; } -void FolderStatusModel::setAccountState(const AccountState* accountState) +void FolderStatusModel::setAccountState(const AccountState *accountState) { beginResetModel(); _dirty = false; _folders.clear(); _accountState = accountState; - connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder*)), - SLOT(slotFolderSyncStateChange(Folder*)), Qt::UniqueConnection); + connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder *)), + SLOT(slotFolderSyncStateChange(Folder *)), Qt::UniqueConnection); connect(FolderMan::instance(), SIGNAL(scheduleQueueChanged()), - SLOT(slotFolderScheduleQueueChanged()), Qt::UniqueConnection); + SLOT(slotFolderScheduleQueueChanged()), Qt::UniqueConnection); auto folders = FolderMan::instance()->map(); foreach (auto f, folders) { - if (!accountState) - break; + if (!accountState) + break; if (f->accountState() != accountState) continue; SubFolderInfo info; @@ -98,38 +103,38 @@ void FolderStatusModel::setAccountState(const AccountState* accountState) } -Qt::ItemFlags FolderStatusModel::flags ( const QModelIndex &index ) const +Qt::ItemFlags FolderStatusModel::flags(const QModelIndex &index) const { - if (!_accountState) { - return 0; - } + if (!_accountState) { + return 0; + } switch (classify(index)) { - case AddButton: { - Qt::ItemFlags ret; + case AddButton: { + Qt::ItemFlags ret; #if QT_VERSION >= QT_VERSION_CHECK(5, 1, 0) - ret = Qt::ItemNeverHasChildren; + ret = Qt::ItemNeverHasChildren; #endif - if (!_accountState->isConnected()) { + if (!_accountState->isConnected()) { + return ret; + } else if (_folders.count() == 1) { + auto remotePath = _folders.at(0)._folder->remotePath(); + // special case when syncing the entire owncloud: disable the add folder button (#3438) + if (remotePath.isEmpty() || remotePath == QLatin1String("/")) { return ret; - } else if (_folders.count() == 1) { - auto remotePath = _folders.at(0)._folder->remotePath(); - // special case when syncing the entire owncloud: disable the add folder button (#3438) - if (remotePath.isEmpty() || remotePath == QLatin1String("/")) { - return ret; - } } - return Qt::ItemIsEnabled | ret; } - case FetchLabel: - return Qt::ItemIsEnabled + return Qt::ItemIsEnabled | ret; + } + case FetchLabel: + return Qt::ItemIsEnabled #if QT_VERSION >= QT_VERSION_CHECK(5, 1, 0) - | Qt::ItemNeverHasChildren + | Qt::ItemNeverHasChildren #endif - ; - case RootFolder: - return Qt::ItemIsEnabled; - case SubFolder: - return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable; + ; + case RootFolder: + return Qt::ItemIsEnabled; + case SubFolder: + return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable; } return 0; } @@ -142,28 +147,28 @@ QVariant FolderStatusModel::data(const QModelIndex &index, int role) const if (role == Qt::EditRole) return QVariant(); - switch(classify(index)) { + switch (classify(index)) { case AddButton: { if (role == FolderStatusDelegate::AddButton) { return QVariant(true); } else if (role == Qt::ToolTipRole) { if (!_accountState->isConnected()) { return tr("You need to be connected to add a folder"); - } if (_folders.count() == 1) { + } + if (_folders.count() == 1) { auto remotePath = _folders.at(0)._folder->remotePath(); if (remotePath.isEmpty() || remotePath == QLatin1String("/")) { // Syncing the entire owncloud: disable the add folder button (#3438) return tr("Adding folder is disabled because you are already syncing all your files. " - "If you want to sync multiple folders, please remove the currently " - "configured root folder."); + "If you want to sync multiple folders, please remove the currently " + "configured root folder."); } } return tr("Click this button to add a folder to synchronize."); } return QVariant(); } - case SubFolder: - { + case SubFolder: { const auto &x = static_cast(index.internalPointer())->_subs[index.row()]; switch (role) { case Qt::DisplayRole: @@ -185,52 +190,60 @@ QVariant FolderStatusModel::data(const QModelIndex &index, int role) const if (!f) return QVariant(); return QVariant(f->path() + x._path); - } + } } } return QVariant(); - case FetchLabel: - { + case FetchLabel: { const auto x = static_cast(index.internalPointer()); - switch(role) { - case Qt::DisplayRole: - if (x->_hasError) { - return QVariant(tr("Error while loading the list of folders from the server.") - + QString("\n") + x->_lastErrorString); - } else { - return tr("Fetching folder list from server..."); - } - break; - default: return QVariant(); + switch (role) { + case Qt::DisplayRole: + if (x->_hasError) { + return QVariant(tr("Error while loading the list of folders from the server.") + + QString("\n") + x->_lastErrorString); + } else { + return tr("Fetching folder list from server..."); + } + break; + default: + return QVariant(); } } case RootFolder: break; } - const SubFolderInfo & folderInfo = _folders.at(index.row()); + const SubFolderInfo &folderInfo = _folders.at(index.row()); auto f = folderInfo._folder; if (!f) return QVariant(); - const SubFolderInfo::Progress & progress = folderInfo._progress; + const SubFolderInfo::Progress &progress = folderInfo._progress; const bool accountConnected = _accountState->isConnected(); switch (role) { - case FolderStatusDelegate::FolderPathRole : return f->shortGuiLocalPath(); - case FolderStatusDelegate::FolderSecondPathRole : return f->remotePath(); - case FolderStatusDelegate::FolderErrorMsg : return f->syncResult().errorStrings(); - case FolderStatusDelegate::SyncRunning : return f->syncResult().status() == SyncResult::SyncRunning; - case FolderStatusDelegate::HeaderRole : return f->shortGuiRemotePathOrAppName(); - case FolderStatusDelegate::FolderAliasRole : return f->alias(); - case FolderStatusDelegate::FolderSyncPaused : return f->syncPaused(); - case FolderStatusDelegate::FolderAccountConnected : return accountConnected; + case FolderStatusDelegate::FolderPathRole: + return f->shortGuiLocalPath(); + case FolderStatusDelegate::FolderSecondPathRole: + return f->remotePath(); + case FolderStatusDelegate::FolderErrorMsg: + return f->syncResult().errorStrings(); + case FolderStatusDelegate::SyncRunning: + return f->syncResult().status() == SyncResult::SyncRunning; + case FolderStatusDelegate::HeaderRole: + return f->shortGuiRemotePathOrAppName(); + case FolderStatusDelegate::FolderAliasRole: + return f->alias(); + case FolderStatusDelegate::FolderSyncPaused: + return f->syncPaused(); + case FolderStatusDelegate::FolderAccountConnected: + return accountConnected; case Qt::ToolTipRole: { QString toolTip; if (!progress.isNull()) { return progress._progressString; } - if ( accountConnected ) + if (accountConnected) toolTip = Theme::instance()->statusHeaderText(f->syncResult().status()); else toolTip = tr("Signed out"); @@ -239,22 +252,22 @@ QVariant FolderStatusModel::data(const QModelIndex &index, int role) const return toolTip; } case FolderStatusDelegate::FolderStatusIconRole: - if ( accountConnected ) { + if (accountConnected) { auto theme = Theme::instance(); auto status = f->syncResult().status(); - if( f->syncPaused() ) { - return theme->folderDisabledIcon( ); + if (f->syncPaused()) { + return theme->folderDisabledIcon(); } else { - if( status == SyncResult::SyncPrepare ) { + if (status == SyncResult::SyncPrepare) { + return theme->syncStateIcon(SyncResult::SyncRunning); + } else if (status == SyncResult::Undefined) { return theme->syncStateIcon(SyncResult::SyncRunning); - } else if( status == SyncResult::Undefined ) { - return theme->syncStateIcon( SyncResult::SyncRunning); } else { // keep the previous icon for the prepare phase. - if( status == SyncResult::Problem) { - return theme->syncStateIcon( SyncResult::Success); + if (status == SyncResult::Problem) { + return theme->syncStateIcon(SyncResult::Success); } else { - return theme->syncStateIcon( status ); + return theme->syncStateIcon(status); } } } @@ -273,9 +286,9 @@ QVariant FolderStatusModel::data(const QModelIndex &index, int role) const return QVariant(); } -bool FolderStatusModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool FolderStatusModel::setData(const QModelIndex &index, const QVariant &value, int role) { - if(role == Qt::CheckStateRole) { + if (role == Qt::CheckStateRole) { auto info = infoForIndex(index); Qt::CheckState checked = static_cast(value.toInt()); @@ -288,7 +301,7 @@ bool FolderStatusModel::setData(const QModelIndex& index, const QVariant& value, auto parentInfo = infoForIndex(parent); if (parentInfo && parentInfo->_checked != Qt::Checked) { bool hasUnchecked = false; - foreach(const auto &sub, parentInfo->_subs) { + foreach (const auto &sub, parentInfo->_subs) { if (sub._checked != Qt::Checked) { hasUnchecked = true; break; @@ -330,7 +343,6 @@ bool FolderStatusModel::setData(const QModelIndex& index, const QVariant& value, setData(parent, Qt::PartiallyChecked, Qt::CheckStateRole); } } - } _dirty = true; emit dirtyChanged(); @@ -341,15 +353,15 @@ bool FolderStatusModel::setData(const QModelIndex& index, const QVariant& value, } -int FolderStatusModel::columnCount(const QModelIndex&) const +int FolderStatusModel::columnCount(const QModelIndex &) const { return 1; } -int FolderStatusModel::rowCount(const QModelIndex& parent) const +int FolderStatusModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { - if( Theme::instance()->singleSyncFolder() && _folders.count() != 0) { + if (Theme::instance()->singleSyncFolder() && _folders.count() != 0) { // "Add folder" button not visible in the singleSyncFolder configuration. return _folders.count(); } @@ -363,9 +375,9 @@ int FolderStatusModel::rowCount(const QModelIndex& parent) const return info->_subs.count(); } -FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex& index) const +FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex &index) const { - if (auto sub = static_cast(index.internalPointer())) { + if (auto sub = static_cast(index.internalPointer())) { if (sub->hasLabel()) { return FetchLabel; } else { @@ -378,11 +390,11 @@ FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex& index return AddButton; } -FolderStatusModel::SubFolderInfo* FolderStatusModel::infoForIndex(const QModelIndex& index) const +FolderStatusModel::SubFolderInfo *FolderStatusModel::infoForIndex(const QModelIndex &index) const { if (!index.isValid()) return 0; - if (auto parentInfo = static_cast(index.internalPointer())) { + if (auto parentInfo = static_cast(index.internalPointer())) { if (parentInfo->hasLabel()) { return 0; } @@ -399,9 +411,9 @@ FolderStatusModel::SubFolderInfo* FolderStatusModel::infoForIndex(const QModelIn } } -QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) const +QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString &path) const { - if( !f ) { + if (!f) { return QModelIndex(); } @@ -409,9 +421,9 @@ QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) cons if (slashPos == -1) { // first level folder for (int i = 0; i < _folders.size(); ++i) { - auto& info = _folders.at(i); + auto &info = _folders.at(i); if (info._folder == f) { - if( path.isEmpty() ) { // the folder object + if (path.isEmpty()) { // the folder object return index(i, 0); } for (int j = 0; j < info._subs.size(); ++j) { @@ -440,7 +452,7 @@ QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) cons return QModelIndex(); } for (int i = 0; i < parentInfo->_subs.size(); ++i) { - if (parentInfo->_subs.at(i)._name == path.mid(slashPos + 1)) { + if (parentInfo->_subs.at(i)._name == path.mid(slashPos + 1)) { return index(i, 0, parent); } } @@ -448,51 +460,51 @@ QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) cons return QModelIndex(); } -QModelIndex FolderStatusModel::index(int row, int column, const QModelIndex& parent) const +QModelIndex FolderStatusModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid()) { - return createIndex(row, column/*, nullptr*/); - } - switch(classify(parent)) { - case AddButton: - case FetchLabel: - return QModelIndex(); - case RootFolder: - if (_folders.count() <= parent.row()) - return QModelIndex(); // should not happen - return createIndex(row, column, const_cast(&_folders[parent.row()])); - case SubFolder: { - auto pinfo = static_cast(parent.internalPointer()); - if (pinfo->_subs.count() <= parent.row()) - return QModelIndex(); // should not happen - auto & info = pinfo->_subs[parent.row()]; - if (!info.hasLabel() - && info._subs.count() <= row) - return QModelIndex(); // should not happen - return createIndex(row, column, &info); - } + return createIndex(row, column /*, nullptr*/); + } + switch (classify(parent)) { + case AddButton: + case FetchLabel: + return QModelIndex(); + case RootFolder: + if (_folders.count() <= parent.row()) + return QModelIndex(); // should not happen + return createIndex(row, column, const_cast(&_folders[parent.row()])); + case SubFolder: { + auto pinfo = static_cast(parent.internalPointer()); + if (pinfo->_subs.count() <= parent.row()) + return QModelIndex(); // should not happen + auto &info = pinfo->_subs[parent.row()]; + if (!info.hasLabel() + && info._subs.count() <= row) + return QModelIndex(); // should not happen + return createIndex(row, column, &info); + } } return QModelIndex(); } -QModelIndex FolderStatusModel::parent(const QModelIndex& child) const +QModelIndex FolderStatusModel::parent(const QModelIndex &child) const { if (!child.isValid()) { return QModelIndex(); } - switch(classify(child)) { - case RootFolder: - case AddButton: - return QModelIndex(); - case SubFolder: - case FetchLabel: - break; + switch (classify(child)) { + case RootFolder: + case AddButton: + return QModelIndex(); + case SubFolder: + case FetchLabel: + break; } - auto pathIdx = static_cast(child.internalPointer())->_pathIdx; + auto pathIdx = static_cast(child.internalPointer())->_pathIdx; int i = 1; ASSERT(pathIdx.at(0) < _folders.count()); if (pathIdx.count() == 1) { - return createIndex(pathIdx.at(0), 0/*, nullptr*/); + return createIndex(pathIdx.at(0), 0 /*, nullptr*/); } const SubFolderInfo *info = &_folders[pathIdx.at(0)]; @@ -504,7 +516,7 @@ QModelIndex FolderStatusModel::parent(const QModelIndex& child) const return createIndex(pathIdx.at(i), 0, const_cast(info)); } -bool FolderStatusModel::hasChildren(const QModelIndex& parent) const +bool FolderStatusModel::hasChildren(const QModelIndex &parent) const { if (!parent.isValid()) return true; @@ -523,11 +535,11 @@ bool FolderStatusModel::hasChildren(const QModelIndex& parent) const } -bool FolderStatusModel::canFetchMore(const QModelIndex& parent) const +bool FolderStatusModel::canFetchMore(const QModelIndex &parent) const { if (!_accountState) { - return false; - } + return false; + } if (_accountState->state() != AccountState::Connected) { return false; } @@ -542,7 +554,7 @@ bool FolderStatusModel::canFetchMore(const QModelIndex& parent) const } -void FolderStatusModel::fetchMore(const QModelIndex& parent) +void FolderStatusModel::fetchMore(const QModelIndex &parent) { auto info = infoForIndex(parent); @@ -558,26 +570,28 @@ void FolderStatusModel::fetchMore(const QModelIndex& parent) path += info->_path; } LsColJob *job = new LsColJob(_accountState->account(), path, this); - job->setProperties(QList() << "resourcetype" << "http://owncloud.org/ns:size" << "http://owncloud.org/ns:permissions"); + job->setProperties(QList() << "resourcetype" + << "http://owncloud.org/ns:size" + << "http://owncloud.org/ns:permissions"); job->setTimeout(60 * 1000); connect(job, SIGNAL(directoryListingSubfolders(QStringList)), - SLOT(slotUpdateDirectories(QStringList))); - connect(job, SIGNAL(finishedWithError(QNetworkReply*)), - this, SLOT(slotLscolFinishedWithError(QNetworkReply*))); - connect(job, SIGNAL(directoryListingIterated(const QString&, const QMap&)), - this, SLOT(slotGatherPermissions(const QString&, const QMap&))); + SLOT(slotUpdateDirectories(QStringList))); + connect(job, SIGNAL(finishedWithError(QNetworkReply *)), + this, SLOT(slotLscolFinishedWithError(QNetworkReply *))); + connect(job, SIGNAL(directoryListingIterated(const QString &, const QMap &)), + this, SLOT(slotGatherPermissions(const QString &, const QMap &))); job->start(); QPersistentModelIndex persistentIndex(parent); - job->setProperty(propertyParentIndexC , QVariant::fromValue(persistentIndex)); + job->setProperty(propertyParentIndexC, QVariant::fromValue(persistentIndex)); // Show 'fetching data...' hint after a while. _fetchingItems[persistentIndex].start(); QTimer::singleShot(1000, this, SLOT(slotShowFetchProgress())); } -void FolderStatusModel::slotGatherPermissions(const QString &href, const QMap &map) +void FolderStatusModel::slotGatherPermissions(const QString &href, const QMap &map) { auto it = map.find("permissions"); if (it == map.end()) @@ -602,7 +616,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list) } if (parentInfo->hasLabel()) { - beginRemoveRows(idx, 0 ,0); + beginRemoveRows(idx, 0, 0); parentInfo->_lastErrorString.clear(); parentInfo->_hasError = false; parentInfo->_fetchingLabel = false; @@ -625,7 +639,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list) } auto selectiveSyncUndecidedList = parentInfo->_folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok2); - if( !(ok1 && ok2) ) { + if (!(ok1 && ok2)) { qCWarning(lcFolderStatus) << "Could not retrieve selective sync info from journal"; return; } @@ -647,7 +661,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list) QVector newSubs; newSubs.reserve(sortedSubfolders.size()); - foreach (const QString& path, sortedSubfolders) { + foreach (const QString &path, sortedSubfolders) { auto relativePath = path.mid(pathToRemove.size()); if (parentInfo->_folder->isFileExcludedRelative(relativePath)) { continue; @@ -670,7 +684,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list) } else if (parentInfo->_checked == Qt::Checked) { newInfo._checked = Qt::Checked; } else { - foreach(const QString &str , selectiveSyncBlackList) { + foreach (const QString &str, selectiveSyncBlackList) { if (str == relativePath || str == QLatin1String("/")) { newInfo._checked = Qt::Unchecked; break; @@ -690,7 +704,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list) // Remove all the items from the selectiveSyncUndecidedSet that starts with this path QString relativePathNext = relativePath; - relativePathNext[relativePathNext.length()-1].unicode()++; + relativePathNext[relativePathNext.length() - 1].unicode()++; auto it2 = selectiveSyncUndecidedSet.lower_bound(relativePathNext); selectiveSyncUndecidedSet.erase(it, it2); } @@ -706,23 +720,23 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list) suggestExpand(idx.child(*it, 0)); } - /* We need lambda function for the following code. +/* We need lambda function for the following code. * It's just a small feature that will be missing if the comiler is too old */ #if !(defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && !defined(Q_CC_CLANG)) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 405) /* Try to remove the the undecided lists the items that are not on the server. */ auto it = std::remove_if(selectiveSyncUndecidedList.begin(), selectiveSyncUndecidedList.end(), - [&](const QString &s) { return selectiveSyncUndecidedSet.count(s); } ); + [&](const QString &s) { return selectiveSyncUndecidedSet.count(s); }); if (it != selectiveSyncUndecidedList.end()) { selectiveSyncUndecidedList.erase(it, selectiveSyncUndecidedList.end()); parentInfo->_folder->journalDb()->setSelectiveSyncList( - SyncJournalDb::SelectiveSyncUndecidedList, selectiveSyncUndecidedList); + SyncJournalDb::SelectiveSyncUndecidedList, selectiveSyncUndecidedList); emit dirtyChanged(); } #endif } -void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply* r) +void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply *r) { auto job = qobject_cast(sender()); ASSERT(job); @@ -749,17 +763,18 @@ void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply* r) } QStringList FolderStatusModel::createBlackList(FolderStatusModel::SubFolderInfo *root, - const QStringList &oldBlackList) const + const QStringList &oldBlackList) const { - if (!root) return QStringList(); - - switch(root->_checked) { - case Qt::Unchecked: - return QStringList(root->_path); - case Qt::Checked: - return QStringList(); - case Qt::PartiallyChecked: - break; + if (!root) + return QStringList(); + + switch (root->_checked) { + case Qt::Unchecked: + return QStringList(root->_path); + case Qt::Checked: + return QStringList(); + case Qt::PartiallyChecked: + break; } QStringList result; @@ -770,7 +785,7 @@ QStringList FolderStatusModel::createBlackList(FolderStatusModel::SubFolderInfo } else { // We did not load from the server so we re-use the one from the old black list QString path = root->_path; - foreach (const QString & it, oldBlackList) { + foreach (const QString &it, oldBlackList) { if (it.startsWith(path)) result += it; } @@ -780,7 +795,8 @@ QStringList FolderStatusModel::createBlackList(FolderStatusModel::SubFolderInfo void FolderStatusModel::slotUpdateFolderState(Folder *folder) { - if( ! folder ) return; + if (!folder) + return; for (int i = 0; i < _folders.count(); ++i) { if (_folders.at(i)._folder == folder) { emit dataChanged(index(i), index(i)); @@ -799,7 +815,7 @@ void FolderStatusModel::slotApplySelectiveSync() bool ok; auto oldBlackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok); - if( !ok ) { + if (!ok) { qCWarning(lcFolderStatus) << "Could not read selective sync list from db."; return; } @@ -811,8 +827,7 @@ void FolderStatusModel::slotApplySelectiveSync() // The folders that were undecided or blacklisted and that are now checked should go on the white list. // The user confirmed them already just now. - QStringList toAddToWhiteList = ((oldBlackListSet + folder->journalDb()->getSelectiveSyncList( - SyncJournalDb::SelectiveSyncUndecidedList, &ok).toSet()) - blackListSet).toList(); + QStringList toAddToWhiteList = ((oldBlackListSet + folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok).toSet()) - blackListSet).toList(); if (!toAddToWhiteList.isEmpty()) { auto whiteList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok); @@ -832,7 +847,7 @@ void FolderStatusModel::slotApplySelectiveSync() } //The part that changed should not be read from the DB on next sync because there might be new folders // (the ones that are no longer in the blacklist) - foreach(const auto &it, changes) { + foreach (const auto &it, changes) { folder->journalDb()->avoidReadFromDbOnNextSync(it); } FolderMan::instance()->scheduleFolder(folder); @@ -844,13 +859,15 @@ void FolderStatusModel::slotApplySelectiveSync() void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) { - auto par = qobject_cast(QObject::parent()); + auto par = qobject_cast(QObject::parent()); if (!par->isVisible()) { return; // for https://github.com/owncloud/client/issues/2648#issuecomment-71377909 } - Folder *f = qobject_cast(sender()); - if( !f ) { return; } + Folder *f = qobject_cast(sender()); + if (!f) { + return; + } int folderIndex = -1; for (int i = 0; i < _folders.count(); ++i) { @@ -859,7 +876,9 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) break; } } - if (folderIndex < 0) { return; } + if (folderIndex < 0) { + return; + } auto *pi = &_folders[folderIndex]._progress; @@ -874,8 +893,8 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) return; } - if(!progress._lastCompletedItem.isEmpty() - && Progress::isWarningKind(progress._lastCompletedItem._status)) { + if (!progress._lastCompletedItem.isEmpty() + && Progress::isWarningKind(progress._lastCompletedItem._status)) { pi->_warningCount++; } @@ -887,14 +906,14 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) quint64 estimatedUpBw = 0; quint64 estimatedDownBw = 0; QString allFilenames; - foreach(const ProgressInfo::ProgressItem &citm, progress._currentItems) { + foreach (const ProgressInfo::ProgressItem &citm, progress._currentItems) { if (curItemProgress == -1 || (ProgressInfo::isSizeDependent(citm._item) - && biggerItemSize < citm._item._size)) { + && biggerItemSize < citm._item._size)) { curItemProgress = citm._progress.completed(); curItem = citm._item; biggerItemSize = citm._item._size; } - if (citm._item._direction != SyncFileItem::Up){ + if (citm._item._direction != SyncFileItem::Up) { estimatedDownBw += progress.fileProgress(citm._item).estimatedBandwidth; } else { estimatedUpBw += progress.fileProgress(citm._item).estimatedBandwidth; @@ -917,8 +936,8 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) QString fileProgressString; if (ProgressInfo::isSizeDependent(curItem)) { - QString s1 = Utility::octetsToString( curItemProgress ); - QString s2 = Utility::octetsToString( curItem._size ); + QString s1 = Utility::octetsToString(curItemProgress); + QString s2 = Utility::octetsToString(curItem._size); //quint64 estimatedBw = progress.fileProgress(curItem).estimatedBandwidth; if (estimatedUpBw || estimatedDownBw) { /* @@ -937,21 +956,25 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) //: Example text: "download 24Kb/s" (%1 is replaced by 24Kb (translated)) fileProgressString.append(tr("download %1/s").arg(Utility::octetsToString(estimatedDownBw))); #else - fileProgressString.append(trUtf8("\u2193" " %1/s").arg(Utility::octetsToString(estimatedDownBw))); + fileProgressString.append(trUtf8("\u2193" + " %1/s") + .arg(Utility::octetsToString(estimatedDownBw))); #endif } if (estimatedUpBw > 0) { fileProgressString.append(tr(", ")); - #ifdef Q_OS_WIN +#ifdef Q_OS_WIN //: Example text: "upload 24Kb/s" (%1 is replaced by 24Kb (translated)) fileProgressString.append(tr("upload %1/s").arg(Utility::octetsToString(estimatedUpBw))); #else - fileProgressString.append(trUtf8("\u2191" " %1/s").arg(Utility::octetsToString(estimatedUpBw))); + fileProgressString.append(trUtf8("\u2191" + " %1/s") + .arg(Utility::octetsToString(estimatedUpBw))); #endif } } else { //: Example text: "uploading foobar.png (2MB of 2MB)" - fileProgressString = tr("%1 %2 (%3 of %4)") .arg(kindString, itemFileName, s1, s2); + fileProgressString = tr("%1 %2 (%3 of %4)").arg(kindString, itemFileName, s1, s2); } } else if (!kindString.isEmpty()) { //: Example text: "uploading foobar.png" @@ -969,33 +992,35 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) quint64 totalFileCount = qMax(currentFile, progress.totalFiles()); QString overallSyncString; if (totalSize > 0) { - QString s1 = Utility::octetsToString( completedSize ); - QString s2 = Utility::octetsToString( totalSize ); + QString s1 = Utility::octetsToString(completedSize); + QString s2 = Utility::octetsToString(totalSize); if (progress.trustEta()) { //: Example text: "5 minutes left, 12 MB of 345 MB, file 6 of 7" overallSyncString = tr("%5 left, %1 of %2, file %3 of %4") - .arg(s1, s2) - .arg(currentFile).arg(totalFileCount) - .arg( Utility::durationToDescriptiveString1(progress.totalProgress().estimatedEta) ); + .arg(s1, s2) + .arg(currentFile) + .arg(totalFileCount) + .arg(Utility::durationToDescriptiveString1(progress.totalProgress().estimatedEta)); } else { //: Example text: "12 MB of 345 MB, file 6 of 7" overallSyncString = tr("%1 of %2, file %3 of %4") - .arg(s1, s2) - .arg(currentFile).arg(totalFileCount); + .arg(s1, s2) + .arg(currentFile) + .arg(totalFileCount); } } else if (totalFileCount > 0) { // Don't attempt to estimate the time left if there is no kb to transfer. - overallSyncString = tr("file %1 of %2") .arg(currentFile).arg(totalFileCount); + overallSyncString = tr("file %1 of %2").arg(currentFile).arg(totalFileCount); } - pi->_overallSyncString = overallSyncString; + pi->_overallSyncString = overallSyncString; int overallPercent = 0; - if( totalFileCount > 0 ) { + if (totalFileCount > 0) { // Add one 'byte' for each file so the percentage is moving when deleting or renaming files - overallPercent = qRound(double(completedSize + completedFile)/double(totalSize + totalFileCount) * 100.0); + overallPercent = qRound(double(completedSize + completedFile) / double(totalSize + totalFileCount) * 100.0); } pi->_overallPercent = qBound(0, overallPercent, 100); emit dataChanged(index(folderIndex), index(folderIndex), roles); @@ -1003,7 +1028,9 @@ void FolderStatusModel::slotSetProgress(const ProgressInfo &progress) void FolderStatusModel::slotFolderSyncStateChange(Folder *f) { - if( !f ) { return; } + if (!f) { + return; + } int folderIndex = -1; for (int i = 0; i < _folders.count(); ++i) { @@ -1012,19 +1039,21 @@ void FolderStatusModel::slotFolderSyncStateChange(Folder *f) break; } } - if (folderIndex < 0) { return; } + if (folderIndex < 0) { + return; + } - auto& pi = _folders[folderIndex]._progress; + auto &pi = _folders[folderIndex]._progress; SyncResult::Status state = f->syncResult().status(); if (!f->canSync()) { // Reset progress info. pi = SubFolderInfo::Progress(); } else if (state == SyncResult::NotYetStarted) { - FolderMan* folderMan = FolderMan::instance(); + FolderMan *folderMan = FolderMan::instance(); int pos = folderMan->scheduleQueue().indexOf(f); if (folderMan->currentSyncFolder() - && folderMan->currentSyncFolder() != f) { + && folderMan->currentSyncFolder() != f) { pos += 1; } QString message; @@ -1050,7 +1079,7 @@ void FolderStatusModel::slotFolderSyncStateChange(Folder *f) if (state == SyncResult::Success && f->syncResult().folderStructureWasChanged()) { // There is a new or a removed folder. reset all data - auto & info = _folders[folderIndex]; + auto &info = _folders[folderIndex]; info.resetSubs(this, index(folderIndex)); } } @@ -1058,7 +1087,7 @@ void FolderStatusModel::slotFolderSyncStateChange(Folder *f) void FolderStatusModel::slotFolderScheduleQueueChanged() { // Update messages on waiting folders. - foreach (Folder* f, FolderMan::instance()->map()) { + foreach (Folder *f, FolderMan::instance()->map()) { slotFolderSyncStateChange(f); } } @@ -1079,7 +1108,7 @@ void FolderStatusModel::slotSyncAllPendingBigFolders() bool ok; auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok); - if( !ok ) { + if (!ok) { qCWarning(lcFolderStatus) << "Could not read selective sync list from db."; return; } @@ -1091,18 +1120,18 @@ void FolderStatusModel::slotSyncAllPendingBigFolders() // Remove all undecided folders from the blacklist auto blackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok); - if( !ok ) { + if (!ok) { qCWarning(lcFolderStatus) << "Could not read selective sync list from db."; return; } - foreach (const auto& undecidedFolder, undecidedList) { + foreach (const auto &undecidedFolder, undecidedList) { blackList.removeAll(undecidedFolder); } folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, blackList); // Add all undecided folders to the white list auto whiteList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok); - if( !ok ) { + if (!ok) { qCWarning(lcFolderStatus) << "Could not read selective sync list from db."; return; } @@ -1151,7 +1180,9 @@ void FolderStatusModel::slotNewBigFolder() break; } } - if (folderIndex < 0) { return; } + if (folderIndex < 0) { + return; + } _folders[folderIndex].resetSubs(this, index(folderIndex)); @@ -1164,10 +1195,9 @@ void FolderStatusModel::slotShowFetchProgress() QMutableMapIterator it(_fetchingItems); while (it.hasNext()) { it.next(); - if (it.value().elapsed() > 800) - { + if (it.value().elapsed() > 800) { auto idx = it.key(); - auto* info = infoForIndex(idx); + auto *info = infoForIndex(idx); if (info && info->_fetching) { bool add = !info->hasLabel(); if (add) { @@ -1188,12 +1218,12 @@ bool FolderStatusModel::SubFolderInfo::hasLabel() const return _hasError || _fetchingLabel; } -void FolderStatusModel::SubFolderInfo::resetSubs(FolderStatusModel* model, QModelIndex index) +void FolderStatusModel::SubFolderInfo::resetSubs(FolderStatusModel *model, QModelIndex index) { _fetched = false; _fetching = false; if (hasLabel()) { - model->beginRemoveRows(index, 0 ,0); + model->beginRemoveRows(index, 0, 0); _fetchingLabel = false; _hasError = false; model->endRemoveRows(); diff --git a/src/gui/folderstatusmodel.h b/src/gui/folderstatusmodel.h index d7ad69cb2..02bb09618 100644 --- a/src/gui/folderstatusmodel.h +++ b/src/gui/folderstatusmodel.h @@ -37,25 +37,35 @@ class FolderStatusModel : public QAbstractItemModel { Q_OBJECT public: - FolderStatusModel(QObject * parent = 0); + FolderStatusModel(QObject *parent = 0); ~FolderStatusModel(); - void setAccountState(const AccountState* accountState); + void setAccountState(const AccountState *accountState); - Qt::ItemFlags flags( const QModelIndex& ) const Q_DECL_OVERRIDE; + Qt::ItemFlags flags(const QModelIndex &) const Q_DECL_OVERRIDE; QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) Q_DECL_OVERRIDE; - int columnCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE; - int rowCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE; - QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE; - QModelIndex parent(const QModelIndex& child) const Q_DECL_OVERRIDE; - bool canFetchMore(const QModelIndex& parent) const Q_DECL_OVERRIDE; - void fetchMore(const QModelIndex& parent) Q_DECL_OVERRIDE; - bool hasChildren(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE; - - struct SubFolderInfo { + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) Q_DECL_OVERRIDE; + int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + QModelIndex parent(const QModelIndex &child) const Q_DECL_OVERRIDE; + bool canFetchMore(const QModelIndex &parent) const Q_DECL_OVERRIDE; + void fetchMore(const QModelIndex &parent) Q_DECL_OVERRIDE; + bool hasChildren(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + + struct SubFolderInfo + { SubFolderInfo() - : _folder(0), _size(0), _isExternal(false), _fetched(false), _fetching(false), - _hasError(false), _fetchingLabel(false), _isUndecided(false), _checked(Qt::Checked) {} + : _folder(0) + , _size(0) + , _isExternal(false) + , _fetched(false) + , _fetching(false) + , _hasError(false) + , _fetchingLabel(false) + , _isUndecided(false) + , _checked(Qt::Checked) + { + } Folder *_folder; QString _name; QString _path; @@ -79,12 +89,19 @@ public: bool hasLabel() const; // Reset all subfolders and fetch status - void resetSubs(FolderStatusModel* model, QModelIndex index); - - struct Progress { - Progress() : _warningCount(0), _overallPercent(0) {} + void resetSubs(FolderStatusModel *model, QModelIndex index); + + struct Progress + { + Progress() + : _warningCount(0) + , _overallPercent(0) + { + } bool isNull() const - { return _progressString.isEmpty() && _warningCount == 0 && _overallSyncString.isEmpty(); } + { + return _progressString.isEmpty() && _warningCount == 0 && _overallSyncString.isEmpty(); + } QString _progressString; QString _overallSyncString; int _warningCount; @@ -95,7 +112,10 @@ public: QVector _folders; - enum ItemType { RootFolder, SubFolder, AddButton, FetchLabel }; + enum ItemType { RootFolder, + SubFolder, + AddButton, + FetchLabel }; ItemType classify(const QModelIndex &index) const; SubFolderInfo *infoForIndex(const QModelIndex &index) const; @@ -118,9 +138,9 @@ public slots: private slots: void slotUpdateDirectories(const QStringList &); - void slotGatherPermissions(const QString &name, const QMap &properties); + void slotGatherPermissions(const QString &name, const QMap &properties); void slotLscolFinishedWithError(QNetworkReply *r); - void slotFolderSyncStateChange(Folder* f); + void slotFolderSyncStateChange(Folder *f); void slotFolderScheduleQueueChanged(); void slotNewBigFolder(); @@ -131,10 +151,10 @@ private slots: void slotShowFetchProgress(); private: - QStringList createBlackList(OCC::FolderStatusModel::SubFolderInfo* root, - const QStringList& oldBlackList) const; - const AccountState* _accountState; - bool _dirty; // If the selective sync checkboxes were changed + QStringList createBlackList(OCC::FolderStatusModel::SubFolderInfo *root, + const QStringList &oldBlackList) const; + const AccountState *_accountState; + bool _dirty; // If the selective sync checkboxes were changed /** * Keeps track of items that are fetching data from the server. @@ -146,7 +166,9 @@ private: #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) //the roles argument was added in Qt5 void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles = QVector()) - { emit QAbstractItemModel::dataChanged(topLeft,bottomRight); } + { + emit QAbstractItemModel::dataChanged(topLeft, bottomRight); + } #endif signals: diff --git a/src/gui/folderwatcher.cpp b/src/gui/folderwatcher.cpp index 8a9308aa6..0f5fee413 100644 --- a/src/gui/folderwatcher.cpp +++ b/src/gui/folderwatcher.cpp @@ -39,9 +39,9 @@ namespace OCC { Q_LOGGING_CATEGORY(lcFolderWatcher, "gui.folderwatcher", QtInfoMsg) -FolderWatcher::FolderWatcher(const QString &root, Folder* folder) - : QObject(folder), - _folder(folder) +FolderWatcher::FolderWatcher(const QString &root, Folder *folder) + : QObject(folder) + , _folder(folder) { _d.reset(new FolderWatcherPrivate(this, root)); @@ -49,12 +49,15 @@ FolderWatcher::FolderWatcher(const QString &root, Folder* folder) } FolderWatcher::~FolderWatcher() -{ } +{ +} -bool FolderWatcher::pathIsIgnored( const QString& path ) +bool FolderWatcher::pathIsIgnored(const QString &path) { - if( path.isEmpty() ) return true; - if( !_folder ) return false; + if (path.isEmpty()) + return true; + if (!_folder) + return false; #ifndef OWNCLOUD_TEST if (_folder->isFileExcludedAbsolute(path)) { @@ -65,13 +68,13 @@ bool FolderWatcher::pathIsIgnored( const QString& path ) return false; } -void FolderWatcher::changeDetected( const QString& path ) +void FolderWatcher::changeDetected(const QString &path) { QStringList paths(path); changeDetected(paths); } -void FolderWatcher::changeDetected( const QStringList& paths ) +void FolderWatcher::changeDetected(const QStringList &paths) { // TODO: this shortcut doesn't look very reliable: // - why is the timeout only 1 second? @@ -80,7 +83,7 @@ void FolderWatcher::changeDetected( const QStringList& paths ) // Check if the same path was reported within the last second. QSet pathsSet = paths.toSet(); - if( pathsSet == _lastPaths && _timer.elapsed() < 1000 ) { + if (pathsSet == _lastPaths && _timer.elapsed() < 1000) { // the same path was reported within the last second. Skip. return; } @@ -92,7 +95,7 @@ void FolderWatcher::changeDetected( const QStringList& paths ) // ------- handle ignores: for (int i = 0; i < paths.size(); ++i) { QString path = paths[i]; - if( pathIsIgnored(path) ) { + if (pathIsIgnored(path)) { continue; } @@ -108,16 +111,15 @@ void FolderWatcher::changeDetected( const QStringList& paths ) } } -void FolderWatcher::addPath(const QString &path ) +void FolderWatcher::addPath(const QString &path) { _d->addPath(path); } -void FolderWatcher::removePath(const QString &path ) +void FolderWatcher::removePath(const QString &path) { _d->removePath(path); } } // namespace OCC - diff --git a/src/gui/folderwatcher.h b/src/gui/folderwatcher.h index 3f1d1a981..334abf1b7 100644 --- a/src/gui/folderwatcher.h +++ b/src/gui/folderwatcher.h @@ -58,7 +58,7 @@ public: /** * @param root Path of the root of the folder */ - FolderWatcher(const QString &root, Folder* folder = 0L); + FolderWatcher(const QString &root, Folder *folder = 0L); virtual ~FolderWatcher(); /** @@ -66,11 +66,11 @@ public: * Those need to be notified when a directory is added or removed while the watcher is disabled. * This is a no-op for backends that are recursive */ - void addPath(const QString&); - void removePath(const QString&); + void addPath(const QString &); + void removePath(const QString &); /* Check if the path is ignored. */ - bool pathIsIgnored( const QString& path ); + bool pathIsIgnored(const QString &path); signals: /** Emitted when one of the watched directories or one @@ -78,12 +78,12 @@ signals: void pathChanged(const QString &path); /** Emitted if an error occurs */ - void error(const QString& error); + void error(const QString &error); protected slots: // called from the implementations to indicate a change in path - void changeDetected( const QString& path); - void changeDetected( const QStringList& paths); + void changeDetected(const QString &path); + void changeDetected(const QStringList &paths); protected: QHash _pendingPathes; @@ -92,11 +92,10 @@ private: QScopedPointer _d; QTime _timer; QSet _lastPaths; - Folder* _folder; + Folder *_folder; friend class FolderWatcherPrivate; }; - } #endif diff --git a/src/gui/folderwatcher_linux.cpp b/src/gui/folderwatcher_linux.cpp index 5a4d2b590..b505b8dd0 100644 --- a/src/gui/folderwatcher_linux.cpp +++ b/src/gui/folderwatcher_linux.cpp @@ -26,33 +26,31 @@ namespace OCC { -FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path) - : QObject(), - _parent(p), - _folder(path) +FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path) + : QObject() + , _parent(p) + , _folder(path) { _fd = inotify_init(); if (_fd != -1) { - _socket.reset( new QSocketNotifier(_fd, QSocketNotifier::Read) ); + _socket.reset(new QSocketNotifier(_fd, QSocketNotifier::Read)); connect(_socket.data(), SIGNAL(activated(int)), SLOT(slotReceivedNotification(int))); } else { qCWarning(lcFolderWatcher) << "notify_init() failed: " << strerror(errno); } QMetaObject::invokeMethod(this, "slotAddFolderRecursive", Q_ARG(QString, path)); - } FolderWatcherPrivate::~FolderWatcherPrivate() { - } // attention: result list passed by reference! -bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullList ) +bool FolderWatcherPrivate::findFoldersBelow(const QDir &dir, QStringList &fullList) { bool ok = true; - if( !(dir.exists() && dir.isReadable()) ) { + if (!(dir.exists() && dir.isReadable())) { qCDebug(lcFolderWatcher) << "Non existing path coming in: " << dir.absolutePath(); ok = false; } else { @@ -63,8 +61,8 @@ bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullL QStringList::const_iterator constIterator; for (constIterator = pathes.constBegin(); constIterator != pathes.constEnd(); - ++constIterator) { - const QString fullPath(dir.path()+QLatin1String("/")+(*constIterator)); + ++constIterator) { + const QString fullPath(dir.path() + QLatin1String("/") + (*constIterator)); fullList.append(fullPath); ok = findFoldersBelow(QDir(fullPath), fullList); } @@ -73,16 +71,14 @@ bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullL return ok; } -void FolderWatcherPrivate::inotifyRegisterPath(const QString& path) +void FolderWatcherPrivate::inotifyRegisterPath(const QString &path) { - if( !path.isEmpty()) { + if (!path.isEmpty()) { int wd = inotify_add_watch(_fd, path.toUtf8().constData(), - IN_CLOSE_WRITE | IN_ATTRIB | IN_MOVE | - IN_CREATE |IN_DELETE | IN_DELETE_SELF | - IN_MOVE_SELF |IN_UNMOUNT |IN_ONLYDIR); - if( wd > -1 ) { + IN_CLOSE_WRITE | IN_ATTRIB | IN_MOVE | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT | IN_ONLYDIR); + if (wd > -1) { _watches.insert(wd, path); - } + } } } @@ -97,16 +93,16 @@ void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path) const QStringList watchedFolders = _watches.values(); QStringList allSubfolders; - if( !findFoldersBelow(QDir(path), allSubfolders)) { + if (!findFoldersBelow(QDir(path), allSubfolders)) { qCWarning(lcFolderWatcher) << "Could not traverse all sub folders"; } QStringListIterator subfoldersIt(allSubfolders); while (subfoldersIt.hasNext()) { QString subfolder = subfoldersIt.next(); - QDir folder (subfolder); + QDir folder(subfolder); if (folder.exists() && !watchedFolders.contains(folder.absolutePath())) { subdirs++; - if( _parent->pathIsIgnored(subfolder) ) { + if (_parent->pathIsIgnored(subfolder)) { qCDebug(lcFolderWatcher) << "* Not adding" << folder.path(); continue; } @@ -116,7 +112,7 @@ void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path) } } - if (subdirs >0) { + if (subdirs > 0) { qCDebug(lcFolderWatcher) << " `-> and" << subdirs << "subdirectories"; } } @@ -124,15 +120,15 @@ void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path) void FolderWatcherPrivate::slotReceivedNotification(int fd) { int len; - struct inotify_event* event; + struct inotify_event *event; int i; int error; QVarLengthArray buffer(2048); do { - len = read(fd, buffer.data(), buffer.size()); - error = errno; - /** + len = read(fd, buffer.data(), buffer.size()); + error = errno; + /** * From inotify documentation: * * The behavior when the buffer given to read(2) is too @@ -141,21 +137,20 @@ void FolderWatcherPrivate::slotReceivedNotification(int fd) * read(2) returns 0; since kernel 2.6.21, read(2) fails with * the error EINVAL. */ - if (len < 0 && error == EINVAL) - { - // double the buffer size - buffer.resize(buffer.size() * 2); - /* and try again ... */ - continue; - } - } while (false); + if (len < 0 && error == EINVAL) { + // double the buffer size + buffer.resize(buffer.size() * 2); + /* and try again ... */ + continue; + } + } while (false); // reset counter i = 0; // while there are enough events in the buffer - while(i + sizeof(struct inotify_event) < static_cast(len)) { + while (i + sizeof(struct inotify_event) < static_cast(len)) { // cast an inotify_event - event = (struct inotify_event*)&buffer[i]; + event = (struct inotify_event *)&buffer[i]; if (event == NULL) { qCDebug(lcFolderWatcher) << "NULL event"; i += sizeof(struct inotify_event); @@ -165,9 +160,7 @@ void FolderWatcherPrivate::slotReceivedNotification(int fd) // Fire event for the path that was changed. if (event->len > 0 && event->wd > -1) { QByteArray fileName(event->name); - if (fileName.startsWith("._sync_") || - fileName.startsWith(".csync_journal.db") || - fileName.startsWith(".owncloudsync.log")) { + if (fileName.startsWith("._sync_") || fileName.startsWith(".csync_journal.db") || fileName.startsWith(".owncloudsync.log")) { } else { const QString p = _watches[event->wd] + '/' + fileName; _parent->changeDetected(p); @@ -177,28 +170,27 @@ void FolderWatcherPrivate::slotReceivedNotification(int fd) // increment counter i += sizeof(struct inotify_event) + event->len; } - } -void FolderWatcherPrivate::addPath(const QString& path) +void FolderWatcherPrivate::addPath(const QString &path) { slotAddFolderRecursive(path); } -void FolderWatcherPrivate::removePath(const QString& path) +void FolderWatcherPrivate::removePath(const QString &path) { int wid = -1; // Remove the inotify watch. QHash::const_iterator i = _watches.constBegin(); while (i != _watches.constEnd()) { - if( i.value() == path ) { + if (i.value() == path) { wid = i.key(); break; } ++i; } - if( wid > -1 ) { + if (wid > -1) { inotify_rm_watch(_fd, wid); _watches.remove(wid); } diff --git a/src/gui/folderwatcher_linux.h b/src/gui/folderwatcher_linux.h index 9c7ef2a98..24d337777 100644 --- a/src/gui/folderwatcher_linux.h +++ b/src/gui/folderwatcher_linux.h @@ -23,8 +23,7 @@ #include "folderwatcher.h" -namespace OCC -{ +namespace OCC { /** * @brief Linux (inotify) API implementation of FolderWatcher @@ -34,7 +33,7 @@ class FolderWatcherPrivate : public QObject { Q_OBJECT public: - FolderWatcherPrivate() { } + FolderWatcherPrivate() {} FolderWatcherPrivate(FolderWatcher *p, const QString &path); ~FolderWatcherPrivate(); @@ -46,18 +45,17 @@ protected slots: void slotAddFolderRecursive(const QString &path); protected: - bool findFoldersBelow( const QDir& dir, QStringList& fullList ); - void inotifyRegisterPath(const QString& path); + bool findFoldersBelow(const QDir &dir, QStringList &fullList); + void inotifyRegisterPath(const QString &path); private: FolderWatcher *_parent; QString _folder; - QHash _watches; + QHash _watches; QScopedPointer _socket; int _fd; }; - } #endif diff --git a/src/gui/folderwatcher_mac.cpp b/src/gui/folderwatcher_mac.cpp index d18ad8dba..a28277fea 100644 --- a/src/gui/folderwatcher_mac.cpp +++ b/src/gui/folderwatcher_mac.cpp @@ -22,12 +22,11 @@ #include - namespace OCC { -FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path) - : _parent(p), - _folder(path) +FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path) + : _parent(p) + , _folder(path) { this->startWatching(); } @@ -40,23 +39,22 @@ FolderWatcherPrivate::~FolderWatcherPrivate() } static void callback( - ConstFSEventStreamRef streamRef, - void *clientCallBackInfo, - size_t numEvents, - void *eventPathsVoid, - const FSEventStreamEventFlags eventFlags[], - const FSEventStreamEventId eventIds[]) + ConstFSEventStreamRef streamRef, + void *clientCallBackInfo, + size_t numEvents, + void *eventPathsVoid, + const FSEventStreamEventFlags eventFlags[], + const FSEventStreamEventId eventIds[]) { Q_UNUSED(streamRef) Q_UNUSED(eventFlags) Q_UNUSED(eventIds) - const FSEventStreamEventFlags c_interestingFlags - = kFSEventStreamEventFlagItemCreated // for new folder/file - | kFSEventStreamEventFlagItemRemoved // for rm - | kFSEventStreamEventFlagItemInodeMetaMod // for mtime change - | kFSEventStreamEventFlagItemRenamed // also coming for moves to trash in finder - | kFSEventStreamEventFlagItemModified; // for content change + const FSEventStreamEventFlags c_interestingFlags = kFSEventStreamEventFlagItemCreated // for new folder/file + | kFSEventStreamEventFlagItemRemoved // for rm + | kFSEventStreamEventFlagItemInodeMetaMod // for mtime change + | kFSEventStreamEventFlagItemRenamed // also coming for moves to trash in finder + | kFSEventStreamEventFlagItemModified; // for content change //We ignore other flags, e.g. for owner change, xattr change, Finder label change etc qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::callback by OS X"; @@ -80,39 +78,37 @@ static void callback( paths.append(fn); } - reinterpret_cast(clientCallBackInfo)->doNotifyParent(paths); + reinterpret_cast(clientCallBackInfo)->doNotifyParent(paths); } void FolderWatcherPrivate::startWatching() { qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::startWatching()" << _folder; CFStringRef folderCF = CFStringCreateWithCharacters(0, reinterpret_cast(_folder.unicode()), - _folder.length()); - CFArrayRef pathsToWatch = CFStringCreateArrayBySeparatingStrings (NULL, folderCF, CFSTR(":")); + _folder.length()); + CFArrayRef pathsToWatch = CFStringCreateArrayBySeparatingStrings(NULL, folderCF, CFSTR(":")); - FSEventStreamContext ctx = {0, this, NULL, NULL, NULL}; + FSEventStreamContext ctx = { 0, this, NULL, NULL, NULL }; // TODO: Add kFSEventStreamCreateFlagFileEvents ? _stream = FSEventStreamCreate(NULL, - &callback, - &ctx, - pathsToWatch, - kFSEventStreamEventIdSinceNow, - 0, // latency - kFSEventStreamCreateFlagUseCFTypes|kFSEventStreamCreateFlagFileEvents|kFSEventStreamCreateFlagIgnoreSelf - ); + &callback, + &ctx, + pathsToWatch, + kFSEventStreamEventIdSinceNow, + 0, // latency + kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagIgnoreSelf); CFRelease(pathsToWatch); FSEventStreamScheduleWithRunLoop(_stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); FSEventStreamStart(_stream); } -void FolderWatcherPrivate::doNotifyParent(const QStringList &paths) { - +void FolderWatcherPrivate::doNotifyParent(const QStringList &paths) +{ _parent->changeDetected(paths); } - } // ns mirall diff --git a/src/gui/folderwatcher_mac.h b/src/gui/folderwatcher_mac.h index 52c0a0a69..a25d89f6d 100644 --- a/src/gui/folderwatcher_mac.h +++ b/src/gui/folderwatcher_mac.h @@ -21,8 +21,7 @@ #include -namespace OCC -{ +namespace OCC { /** * @brief Mac OS X API implementation of FolderWatcher @@ -31,7 +30,6 @@ namespace OCC class FolderWatcherPrivate { public: - FolderWatcherPrivate(FolderWatcher *p, const QString &path); ~FolderWatcherPrivate(); @@ -48,7 +46,6 @@ private: FSEventStreamRef _stream; }; - } #endif diff --git a/src/gui/folderwatcher_win.cpp b/src/gui/folderwatcher_win.cpp index 4bf3a7a80..19c623f56 100644 --- a/src/gui/folderwatcher_win.cpp +++ b/src/gui/folderwatcher_win.cpp @@ -26,23 +26,21 @@ namespace OCC { void WatcherThread::watchChanges(size_t fileNotifyBufferSize, - bool* increaseBufferSize) + bool *increaseBufferSize) { *increaseBufferSize = false; QString longPath = FileSystem::longWinPath(_path); _directory = CreateFileW( - (wchar_t*) longPath.utf16(), + (wchar_t *)longPath.utf16(), FILE_LIST_DIRECTORY, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, - NULL - ); + NULL); - if (_directory == INVALID_HANDLE_VALUE) - { + if (_directory == INVALID_HANDLE_VALUE) { DWORD errorCode = GetLastError(); qCWarning(lcFolderWatcher) << "Failed to create handle for" << _path << ", error:" << errorCode; _directory = 0; @@ -53,7 +51,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, overlapped.hEvent = _resultEvent; // QVarLengthArray ensures the stack-buffer is aligned like double and qint64. - QVarLengthArray fileNotifyBuffer; + QVarLengthArray fileNotifyBuffer; fileNotifyBuffer.resize(fileNotifyBufferSize); const size_t fileNameBufferSize = 4096; @@ -64,18 +62,15 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, ResetEvent(_resultEvent); FILE_NOTIFY_INFORMATION *pFileNotifyBuffer = - (FILE_NOTIFY_INFORMATION*)fileNotifyBuffer.data(); + (FILE_NOTIFY_INFORMATION *)fileNotifyBuffer.data(); DWORD dwBytesReturned = 0; SecureZeroMemory(pFileNotifyBuffer, fileNotifyBufferSize); - if(! ReadDirectoryChangesW( _directory, (LPVOID)pFileNotifyBuffer, - fileNotifyBufferSize, true, - FILE_NOTIFY_CHANGE_FILE_NAME | - FILE_NOTIFY_CHANGE_DIR_NAME | - FILE_NOTIFY_CHANGE_LAST_WRITE, - &dwBytesReturned, - &overlapped, - NULL)) - { + if (!ReadDirectoryChangesW(_directory, (LPVOID)pFileNotifyBuffer, + fileNotifyBufferSize, true, + FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE, + &dwBytesReturned, + &overlapped, + NULL)) { DWORD errorCode = GetLastError(); if (errorCode == ERROR_NOTIFY_ENUM_DIR) { qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing"; @@ -87,11 +82,11 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, break; } - HANDLE handles[] = {_resultEvent, _stopEvent}; + HANDLE handles[] = { _resultEvent, _stopEvent }; DWORD result = WaitForMultipleObjects( - 2, handles, - false, // awake once one of them arrives - INFINITE); + 2, handles, + false, // awake once one of them arrives + INFINITE); if (result == 1) { qCDebug(lcFolderWatcher) << "Received stop event, aborting folder watcher thread"; break; @@ -102,7 +97,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, } bool ok = GetOverlappedResult(_directory, &overlapped, &dwBytesReturned, false); - if (! ok) { + if (!ok) { DWORD errorCode = GetLastError(); if (errorCode == ERROR_NOTIFY_ENUM_DIR) { qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing"; @@ -123,7 +118,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, // TODO: We could still try expanding the path in the tricky cases... QString longfile = file; if (curEntry->Action != FILE_ACTION_REMOVED - && curEntry->Action != FILE_ACTION_RENAMED_OLD_NAME) { + && curEntry->Action != FILE_ACTION_RENAMED_OLD_NAME) { size_t longNameSize = GetLongPathNameW(reinterpret_cast(file.utf16()), fileNameBuffer, fileNameBufferSize); if (longNameSize > 0) { longfile = QString::fromUtf16(reinterpret_cast(fileNameBuffer), longNameSize); @@ -137,7 +132,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, // and new files in a folder, probably because of the folder's mtime // changing. We don't need them. bool skip = curEntry->Action == FILE_ACTION_MODIFIED - && QFileInfo(longfile).isDir(); + && QFileInfo(longfile).isDir(); if (!skip) { emit changed(longfile); @@ -146,8 +141,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize, if (curEntry->NextEntryOffset == 0) { break; } - curEntry = (FILE_NOTIFY_INFORMATION*)( - (char*)curEntry + curEntry->NextEntryOffset); + curEntry = (FILE_NOTIFY_INFORMATION *)((char *)curEntry + curEntry->NextEntryOffset); } } @@ -170,15 +164,15 @@ void WatcherThread::run() // If this buffer fills up before we've extracted its data we will lose // change information. Therefore start big. - size_t bufferSize = 4096*10; - size_t maxBuffer = 64*1024; + size_t bufferSize = 4096 * 10; + size_t maxBuffer = 64 * 1024; while (!_done) { bool increaseBufferSize = false; watchChanges(bufferSize, &increaseBufferSize); if (increaseBufferSize) { - bufferSize = qMin(bufferSize*2, maxBuffer); + bufferSize = qMin(bufferSize * 2, maxBuffer); } else if (!_done) { // Other errors shouldn't actually happen, // so sleep a bit to avoid running into the same error case in a @@ -199,12 +193,12 @@ void WatcherThread::stop() SetEvent(_stopEvent); } -FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path) +FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path) : _parent(p) { _thread = new WatcherThread(path); - connect(_thread, SIGNAL(changed(const QString&)), - _parent,SLOT(changeDetected(const QString&))); + connect(_thread, SIGNAL(changed(const QString &)), + _parent, SLOT(changeDetected(const QString &))); _thread->start(); } diff --git a/src/gui/folderwatcher_win.h b/src/gui/folderwatcher_win.h index dd5af77fe..687ec891d 100644 --- a/src/gui/folderwatcher_win.h +++ b/src/gui/folderwatcher_win.h @@ -27,17 +27,19 @@ class FolderWatcher; * @brief The WatcherThread class * @ingroup gui */ -class WatcherThread : public QThread { +class WatcherThread : public QThread +{ Q_OBJECT public: - WatcherThread(const QString &path) : - QThread(), - _path(path), - _directory(0), - _resultEvent(0), - _stopEvent(0), - _done(false) - {} + WatcherThread(const QString &path) + : QThread() + , _path(path) + , _directory(0) + , _resultEvent(0) + , _stopEvent(0) + , _done(false) + { + } ~WatcherThread(); @@ -46,7 +48,7 @@ public: protected: void run(); void watchChanges(size_t fileNotifyBufferSize, - bool* increaseBufferSize); + bool *increaseBufferSize); void closeHandle(); signals: @@ -64,10 +66,11 @@ private: * @brief Windows implementation of FolderWatcher * @ingroup gui */ -class FolderWatcherPrivate : public QObject { +class FolderWatcherPrivate : public QObject +{ Q_OBJECT public: - FolderWatcherPrivate(FolderWatcher *p, const QString& path); + FolderWatcherPrivate(FolderWatcher *p, const QString &path); ~FolderWatcherPrivate(); void addPath(const QString &) {} @@ -77,7 +80,6 @@ private: FolderWatcher *_parent; WatcherThread *_thread; }; - } #endif // MIRALL_FOLDERWATCHER_WIN_H diff --git a/src/gui/folderwizard.cpp b/src/gui/folderwizard.cpp index 199977efa..940cf8b3a 100644 --- a/src/gui/folderwizard.cpp +++ b/src/gui/folderwizard.cpp @@ -37,8 +37,7 @@ #include -namespace OCC -{ +namespace OCC { QString FormatWarningsWizardPage::formatWarnings(const QStringList &warnings) const { @@ -47,7 +46,7 @@ QString FormatWarningsWizardPage::formatWarnings(const QStringList &warnings) co ret = tr("Warning: %1").arg(warnings.first()); } else if (warnings.count() > 1) { ret = tr("Warning:") + "
    "; - Q_FOREACH(QString warning, warnings) { + Q_FOREACH (QString warning, warnings) { ret += QString::fromLatin1("
  • %1
  • ").arg(warning); } ret += "
"; @@ -56,9 +55,9 @@ QString FormatWarningsWizardPage::formatWarnings(const QStringList &warnings) co return ret; } -FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr& account) - : FormatWarningsWizardPage(), - _account(account) +FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr &account) + : FormatWarningsWizardPage() + , _account(account) { _ui.setupUi(this); registerField(QLatin1String("sourceFolder*"), _ui.localFolderLineEdit); @@ -67,7 +66,7 @@ FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr& account) QString defaultPath = QDir::homePath() + QLatin1Char('/') + Theme::instance()->appName(); defaultPath = FolderMan::instance()->findGoodPathForNewSyncFolder(defaultPath, account->url()); - _ui.localFolderLineEdit->setText( QDir::toNativeSeparators( defaultPath ) ); + _ui.localFolderLineEdit->setText(QDir::toNativeSeparators(defaultPath)); _ui.localFolderLineEdit->setToolTip(tr("Enter the path to the local folder.")); _ui.warnLabel->setTextFormat(Qt::RichText); @@ -76,45 +75,43 @@ FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr& account) FolderWizardLocalPath::~FolderWizardLocalPath() { - } void FolderWizardLocalPath::initializePage() { - _ui.warnLabel->hide(); + _ui.warnLabel->hide(); } void FolderWizardLocalPath::cleanupPage() { - _ui.warnLabel->hide(); + _ui.warnLabel->hide(); } bool FolderWizardLocalPath::isComplete() const { QUrl serverUrl = _account->url(); - serverUrl.setUserName( _account->credentials()->user() ); + serverUrl.setUserName(_account->credentials()->user()); QString errorStr = FolderMan::instance()->checkPathValidityForNewFolder( QDir::fromNativeSeparators(_ui.localFolderLineEdit->text()), serverUrl); - bool isOk = errorStr.isEmpty(); QStringList warnStrings; if (!isOk) { warnStrings << errorStr; } - _ui.warnLabel->setWordWrap(true); - if( isOk ) { - _ui.warnLabel->hide(); - _ui.warnLabel->setText( QString::null ); - } else { - _ui.warnLabel->show(); - QString warnings = formatWarnings(warnStrings); - _ui.warnLabel->setText( warnings ); - } - return isOk; + _ui.warnLabel->setWordWrap(true); + if (isOk) { + _ui.warnLabel->hide(); + _ui.warnLabel->setText(QString::null); + } else { + _ui.warnLabel->show(); + QString warnings = formatWarnings(warnStrings); + _ui.warnLabel->setText(warnings); + } + return isOk; } void FolderWizardLocalPath::slotChooseLocalFolder() @@ -125,13 +122,14 @@ void FolderWizardLocalPath::slotChooseLocalFolder() // open the first entry of the home dir. Otherwise the dir picker comes // up with the closed home dir icon, stupid Qt default... QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks, - QDir::DirsFirst|QDir::Name); + QDir::DirsFirst | QDir::Name); - if(dirs.count() > 0) sf += "/"+dirs.at(0); // Take the first dir in home dir. + if (dirs.count() > 0) + sf += "/" + dirs.at(0); // Take the first dir in home dir. QString dir = QFileDialog::getExistingDirectory(this, - tr("Select the source folder"), - sf); + tr("Select the source folder"), + sf); if (!dir.isEmpty()) { // set the last directory component name as alias _ui.localFolderLineEdit->setText(QDir::toNativeSeparators(dir)); @@ -140,10 +138,10 @@ void FolderWizardLocalPath::slotChooseLocalFolder() } // ================================================================================= -FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr& account) +FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr &account) : FormatWarningsWizardPage() - ,_warnWasVisible(false) - ,_account(account) + , _warnWasVisible(false) + , _account(account) { _ui.setupUi(this); @@ -154,8 +152,8 @@ FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr& account) connect(_ui.addFolderButton, SIGNAL(clicked()), SLOT(slotAddRemoteFolder())); connect(_ui.refreshButton, SIGNAL(clicked()), SLOT(slotRefreshFolders())); - connect(_ui.folderTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(slotItemExpanded(QTreeWidgetItem*))); - connect(_ui.folderTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(slotCurrentItemChanged(QTreeWidgetItem*))); + connect(_ui.folderTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem *)), SLOT(slotItemExpanded(QTreeWidgetItem *))); + connect(_ui.folderTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), SLOT(slotCurrentItemChanged(QTreeWidgetItem *))); connect(_ui.folderEntry, SIGNAL(textEdited(QString)), SLOT(slotFolderEntryEdited(QString))); _lscolTimer.setInterval(500); @@ -163,7 +161,7 @@ FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr& account) connect(&_lscolTimer, SIGNAL(timeout()), SLOT(slotLsColFolderEntry())); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - _ui.folderTreeWidget->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents); + _ui.folderTreeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); // Make sure that there will be a scrollbar when the contents is too wide _ui.folderTreeWidget->header()->setStretchLastSection(false); #endif @@ -182,14 +180,15 @@ void FolderWizardRemotePath::slotAddRemoteFolder() dlg->setWindowTitle(tr("Create Remote Folder")); dlg->setLabelText(tr("Enter the name of the new folder to be created below '%1':") - .arg(parent)); + .arg(parent)); dlg->open(this, SLOT(slotCreateRemoteFolder(QString))); dlg->setAttribute(Qt::WA_DeleteOnClose); } void FolderWizardRemotePath::slotCreateRemoteFolder(const QString &folder) { - if( folder.isEmpty() ) return; + if (folder.isEmpty()) + return; QTreeWidgetItem *current = _ui.folderTreeWidget->currentItem(); QString fullPath; @@ -201,8 +200,8 @@ void FolderWizardRemotePath::slotCreateRemoteFolder(const QString &folder) MkColJob *job = new MkColJob(_account, fullPath, this); /* check the owncloud configuration file and query the ownCloud */ connect(job, SIGNAL(finished(QNetworkReply::NetworkError)), - SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError))); - connect(job, SIGNAL(networkError(QNetworkReply*)), SLOT(slotHandleMkdirNetworkError(QNetworkReply*))); + SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError))); + connect(job, SIGNAL(networkError(QNetworkReply *)), SLOT(slotHandleMkdirNetworkError(QNetworkReply *))); job->start(); } @@ -220,22 +219,22 @@ void FolderWizardRemotePath::slotCreateRemoteFolderFinished(QNetworkReply::Netwo void FolderWizardRemotePath::slotHandleMkdirNetworkError(QNetworkReply *reply) { qCWarning(lcWizard) << "webdav mkdir request failed:" << reply->error(); - if( !_account->credentials()->stillValid(reply) ) { + if (!_account->credentials()->stillValid(reply)) { showWarn(tr("Authentication failed accessing %1").arg(Theme::instance()->appNameGUI())); } else { showWarn(tr("Failed to create the folder on %1. Please check manually.") - .arg(Theme::instance()->appNameGUI())); + .arg(Theme::instance()->appNameGUI())); } } -void FolderWizardRemotePath::slotHandleLsColNetworkError(QNetworkReply */*reply*/) +void FolderWizardRemotePath::slotHandleLsColNetworkError(QNetworkReply * /*reply*/) { auto job = qobject_cast(sender()); showWarn(tr("Failed to list a folder. Error: %1") - .arg(job->errorStringParsingBody())); + .arg(job->errorStringParsingBody())); } -static QTreeWidgetItem* findFirstChild(QTreeWidgetItem *parent, const QString& text) +static QTreeWidgetItem *findFirstChild(QTreeWidgetItem *parent, const QString &text) { for (int i = 0; i < parent->childCount(); ++i) { QTreeWidgetItem *child = parent->child(i); @@ -287,7 +286,7 @@ bool FolderWizardRemotePath::selectByPath(QString path) QTreeWidgetItem *it = _ui.folderTreeWidget->topLevelItem(0); if (!path.isEmpty()) { const QStringList pathTrail = path.split(QLatin1Char('/')); - foreach (const QString& path, pathTrail) { + foreach (const QString &path, pathTrail) { if (!it) { return false; } @@ -320,7 +319,8 @@ void FolderWizardRemotePath::slotUpdateDirectories(const QStringList &list) foreach (QString path, sortedList) { path.remove(webdavFolder); QStringList paths = path.split('/'); - if (paths.last().isEmpty()) paths.removeLast(); + if (paths.last().isEmpty()) + paths.removeLast(); recursiveInsert(root, paths, path); } root->setExpanded(true); @@ -352,7 +352,7 @@ void FolderWizardRemotePath::slotCurrentItemChanged(QTreeWidgetItem *item) emit completeChanged(); } -void FolderWizardRemotePath::slotFolderEntryEdited(const QString& text) +void FolderWizardRemotePath::slotFolderEntryEdited(const QString &text) { if (selectByPath(text)) { _lscolTimer.stop(); @@ -373,19 +373,19 @@ void FolderWizardRemotePath::slotLsColFolderEntry() // No error handling, no updating, we do this manually // because of extra logic in the typed-path case. disconnect(job, 0, this, 0); - connect(job, SIGNAL(finishedWithError(QNetworkReply*)), - SLOT(slotTypedPathError(QNetworkReply*))); + connect(job, SIGNAL(finishedWithError(QNetworkReply *)), + SLOT(slotTypedPathError(QNetworkReply *))); connect(job, SIGNAL(directoryListingSubfolders(QStringList)), - SLOT(slotTypedPathFound(QStringList))); + SLOT(slotTypedPathFound(QStringList))); } -void FolderWizardRemotePath::slotTypedPathFound(const QStringList& subpaths) +void FolderWizardRemotePath::slotTypedPathFound(const QStringList &subpaths) { slotUpdateDirectories(subpaths); selectByPath(_ui.folderEntry->text()); } -void FolderWizardRemotePath::slotTypedPathError(QNetworkReply* reply) +void FolderWizardRemotePath::slotTypedPathError(QNetworkReply *reply) { // Ignore 404s, otherwise users will get annoyed by error popups // when not typing fast enough. It's still clear that a given path @@ -400,14 +400,14 @@ void FolderWizardRemotePath::slotTypedPathError(QNetworkReply* reply) slotHandleLsColNetworkError(reply); } -LsColJob* FolderWizardRemotePath::runLsColJob(const QString& path) +LsColJob *FolderWizardRemotePath::runLsColJob(const QString &path) { LsColJob *job = new LsColJob(_account, path, this); job->setProperties(QList() << "resourcetype"); connect(job, SIGNAL(directoryListingSubfolders(QStringList)), - SLOT(slotUpdateDirectories(QStringList))); - connect(job, SIGNAL(finishedWithError(QNetworkReply*)), - SLOT(slotHandleLsColNetworkError(QNetworkReply*))); + SLOT(slotUpdateDirectories(QStringList))); + connect(job, SIGNAL(finishedWithError(QNetworkReply *)), + SLOT(slotHandleLsColNetworkError(QNetworkReply *))); job->start(); return job; @@ -431,8 +431,8 @@ bool FolderWizardRemotePath::isComplete() const Folder::Map map = FolderMan::instance()->map(); Folder::Map::const_iterator i = map.constBegin(); - for(i = map.constBegin();i != map.constEnd(); i++ ) { - Folder *f = static_cast(i.value()); + for (i = map.constBegin(); i != map.constEnd(); i++) { + Folder *f = static_cast(i.value()); if (f->accountState()->account() != _account) { continue; } @@ -443,8 +443,7 @@ bool FolderWizardRemotePath::isComplete() const if (QDir::cleanPath(dir) == QDir::cleanPath(curDir)) { warnStrings.append(tr("This folder is already being synced.")); } else if (dir.startsWith(curDir + QLatin1Char('/'))) { - warnStrings.append(tr("You are already syncing %1, which is a parent folder of %2.").arg( - Utility::escape(curDir), Utility::escape(dir))); + warnStrings.append(tr("You are already syncing %1, which is a parent folder of %2.").arg(Utility::escape(curDir), Utility::escape(dir))); } if (curDir == QLatin1String("/")) { @@ -469,20 +468,20 @@ void FolderWizardRemotePath::initializePage() slotRefreshFolders(); } -void FolderWizardRemotePath::showWarn( const QString& msg ) const +void FolderWizardRemotePath::showWarn(const QString &msg) const { - if( msg.isEmpty() ) { - _ui.warnFrame->hide(); + if (msg.isEmpty()) { + _ui.warnFrame->hide(); - } else { - _ui.warnFrame->show(); - _ui.warnLabel->setText( msg ); - } + } else { + _ui.warnFrame->show(); + _ui.warnLabel->setText(msg); + } } // ==================================================================================== -FolderWizardSelectiveSync::FolderWizardSelectiveSync(const AccountPtr& account) +FolderWizardSelectiveSync::FolderWizardSelectiveSync(const AccountPtr &account) { QVBoxLayout *layout = new QVBoxLayout(this); _selectiveSync = new SelectiveSyncWidget(account, this); @@ -496,11 +495,11 @@ FolderWizardSelectiveSync::~FolderWizardSelectiveSync() void FolderWizardSelectiveSync::initializePage() { - QString targetPath = wizard()->property("targetPath").toString(); + QString targetPath = wizard()->property("targetPath").toString(); if (targetPath.startsWith('/')) { targetPath = targetPath.mid(1); } - QString alias = QFileInfo(targetPath).fileName(); + QString alias = QFileInfo(targetPath).fileName(); if (alias.isEmpty()) alias = Theme::instance()->appName(); QStringList initialBlacklist; @@ -519,8 +518,8 @@ bool FolderWizardSelectiveSync::validatePage() void FolderWizardSelectiveSync::cleanupPage() { - QString targetPath = wizard()->property("targetPath").toString(); - QString alias = QFileInfo(targetPath).fileName(); + QString targetPath = wizard()->property("targetPath").toString(); + QString alias = QFileInfo(targetPath).fileName(); if (alias.isEmpty()) alias = Theme::instance()->appName(); _selectiveSync->setFolderInfo(targetPath, alias); @@ -528,8 +527,6 @@ void FolderWizardSelectiveSync::cleanupPage() } - - // ==================================================================================== @@ -538,20 +535,20 @@ void FolderWizardSelectiveSync::cleanupPage() */ FolderWizard::FolderWizard(AccountPtr account, QWidget *parent) - : QWizard(parent), - _folderWizardSourcePage(new FolderWizardLocalPath(account)), - _folderWizardTargetPage(0), - _folderWizardSelectiveSyncPage(new FolderWizardSelectiveSync(account)) + : QWizard(parent) + , _folderWizardSourcePage(new FolderWizardLocalPath(account)) + , _folderWizardTargetPage(0) + , _folderWizardSelectiveSyncPage(new FolderWizardSelectiveSync(account)) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - setPage(Page_Source, _folderWizardSourcePage ); + setPage(Page_Source, _folderWizardSourcePage); if (!Theme::instance()->singleSyncFolder()) { _folderWizardTargetPage = new FolderWizardRemotePath(account); - setPage(Page_Target, _folderWizardTargetPage ); + setPage(Page_Target, _folderWizardTargetPage); } setPage(Page_SelectiveSync, _folderWizardSelectiveSyncPage); - setWindowTitle( tr("Add Folder Sync Connection") ); + setWindowTitle(tr("Add Folder Sync Connection")); setOptions(QWizard::CancelButtonOnLeft); setButtonText(QWizard::FinishButton, tr("Add Sync Connection")); } @@ -562,4 +559,3 @@ FolderWizard::~FolderWizard() } // end namespace - diff --git a/src/gui/folderwizard.h b/src/gui/folderwizard.h index f598b1475..e24cb5ac9 100644 --- a/src/gui/folderwizard.h +++ b/src/gui/folderwizard.h @@ -35,7 +35,8 @@ class ownCloudInfo; * @brief The FormatWarningsWizardPage class * @ingroup gui */ -class FormatWarningsWizardPage : public QWizardPage { +class FormatWarningsWizardPage : public QWizardPage +{ Q_OBJECT protected: QString formatWarnings(const QStringList &warnings) const; @@ -49,14 +50,14 @@ class FolderWizardLocalPath : public FormatWarningsWizardPage { Q_OBJECT public: - explicit FolderWizardLocalPath(const AccountPtr& account); + explicit FolderWizardLocalPath(const AccountPtr &account); ~FolderWizardLocalPath(); virtual bool isComplete() const Q_DECL_OVERRIDE; void initializePage() Q_DECL_OVERRIDE; void cleanupPage() Q_DECL_OVERRIDE; - void setFolderMap( const Folder::Map &fm ) { _folderMap = fm; } + void setFolderMap(const Folder::Map &fm) { _folderMap = fm; } protected slots: void slotChooseLocalFolder(); @@ -76,7 +77,7 @@ class FolderWizardRemotePath : public FormatWarningsWizardPage { Q_OBJECT public: - explicit FolderWizardRemotePath(const AccountPtr& account); + explicit FolderWizardRemotePath(const AccountPtr &account); ~FolderWizardRemotePath(); virtual bool isComplete() const Q_DECL_OVERRIDE; @@ -86,22 +87,23 @@ public: protected slots: - void showWarn( const QString& = QString() ) const; + void showWarn(const QString & = QString()) const; void slotAddRemoteFolder(); - void slotCreateRemoteFolder(const QString&); + void slotCreateRemoteFolder(const QString &); void slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error); - void slotHandleMkdirNetworkError(QNetworkReply*); - void slotHandleLsColNetworkError(QNetworkReply*); - void slotUpdateDirectories(const QStringList&); + void slotHandleMkdirNetworkError(QNetworkReply *); + void slotHandleLsColNetworkError(QNetworkReply *); + void slotUpdateDirectories(const QStringList &); void slotRefreshFolders(); - void slotItemExpanded(QTreeWidgetItem*); - void slotCurrentItemChanged(QTreeWidgetItem*); - void slotFolderEntryEdited(const QString& text); + void slotItemExpanded(QTreeWidgetItem *); + void slotCurrentItemChanged(QTreeWidgetItem *); + void slotFolderEntryEdited(const QString &text); void slotLsColFolderEntry(); - void slotTypedPathFound(const QStringList& subpaths); - void slotTypedPathError(QNetworkReply* reply); + void slotTypedPathFound(const QStringList &subpaths); + void slotTypedPathError(QNetworkReply *reply); + private: - LsColJob* runLsColJob(const QString& path); + LsColJob *runLsColJob(const QString &path); void recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path); bool selectByPath(QString path); Ui_FolderWizardTargetPage _ui; @@ -118,7 +120,7 @@ class FolderWizardSelectiveSync : public QWizardPage { Q_OBJECT public: - explicit FolderWizardSelectiveSync(const AccountPtr& account); + explicit FolderWizardSelectiveSync(const AccountPtr &account); ~FolderWizardSelectiveSync(); virtual bool validatePage() Q_DECL_OVERRIDE; @@ -128,7 +130,6 @@ public: private: SelectiveSyncWidget *_selectiveSync; - }; /** @@ -139,7 +140,6 @@ class FolderWizard : public QWizard { Q_OBJECT public: - enum { Page_Source, Page_Target, @@ -150,7 +150,6 @@ public: ~FolderWizard(); private: - FolderWizardLocalPath *_folderWizardSourcePage; FolderWizardRemotePath *_folderWizardTargetPage; FolderWizardSelectiveSync *_folderWizardSelectiveSyncPage; diff --git a/src/gui/generalsettings.cpp b/src/gui/generalsettings.cpp index 9f285f9bf..853fd730b 100644 --- a/src/gui/generalsettings.cpp +++ b/src/gui/generalsettings.cpp @@ -36,15 +36,15 @@ namespace OCC { -GeneralSettings::GeneralSettings(QWidget *parent) : - QWidget(parent), - _ui(new Ui::GeneralSettings), - _currentlyLoading(false) +GeneralSettings::GeneralSettings(QWidget *parent) + : QWidget(parent) + , _ui(new Ui::GeneralSettings) + , _currentlyLoading(false) { _ui->setupUi(this); connect(_ui->desktopNotificationsCheckBox, SIGNAL(toggled(bool)), - SLOT(slotToggleOptionalDesktopNotifications(bool))); + SLOT(slotToggleOptionalDesktopNotifications(bool))); _ui->autostartCheckBox->setChecked(Utility::hasLaunchOnStartup(Theme::instance()->appName())); connect(_ui->autostartCheckBox, SIGNAL(toggled(bool)), SLOT(slotToggleLaunchOnStartup(bool))); @@ -78,8 +78,8 @@ GeneralSettings::GeneralSettings(QWidget *parent) : * align properly vertically , fixes bug #3758 */ int m0, m1, m2, m3; - _ui->horizontalLayout_3->getContentsMargins( &m0, &m1, &m2, &m3 ); - _ui->horizontalLayout_3->setContentsMargins(0, m1, m2, m3 ); + _ui->horizontalLayout_3->getContentsMargins(&m0, &m1, &m2, &m3); + _ui->horizontalLayout_3->setContentsMargins(0, m1, m2, m3); // OEM themes are not obliged to ship mono icons, so there // is no point in offering an option @@ -88,7 +88,7 @@ GeneralSettings::GeneralSettings(QWidget *parent) : connect(_ui->ignoredFilesButton, SIGNAL(clicked()), SLOT(slotIgnoreFilesEditor())); // accountAdded means the wizard was finished and the wizard might change some options. - connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)), this, SLOT(loadMiscSettings())); + connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)), this, SLOT(loadMiscSettings())); } GeneralSettings::~GeneralSettings() @@ -97,13 +97,14 @@ GeneralSettings::~GeneralSettings() delete _syncLogDialog; } -QSize GeneralSettings::sizeHint() const { +QSize GeneralSettings::sizeHint() const +{ return QSize(ownCloudGui::settingsDialogSize().width(), QWidget::sizeHint().height()); } void GeneralSettings::loadMiscSettings() { -#if QT_VERSION < QT_VERSION_CHECK( 5, 4, 0 ) +#if QT_VERSION < QT_VERSION_CHECK(5, 4, 0) QScopedValueRollback scope(_currentlyLoading); _currentlyLoading = true; #else @@ -123,7 +124,7 @@ void GeneralSettings::loadMiscSettings() void GeneralSettings::slotUpdateInfo() { // Note: the sparkle-updater is not an OCUpdater - OCUpdater *updater = qobject_cast(Updater::instance()); + OCUpdater *updater = qobject_cast(Updater::instance()); if (ConfigFile().skipUpdateCheck()) { updater = 0; // don't show update info if updates are disabled } @@ -151,7 +152,7 @@ void GeneralSettings::saveMiscSettings() cfgFile.setCrashReporter(_ui->crashreporterCheckBox->isChecked()); cfgFile.setNewBigFolderSizeLimit(_ui->newFolderLimitCheckBox->isChecked(), - _ui->newFolderLimitSpinBox->value()); + _ui->newFolderLimitSpinBox->value()); cfgFile.setConfirmExternalStorage(_ui->newExternalStorage->isChecked()); } @@ -171,7 +172,7 @@ void GeneralSettings::slotIgnoreFilesEditor() { if (_ignoreEditor.isNull()) { _ignoreEditor = new IgnoreListEditor(this); - _ignoreEditor->setAttribute( Qt::WA_DeleteOnClose, true ); + _ignoreEditor->setAttribute(Qt::WA_DeleteOnClose, true); _ignoreEditor->open(); } else { ownCloudGui::raiseDialog(_ignoreEditor); diff --git a/src/gui/generalsettings.h b/src/gui/generalsettings.h index 8652a7dbb..360e65167 100644 --- a/src/gui/generalsettings.h +++ b/src/gui/generalsettings.h @@ -23,7 +23,7 @@ class IgnoreListEditor; class SyncLogDialog; namespace Ui { -class GeneralSettings; + class GeneralSettings; } /** @@ -48,7 +48,6 @@ private slots: void loadMiscSettings(); private: - Ui::GeneralSettings *_ui; QPointer _ignoreEditor; QPointer _syncLogDialog; diff --git a/src/gui/ignorelisteditor.cpp b/src/gui/ignorelisteditor.cpp index d21cd0d87..83fd39ffd 100644 --- a/src/gui/ignorelisteditor.cpp +++ b/src/gui/ignorelisteditor.cpp @@ -31,9 +31,9 @@ namespace OCC { static int patternCol = 0; static int deletableCol = 1; -IgnoreListEditor::IgnoreListEditor(QWidget *parent) : - QDialog(parent), - ui(new Ui::IgnoreListEditor) +IgnoreListEditor::IgnoreListEditor(QWidget *parent) + : QDialog(parent) + , ui(new Ui::IgnoreListEditor) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); @@ -46,7 +46,7 @@ IgnoreListEditor::IgnoreListEditor(QWidget *parent) : ConfigFile cfgFile; readOnlyTooltip = tr("This entry is provided by the system at '%1' " "and cannot be modified in this view.") - .arg(QDir::toNativeSeparators(cfgFile.excludeFile(ConfigFile::SystemScope))); + .arg(QDir::toNativeSeparators(cfgFile.excludeFile(ConfigFile::SystemScope))); readIgnoreFile(cfgFile.excludeFile(ConfigFile::SystemScope), true); readIgnoreFile(cfgFile.excludeFile(ConfigFile::UserScope), false); @@ -61,7 +61,7 @@ IgnoreListEditor::IgnoreListEditor(QWidget *parent) : ui->tableWidget->horizontalHeader()->setResizeMode(patternCol, QHeaderView::Stretch); ui->tableWidget->verticalHeader()->setVisible(false); - ui->syncHiddenFilesCheckBox->setChecked( !FolderMan::instance()->ignoreHiddenFiles() ); + ui->syncHiddenFilesCheckBox->setChecked(!FolderMan::instance()->ignoreHiddenFiles()); } IgnoreListEditor::~IgnoreListEditor() @@ -71,7 +71,7 @@ IgnoreListEditor::~IgnoreListEditor() bool IgnoreListEditor::ignoreHiddenFiles() { - return ! ui->syncHiddenFilesCheckBox->isChecked(); + return !ui->syncHiddenFilesCheckBox->isChecked(); } void IgnoreListEditor::slotItemSelectionChanged() @@ -97,7 +97,7 @@ void IgnoreListEditor::slotUpdateLocalIgnoreList() QString ignoreFile = cfgFile.excludeFile(ConfigFile::UserScope); QFile ignores(ignoreFile); if (ignores.open(QIODevice::WriteOnly)) { - for(int row = 0; row < ui->tableWidget->rowCount(); ++row) { + for (int row = 0; row < ui->tableWidget->rowCount(); ++row) { QTableWidgetItem *patternItem = ui->tableWidget->item(row, patternCol); QTableWidgetItem *deletableItem = ui->tableWidget->item(row, deletableCol); if (patternItem->flags() & Qt::ItemIsEnabled) { @@ -105,16 +105,16 @@ void IgnoreListEditor::slotUpdateLocalIgnoreList() if (deletableItem->checkState() == Qt::Checked) { prepend = "]"; } - ignores.write(prepend+patternItem->text().toUtf8()+'\n'); + ignores.write(prepend + patternItem->text().toUtf8() + '\n'); } } } else { QMessageBox::warning(this, tr("Could not open file"), - tr("Cannot write changes to '%1'.").arg(ignoreFile)); + tr("Cannot write changes to '%1'.").arg(ignoreFile)); } ignores.close(); //close the file before reloading stuff. - FolderMan * folderMan = FolderMan::instance(); + FolderMan *folderMan = FolderMan::instance(); /* handle the hidden file checkbox */ @@ -126,7 +126,7 @@ void IgnoreListEditor::slotUpdateLocalIgnoreList() // We need to force a remote discovery after a change of the ignore list. // Otherwise we would not download the files/directories that are no longer // ignored (because the remote etag did not change) (issue #3172) - foreach (Folder* folder, folderMan->map()) { + foreach (Folder *folder, folderMan->map()) { folder->journalDb()->forceRemoteDiscoveryNextSync(); folderMan->scheduleFolder(folder); } @@ -138,8 +138,8 @@ void IgnoreListEditor::slotAddPattern() { bool okClicked; QString pattern = QInputDialog::getText(this, tr("Add Ignore Pattern"), - tr("Add a new ignore pattern:"), - QLineEdit::Normal, QString(), &okClicked); + tr("Add a new ignore pattern:"), + QLineEdit::Normal, QString(), &okClicked); if (!okClicked || pattern.isEmpty()) return; diff --git a/src/gui/ignorelisteditor.h b/src/gui/ignorelisteditor.h index b6fcf0df6..0018e2361 100644 --- a/src/gui/ignorelisteditor.h +++ b/src/gui/ignorelisteditor.h @@ -22,7 +22,7 @@ class QListWidgetItem; namespace OCC { namespace Ui { -class IgnoreListEditor; + class IgnoreListEditor; } /** @@ -46,8 +46,8 @@ private slots: void slotAddPattern(); private: - void readIgnoreFile(const QString& file, bool readOnly); - int addPattern(const QString& pattern, bool deletable, bool readOnly); + void readIgnoreFile(const QString &file, bool readOnly); + int addPattern(const QString &pattern, bool deletable, bool readOnly); QString readOnlyTooltip; Ui::IgnoreListEditor *ui; }; diff --git a/src/gui/lockwatcher.cpp b/src/gui/lockwatcher.cpp index 832edc900..da83744a9 100644 --- a/src/gui/lockwatcher.cpp +++ b/src/gui/lockwatcher.cpp @@ -24,15 +24,15 @@ Q_LOGGING_CATEGORY(lcLockWatcher, "gui.lockwatcher", QtInfoMsg) static const int check_frequency = 20 * 1000; // ms -LockWatcher::LockWatcher(QObject* parent) +LockWatcher::LockWatcher(QObject *parent) : QObject(parent) { connect(&_timer, SIGNAL(timeout()), - SLOT(checkFiles())); + SLOT(checkFiles())); _timer.start(check_frequency); } -void LockWatcher::addFile(const QString& path) +void LockWatcher::addFile(const QString &path) { qCInfo(lcLockWatcher) << "Watching for lock of" << path << "being released"; _watchedPaths.insert(path); @@ -42,7 +42,7 @@ void LockWatcher::checkFiles() { QSet unlocked; - foreach (const QString& path, _watchedPaths) { + foreach (const QString &path, _watchedPaths) { if (!FileSystem::isFileLocked(path)) { qCInfo(lcLockWatcher) << "Lock of" << path << "was released"; emit fileUnlocked(path); diff --git a/src/gui/lockwatcher.h b/src/gui/lockwatcher.h index 981594071..ba2d8f8a7 100644 --- a/src/gui/lockwatcher.h +++ b/src/gui/lockwatcher.h @@ -42,19 +42,19 @@ class LockWatcher : public QObject { Q_OBJECT public: - explicit LockWatcher(QObject* parent = 0); + explicit LockWatcher(QObject *parent = 0); /** Start watching a file. * * If the file is not locked later on, the fileUnlocked signal will be * emitted once. */ - void addFile(const QString& path); + void addFile(const QString &path); signals: /** Emitted when one of the watched files is no longer * being locked. */ - void fileUnlocked(const QString& path); + void fileUnlocked(const QString &path); private slots: void checkFiles(); @@ -63,5 +63,4 @@ private: QSet _watchedPaths; QTimer _timer; }; - } diff --git a/src/gui/logbrowser.cpp b/src/gui/logbrowser.cpp index b4971bf45..41b526a3c 100644 --- a/src/gui/logbrowser.cpp +++ b/src/gui/logbrowser.cpp @@ -38,20 +38,20 @@ namespace OCC { // ============================================================================== LogWidget::LogWidget(QWidget *parent) - :QPlainTextEdit(parent) + : QPlainTextEdit(parent) { - setReadOnly( true ); + setReadOnly(true); QFont font; font.setFamily(QLatin1String("Courier New")); font.setFixedPitch(true); - document()->setDefaultFont( font ); + document()->setDefaultFont(font); } // ============================================================================== -LogBrowser::LogBrowser(QWidget *parent) : - QDialog(parent), - _logWidget( new LogWidget(parent) ) +LogBrowser::LogBrowser(QWidget *parent) + : QDialog(parent) + , _logWidget(new LogWidget(parent)) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setObjectName("LogBrowser"); // for save/restoreGeometry() @@ -61,62 +61,62 @@ LogBrowser::LogBrowser(QWidget *parent) : QVBoxLayout *mainLayout = new QVBoxLayout; // mainLayout->setMargin(0); - mainLayout->addWidget( _logWidget ); + mainLayout->addWidget(_logWidget); QHBoxLayout *toolLayout = new QHBoxLayout; - mainLayout->addLayout( toolLayout ); + mainLayout->addLayout(toolLayout); // Search input field QLabel *lab = new QLabel(tr("&Search:") + " "); _findTermEdit = new QLineEdit; - lab->setBuddy( _findTermEdit ); + lab->setBuddy(_findTermEdit); toolLayout->addWidget(lab); - toolLayout->addWidget( _findTermEdit ); + toolLayout->addWidget(_findTermEdit); // find button QPushButton *findBtn = new QPushButton; - findBtn->setText( tr("&Find") ); - connect( findBtn, SIGNAL(clicked()), this, SLOT(slotFind())); - toolLayout->addWidget( findBtn ); + findBtn->setText(tr("&Find")); + connect(findBtn, SIGNAL(clicked()), this, SLOT(slotFind())); + toolLayout->addWidget(findBtn); // stretch toolLayout->addStretch(1); _statusLabel = new QLabel; - toolLayout->addWidget( _statusLabel ); + toolLayout->addWidget(_statusLabel); toolLayout->addStretch(5); // Debug logging _logDebugCheckBox = new QCheckBox(tr("&Capture debug messages") + " "); connect(_logDebugCheckBox, SIGNAL(stateChanged(int)), SLOT(slotDebugCheckStateChanged(int))); - toolLayout->addWidget( _logDebugCheckBox ); + toolLayout->addWidget(_logDebugCheckBox); QDialogButtonBox *btnbox = new QDialogButtonBox; - QPushButton *closeBtn = btnbox->addButton( QDialogButtonBox::Close ); - connect(closeBtn,SIGNAL(clicked()),this,SLOT(close())); + QPushButton *closeBtn = btnbox->addButton(QDialogButtonBox::Close); + connect(closeBtn, SIGNAL(clicked()), this, SLOT(close())); - mainLayout->addWidget( btnbox ); + mainLayout->addWidget(btnbox); // clear button _clearBtn = new QPushButton; - _clearBtn->setText( tr("Clear") ); - _clearBtn->setToolTip( tr("Clear the log display.") ); + _clearBtn->setText(tr("Clear")); + _clearBtn->setToolTip(tr("Clear the log display.")); btnbox->addButton(_clearBtn, QDialogButtonBox::ActionRole); - connect( _clearBtn, SIGNAL(clicked()), this, SLOT(slotClearLog())); + connect(_clearBtn, SIGNAL(clicked()), this, SLOT(slotClearLog())); // save Button _saveBtn = new QPushButton; - _saveBtn->setText( tr("S&ave") ); + _saveBtn->setText(tr("S&ave")); _saveBtn->setToolTip(tr("Save the log file to a file on disk for debugging.")); btnbox->addButton(_saveBtn, QDialogButtonBox::ActionRole); - connect( _saveBtn, SIGNAL(clicked()),this, SLOT(slotSave())); + connect(_saveBtn, SIGNAL(clicked()), this, SLOT(slotSave())); - setLayout( mainLayout ); + setLayout(mainLayout); setModal(false); Logger::instance()->setLogWindowActivated(true); // Direct connection for log coming from this thread, and queued for the one in a different thread - connect(Logger::instance(), SIGNAL(logWindowLog(QString)),this,SLOT(slotNewLog(QString)), Qt::AutoConnection); + connect(Logger::instance(), SIGNAL(logWindowLog(QString)), this, SLOT(slotNewLog(QString)), Qt::AutoConnection); QAction *showLogWindow = new QAction(this); showLogWindow->setShortcut(QKeySequence("F12")); @@ -126,8 +126,7 @@ LogBrowser::LogBrowser(QWidget *parent) : ConfigFile cfg; cfg.restoreGeometry(this); int lines = cfg.maxLogLines(); - _logWidget->document()->setMaximumBlockCount( lines ); - + _logWidget->document()->setMaximumBlockCount(lines); } LogBrowser::~LogBrowser() @@ -147,10 +146,10 @@ void LogBrowser::closeEvent(QCloseEvent *) } -void LogBrowser::slotNewLog( const QString& msg ) +void LogBrowser::slotNewLog(const QString &msg) { - if( _logWidget->isVisible() ) { - _logWidget->appendPlainText( msg ); + if (_logWidget->isVisible()) { + _logWidget->appendPlainText(msg); } } @@ -159,9 +158,10 @@ void LogBrowser::slotFind() { QString searchText = _findTermEdit->text(); - if( searchText.isEmpty() ) return; + if (searchText.isEmpty()) + return; - search( searchText ); + search(searchText); } void LogBrowser::slotDebugCheckStateChanged(int checkState) @@ -169,7 +169,7 @@ void LogBrowser::slotDebugCheckStateChanged(int checkState) Logger::instance()->setLogDebug(checkState == Qt::Checked); } -void LogBrowser::search( const QString& str ) +void LogBrowser::search(const QString &str) { QList extraSelections; @@ -177,8 +177,7 @@ void LogBrowser::search( const QString& str ) QColor color = QColor(Qt::gray).lighter(130); _statusLabel->clear(); - while(_logWidget->find(str)) - { + while (_logWidget->find(str)) { QTextEdit::ExtraSelection extra; extra.format.setBackground(color); @@ -196,9 +195,9 @@ void LogBrowser::slotSave() { _saveBtn->setEnabled(false); - QString saveFile = QFileDialog::getSaveFileName( this, tr("Save log file"), QDir::homePath() ); + QString saveFile = QFileDialog::getSaveFileName(this, tr("Save log file"), QDir::homePath()); - if( ! saveFile.isEmpty() ) { + if (!saveFile.isEmpty()) { QFile file(saveFile); if (file.open(QIODevice::WriteOnly)) { @@ -210,7 +209,6 @@ void LogBrowser::slotSave() } } _saveBtn->setEnabled(true); - } void LogBrowser::slotClearLog() diff --git a/src/gui/logbrowser.h b/src/gui/logbrowser.h index 940e7a927..a1c5c6da0 100644 --- a/src/gui/logbrowser.h +++ b/src/gui/logbrowser.h @@ -33,14 +33,13 @@ namespace OCC { * @brief The LogWidget class * @ingroup gui */ -class LogWidget : public QPlainTextEdit +class LogWidget : public QPlainTextEdit { Q_OBJECT public: explicit LogWidget(QWidget *parent = 0); signals: - }; /** @@ -49,22 +48,22 @@ signals: */ class LogBrowser : public QDialog { - Q_OBJECT + Q_OBJECT public: explicit LogBrowser(QWidget *parent = 0); ~LogBrowser(); - void setLogFile(const QString& , bool ); + void setLogFile(const QString &, bool); protected: void showEvent(QShowEvent *) Q_DECL_OVERRIDE; void closeEvent(QCloseEvent *) Q_DECL_OVERRIDE; protected slots: - void slotNewLog( const QString &msg ); + void slotNewLog(const QString &msg); void slotFind(); void slotDebugCheckStateChanged(int); - void search( const QString& ); + void search(const QString &); void slotSave(); void slotClearLog(); @@ -74,8 +73,7 @@ private: QCheckBox *_logDebugCheckBox; QPushButton *_saveBtn; QPushButton *_clearBtn; - QLabel *_statusLabel; - + QLabel *_statusLabel; }; } // namespace diff --git a/src/gui/main.cpp b/src/gui/main.cpp index f846f6ae3..8f77b50bc 100644 --- a/src/gui/main.cpp +++ b/src/gui/main.cpp @@ -36,11 +36,11 @@ using namespace OCC; void warnSystray() { QMessageBox::critical(0, qApp->translate("main.cpp", "System Tray not available"), - qApp->translate("main.cpp", "%1 requires on a working system tray. " - "If you are running XFCE, please follow " - "these instructions. " - "Otherwise, please install a system tray application such as 'trayer' and try again.") - .arg(Theme::instance()->appNameGUI())); + qApp->translate("main.cpp", "%1 requires on a working system tray. " + "If you are running XFCE, please follow " + "these instructions. " + "Otherwise, please install a system tray application such as 'trayer' and try again.") + .arg(Theme::instance()->appNameGUI())); } int main(int argc, char **argv) @@ -48,14 +48,14 @@ int main(int argc, char **argv) Q_INIT_RESOURCE(client); #ifdef Q_OS_WIN - // If the font size ratio is set on Windows, we need to - // enable the auto pixelRatio in Qt since we don't - // want to use sizes relative to the font size everywhere. - // This is automatic on OS X, but opt-in on Windows and Linux - // https://doc-snapshots.qt.io/qt5-5.6/highdpi.html#qt-support - // We do not define it on linux so the behaviour is kept the same - // as other Qt apps in the desktop environment. (which may or may - // not set this envoronment variable) +// If the font size ratio is set on Windows, we need to +// enable the auto pixelRatio in Qt since we don't +// want to use sizes relative to the font size everywhere. +// This is automatic on OS X, but opt-in on Windows and Linux +// https://doc-snapshots.qt.io/qt5-5.6/highdpi.html#qt-support +// We do not define it on linux so the behaviour is kept the same +// as other Qt apps in the desktop environment. (which may or may +// not set this envoronment variable) #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "1"); #else @@ -81,18 +81,18 @@ int main(int argc, char **argv) #ifndef Q_OS_WIN signal(SIGPIPE, SIG_IGN); #endif - if( app.giveHelp() ) { + if (app.giveHelp()) { app.showHelp(); return 0; } - if( app.versionOnly() ) { + if (app.versionOnly()) { app.showVersion(); return 0; } - // check a environment variable for core dumps +// check a environment variable for core dumps #ifdef Q_OS_UNIX - if( !qgetenv("OWNCLOUD_CORE_DUMP").isEmpty() ) { + if (!qgetenv("OWNCLOUD_CORE_DUMP").isEmpty()) { struct rlimit core_limit; core_limit.rlim_cur = RLIM_INFINITY; core_limit.rlim_max = RLIM_INFINITY; @@ -108,12 +108,12 @@ int main(int argc, char **argv) // needs to terminate here, e.g. because // the updater is triggered Updater *updater = Updater::instance(); - if ( updater && updater->handleStartup()) { + if (updater && updater->handleStartup()) { return true; } // if the application is already running, notify it. - if(app.isRunning()) { + if (app.isRunning()) { qCInfo(lcApplication) << "Already running, exiting..."; if (app.isSessionRestored()) { // This call is mirrored with the one in Application::slotParseMessage @@ -124,18 +124,18 @@ int main(int argc, char **argv) QStringList args = app.arguments(); if (args.size() > 1) { QString msg = args.join(QLatin1String("|")); - if(!app.sendMessage(QLatin1String("MSG_PARSEOPTIONS:") + msg)) + if (!app.sendMessage(QLatin1String("MSG_PARSEOPTIONS:") + msg)) return -1; } - if(!app.sendMessage(QLatin1String("MSG_SHOWSETTINGS"))) { + if (!app.sendMessage(QLatin1String("MSG_SHOWSETTINGS"))) { return -1; } return 0; } #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0) if (qgetenv("QT_QPA_PLATFORMTHEME") != "appmenu-qt5") - // We can't call isSystemTrayAvailable with appmenu-qt5 begause it hides the systemtray - // (issue #4693) +// We can't call isSystemTrayAvailable with appmenu-qt5 begause it hides the systemtray +// (issue #4693) #endif { if (!QSystemTrayIcon::isSystemTrayAvailable()) { @@ -153,7 +153,8 @@ int main(int argc, char **argv) if (!QSystemTrayIcon::isSystemTrayAvailable()) { Utility::sleep(1); attempts++; - if (attempts < 30) continue; + if (attempts < 30) + continue; } else { break; } @@ -168,4 +169,3 @@ int main(int argc, char **argv) return app.exec(); } - diff --git a/src/gui/networksettings.cpp b/src/gui/networksettings.cpp index 88f38259a..ff99524e1 100644 --- a/src/gui/networksettings.cpp +++ b/src/gui/networksettings.cpp @@ -26,9 +26,9 @@ namespace OCC { -NetworkSettings::NetworkSettings(QWidget *parent) : - QWidget(parent), - _ui(new Ui::NetworkSettings) +NetworkSettings::NetworkSettings(QWidget *parent) + : QWidget(parent) + , _ui(new Ui::NetworkSettings) { _ui->setupUi(this); @@ -47,12 +47,12 @@ NetworkSettings::NetworkSettings(QWidget *parent) : _ui->passwordLineEdit->setEnabled(true); _ui->authWidgets->setEnabled(_ui->authRequiredcheckBox->isChecked()); connect(_ui->authRequiredcheckBox, SIGNAL(toggled(bool)), - _ui->authWidgets, SLOT(setEnabled(bool))); + _ui->authWidgets, SLOT(setEnabled(bool))); connect(_ui->manualProxyRadioButton, SIGNAL(toggled(bool)), - _ui->manualSettings, SLOT(setEnabled(bool))); + _ui->manualSettings, SLOT(setEnabled(bool))); connect(_ui->manualProxyRadioButton, SIGNAL(toggled(bool)), - _ui->typeComboBox, SLOT(setEnabled(bool))); + _ui->typeComboBox, SLOT(setEnabled(bool))); loadProxySettings(); loadBWLimitSettings(); @@ -81,7 +81,8 @@ NetworkSettings::~NetworkSettings() delete _ui; } -QSize NetworkSettings::sizeHint() const { +QSize NetworkSettings::sizeHint() const +{ return QSize(ownCloudGui::settingsDialogSize().width(), QWidget::sizeHint().height()); } @@ -125,7 +126,7 @@ void NetworkSettings::loadBWLimitSettings() { ConfigFile cfgFile; -#if QT_VERSION < QT_VERSION_CHECK(5,3,3) +#if QT_VERSION < QT_VERSION_CHECK(5, 3, 3) // QNAM bandwidth limiting only works with versions of Qt greater or equal to 5.3.3 // (It needs Qt commits 097b641 and b99fa32) @@ -147,9 +148,9 @@ void NetworkSettings::loadBWLimitSettings() #endif int useDownloadLimit = cfgFile.useDownloadLimit(); - if ( useDownloadLimit >= 1 ) { + if (useDownloadLimit >= 1) { _ui->downloadLimitRadioButton->setChecked(true); - } else if (useDownloadLimit == 0){ + } else if (useDownloadLimit == 0) { _ui->noDownloadLimitRadioButton->setChecked(true); } else { _ui->autoDownloadLimitRadioButton->setChecked(true); @@ -157,9 +158,9 @@ void NetworkSettings::loadBWLimitSettings() _ui->downloadSpinBox->setValue(cfgFile.downloadLimit()); int useUploadLimit = cfgFile.useUploadLimit(); - if ( useUploadLimit >= 1 ) { + if (useUploadLimit >= 1) { _ui->uploadLimitRadioButton->setChecked(true); - } else if (useUploadLimit == 0){ + } else if (useUploadLimit == 0) { _ui->noUploadLimitRadioButton->setChecked(true); } else { _ui->autoUploadLimitRadioButton->setChecked(true); @@ -171,9 +172,9 @@ void NetworkSettings::saveProxySettings() { ConfigFile cfgFile; - if (_ui->noProxyRadioButton->isChecked()){ + if (_ui->noProxyRadioButton->isChecked()) { cfgFile.setProxyType(QNetworkProxy::NoProxy); - } else if (_ui->systemProxyRadioButton->isChecked()){ + } else if (_ui->systemProxyRadioButton->isChecked()) { cfgFile.setProxyType(QNetworkProxy::DefaultProxy); } else if (_ui->manualProxyRadioButton->isChecked()) { int type = _ui->typeComboBox->itemData(_ui->typeComboBox->currentIndex()).toInt(); @@ -181,7 +182,7 @@ void NetworkSettings::saveProxySettings() QString user = _ui->userLineEdit->text(); QString pass = _ui->passwordLineEdit->text(); cfgFile.setProxyType(type, _ui->hostLineEdit->text(), - _ui->portSpinBox->value(), needsAuth, user, pass); + _ui->portSpinBox->value(), needsAuth, user, pass); } ClientProxy proxy; diff --git a/src/gui/networksettings.h b/src/gui/networksettings.h index a64eaff29..34419a261 100644 --- a/src/gui/networksettings.h +++ b/src/gui/networksettings.h @@ -21,7 +21,7 @@ namespace OCC { namespace Ui { -class NetworkSettings; + class NetworkSettings; } /** diff --git a/src/gui/notificationconfirmjob.cpp b/src/gui/notificationconfirmjob.cpp index 537f763c7..871ce6449 100644 --- a/src/gui/notificationconfirmjob.cpp +++ b/src/gui/notificationconfirmjob.cpp @@ -23,19 +23,19 @@ namespace OCC { Q_DECLARE_LOGGING_CATEGORY(lcNotifications) NotificationConfirmJob::NotificationConfirmJob(AccountPtr account) -: AbstractNetworkJob(account, ""), - _widget(0) + : AbstractNetworkJob(account, "") + , _widget(0) { setIgnoreCredentialFailure(true); } -void NotificationConfirmJob::setLinkAndVerb(const QUrl& link, const QByteArray &verb) +void NotificationConfirmJob::setLinkAndVerb(const QUrl &link, const QByteArray &verb) { _link = link; _verb = verb; } -void NotificationConfirmJob::setWidget( NotificationWidget *widget ) +void NotificationConfirmJob::setWidget(NotificationWidget *widget) { _widget = widget; } @@ -47,7 +47,7 @@ NotificationWidget *NotificationConfirmJob::widget() void NotificationConfirmJob::start() { - if( !_link.isValid() ) { + if (!_link.isValid()) { qCWarning(lcNotifications) << "Attempt to trigger invalid URL: " << _link.toString(); return; } @@ -66,17 +66,15 @@ bool NotificationConfirmJob::finished() // FIXME: check for the reply code! const QString replyStr = reply()->readAll(); - if( replyStr.contains( "") ) { - QRegExp rex("(\\d+)"); - if( replyStr.contains(rex) ) { - // this is a error message coming back from ocs. - replyCode = rex.cap(1).toInt(); - } + if (replyStr.contains("")) { + QRegExp rex("(\\d+)"); + if (replyStr.contains(rex)) { + // this is a error message coming back from ocs. + replyCode = rex.cap(1).toInt(); + } } emit jobFinished(replyStr, replyCode); return true; - } - } diff --git a/src/gui/notificationconfirmjob.h b/src/gui/notificationconfirmjob.h index a65e458d1..4602dcf67 100644 --- a/src/gui/notificationconfirmjob.h +++ b/src/gui/notificationconfirmjob.h @@ -35,11 +35,11 @@ class NotificationWidget; * All the communication logic is handled in this class. * */ -class NotificationConfirmJob : public AbstractNetworkJob { +class NotificationConfirmJob : public AbstractNetworkJob +{ Q_OBJECT public: - explicit NotificationConfirmJob(AccountPtr account); /** @@ -47,7 +47,7 @@ public: * * @param verb currently supported GET PUT POST DELETE */ - void setLinkAndVerb(const QUrl& link, const QByteArray &verb); + void setLinkAndVerb(const QUrl &link, const QByteArray &verb); /** * @brief Start the OCS request @@ -59,7 +59,7 @@ public: * it when the job has finished * @param widget pointer to the notification widget to store */ - void setWidget( NotificationWidget *widget ); + void setWidget(NotificationWidget *widget); /** * @brief widget - get the associated notification widget as stored @@ -85,7 +85,6 @@ private: QUrl _link; NotificationWidget *_widget; }; - } #endif // NotificationConfirmJob_H diff --git a/src/gui/notificationwidget.cpp b/src/gui/notificationwidget.cpp index 6d6cfa952..7d1132c6a 100644 --- a/src/gui/notificationwidget.cpp +++ b/src/gui/notificationwidget.cpp @@ -25,14 +25,15 @@ namespace OCC { Q_LOGGING_CATEGORY(lcNotifications, "gui.notifications", QtInfoMsg) -NotificationWidget::NotificationWidget(QWidget *parent) : QWidget(parent) +NotificationWidget::NotificationWidget(QWidget *parent) + : QWidget(parent) { _ui.setupUi(this); _progressIndi = new QProgressIndicator(this); _ui.horizontalLayout->addWidget(_progressIndi); } -void NotificationWidget::setActivity(const Activity& activity) +void NotificationWidget::setActivity(const Activity &activity) { _myActivity = activity; @@ -40,8 +41,8 @@ void NotificationWidget::setActivity(const Activity& activity) ASSERT(!_accountName.isEmpty()); // _ui._headerLabel->setText( ); - _ui._subjectLabel->setVisible( !activity._subject.isEmpty() ); - _ui._messageLabel->setVisible( !activity._message.isEmpty() ); + _ui._subjectLabel->setVisible(!activity._subject.isEmpty()); + _ui._messageLabel->setVisible(!activity._message.isEmpty()); _ui._subjectLabel->setText(activity._subject); _ui._messageLabel->setText(activity._message); @@ -55,20 +56,20 @@ void NotificationWidget::setActivity(const Activity& activity) _ui._timeLabel->setText(tText); // always remove the buttons - foreach( auto button, _ui._buttonBox->buttons() ) { + foreach (auto button, _ui._buttonBox->buttons()) { _ui._buttonBox->removeButton(button); } _buttons.clear(); // display buttons for the links - if( activity._links.isEmpty() ) { + if (activity._links.isEmpty()) { // in case there is no action defined, do a close button. - QPushButton *b = _ui._buttonBox->addButton( QDialogButtonBox::Close ); + QPushButton *b = _ui._buttonBox->addButton(QDialogButtonBox::Close); b->setDefault(true); connect(b, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); _buttons.append(b); } else { - foreach( auto link, activity._links ) { + foreach (auto link, activity._links) { QPushButton *b = _ui._buttonBox->addButton(link._label, QDialogButtonBox::AcceptRole); b->setDefault(link._isPrimary); connect(b, SIGNAL(clicked()), this, SLOT(slotButtonClicked())); @@ -86,18 +87,18 @@ void NotificationWidget::slotButtonClicked() { QObject *buttonWidget = QObject::sender(); int index = -1; - if( buttonWidget ) { + if (buttonWidget) { // find the button that was clicked, it has to be in the list // of buttons that were added to the button box before. - for( int i = 0; i < _buttons.count(); i++ ) { - if( _buttons.at(i) == buttonWidget ) { + for (int i = 0; i < _buttons.count(); i++) { + if (_buttons.at(i) == buttonWidget) { index = i; } _buttons.at(i)->setEnabled(false); } // if the button was found, the link must be called - if( index > -1 && _myActivity._links.count() == 0 ) { + if (index > -1 && _myActivity._links.count() == 0) { // no links, that means it was the close button // empty link. Just close and remove the widget. QString doneText = tr("Closing in a few seconds..."); @@ -106,14 +107,14 @@ void NotificationWidget::slotButtonClicked() return; } - if( index > -1 && index < _myActivity._links.count() ) { + if (index > -1 && index < _myActivity._links.count()) { ActivityLink triggeredLink = _myActivity._links.at(index); _actionLabel = triggeredLink._label; - if( ! triggeredLink._link.isEmpty() ) { - qCInfo(lcNotifications) << "Notification Link: "<< triggeredLink._verb << triggeredLink._link; + if (!triggeredLink._link.isEmpty()) { + qCInfo(lcNotifications) << "Notification Link: " << triggeredLink._verb << triggeredLink._link; _progressIndi->startAnimation(); - emit sendNotificationRequest( _accountName, triggeredLink._link, triggeredLink._verb ); + emit sendNotificationRequest(_accountName, triggeredLink._link, triggeredLink._verb); } } } @@ -128,9 +129,9 @@ void NotificationWidget::slotNotificationRequestFinished(int statusCode) QString timeStr = locale.toString(QTime::currentTime()); // the ocs API returns stat code 100 if it succeeded. - if( statusCode != OCS_SUCCESS_STATUS_CODE ) { + if (statusCode != OCS_SUCCESS_STATUS_CODE) { qCWarning(lcNotifications) << "Notification Request to Server failed, leave button visible."; - for( i = 0; i < _buttons.count(); i++ ) { + for (i = 0; i < _buttons.count(); i++) { _buttons.at(i)->setEnabled(true); } //: The second parameter is a time, such as 'failed at 09:58pm' @@ -142,10 +143,8 @@ void NotificationWidget::slotNotificationRequestFinished(int statusCode) //: The second parameter is a time, such as 'selected at 09:58pm' doneText = tr("'%1' selected at %2").arg(_actionLabel, timeStr); } - _ui._timeLabel->setText( doneText ); + _ui._timeLabel->setText(doneText); _progressIndi->stopAnimation(); - } - } diff --git a/src/gui/notificationwidget.h b/src/gui/notificationwidget.h index 06265494d..ce0e95f2b 100644 --- a/src/gui/notificationwidget.h +++ b/src/gui/notificationwidget.h @@ -37,25 +37,24 @@ public: Activity activity() const; signals: - void sendNotificationRequest( const QString&, const QString& link, const QByteArray& verb); - void requestCleanupAndBlacklist( const Activity& activity ); + void sendNotificationRequest(const QString &, const QString &link, const QByteArray &verb); + void requestCleanupAndBlacklist(const Activity &activity); public slots: - void setActivity(const Activity& activity); - void slotNotificationRequestFinished(int statusCode); + void setActivity(const Activity &activity); + void slotNotificationRequestFinished(int statusCode); private slots: - void slotButtonClicked(); + void slotButtonClicked(); private: Ui_NotificationWidget _ui; Activity _myActivity; - QList _buttons; + QList _buttons; QString _accountName; QProgressIndicator *_progressIndi; QString _actionLabel; }; - } #endif // NOTIFICATIONWIDGET_H diff --git a/src/gui/ocsjob.cpp b/src/gui/ocsjob.cpp index 3ce974169..cc1e0d9fa 100644 --- a/src/gui/ocsjob.cpp +++ b/src/gui/ocsjob.cpp @@ -25,7 +25,7 @@ namespace OCC { Q_LOGGING_CATEGORY(lcOcs, "gui.sharing.ocs", QtInfoMsg) OcsJob::OcsJob(AccountPtr account) -: AbstractNetworkJob(account, "") + : AbstractNetworkJob(account, "") { _passStatusCodes.append(OCS_SUCCESS_STATUS_CODE); setIgnoreCredentialFailure(true); @@ -53,10 +53,10 @@ void OcsJob::appendPath(const QString &id) static QList> percentEncodeQueryItems( - const QList> & items) + const QList> &items) { QList> result; - foreach (const auto& item, items) { + foreach (const auto &item, items) { result.append(qMakePair( QUrl::toPercentEncoding(item.first), QUrl::toPercentEncoding(item.second))); @@ -80,7 +80,7 @@ void OcsJob::start() } else if (_verb == "POST" || _verb == "PUT") { // Url encode the _postParams and put them in a buffer. QByteArray postData; - Q_FOREACH(auto tmp, _params) { + Q_FOREACH (auto tmp, _params) { if (!postData.isEmpty()) { postData.append("&"); } @@ -107,22 +107,22 @@ bool OcsJob::finished() QJsonParseError error; auto json = QJsonDocument::fromJson(replyData, &error); if (error.error != QJsonParseError::NoError) { - qCWarning(lcOcs) << "Could not parse reply to" - << _verb - << Utility::concatUrlPath(account()->url(), path()) - << _params - << error.errorString() - << ":" << replyData; + qCWarning(lcOcs) << "Could not parse reply to" + << _verb + << Utility::concatUrlPath(account()->url(), path()) + << _params + << error.errorString() + << ":" << replyData; } QString message; const int statusCode = getJsonReturnCode(json, message); if (!_passStatusCodes.contains(statusCode)) { qCWarning(lcOcs) << "Reply to" - << _verb - << Utility::concatUrlPath(account()->url(), path()) - << _params - << "has unexpected status code:" << statusCode << replyData; + << _verb + << Utility::concatUrlPath(account()->url(), path()) + << _params + << "has unexpected status code:" << statusCode << replyData; emit ocsError(statusCode, message); } else { emit jobFinished(json); @@ -139,5 +139,4 @@ int OcsJob::getJsonReturnCode(const QJsonDocument &json, QString &message) return code; } - } diff --git a/src/gui/ocsjob.h b/src/gui/ocsjob.h index 9a02201e5..4560b3a36 100644 --- a/src/gui/ocsjob.h +++ b/src/gui/ocsjob.h @@ -38,11 +38,11 @@ namespace OCC { * * All OCS jobs (e.g. sharing) should extend this class. */ -class OcsJob : public AbstractNetworkJob { +class OcsJob : public AbstractNetworkJob +{ Q_OBJECT protected: - explicit OcsJob(AccountPtr account); /** @@ -50,7 +50,7 @@ protected: * * @param verb currently supported PUT POST DELETE */ - void setVerb(const QByteArray& verb); + void setVerb(const QByteArray &verb); /** * Add a new parameter to the request. @@ -59,7 +59,7 @@ protected: * @param name The name of the parameter * @param value The value of the parameter */ - void addParam(const QString& name, const QString &value); + void addParam(const QString &name, const QString &value); /** * Set the post parameters @@ -67,7 +67,7 @@ protected: * @param postParams list of pairs to add (urlEncoded) to the body of the * request */ - void setPostParams(const QList >& postParams); + void setPostParams(const QList> &postParams); /** * List of expected statuscodes for this request @@ -127,10 +127,9 @@ private slots: private: QByteArray _verb; - QList > _params; + QList> _params; QVector _passStatusCodes; }; - } #endif // OCSJOB_H diff --git a/src/gui/ocsshareejob.cpp b/src/gui/ocsshareejob.cpp index 652859dd9..b359201c0 100644 --- a/src/gui/ocsshareejob.cpp +++ b/src/gui/ocsshareejob.cpp @@ -17,17 +17,16 @@ namespace OCC { OcsShareeJob::OcsShareeJob(AccountPtr account) -: OcsJob(account) + : OcsJob(account) { setPath("ocs/v1.php/apps/files_sharing/api/v1/sharees"); connect(this, SIGNAL(jobFinished(QJsonDocument)), SLOT(jobDone(QJsonDocument))); - } void OcsShareeJob::getSharees(const QString &search, - const QString &itemType, - int page, - int perPage) + const QString &itemType, + int page, + int perPage) { setVerb("GET"); @@ -43,5 +42,4 @@ void OcsShareeJob::jobDone(const QJsonDocument &reply) { emit shareeJobFinished(reply); } - } diff --git a/src/gui/ocsshareejob.h b/src/gui/ocsshareejob.h index c38016768..f511f5fb8 100644 --- a/src/gui/ocsshareejob.h +++ b/src/gui/ocsshareejob.h @@ -27,10 +27,10 @@ namespace OCC { * * Fetching sharees from the OCS Sharee API */ -class OcsShareeJob : public OcsJob { +class OcsShareeJob : public OcsJob +{ Q_OBJECT public: - explicit OcsShareeJob(AccountPtr account); /** @@ -38,7 +38,7 @@ public: * * @param path Path to request shares for (default all shares) */ - void getSharees(const QString& search, const QString& itemType, int page = 1, int perPage = 50); + void getSharees(const QString &search, const QString &itemType, int page = 1, int perPage = 50); signals: /** * Result of the OCS request @@ -49,9 +49,7 @@ signals: private slots: void jobDone(const QJsonDocument &reply); - }; - } #endif // OCSSHAREEJOB_H diff --git a/src/gui/ocssharejob.cpp b/src/gui/ocssharejob.cpp index b73cc72a1..9b93ee99f 100644 --- a/src/gui/ocssharejob.cpp +++ b/src/gui/ocssharejob.cpp @@ -22,7 +22,7 @@ namespace OCC { OcsShareJob::OcsShareJob(AccountPtr account) -: OcsJob(account) + : OcsJob(account) { setPath("ocs/v1.php/apps/files_sharing/api/v1/shares"); connect(this, SIGNAL(jobFinished(QJsonDocument)), this, SLOT(jobDone(QJsonDocument))); @@ -94,8 +94,8 @@ void OcsShareJob::setName(const QString &shareId, const QString &name) start(); } -void OcsShareJob::setPermissions(const QString &shareId, - const Share::Permissions permissions) +void OcsShareJob::setPermissions(const QString &shareId, + const Share::Permissions permissions) { appendPath(shareId); setVerb("PUT"); @@ -107,8 +107,8 @@ void OcsShareJob::setPermissions(const QString &shareId, } void OcsShareJob::createLinkShare(const QString &path, - const QString &name, - const QString &password) + const QString &name, + const QString &password) { setVerb("POST"); @@ -127,10 +127,10 @@ void OcsShareJob::createLinkShare(const QString &path, start(); } -void OcsShareJob::createShare(const QString& path, - const Share::ShareType shareType, - const QString& shareWith, - const Share::Permissions permissions) +void OcsShareJob::createShare(const QString &path, + const Share::ShareType shareType, + const QString &shareWith, + const Share::Permissions permissions) { setVerb("POST"); @@ -155,5 +155,4 @@ void OcsShareJob::jobDone(QJsonDocument reply) { emit shareJobFinished(reply, _value); } - } diff --git a/src/gui/ocssharejob.h b/src/gui/ocssharejob.h index 6e2d83407..09c69410d 100644 --- a/src/gui/ocssharejob.h +++ b/src/gui/ocssharejob.h @@ -30,10 +30,10 @@ namespace OCC { * Handle talking to the OCS Share API. * For creation, deletion and modification of shares. */ -class OcsShareJob : public OcsJob { +class OcsShareJob : public OcsJob +{ Q_OBJECT public: - /** * Constructor for new shares or listing of shares */ @@ -44,7 +44,7 @@ public: * * @param path Path to request shares for (default all shares) */ - void getShares(const QString& path = ""); + void getShares(const QString &path = ""); /** * Delete the current Share @@ -57,7 +57,7 @@ public: * @param date The expire date, if this date is invalid the expire date * will be removed */ - void setExpireDate(const QString &shareId, const QDate& date); + void setExpireDate(const QString &shareId, const QDate &date); /** * Set the password of a share @@ -65,7 +65,7 @@ public: * @param password The password of the share, if the password is empty the * share will be removed */ - void setPassword(const QString &shareId, const QString& password); + void setPassword(const QString &shareId, const QString &password); /** * Set the share to be public upload @@ -84,8 +84,8 @@ public: * * @param permissions */ - void setPermissions(const QString &shareId, - const Share::Permissions permissions); + void setPermissions(const QString &shareId, + const Share::Permissions permissions); /** * Create a new link share @@ -94,9 +94,9 @@ public: * @param name The name of the link share, empty name auto-generates one * @param password Optionally a password for the share */ - void createLinkShare(const QString& path, - const QString& name, - const QString& password); + void createLinkShare(const QString &path, + const QString &name, + const QString &password); /** * Create a new share @@ -106,10 +106,10 @@ public: * @param shareWith The uid/gid/federated id to share with * @param permissions The permissions the share will have */ - void createShare(const QString& path, - const Share::ShareType shareType, - const QString& shareWith = "", - const Share::Permissions permissions = SharePermissionRead); + void createShare(const QString &path, + const Share::ShareType shareType, + const QString &shareWith = "", + const Share::Permissions permissions = SharePermissionRead); /** * Returns information on the items shared with the current user. @@ -134,7 +134,6 @@ private slots: private: QVariant _value; }; - } #endif // OCSSHAREJOB_H diff --git a/src/gui/openfilemanager.cpp b/src/gui/openfilemanager.cpp index 84e066e12..d06402eca 100644 --- a/src/gui/openfilemanager.cpp +++ b/src/gui/openfilemanager.cpp @@ -39,7 +39,7 @@ static QStringList xdgDataDirs() // local location QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME")); if (xdgDataHome.isEmpty()) { - xdgDataHome = QDir::homePath()+"/.local/share"; + xdgDataHome = QDir::homePath() + "/.local/share"; } dirs.prepend(xdgDataHome); return dirs; @@ -49,7 +49,10 @@ static QStringList xdgDataDirs() static QString findDefaultFileManager() { QProcess p; - p.start("xdg-mime", QStringList() << "query" << "default" << "inode/directory", QFile::ReadOnly); + p.start("xdg-mime", QStringList() << "query" + << "default" + << "inode/directory", + QFile::ReadOnly); p.waitForFinished(); QString fileName = QString::fromUtf8(p.readAll().trimmed()); if (fileName.isEmpty()) @@ -58,9 +61,10 @@ static QString findDefaultFileManager() QFileInfo fi; QStringList dirs = xdgDataDirs(); QStringList subdirs; - subdirs << "/applications/" << "/applications/kde4/"; - foreach(QString dir, dirs) { - foreach(QString subdir, subdirs) { + subdirs << "/applications/" + << "/applications/kde4/"; + foreach (QString dir, dirs) { + foreach (QString subdir, subdirs) { fi.setFile(dir + subdir + fileName); if (fi.exists()) { return fi.absoluteFilePath(); @@ -93,7 +97,7 @@ void showInFileManager(const QString &localPath) QFileInfo fi(localPath); // canonicalFilePath returns empty if the file does not exist - if( !fi.canonicalFilePath().isEmpty() ) { + if (!fi.canonicalFilePath().isEmpty()) { QString nativeArgs; if (!fi.isDir()) { nativeArgs += QLatin1String("/select,"); @@ -116,7 +120,7 @@ void showInFileManager(const QString &localPath) QStringList scriptArgs; scriptArgs << QLatin1String("-e") << QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"") - .arg(localPath); + .arg(localPath); QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs); scriptArgs.clear(); scriptArgs << QLatin1String("-e") @@ -135,7 +139,8 @@ void showInFileManager(const QString &localPath) bool canHandleFile = false; // assume dumb fm args = exec.split(' '); - if (args.count() > 0) app = args.takeFirst(); + if (args.count() > 0) + app = args.takeFirst(); QString kdeSelectParam("--select"); @@ -145,8 +150,7 @@ void showInFileManager(const QString &localPath) canHandleFile = true; } - if (app.contains("dolphin")) - { + if (app.contains("dolphin")) { static bool dolphinCanSelect = checkDolphinCanSelect(); if (dolphinCanSelect && !args.contains(kdeSelectParam)) { args.prepend(kdeSelectParam); @@ -181,7 +185,8 @@ void showInFileManager(const QString &localPath) } - if (args.count() == 0) args << fileToOpen; + if (args.count() == 0) + args << fileToOpen; if (app.isEmpty() || args.isEmpty() || !canHandleFile) { // fall back: open the default file manager, without ever selecting the file @@ -191,5 +196,4 @@ void showInFileManager(const QString &localPath) } } } - } diff --git a/src/gui/owncloudgui.cpp b/src/gui/owncloudgui.cpp index a82836f8b..25418c62a 100644 --- a/src/gui/owncloudgui.cpp +++ b/src/gui/owncloudgui.cpp @@ -22,10 +22,10 @@ #include "owncloudsetupwizard.h" #include "sharedialog.h" #if defined(Q_OS_MAC) -# include "settingsdialogmac.h" -# include "macwindow.h" // qtmacgoodies +#include "settingsdialogmac.h" +#include "macwindow.h" // qtmacgoodies #else -# include "settingsdialog.h" +#include "settingsdialog.h" #endif #include "logger.h" #include "logbrowser.h" @@ -48,30 +48,33 @@ namespace OCC { const char propertyAccountC[] = "oc_account"; -ownCloudGui::ownCloudGui(Application *parent) : - QObject(parent), - _tray(0), +ownCloudGui::ownCloudGui(Application *parent) + : QObject(parent) + , _tray(0) + , #if defined(Q_OS_MAC) - _settingsDialog(new SettingsDialogMac(this)), + _settingsDialog(new SettingsDialogMac(this)) + , #else - _settingsDialog(new SettingsDialog(this)), + _settingsDialog(new SettingsDialog(this)) + , #endif - _logBrowser(0), - _contextMenuVisibleOsx(false), - _recentActionsMenu(0), - _qdbusmenuWorkaround(false), - _folderOpenActionMapper(new QSignalMapper(this)), - _recentItemsMapper(new QSignalMapper(this)), - _app(parent) + _logBrowser(0) + , _contextMenuVisibleOsx(false) + , _recentActionsMenu(0) + , _qdbusmenuWorkaround(false) + , _folderOpenActionMapper(new QSignalMapper(this)) + , _recentItemsMapper(new QSignalMapper(this)) + , _app(parent) { _tray = new Systray(); _tray->setParent(this); // for the beginning, set the offline icon until the account was verified - _tray->setIcon( Theme::instance()->folderOfflineIcon(/*systray?*/ true, /*currently visible?*/ false)); + _tray->setIcon(Theme::instance()->folderOfflineIcon(/*systray?*/ true, /*currently visible?*/ false)); connect(_tray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)), - SLOT(slotTrayClicked(QSystemTrayIcon::ActivationReason))); + SLOT(slotTrayClicked(QSystemTrayIcon::ActivationReason))); setupActions(); setupContextMenu(); @@ -80,30 +83,30 @@ ownCloudGui::ownCloudGui(Application *parent) : /* use a signal mapper to map the open requests to the alias names */ connect(_folderOpenActionMapper, SIGNAL(mapped(QString)), - this, SLOT(slotFolderOpenAction(QString))); + this, SLOT(slotFolderOpenAction(QString))); connect(_recentItemsMapper, SIGNAL(mapped(QString)), - this, SLOT(slotOpenPath(QString))); + this, SLOT(slotOpenPath(QString))); ProgressDispatcher *pd = ProgressDispatcher::instance(); - connect( pd, SIGNAL(progressInfo(QString,ProgressInfo)), this, - SLOT(slotUpdateProgress(QString,ProgressInfo)) ); + connect(pd, SIGNAL(progressInfo(QString, ProgressInfo)), this, + SLOT(slotUpdateProgress(QString, ProgressInfo))); FolderMan *folderMan = FolderMan::instance(); - connect( folderMan, SIGNAL(folderSyncStateChange(Folder*)), - this,SLOT(slotSyncStateChange(Folder*))); + connect(folderMan, SIGNAL(folderSyncStateChange(Folder *)), + this, SLOT(slotSyncStateChange(Folder *))); - connect( AccountManager::instance(), SIGNAL(accountAdded(AccountState*)), - SLOT(updateContextMenuNeeded())); - connect( AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)), - SLOT(updateContextMenuNeeded())); + connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)), + SLOT(updateContextMenuNeeded())); + connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)), + SLOT(updateContextMenuNeeded())); - connect( Logger::instance(), SIGNAL(guiLog(QString,QString)), - SLOT(slotShowTrayMessage(QString,QString))); - connect( Logger::instance(), SIGNAL(optionalGuiLog(QString,QString)), - SLOT(slotShowOptionalTrayMessage(QString,QString))); - connect( Logger::instance(), SIGNAL(guiMessage(QString,QString)), - SLOT(slotShowGuiMessage(QString,QString))); + connect(Logger::instance(), SIGNAL(guiLog(QString, QString)), + SLOT(slotShowTrayMessage(QString, QString))); + connect(Logger::instance(), SIGNAL(optionalGuiLog(QString, QString)), + SLOT(slotShowOptionalTrayMessage(QString, QString))); + connect(Logger::instance(), SIGNAL(guiMessage(QString, QString)), + SLOT(slotShowGuiMessage(QString, QString))); setupOverlayIcons(); } @@ -127,21 +130,21 @@ void ownCloudGui::setupOverlayIcons() " end try\n" "end tell\n"); - QString osascript = "/usr/bin/osascript"; - QStringList processArguments; - // processArguments << "-l" << "AppleScript"; - - QProcess p; - p.start(osascript, processArguments); - p.write(aScript.toUtf8()); - p.closeWriteChannel(); - //p.waitForReadyRead(-1); - p.waitForFinished(5000); - QByteArray result = p.readAll(); - QString resultAsString(result); // if appropriate - qCInfo(lcApplication) << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode() - << (p.exitCode() != 0 ? p.errorString() : QString::null); - } else { + QString osascript = "/usr/bin/osascript"; + QStringList processArguments; + // processArguments << "-l" << "AppleScript"; + + QProcess p; + p.start(osascript, processArguments); + p.write(aScript.toUtf8()); + p.closeWriteChannel(); + //p.waitForReadyRead(-1); + p.waitForFinished(5000); + QByteArray result = p.readAll(); + QString resultAsString(result); // if appropriate + qCInfo(lcApplication) << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode() + << (p.exitCode() != 0 ? p.errorString() : QString::null); + } else { qCWarning(lcApplication) << finderExtension << "does not exist! Finder Overlay Plugin loading failed"; } } @@ -152,7 +155,7 @@ void ownCloudGui::setupOverlayIcons() void ownCloudGui::slotOpenSettingsDialog() { // if account is set up, start the configuration wizard. - if( !AccountManager::instance()->accounts().isEmpty() ) { + if (!AccountManager::instance()->accounts().isEmpty()) { if (_settingsDialog.isNull() || QApplication::activeWindow() != _settingsDialog) { slotShowSettings(); } else { @@ -164,7 +167,7 @@ void ownCloudGui::slotOpenSettingsDialog() } } -void ownCloudGui::slotTrayClicked( QSystemTrayIcon::ActivationReason reason ) +void ownCloudGui::slotTrayClicked(QSystemTrayIcon::ActivationReason reason) { if (_qdbusmenuWorkaround) { static QElapsedTimer last_click; @@ -175,12 +178,12 @@ void ownCloudGui::slotTrayClicked( QSystemTrayIcon::ActivationReason reason ) } // Left click - if( reason == QSystemTrayIcon::Trigger ) { + if (reason == QSystemTrayIcon::Trigger) { if (OwncloudSetupWizard::bringWizardToFrontIfVisible()) { // brought wizard to front } else if (_shareDialogs.size() > 0) { // Share dialog(s) be hidden by other apps, bring them back - Q_FOREACH(const QPointer &shareDialog, _shareDialogs) { + Q_FOREACH (const QPointer &shareDialog, _shareDialogs) { Q_ASSERT(shareDialog.data()); raiseDialog(shareDialog); } @@ -201,25 +204,25 @@ void ownCloudGui::slotTrayClicked( QSystemTrayIcon::ActivationReason reason ) // or SSL error dialog also comes to front. } -void ownCloudGui::slotSyncStateChange( Folder* folder ) +void ownCloudGui::slotSyncStateChange(Folder *folder) { slotComputeOverallSyncStatus(); updateContextMenuNeeded(); - if( !folder ) { + if (!folder) { return; // Valid, just a general GUI redraw was needed. } auto result = folder->syncResult(); - qCInfo(lcApplication) << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString(); + qCInfo(lcApplication) << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString(); if (result.status() == SyncResult::Success || result.status() == SyncResult::Error) { Logger::instance()->enterNextLogFile(); } if (result.status() == SyncResult::NotYetStarted) { - _settingsDialog->slotRefreshActivity( folder->accountState() ); + _settingsDialog->slotRefreshActivity(folder->accountState()); } } @@ -240,15 +243,15 @@ void ownCloudGui::slotAccountStateChanged() slotComputeOverallSyncStatus(); } -void ownCloudGui::slotTrayMessageIfServerUnsupported(Account* account) +void ownCloudGui::slotTrayMessageIfServerUnsupported(Account *account) { if (account->serverVersionUnsupported()) { slotShowTrayMessage( - tr("Unsupported Server Version"), - tr("The server on account %1 runs an old and unsupported version %2. " - "Using this client with unsupported server versions is untested and " - "potentially dangerous. Proceed at your own risk.") - .arg(account->displayName(), account->serverVersion())); + tr("Unsupported Server Version"), + tr("The server on account %1 runs an old and unsupported version %2. " + "Using this client with unsupported server versions is untested and " + "potentially dangerous. Proceed at your own risk.") + .arg(account->displayName(), account->serverVersion())); } } @@ -265,7 +268,7 @@ void ownCloudGui::slotComputeOverallSyncStatus() problemAccounts.append(a); } } - foreach (Folder* f, FolderMan::instance()->map()) { + foreach (Folder *f, FolderMan::instance()->map()) { if (!f->syncPaused()) { allPaused = false; } @@ -279,15 +282,13 @@ void ownCloudGui::slotComputeOverallSyncStatus() foreach (AccountStatePtr a, problemAccounts) { accountNames.append(a->account()->displayName()); } - _tray->setToolTip(tr("Disconnected from %1").arg( - accountNames.join(QLatin1String(", ")))); + _tray->setToolTip(tr("Disconnected from %1").arg(accountNames.join(QLatin1String(", ")))); #else QStringList messages; messages.append(tr("Disconnected from accounts:")); foreach (AccountStatePtr a, problemAccounts) { - QString message = tr("Account %1: %2").arg( - a->account()->displayName(), a->stateString(a->state())); - if (! a->connectionErrors().empty()) { + QString message = tr("Account %1: %2").arg(a->account()->displayName(), a->stateString(a->state())); + if (!a->connectionErrors().empty()) { message += QLatin1String("\n"); message += a->connectionErrors().join(QLatin1String("\n")); } @@ -315,14 +316,14 @@ void ownCloudGui::slotComputeOverallSyncStatus() SyncResult overallResult = FolderMan::accountStatus(map.values()); // create the tray blob message, check if we have an defined state - if( overallResult.status() != SyncResult::Undefined ) { - if( map.count() > 0 ) { + if (overallResult.status() != SyncResult::Undefined) { + if (map.count() > 0) { #ifdef Q_OS_WIN // Windows has a 128-char tray tooltip length limit. trayMessage = folderMan->statusToString(overallResult.status(), false); #else QStringList allStatusStrings; - foreach(Folder* folder, map.values()) { + foreach (Folder *folder, map.values()) { QString folderMessage = folderMan->statusToString(folder->syncResult().status(), folder->syncPaused()); allStatusStrings += tr("Folder %1: %2").arg(folder->shortGuiLocalPath(), folderMessage); } @@ -332,13 +333,13 @@ void ownCloudGui::slotComputeOverallSyncStatus() trayMessage = tr("No sync folders configured."); } - QIcon statusIcon = Theme::instance()->syncStateIcon( overallResult.status(), true, contextMenuVisible()); - _tray->setIcon( statusIcon ); + QIcon statusIcon = Theme::instance()->syncStateIcon(overallResult.status(), true, contextMenuVisible()); + _tray->setIcon(statusIcon); _tray->setToolTip(trayMessage); } else { // undefined because there are no folders. QIcon icon = Theme::instance()->syncStateIcon(SyncResult::Problem, true, contextMenuVisible()); - _tray->setIcon( icon ); + _tray->setIcon(icon); _tray->setToolTip(tr("There are no sync folders configured.")); } } @@ -360,7 +361,7 @@ void ownCloudGui::addAccountContextMenu(AccountStatePtr accountState, QMenu *men bool singleSyncFolder = folderMan->map().size() == 1 && Theme::instance()->singleSyncFolder(); bool onePaused = false; bool allPaused = true; - foreach (Folder* folder, folderMan->map()) { + foreach (Folder *folder, folderMan->map()) { if (folder->accountState() != accountState.data()) { continue; } @@ -377,36 +378,35 @@ void ownCloudGui::addAccountContextMenu(AccountStatePtr accountState, QMenu *men menu->addAction(tr("Managed Folders:"))->setDisabled(true); } - QAction *action = new QAction( tr("Open folder '%1'").arg(folder->shortGuiLocalPath()), menu ); - connect(action, SIGNAL(triggered()),_folderOpenActionMapper, SLOT(map())); - _folderOpenActionMapper->setMapping( action, folder->alias() ); + QAction *action = new QAction(tr("Open folder '%1'").arg(folder->shortGuiLocalPath()), menu); + connect(action, SIGNAL(triggered()), _folderOpenActionMapper, SLOT(map())); + _folderOpenActionMapper->setMapping(action, folder->alias()); menu->addAction(action); } - menu->addSeparator(); - if (separateMenu) { - if (onePaused) { - QAction* enable = menu->addAction(tr("Unpause all folders")); - enable->setProperty(propertyAccountC, QVariant::fromValue(accountState)); - connect(enable, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders())); - } - if (!allPaused) { - QAction* enable = menu->addAction(tr("Pause all folders")); - enable->setProperty(propertyAccountC, QVariant::fromValue(accountState)); - connect(enable, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders())); - } - - if (accountState->isSignedOut()) { - QAction* signin = menu->addAction(tr("Log in...")); - signin->setProperty(propertyAccountC, QVariant::fromValue(accountState)); - connect(signin, SIGNAL(triggered()), this, SLOT(slotLogin())); - } else { - QAction* signout = menu->addAction(tr("Log out")); - signout->setProperty(propertyAccountC, QVariant::fromValue(accountState)); - connect(signout, SIGNAL(triggered()), this, SLOT(slotLogout())); - } - } + menu->addSeparator(); + if (separateMenu) { + if (onePaused) { + QAction *enable = menu->addAction(tr("Unpause all folders")); + enable->setProperty(propertyAccountC, QVariant::fromValue(accountState)); + connect(enable, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders())); + } + if (!allPaused) { + QAction *enable = menu->addAction(tr("Pause all folders")); + enable->setProperty(propertyAccountC, QVariant::fromValue(accountState)); + connect(enable, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders())); + } + if (accountState->isSignedOut()) { + QAction *signin = menu->addAction(tr("Log in...")); + signin->setProperty(propertyAccountC, QVariant::fromValue(accountState)); + connect(signin, SIGNAL(triggered()), this, SLOT(slotLogin())); + } else { + QAction *signout = menu->addAction(tr("Log out")); + signout->setProperty(propertyAccountC, QVariant::fromValue(accountState)); + connect(signout, SIGNAL(triggered()), this, SLOT(slotLogout())); + } + } } void ownCloudGui::slotContextMenuAboutToShow() @@ -469,7 +469,7 @@ void ownCloudGui::setupContextMenu() } _contextMenu.reset(new QMenu()); - _contextMenu->setTitle(Theme::instance()->appNameGUI() ); + _contextMenu->setTitle(Theme::instance()->appNameGUI()); _recentActionsMenu = new QMenu(tr("Recent Changes"), _contextMenu.data()); @@ -484,21 +484,21 @@ void ownCloudGui::setupContextMenu() return; } - // Enables workarounds for bugs introduced in Qt 5.5.0 - // In particular QTBUG-47863 #3672 (tray menu fails to update and - // becomes unresponsive) and QTBUG-48068 #3722 (click signal is - // emitted several times) - // The Qt version check intentionally uses 5.0.0 (where platformMenu() - // was introduced) instead of 5.5.0 to avoid issues where the Qt - // version used to build is different from the one used at runtime. - // If we build with 5.6.1 or newer, we can skip this because the - // bugs should be fixed there. +// Enables workarounds for bugs introduced in Qt 5.5.0 +// In particular QTBUG-47863 #3672 (tray menu fails to update and +// becomes unresponsive) and QTBUG-48068 #3722 (click signal is +// emitted several times) +// The Qt version check intentionally uses 5.0.0 (where platformMenu() +// was introduced) instead of 5.5.0 to avoid issues where the Qt +// version used to build is different from the one used at runtime. +// If we build with 5.6.1 or newer, we can skip this because the +// bugs should be fixed there. #ifdef Q_OS_LINUX #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && (QT_VERSION < QT_VERSION_CHECK(5, 6, 0)) if (qVersion() == QByteArray("5.5.0")) { - QObject* platformMenu = reinterpret_cast(_tray->contextMenu()->platformMenu()); + QObject *platformMenu = reinterpret_cast(_tray->contextMenu()->platformMenu()); if (platformMenu - && platformMenu->metaObject()->className() == QLatin1String("QDBusPlatformMenu")) { + && platformMenu->metaObject()->className() == QLatin1String("QDBusPlatformMenu")) { _qdbusmenuWorkaround = true; qCWarning(lcApplication) << "Enabled QDBusPlatformMenu workaround"; } @@ -519,8 +519,8 @@ void ownCloudGui::setupContextMenu() _workaroundBatchTrayUpdate.setInterval(30 * 1000); _workaroundBatchTrayUpdate.setSingleShot(true); } else { - // Update the context menu whenever we're about to show it - // to the user. +// Update the context menu whenever we're about to show it +// to the user. #ifdef Q_OS_MAC // https://bugreports.qt.io/browse/QTBUG-54633 connect(_contextMenu.data(), SIGNAL(aboutToShow()), SLOT(slotContextMenuAboutToShow())); @@ -557,7 +557,9 @@ void ownCloudGui::updateContextMenu() slotRebuildRecentMenus(); // We must call deleteLater because we might be called from the press in one of the actions. - foreach (auto menu, _accountMenus) { menu->deleteLater(); } + foreach (auto menu, _accountMenus) { + menu->deleteLater(); + } _accountMenus.clear(); @@ -589,7 +591,7 @@ void ownCloudGui::updateContextMenu() if (accountList.count() > 1) { foreach (AccountStatePtr account, accountList) { - QMenu* accountMenu = new QMenu(account->account()->displayName(), _contextMenu.data()); + QMenu *accountMenu = new QMenu(account->account()->displayName(), _contextMenu.data()); _accountMenus.append(accountMenu); _contextMenu->addMenu(accountMenu); @@ -614,7 +616,7 @@ void ownCloudGui::updateContextMenu() _contextMenu->addAction(_actionHelp); } - if(_actionCrash) { + if (_actionCrash) { _contextMenu->addAction(_actionCrash); } @@ -626,7 +628,7 @@ void ownCloudGui::updateContextMenu() } else { text = tr("Unpause synchronization"); } - QAction* action = _contextMenu->addAction(text); + QAction *action = _contextMenu->addAction(text); connect(action, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders())); } if (atLeastOneNotPaused) { @@ -636,7 +638,7 @@ void ownCloudGui::updateContextMenu() } else { text = tr("Pause synchronization"); } - QAction* action = _contextMenu->addAction(text); + QAction *action = _contextMenu->addAction(text); connect(action, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders())); } if (atLeastOneSignedIn) { @@ -690,7 +692,7 @@ void ownCloudGui::updateContextMenuNeeded() void ownCloudGui::slotShowTrayMessage(const QString &title, const QString &msg) { - if( _tray ) + if (_tray) _tray->showMessage(title, msg); else qCWarning(lcApplication) << "Tray not ready: " << msg; @@ -708,10 +710,10 @@ void ownCloudGui::slotShowOptionalTrayMessage(const QString &title, const QStrin /* * open the folder with the given Alias */ -void ownCloudGui::slotFolderOpenAction( const QString& alias ) +void ownCloudGui::slotFolderOpenAction(const QString &alias) { Folder *f = FolderMan::instance()->folder(alias); - if( f ) { + if (f) { qCInfo(lcApplication) << "opening local url " << f->path(); QUrl url = QUrl::fromLocalFile(f->path()); @@ -731,11 +733,11 @@ void ownCloudGui::slotFolderOpenAction( const QString& alias ) void ownCloudGui::setupActions() { _actionStatus = new QAction(tr("Unknown status"), this); - _actionStatus->setEnabled( false ); + _actionStatus->setEnabled(false); _actionSettings = new QAction(tr("Settings..."), this); _actionNewAccountWizard = new QAction(tr("New account..."), this); _actionRecent = new QAction(tr("Details..."), this); - _actionRecent->setEnabled( true ); + _actionRecent->setEnabled(true); QObject::connect(_actionRecent, SIGNAL(triggered(bool)), SLOT(slotShowSyncProtocol())); QObject::connect(_actionSettings, SIGNAL(triggered(bool)), SLOT(slotShowSettings())); @@ -750,20 +752,19 @@ void ownCloudGui::setupActions() _actionLogout = new QAction(tr("Log out"), this); connect(_actionLogout, SIGNAL(triggered()), this, SLOT(slotLogout())); - if(_app->debugMode()) { + if (_app->debugMode()) { _actionCrash = new QAction(tr("Crash now", "Only shows in debug mode to allow testing the crash handler"), this); connect(_actionCrash, SIGNAL(triggered()), _app, SLOT(slotCrash())); } else { _actionCrash = 0; } - } void ownCloudGui::slotRebuildRecentMenus() { _recentActionsMenu->clear(); if (!_recentItemsActions.isEmpty()) { - foreach(QAction *a, _recentItemsActions) { + foreach (QAction *a, _recentItemsActions) { _recentActionsMenu->addAction(a); } _recentActionsMenu->addSeparator(); @@ -776,53 +777,53 @@ void ownCloudGui::slotRebuildRecentMenus() /// Returns true if the completion of a given item should show up in the /// 'Recent Activity' menu -static bool shouldShowInRecentsMenu(const SyncFileItem& item) +static bool shouldShowInRecentsMenu(const SyncFileItem &item) { - return - !Progress::isIgnoredKind(item._status) - && item._instruction != CSYNC_INSTRUCTION_EVAL - && item._instruction != CSYNC_INSTRUCTION_NONE; + return !Progress::isIgnoredKind(item._status) + && item._instruction != CSYNC_INSTRUCTION_EVAL + && item._instruction != CSYNC_INSTRUCTION_NONE; } -void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo& progress) +void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo &progress) { Q_UNUSED(folder); if (!progress._currentDiscoveredFolder.isEmpty()) { - _actionStatus->setText( tr("Checking for changes in '%1'") - .arg( progress._currentDiscoveredFolder )); - } else if (progress.totalSize() == 0 ) { + _actionStatus->setText(tr("Checking for changes in '%1'") + .arg(progress._currentDiscoveredFolder)); + } else if (progress.totalSize() == 0) { quint64 currentFile = progress.currentFile(); quint64 totalFileCount = qMax(progress.totalFiles(), currentFile); QString msg; if (progress.trustEta()) { msg = tr("Syncing %1 of %2 (%3 left)") - .arg( currentFile ).arg( totalFileCount ) - .arg( Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta) ); + .arg(currentFile) + .arg(totalFileCount) + .arg(Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta)); } else { msg = tr("Syncing %1 of %2") - .arg( currentFile ).arg( totalFileCount ); + .arg(currentFile) + .arg(totalFileCount); } - _actionStatus->setText( msg ); + _actionStatus->setText(msg); } else { - QString totalSizeStr = Utility::octetsToString( progress.totalSize() ); + QString totalSizeStr = Utility::octetsToString(progress.totalSize()); QString msg; if (progress.trustEta()) { msg = tr("Syncing %1 (%2 left)") - .arg( totalSizeStr, Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta) ); + .arg(totalSizeStr, Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta)); } else { msg = tr("Syncing %1") - .arg( totalSizeStr ); + .arg(totalSizeStr); } - _actionStatus->setText( msg ); + _actionStatus->setText(msg); } - _actionRecent->setIcon( QIcon() ); // Fixme: Set a "in-progress"-item eventually. + _actionRecent->setIcon(QIcon()); // Fixme: Set a "in-progress"-item eventually. if (!progress._lastCompletedItem.isEmpty() - && shouldShowInRecentsMenu(progress._lastCompletedItem)) { - + && shouldShowInRecentsMenu(progress._lastCompletedItem)) { if (Progress::isWarningKind(progress._lastCompletedItem._status)) { // display a warn icon if warnings happened. QIcon warnIcon(":/client/resources/warning"); @@ -856,8 +857,8 @@ void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo& } if (progress.isUpdatingEstimates() - && progress.completedFiles() >= progress.totalFiles() - && progress._currentDiscoveredFolder.isEmpty()) { + && progress.completedFiles() >= progress.totalFiles() + && progress._currentDiscoveredFolder.isEmpty()) { QTimer::singleShot(2000, this, SLOT(slotDisplayIdle())); } } @@ -909,7 +910,7 @@ void ownCloudGui::slotNewAccountWizard() void ownCloudGui::setPauseOnAllFoldersHelper(bool pause) { - QList accounts; + QList accounts; if (auto account = qvariant_cast(sender()->property(propertyAccountC))) { accounts.append(account.data()); } else { @@ -917,7 +918,7 @@ void ownCloudGui::setPauseOnAllFoldersHelper(bool pause) accounts.append(a.data()); } } - foreach (Folder* f, FolderMan::instance()->map()) { + foreach (Folder *f, FolderMan::instance()->map()) { if (accounts.contains(f->accountState())) { f->setSyncPaused(pause); if (pause) { @@ -943,11 +944,11 @@ void ownCloudGui::slotShowSettings() if (_settingsDialog.isNull()) { _settingsDialog = #if defined(Q_OS_MAC) - new SettingsDialogMac(this); + new SettingsDialogMac(this); #else - new SettingsDialog(this); + new SettingsDialog(this); #endif - _settingsDialog->setAttribute( Qt::WA_DeleteOnClose, true ); + _settingsDialog->setAttribute(Qt::WA_DeleteOnClose, true); _settingsDialog->show(); } raiseDialog(_settingsDialog.data()); @@ -966,8 +967,10 @@ void ownCloudGui::slotShutdown() // that saving the geometries happens ASAP during a OS shutdown // those do delete on close - if (!_settingsDialog.isNull()) _settingsDialog->close(); - if (!_logBrowser.isNull()) _logBrowser->deleteLater(); + if (!_settingsDialog.isNull()) + _settingsDialog->close(); + if (!_logBrowser.isNull()) + _logBrowser->deleteLater(); } void ownCloudGui::slotToggleLogBrowser() @@ -978,7 +981,7 @@ void ownCloudGui::slotToggleLogBrowser() // ## TODO: allow new log name maybe? } - if (_logBrowser->isVisible() ) { + if (_logBrowser->isVisible()) { _logBrowser->hide(); } else { raiseDialog(_logBrowser); @@ -997,9 +1000,9 @@ void ownCloudGui::slotHelp() QDesktopServices::openUrl(QUrl(Theme::instance()->helpUrl())); } -void ownCloudGui::raiseDialog( QWidget *raiseWidget ) +void ownCloudGui::raiseDialog(QWidget *raiseWidget) { - if( raiseWidget && raiseWidget->parentWidget() == 0) { + if (raiseWidget && raiseWidget->parentWidget() == 0) { // Qt has a bug which causes parent-less dialogs to pop-under. raiseWidget->showNormal(); raiseWidget->raise(); @@ -1026,10 +1029,10 @@ void ownCloudGui::raiseDialog( QWidget *raiseWidget ) e.xclient.data.l[4] = 0l; Display *display = QX11Info::display(); XSendEvent(display, - RootWindow(display, DefaultScreen(display)), - False, // propagate - SubstructureRedirectMask|SubstructureNotifyMask, - &e); + RootWindow(display, DefaultScreen(display)), + False, // propagate + SubstructureRedirectMask | SubstructureNotifyMask, + &e); #endif } } @@ -1054,9 +1057,9 @@ void ownCloudGui::slotShowShareDialog(const QString &sharePath, const QString &l // The correct value will be found with a propfind from ShareDialog. // (we want to show the dialog directly, not wait for the propfind first) SharePermissions maxSharingPermissions = - SharePermissionRead - | SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete - | SharePermissionShare; + SharePermissionRead + | SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete + | SharePermissionShare; if (!resharingAllowed) { maxSharingPermissions = 0; } @@ -1069,20 +1072,20 @@ void ownCloudGui::slotShowShareDialog(const QString &sharePath, const QString &l } else { qCInfo(lcApplication) << "Opening share dialog" << sharePath << localPath << maxSharingPermissions; w = new ShareDialog(accountState, sharePath, localPath, maxSharingPermissions); - w->setAttribute( Qt::WA_DeleteOnClose, true ); + w->setAttribute(Qt::WA_DeleteOnClose, true); _shareDialogs[localPath] = w; - connect(w, SIGNAL(destroyed(QObject*)), SLOT(slotRemoveDestroyedShareDialogs())); + connect(w, SIGNAL(destroyed(QObject *)), SLOT(slotRemoveDestroyedShareDialogs())); } raiseDialog(w); } void ownCloudGui::slotRemoveDestroyedShareDialogs() { - QMutableMapIterator > it(_shareDialogs); + QMutableMapIterator> it(_shareDialogs); while (it.hasNext()) { it.next(); - if (! it.value() || it.value() == sender()) { + if (!it.value() || it.value() == sender()) { it.remove(); } } diff --git a/src/gui/owncloudgui.h b/src/gui/owncloudgui.h index f72a5a437..c0238a761 100644 --- a/src/gui/owncloudgui.h +++ b/src/gui/owncloudgui.h @@ -69,21 +69,21 @@ public slots: void slotComputeOverallSyncStatus(); void slotShowTrayMessage(const QString &title, const QString &msg); void slotShowOptionalTrayMessage(const QString &title, const QString &msg); - void slotFolderOpenAction( const QString& alias ); + void slotFolderOpenAction(const QString &alias); void slotRebuildRecentMenus(); - void slotUpdateProgress(const QString &folder, const ProgressInfo& progress); + void slotUpdateProgress(const QString &folder, const ProgressInfo &progress); void slotShowGuiMessage(const QString &title, const QString &message); void slotFoldersChanged(); void slotShowSettings(); void slotShowSyncProtocol(); void slotShutdown(); - void slotSyncStateChange(Folder*); - void slotTrayClicked( QSystemTrayIcon::ActivationReason reason ); + void slotSyncStateChange(Folder *); + void slotTrayClicked(QSystemTrayIcon::ActivationReason reason); void slotToggleLogBrowser(); void slotOpenOwnCloud(); void slotOpenSettingsDialog(); void slotHelp(); - void slotOpenPath(const QString& path); + void slotOpenPath(const QString &path); void slotAccountStateChanged(); void slotTrayMessageIfServerUnsupported(Account *account); void slotShowShareDialog(const QString &sharePath, const QString &localPath, bool resharingAllowed); @@ -100,7 +100,7 @@ private slots: private: void setPauseOnAllFoldersHelper(bool pause); void setupActions(); - void addAccountContextMenu(AccountStatePtr accountState, QMenu* menu, bool separateMenu); + void addAccountContextMenu(AccountStatePtr accountState, QMenu *menu, bool separateMenu); QPointer _tray; #if defined(Q_OS_MAC) @@ -108,8 +108,8 @@ private: #else QPointer _settingsDialog; #endif - QPointer_logBrowser; - // tray's menu + QPointer _logBrowser; + // tray's menu QScopedPointer _contextMenu; // Manually tracking whether the context menu is visible, but only works @@ -117,10 +117,10 @@ private: bool _contextMenuVisibleOsx; QMenu *_recentActionsMenu; - QVector _accountMenus; + QVector _accountMenus; bool _qdbusmenuWorkaround; QTimer _workaroundBatchTrayUpdate; - QMap > _shareDialogs; + QMap> _shareDialogs; QAction *_actionLogin; QAction *_actionLogout; @@ -134,7 +134,7 @@ private: QAction *_actionQuit; QAction *_actionCrash; - QList _recentItemsActions; + QList _recentItemsActions; QSignalMapper *_folderOpenActionMapper; QSignalMapper *_recentItemsMapper; diff --git a/src/gui/owncloudsetupwizard.cpp b/src/gui/owncloudsetupwizard.cpp index 7a5289979..9a7359f3e 100644 --- a/src/gui/owncloudsetupwizard.cpp +++ b/src/gui/owncloudsetupwizard.cpp @@ -40,24 +40,24 @@ namespace OCC { -OwncloudSetupWizard::OwncloudSetupWizard(QObject* parent) : - QObject( parent ), - _ocWizard(new OwncloudWizard), - _remoteFolder() +OwncloudSetupWizard::OwncloudSetupWizard(QObject *parent) + : QObject(parent) + , _ocWizard(new OwncloudWizard) + , _remoteFolder() { - connect( _ocWizard, SIGNAL(determineAuthType(const QString&)), - this, SLOT(slotDetermineAuthType(const QString&))); - connect( _ocWizard, SIGNAL(connectToOCUrl( const QString& ) ), - this, SLOT(slotConnectToOCUrl( const QString& ))); - connect( _ocWizard, SIGNAL(createLocalAndRemoteFolders(QString, QString)), - this, SLOT(slotCreateLocalAndRemoteFolders(QString, QString))); + connect(_ocWizard, SIGNAL(determineAuthType(const QString &)), + this, SLOT(slotDetermineAuthType(const QString &))); + connect(_ocWizard, SIGNAL(connectToOCUrl(const QString &)), + this, SLOT(slotConnectToOCUrl(const QString &))); + connect(_ocWizard, SIGNAL(createLocalAndRemoteFolders(QString, QString)), + this, SLOT(slotCreateLocalAndRemoteFolders(QString, QString))); /* basicSetupFinished might be called from a reply from the network. slotAssistantFinished might destroy the temporary QNetworkAccessManager. Therefore Qt::QueuedConnection is required */ - connect( _ocWizard, SIGNAL(basicSetupFinished(int)), - this, SLOT(slotAssistantFinished(int)), Qt::QueuedConnection); - connect( _ocWizard, SIGNAL(finished(int)), SLOT(deleteLater())); - connect( _ocWizard, SIGNAL(skipFolderConfiguration()), SLOT(slotSkipFolderConfiguration())); + connect(_ocWizard, SIGNAL(basicSetupFinished(int)), + this, SLOT(slotAssistantFinished(int)), Qt::QueuedConnection); + connect(_ocWizard, SIGNAL(finished(int)), SLOT(deleteLater())); + connect(_ocWizard, SIGNAL(skipFolderConfiguration()), SLOT(slotSkipFolderConfiguration())); } OwncloudSetupWizard::~OwncloudSetupWizard() @@ -67,14 +67,14 @@ OwncloudSetupWizard::~OwncloudSetupWizard() static QPointer wiz = 0; -void OwncloudSetupWizard::runWizard(QObject* obj, const char* amember, QWidget *parent) +void OwncloudSetupWizard::runWizard(QObject *obj, const char *amember, QWidget *parent) { if (!wiz.isNull()) { return; } wiz = new OwncloudSetupWizard(parent); - connect( wiz, SIGNAL(ownCloudWizardDone(int)), obj, amember); + connect(wiz, SIGNAL(ownCloudWizardDone(int)), obj, amember); FolderMan::instance()->setSyncEnabled(false); wiz->startWizard(); } @@ -103,7 +103,7 @@ void OwncloudSetupWizard::startWizard() // if its a relative path, prepend with users home dir, otherwise use as absolute path - if( !QDir(localFolder).isAbsolute() ) { + if (!QDir(localFolder).isAbsolute()) { localFolder = QDir::homePath() + QDir::separator() + localFolder; } @@ -111,7 +111,7 @@ void OwncloudSetupWizard::startWizard() // remember the local folder to compare later if it changed, but clean first QString lf = QDir::fromNativeSeparators(localFolder); - if( !lf.endsWith(QLatin1Char('/'))) { + if (!lf.endsWith(QLatin1Char('/'))) { lf.append(QLatin1Char('/')); } @@ -146,7 +146,7 @@ void OwncloudSetupWizard::slotDetermineAuthType(const QString &urlString) if (ClientProxy::isUsingSystemDefault()) { qCDebug(lcWizard) << "Trying to look up system proxy"; ClientProxy::lookupSystemProxyAsync(account->url(), - this, SLOT(slotSystemProxyLookupDone(QNetworkProxy))); + this, SLOT(slotSystemProxyLookupDone(QNetworkProxy))); } else { // We want to reset the QNAM proxy so that the global proxy settings are used (via ClientProxy settings) account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy)); @@ -176,22 +176,22 @@ void OwncloudSetupWizard::slotContinueDetermineAuth() account->setCredentials(CredentialsFactory::create("dummy")); CheckServerJob *job = new CheckServerJob(_ocWizard->account(), this); job->setIgnoreCredentialFailure(true); - connect(job, SIGNAL(instanceFound(QUrl,QJsonObject)), SLOT(slotOwnCloudFoundAuth(QUrl,QJsonObject))); - connect(job, SIGNAL(instanceNotFound(QNetworkReply*)), SLOT(slotNoOwnCloudFoundAuth(QNetworkReply*))); - connect(job, SIGNAL(timeout(const QUrl&)), SLOT(slotNoOwnCloudFoundAuthTimeout(const QUrl&))); - job->setTimeout((account->url().scheme() == "https") ? 30*1000 : 10*1000); + connect(job, SIGNAL(instanceFound(QUrl, QJsonObject)), SLOT(slotOwnCloudFoundAuth(QUrl, QJsonObject))); + connect(job, SIGNAL(instanceNotFound(QNetworkReply *)), SLOT(slotNoOwnCloudFoundAuth(QNetworkReply *))); + connect(job, SIGNAL(timeout(const QUrl &)), SLOT(slotNoOwnCloudFoundAuthTimeout(const QUrl &))); + job->setTimeout((account->url().scheme() == "https") ? 30 * 1000 : 10 * 1000); job->start(); } -void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl& url, const QJsonObject &info) +void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl &url, const QJsonObject &info) { auto serverVersion = CheckServerJob::version(info); _ocWizard->appendToConfigurationLog(tr("Successfully connected to %1: %2 version %3 (%4)

") - .arg(Utility::escape(url.toString()), - Utility::escape(Theme::instance()->appNameGUI()), - Utility::escape(CheckServerJob::versionString(info)), - Utility::escape(serverVersion))); + .arg(Utility::escape(url.toString()), + Utility::escape(Theme::instance()->appNameGUI()), + Utility::escape(CheckServerJob::versionString(info)), + Utility::escape(serverVersion))); // Note with newer servers we get the version actually only later in capabilities // https://github.com/owncloud/core/pull/27473/files @@ -209,7 +209,7 @@ void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl& url, const QJsonObje DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_ocWizard->account(), this); job->setIgnoreCredentialFailure(true); connect(job, SIGNAL(authType(WizardCommon::AuthType)), - _ocWizard, SLOT(setAuthType(WizardCommon::AuthType))); + _ocWizard, SLOT(setAuthType(WizardCommon::AuthType))); job->start(); } @@ -226,8 +226,8 @@ void OwncloudSetupWizard::slotNoOwnCloudFoundAuth(QNetworkReply *reply) } else { msg = tr("Failed to connect to %1 at %2:
%3") .arg(Utility::escape(Theme::instance()->appNameGUI()), - Utility::escape(reply->url().toString()), - Utility::escape(job->errorString())); + Utility::escape(reply->url().toString()), + Utility::escape(job->errorString())); } bool isDowngradeAdvised = checkDowngradeAdvised(reply); @@ -238,7 +238,7 @@ void OwncloudSetupWizard::slotNoOwnCloudFoundAuth(QNetworkReply *reply) if (resultCode != 200 && contentType.startsWith("text/")) { // FIXME: Synchronous dialogs are not so nice because of event loop recursion // (we already create a dialog further below) - QString serverError = reply->peek(1024*20); + QString serverError = reply->peek(1024 * 20); qCDebug(lcWizard) << serverError; QMessageBox messageBox(_ocWizard); messageBox.setText(serverError); @@ -255,7 +255,7 @@ void OwncloudSetupWizard::slotNoOwnCloudFoundAuth(QNetworkReply *reply) _ocWizard->account()->resetRejectedCertificates(); } -void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl&url) +void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl &url) { _ocWizard->displayError( tr("Timeout while trying to connect to %1 at %2.") @@ -263,14 +263,15 @@ void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl&url) false); } -void OwncloudSetupWizard::slotConnectToOCUrl( const QString& url ) +void OwncloudSetupWizard::slotConnectToOCUrl(const QString &url) { qCInfo(lcWizard) << "Connect to url: " << url; AbstractCredentials *creds = _ocWizard->getCredentials(); _ocWizard->account()->setCredentials(creds); - _ocWizard->setField(QLatin1String("OCUrl"), url ); + _ocWizard->setField(QLatin1String("OCUrl"), url); _ocWizard->appendToConfigurationLog(tr("Trying to connect to %1 at %2...") - .arg( Theme::instance()->appNameGUI() ).arg(url) ); + .arg(Theme::instance()->appNameGUI()) + .arg(url)); testOwnCloudConnect(); } @@ -294,12 +295,12 @@ void OwncloudSetupWizard::slotAuthError() { QString errorMsg; - PropfindJob* job = qobject_cast(sender()); + PropfindJob *job = qobject_cast(sender()); if (!job) { qCWarning(lcWizard) << "Can't check for authed redirects. This slot should be invoked from PropfindJob!"; return; } - QNetworkReply* reply = job->reply(); + QNetworkReply *reply = job->reply(); // If there were redirects on the *authed* requests, also store // the updated server URL, similar to redirects on status.php. @@ -323,13 +324,13 @@ void OwncloudSetupWizard::slotAuthError() "'%1'. The URL is bad, the server is misconfigured.") .arg(Utility::escape(redirectUrl.toString())); - // A 404 is actually a success: we were authorized to know that the folder does - // not exist. It will be created later... + // A 404 is actually a success: we were authorized to know that the folder does + // not exist. It will be created later... } else if (reply->error() == QNetworkReply::ContentNotFoundError) { _ocWizard->successfulStep(); return; - // Provide messages for other errors, such as invalid credentials. + // Provide messages for other errors, such as invalid credentials. } else if (reply->error() != QNetworkReply::NoError) { if (!_ocWizard->account()->credentials()->stillValid(reply)) { errorMsg = tr("Access forbidden by server. To verify that you have proper access, " @@ -339,7 +340,7 @@ void OwncloudSetupWizard::slotAuthError() errorMsg = job->errorStringParsingBody(); } - // Something else went wrong, maybe the response was 200 but with invalid data. + // Something else went wrong, maybe the response was 200 but with invalid data. } else { errorMsg = tr("There was an invalid response to an authenticated webdav request"); } @@ -351,9 +352,9 @@ void OwncloudSetupWizard::slotAuthError() _ocWizard->displayError(errorMsg, _ocWizard->currentId() == WizardCommon::Page_ServerSetup && checkDowngradeAdvised(reply)); } -bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply* reply) +bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply *reply) { - if(reply->url().scheme() != QLatin1String("https")) { + if (reply->url().scheme() != QLatin1String("https")) { return false; } @@ -374,13 +375,13 @@ bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply* reply) return true; } -void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFolder, const QString& remoteFolder) +void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString &localFolder, const QString &remoteFolder) { qCInfo(lcWizard) << "Setup local sync folder for new oC connection " << localFolder; - const QDir fi( localFolder ); + const QDir fi(localFolder); bool nextStep = true; - if( fi.exists() ) { + if (fi.exists()) { FileSystem::setFolderMinimumPermissions(localFolder); // there is an existing local folder. If its non empty, it can only be synced if the // ownCloud is newly created. @@ -389,9 +390,9 @@ void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFo .arg(Utility::escape(localFolder))); } else { QString res = tr("Creating local sync folder %1...").arg(localFolder); - if( fi.mkpath( localFolder ) ) { + if (fi.mkpath(localFolder)) { FileSystem::setFolderMinimumPermissions(localFolder); - Utility::setupFavLink( localFolder ); + Utility::setupFavLink(localFolder); res += tr("ok"); } else { res += tr("failed."); @@ -399,14 +400,14 @@ void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFo _ocWizard->displayError(tr("Could not create local folder %1").arg(Utility::escape(localFolder)), false); nextStep = false; } - _ocWizard->appendToConfigurationLog( res ); + _ocWizard->appendToConfigurationLog(res); } if (nextStep) { EntityExistsJob *job = new EntityExistsJob(_ocWizard->account(), _ocWizard->account()->davPath() + remoteFolder, this); - connect(job, SIGNAL(exists(QNetworkReply*)), SLOT(slotRemoteFolderExists(QNetworkReply*))); + connect(job, SIGNAL(exists(QNetworkReply *)), SLOT(slotRemoteFolderExists(QNetworkReply *))); job->start(); } else { - finalizeSetup( false ); + finalizeSetup(false); } } @@ -418,10 +419,10 @@ void OwncloudSetupWizard::slotRemoteFolderExists(QNetworkReply *reply) QString error; QNetworkReply::NetworkError errId = reply->error(); - if( errId == QNetworkReply::NoError ) { + if (errId == QNetworkReply::NoError) { qCInfo(lcWizard) << "Remote folder found, all cool!"; - } else if( errId == QNetworkReply::ContentNotFoundError ) { - if( _remoteFolder.isEmpty() ) { + } else if (errId == QNetworkReply::ContentNotFoundError) { + if (_remoteFolder.isEmpty()) { error = tr("No remote folder specified!"); ok = false; } else { @@ -432,23 +433,23 @@ void OwncloudSetupWizard::slotRemoteFolderExists(QNetworkReply *reply) ok = false; } - if( !ok ) { + if (!ok) { _ocWizard->displayError(Utility::escape(error), false); } - finalizeSetup( ok ); + finalizeSetup(ok); } void OwncloudSetupWizard::createRemoteFolder() { - _ocWizard->appendToConfigurationLog( tr("creating folder on ownCloud: %1" ).arg( _remoteFolder )); + _ocWizard->appendToConfigurationLog(tr("creating folder on ownCloud: %1").arg(_remoteFolder)); MkColJob *job = new MkColJob(_ocWizard->account(), _remoteFolder, this); connect(job, SIGNAL(finished(QNetworkReply::NetworkError)), SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError))); job->start(); } -void OwncloudSetupWizard::slotCreateRemoteFolderFinished( QNetworkReply::NetworkError error ) +void OwncloudSetupWizard::slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error) { qCDebug(lcWizard) << "** webdav mkdir request finished " << error; // disconnect(ownCloudInfo::instance(), SIGNAL(webdavColCreated(QNetworkReply::NetworkError)), @@ -456,70 +457,73 @@ void OwncloudSetupWizard::slotCreateRemoteFolderFinished( QNetworkReply::Network bool success = true; - if( error == QNetworkReply::NoError ) { - _ocWizard->appendToConfigurationLog( tr("Remote folder %1 created successfully.").arg(_remoteFolder)); - } else if( error == 202 ) { - _ocWizard->appendToConfigurationLog( tr("The remote folder %1 already exists. Connecting it for syncing.").arg(_remoteFolder)); - } else if( error > 202 && error < 300 ) { - _ocWizard->displayError( tr("The folder creation resulted in HTTP error code %1").arg((int)error ), false); - - _ocWizard->appendToConfigurationLog( tr("The folder creation resulted in HTTP error code %1").arg((int)error) ); - } else if( error == QNetworkReply::OperationCanceledError ) { - _ocWizard->displayError( tr("The remote folder creation failed because the provided credentials " - "are wrong!" - "
Please go back and check your credentials.

"), false); - _ocWizard->appendToConfigurationLog( tr("

Remote folder creation failed probably because the provided credentials are wrong." - "
Please go back and check your credentials.

")); + if (error == QNetworkReply::NoError) { + _ocWizard->appendToConfigurationLog(tr("Remote folder %1 created successfully.").arg(_remoteFolder)); + } else if (error == 202) { + _ocWizard->appendToConfigurationLog(tr("The remote folder %1 already exists. Connecting it for syncing.").arg(_remoteFolder)); + } else if (error > 202 && error < 300) { + _ocWizard->displayError(tr("The folder creation resulted in HTTP error code %1").arg((int)error), false); + + _ocWizard->appendToConfigurationLog(tr("The folder creation resulted in HTTP error code %1").arg((int)error)); + } else if (error == QNetworkReply::OperationCanceledError) { + _ocWizard->displayError(tr("The remote folder creation failed because the provided credentials " + "are wrong!" + "
Please go back and check your credentials.

"), + false); + _ocWizard->appendToConfigurationLog(tr("

Remote folder creation failed probably because the provided credentials are wrong." + "
Please go back and check your credentials.

")); _remoteFolder.clear(); success = false; } else { - _ocWizard->appendToConfigurationLog( tr("Remote folder %1 creation failed with error %2.").arg(Utility::escape(_remoteFolder)).arg(error)); - _ocWizard->displayError( tr("Remote folder %1 creation failed with error %2.").arg(Utility::escape(_remoteFolder)).arg(error), false ); + _ocWizard->appendToConfigurationLog(tr("Remote folder %1 creation failed with error %2.").arg(Utility::escape(_remoteFolder)).arg(error)); + _ocWizard->displayError(tr("Remote folder %1 creation failed with error %2.").arg(Utility::escape(_remoteFolder)).arg(error), false); _remoteFolder.clear(); success = false; } - finalizeSetup( success ); + finalizeSetup(success); } -void OwncloudSetupWizard::finalizeSetup( bool success ) +void OwncloudSetupWizard::finalizeSetup(bool success) { // enable/disable the finish button. _ocWizard->enableFinishOnResultWidget(success); const QString localFolder = _ocWizard->property("localFolder").toString(); - if( success ) { - if( !(localFolder.isEmpty() || _remoteFolder.isEmpty() )) { + if (success) { + if (!(localFolder.isEmpty() || _remoteFolder.isEmpty())) { _ocWizard->appendToConfigurationLog( tr("A sync connection from %1 to remote directory %2 was set up.") .arg(localFolder, _remoteFolder)); } - _ocWizard->appendToConfigurationLog( QLatin1String(" ")); - _ocWizard->appendToConfigurationLog( QLatin1String("

") - + tr("Successfully connected to %1!") - .arg(Theme::instance()->appNameGUI()) - + QLatin1String("

")); + _ocWizard->appendToConfigurationLog(QLatin1String(" ")); + _ocWizard->appendToConfigurationLog(QLatin1String("

") + + tr("Successfully connected to %1!") + .arg(Theme::instance()->appNameGUI()) + + QLatin1String("

")); _ocWizard->successfulStep(); } else { // ### this is not quite true, pass in the real problem as optional parameter _ocWizard->appendToConfigurationLog(QLatin1String("

") - + tr("Connection to %1 could not be established. Please check again.") - .arg(Theme::instance()->appNameGUI()) - + QLatin1String("

")); + + tr("Connection to %1 could not be established. Please check again.") + .arg(Theme::instance()->appNameGUI()) + + QLatin1String("

")); } } -bool OwncloudSetupWizard::ensureStartFromScratch(const QString &localFolder) { +bool OwncloudSetupWizard::ensureStartFromScratch(const QString &localFolder) +{ // first try to rename (backup) the current local dir. bool renameOk = false; - while( !renameOk ) { + while (!renameOk) { renameOk = FolderMan::instance()->startFromScratch(localFolder); - if( ! renameOk ) { + if (!renameOk) { QMessageBox::StandardButton but; - but = QMessageBox::question( 0, tr("Folder rename failed"), - tr("Can't remove and back up the folder because the folder or a file in it is open in another program." - " Please close the folder or file and hit retry or cancel the setup."), QMessageBox::Retry | QMessageBox::Abort, QMessageBox::Retry); - if( but == QMessageBox::Abort ) { + but = QMessageBox::question(0, tr("Folder rename failed"), + tr("Can't remove and back up the folder because the folder or a file in it is open in another program." + " Please close the folder or file and hit retry or cancel the setup."), + QMessageBox::Retry | QMessageBox::Abort, QMessageBox::Retry); + if (but == QMessageBox::Abort) { break; } } @@ -528,14 +532,14 @@ bool OwncloudSetupWizard::ensureStartFromScratch(const QString &localFolder) { } // Method executed when the user end has finished the basic setup. -void OwncloudSetupWizard::slotAssistantFinished( int result ) +void OwncloudSetupWizard::slotAssistantFinished(int result) { FolderMan *folderMan = FolderMan::instance(); - if( result == QDialog::Rejected ) { + if (result == QDialog::Rejected) { qCInfo(lcWizard) << "Rejected the new config, use the old!"; - } else if( result == QDialog::Accepted ) { + } else if (result == QDialog::Accepted) { // This may or may not wipe all folder definitions, depending // on whether a new account is activated or the existing one // is changed. @@ -554,11 +558,11 @@ void OwncloudSetupWizard::slotAssistantFinished( int result ) auto f = folderMan->addFolder(account, folderDefinition); if (f) { f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, - _ocWizard->selectiveSyncBlacklist()); + _ocWizard->selectiveSyncBlacklist()); if (!_ocWizard->isConfirmBigFolderChecked()) { // The user already accepted the selective sync dialog. everything is in the white list f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, - QStringList() << QLatin1String("/")); + QStringList() << QLatin1String("/")); } } _ocWizard->appendToConfigurationLog(tr("Local sync folder %1 successfully created!").arg(localFolder)); @@ -566,17 +570,17 @@ void OwncloudSetupWizard::slotAssistantFinished( int result ) } // notify others. - emit ownCloudWizardDone( result ); + emit ownCloudWizardDone(result); } void OwncloudSetupWizard::slotSkipFolderConfiguration() { applyAccountChanges(); - disconnect( _ocWizard, SIGNAL(basicSetupFinished(int)), - this, SLOT(slotAssistantFinished(int)) ); + disconnect(_ocWizard, SIGNAL(basicSetupFinished(int)), + this, SLOT(slotAssistantFinished(int))); _ocWizard->close(); - emit ownCloudWizardDone( QDialog::Accepted ); + emit ownCloudWizardDone(QDialog::Accepted); } AccountState *OwncloudSetupWizard::applyAccountChanges() diff --git a/src/gui/owncloudsetupwizard.h b/src/gui/owncloudsetupwizard.h index d26fb9cdc..39f401db6 100644 --- a/src/gui/owncloudsetupwizard.h +++ b/src/gui/owncloudsetupwizard.h @@ -37,7 +37,8 @@ class OwncloudWizard; * @brief The DetermineAuthTypeJob class * @ingroup gui */ -class DetermineAuthTypeJob : public AbstractNetworkJob { +class DetermineAuthTypeJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit DetermineAuthTypeJob(AccountPtr account, QObject *parent = 0); @@ -46,6 +47,7 @@ signals: void authType(WizardCommon::AuthType); private slots: bool finished() Q_DECL_OVERRIDE; + private: int _redirects; }; @@ -59,45 +61,44 @@ class OwncloudSetupWizard : public QObject Q_OBJECT public: /** Run the wizard */ - static void runWizard(QObject *obj, const char* amember, QWidget *parent = 0 ); + static void runWizard(QObject *obj, const char *amember, QWidget *parent = 0); static bool bringWizardToFrontIfVisible(); signals: // overall dialog close signal. - void ownCloudWizardDone( int ); + void ownCloudWizardDone(int); private slots: - void slotDetermineAuthType(const QString&); + void slotDetermineAuthType(const QString &); void slotSystemProxyLookupDone(const QNetworkProxy &proxy); void slotContinueDetermineAuth(); - void slotOwnCloudFoundAuth(const QUrl&, const QJsonObject&); + void slotOwnCloudFoundAuth(const QUrl &, const QJsonObject &); void slotNoOwnCloudFoundAuth(QNetworkReply *reply); - void slotNoOwnCloudFoundAuthTimeout(const QUrl&url); + void slotNoOwnCloudFoundAuthTimeout(const QUrl &url); - void slotConnectToOCUrl(const QString&); + void slotConnectToOCUrl(const QString &); void slotAuthError(); - void slotCreateLocalAndRemoteFolders(const QString&, const QString&); - void slotRemoteFolderExists(QNetworkReply*); + void slotCreateLocalAndRemoteFolders(const QString &, const QString &); + void slotRemoteFolderExists(QNetworkReply *); void slotCreateRemoteFolderFinished(QNetworkReply::NetworkError); - void slotAssistantFinished( int ); + void slotAssistantFinished(int); void slotSkipFolderConfiguration(); private: - explicit OwncloudSetupWizard(QObject *parent = 0 ); + explicit OwncloudSetupWizard(QObject *parent = 0); ~OwncloudSetupWizard(); void startWizard(); void testOwnCloudConnect(); void createRemoteFolder(); - void finalizeSetup( bool ); + void finalizeSetup(bool); bool ensureStartFromScratch(const QString &localFolder); AccountState *applyAccountChanges(); - bool checkDowngradeAdvised(QNetworkReply* reply); + bool checkDowngradeAdvised(QNetworkReply *reply); - OwncloudWizard* _ocWizard; + OwncloudWizard *_ocWizard; QString _initLocalFolder; QString _remoteFolder; }; - } #endif // OWNCLOUDSETUPWIZARD_H diff --git a/src/gui/protocolwidget.cpp b/src/gui/protocolwidget.cpp index 8828d2fd6..9d7058dd8 100644 --- a/src/gui/protocolwidget.cpp +++ b/src/gui/protocolwidget.cpp @@ -35,19 +35,19 @@ namespace OCC { -ProtocolWidget::ProtocolWidget(QWidget *parent) : - QWidget(parent), - IgnoredIndicatorRole( Qt::UserRole +1 ), - _ui(new Ui::ProtocolWidget) +ProtocolWidget::ProtocolWidget(QWidget *parent) + : QWidget(parent) + , IgnoredIndicatorRole(Qt::UserRole + 1) + , _ui(new Ui::ProtocolWidget) { _ui->setupUi(this); - connect(ProgressDispatcher::instance(), SIGNAL(progressInfo(QString,ProgressInfo)), - this, SLOT(slotProgressInfo(QString,ProgressInfo))); - connect(ProgressDispatcher::instance(), SIGNAL(itemCompleted(QString,SyncFileItemPtr)), - this, SLOT(slotItemCompleted(QString,SyncFileItemPtr))); + connect(ProgressDispatcher::instance(), SIGNAL(progressInfo(QString, ProgressInfo)), + this, SLOT(slotProgressInfo(QString, ProgressInfo))); + connect(ProgressDispatcher::instance(), SIGNAL(itemCompleted(QString, SyncFileItemPtr)), + this, SLOT(slotItemCompleted(QString, SyncFileItemPtr))); - connect(_ui->_treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)), SLOT(slotOpenFile(QTreeWidgetItem*,int))); + connect(_ui->_treeWidget, SIGNAL(itemActivated(QTreeWidgetItem *, int)), SLOT(slotOpenFile(QTreeWidgetItem *, int))); // Adjust copyToClipboard() when making changes here! QStringList header; @@ -62,7 +62,7 @@ ProtocolWidget::ProtocolWidget(QWidget *parent) : timestampColumnExtra = 20; // font metrics are broken on Windows, see #4721 #endif - _ui->_treeWidget->setHeaderLabels( header ); + _ui->_treeWidget->setHeaderLabels(header); int timestampColumnWidth = _ui->_treeWidget->fontMetrics().width(timeString(QDateTime::currentDateTime())) + timestampColumnExtra; @@ -78,7 +78,7 @@ ProtocolWidget::ProtocolWidget(QWidget *parent) : _ui->_headerLabel->setText(tr("Local sync protocol")); QPushButton *copyBtn = _ui->_dialogButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole); - copyBtn->setToolTip( tr("Copy the activity list to the clipboard.")); + copyBtn->setToolTip(tr("Copy the activity list to the clipboard.")); copyBtn->setEnabled(true); connect(copyBtn, SIGNAL(clicked()), SIGNAL(copyToClipboard())); @@ -87,19 +87,19 @@ ProtocolWidget::ProtocolWidget(QWidget *parent) : // be embedded into another gui element. _issueItemView = new QTreeWidget(this); header.removeLast(); - _issueItemView->setHeaderLabels( header ); + _issueItemView->setHeaderLabels(header); timestampColumnWidth = - ActivityItemDelegate::rowHeight() // icon - + _issueItemView->fontMetrics().width(timeString(QDateTime::currentDateTime())) - + timestampColumnExtra; + ActivityItemDelegate::rowHeight() // icon + + _issueItemView->fontMetrics().width(timeString(QDateTime::currentDateTime())) + + timestampColumnExtra; _issueItemView->setColumnWidth(0, timestampColumnWidth); _issueItemView->setColumnWidth(1, 180); _issueItemView->setColumnCount(4); _issueItemView->setRootIsDecorated(false); _issueItemView->setTextElideMode(Qt::ElideMiddle); _issueItemView->header()->setObjectName("ActivityErrorListHeader"); - connect(_issueItemView, SIGNAL(itemActivated(QTreeWidgetItem*,int)), - SLOT(slotOpenFile(QTreeWidgetItem*,int))); + connect(_issueItemView, SIGNAL(itemActivated(QTreeWidgetItem *, int)), + SLOT(slotOpenFile(QTreeWidgetItem *, int))); } ProtocolWidget::~ProtocolWidget() @@ -117,24 +117,24 @@ void ProtocolWidget::showEvent(QShowEvent *ev) void ProtocolWidget::hideEvent(QHideEvent *ev) { ConfigFile cfg; - cfg.saveGeometryHeader(_ui->_treeWidget->header() ); + cfg.saveGeometryHeader(_ui->_treeWidget->header()); QWidget::hideEvent(ev); } -void ProtocolWidget::cleanItems(const QString& folder) +void ProtocolWidget::cleanItems(const QString &folder) { // The issue list is a state, clear it and let the next sync fill it // with ignored files and propagation errors. int itemCnt = _issueItemView->topLevelItemCount(); - for( int cnt = itemCnt-1; cnt >=0 ; cnt-- ) { + for (int cnt = itemCnt - 1; cnt >= 0; cnt--) { QTreeWidgetItem *item = _issueItemView->topLevelItem(cnt); QString itemFolder = item->data(2, Qt::UserRole).toString(); - if( itemFolder == folder ) { + if (itemFolder == folder) { delete item; } } // update the tabtext - emit( issueItemCountUpdated(_issueItemView->topLevelItemCount()) ); + emit(issueItemCountUpdated(_issueItemView->topLevelItemCount())); } QString ProtocolWidget::timeString(QDateTime dt, QLocale::FormatType format) const @@ -146,7 +146,7 @@ QString ProtocolWidget::timeString(QDateTime dt, QLocale::FormatType format) con return loc.toString(dt, dtFormat); } -void ProtocolWidget::slotOpenFile( QTreeWidgetItem *item, int ) +void ProtocolWidget::slotOpenFile(QTreeWidgetItem *item, int) { QString folderName = item->data(2, Qt::UserRole).toString(); QString fileName = item->text(1); @@ -161,7 +161,7 @@ void ProtocolWidget::slotOpenFile( QTreeWidgetItem *item, int ) } } -QTreeWidgetItem* ProtocolWidget::createCompletedTreewidgetItem(const QString& folder, const SyncFileItem& item) +QTreeWidgetItem *ProtocolWidget::createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item) { auto f = FolderMan::instance()->folder(folder); if (!f) { @@ -186,14 +186,14 @@ QTreeWidgetItem* ProtocolWidget::createCompletedTreewidgetItem(const QString& fo QIcon icon; if (item._status == SyncFileItem::NormalError - || item._status == SyncFileItem::FatalError) { + || item._status == SyncFileItem::FatalError) { icon = Theme::instance()->syncStateIcon(SyncResult::Error); } else if (Progress::isWarningKind(item._status)) { icon = Theme::instance()->syncStateIcon(SyncResult::Problem); } if (ProgressInfo::isSizeDependent(item)) { - columns << Utility::octetsToString( item._size ); + columns << Utility::octetsToString(item._size); } QTreeWidgetItem *twitem = new QTreeWidgetItem(columns); @@ -206,14 +206,14 @@ QTreeWidgetItem* ProtocolWidget::createCompletedTreewidgetItem(const QString& fo twitem->setIcon(0, icon); twitem->setToolTip(0, longTimeStr); twitem->setToolTip(1, item._file); - twitem->setToolTip(3, message ); - twitem->setData(2, Qt::UserRole, folder); + twitem->setToolTip(3, message); + twitem->setData(2, Qt::UserRole, folder); return twitem; } -void ProtocolWidget::slotProgressInfo( const QString& folder, const ProgressInfo& progress ) +void ProtocolWidget::slotProgressInfo(const QString &folder, const ProgressInfo &progress) { - if( !progress.isUpdatingEstimates() ) { + if (!progress.isUpdatingEstimates()) { // The sync is restarting, clean the old items cleanItems(folder); } else if (progress.completedFiles() >= progress.totalFiles()) { @@ -224,14 +224,14 @@ void ProtocolWidget::slotProgressInfo( const QString& folder, const ProgressInfo void ProtocolWidget::slotItemCompleted(const QString &folder, const SyncFileItemPtr &item) { QTreeWidgetItem *line = createCompletedTreewidgetItem(folder, *item); - if(line) { - if( item->hasErrorStatus() ) { + if (line) { + if (item->hasErrorStatus()) { _issueItemView->insertTopLevelItem(0, line); emit issueItemCountUpdated(_issueItemView->topLevelItemCount()); } else { // Limit the number of items int itemCnt = _ui->_treeWidget->topLevelItemCount(); - while(itemCnt > 2000) { + while (itemCnt > 2000) { delete _ui->_treeWidget->takeTopLevelItem(itemCnt - 1); itemCnt--; } @@ -241,38 +241,38 @@ void ProtocolWidget::slotItemCompleted(const QString &folder, const SyncFileItem } -void ProtocolWidget::storeSyncActivity(QTextStream& ts) +void ProtocolWidget::storeSyncActivity(QTextStream &ts) { int topLevelItems = _ui->_treeWidget->topLevelItemCount(); for (int i = 0; i < topLevelItems; i++) { QTreeWidgetItem *child = _ui->_treeWidget->topLevelItem(i); ts << right - // time stamp + // time stamp << qSetFieldWidth(20) - << child->data(0,Qt::DisplayRole).toString() - // separator + << child->data(0, Qt::DisplayRole).toString() + // separator << qSetFieldWidth(0) << "," - // file name + // file name << qSetFieldWidth(64) - << child->data(1,Qt::DisplayRole).toString() - // separator + << child->data(1, Qt::DisplayRole).toString() + // separator << qSetFieldWidth(0) << "," - // folder + // folder << qSetFieldWidth(30) << child->data(2, Qt::DisplayRole).toString() - // separator + // separator << qSetFieldWidth(0) << "," - // action + // action << qSetFieldWidth(15) << child->data(3, Qt::DisplayRole).toString() - // separator + // separator << qSetFieldWidth(0) << "," - // size + // size << qSetFieldWidth(10) << child->data(4, Qt::DisplayRole).toString() << qSetFieldWidth(0) @@ -280,37 +280,36 @@ void ProtocolWidget::storeSyncActivity(QTextStream& ts) } } -void ProtocolWidget::storeSyncIssues(QTextStream& ts) +void ProtocolWidget::storeSyncIssues(QTextStream &ts) { int topLevelItems = _issueItemView->topLevelItemCount(); for (int i = 0; i < topLevelItems; i++) { QTreeWidgetItem *child = _issueItemView->topLevelItem(i); ts << right - // time stamp + // time stamp << qSetFieldWidth(20) - << child->data(0,Qt::DisplayRole).toString() - // separator + << child->data(0, Qt::DisplayRole).toString() + // separator << qSetFieldWidth(0) << "," - // file name + // file name << qSetFieldWidth(64) - << child->data(1,Qt::DisplayRole).toString() - // separator + << child->data(1, Qt::DisplayRole).toString() + // separator << qSetFieldWidth(0) << "," - // folder + // folder << qSetFieldWidth(30) << child->data(2, Qt::DisplayRole).toString() - // separator + // separator << qSetFieldWidth(0) << "," - // action + // action << qSetFieldWidth(15) << child->data(3, Qt::DisplayRole).toString() << qSetFieldWidth(0) << endl; } } - } diff --git a/src/gui/protocolwidget.h b/src/gui/protocolwidget.h index de11bdcd0..927a23c4b 100644 --- a/src/gui/protocolwidget.h +++ b/src/gui/protocolwidget.h @@ -30,7 +30,7 @@ namespace OCC { class SyncResult; namespace Ui { - class ProtocolWidget; + class ProtocolWidget; } class Application; @@ -47,13 +47,13 @@ public: QSize sizeHint() const { return ownCloudGui::settingsDialogSize(); } QTreeWidget *issueWidget() { return _issueItemView; } - void storeSyncActivity(QTextStream& ts); - void storeSyncIssues(QTextStream& ts); + void storeSyncActivity(QTextStream &ts); + void storeSyncIssues(QTextStream &ts); public slots: - void slotProgressInfo( const QString& folder, const ProgressInfo& progress ); - void slotItemCompleted( const QString& folder, const SyncFileItemPtr& item); - void slotOpenFile( QTreeWidgetItem* item, int ); + void slotProgressInfo(const QString &folder, const ProgressInfo &progress); + void slotItemCompleted(const QString &folder, const SyncFileItemPtr &item); + void slotOpenFile(QTreeWidgetItem *item, int); protected: void showEvent(QShowEvent *); @@ -64,10 +64,10 @@ signals: void issueItemCountUpdated(int); private: - void setSyncResultStatus(const SyncResult& result ); - void cleanItems( const QString& folder ); + void setSyncResultStatus(const SyncResult &result); + void cleanItems(const QString &folder); - QTreeWidgetItem* createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item ); + QTreeWidgetItem *createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item); QString timeString(QDateTime dt, QLocale::FormatType format = QLocale::NarrowFormat) const; @@ -75,6 +75,5 @@ private: Ui::ProtocolWidget *_ui; QTreeWidget *_issueItemView; }; - } #endif // PROTOCOLWIDGET_H diff --git a/src/gui/proxyauthdialog.cpp b/src/gui/proxyauthdialog.cpp index 044d8c9f2..c5680bb7e 100644 --- a/src/gui/proxyauthdialog.cpp +++ b/src/gui/proxyauthdialog.cpp @@ -17,9 +17,9 @@ namespace OCC { -ProxyAuthDialog::ProxyAuthDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::ProxyAuthDialog) +ProxyAuthDialog::ProxyAuthDialog(QWidget *parent) + : QDialog(parent) + , ui(new Ui::ProxyAuthDialog) { ui->setupUi(this); } diff --git a/src/gui/proxyauthdialog.h b/src/gui/proxyauthdialog.h index 5b6f27d03..5a6e7bd4c 100644 --- a/src/gui/proxyauthdialog.h +++ b/src/gui/proxyauthdialog.h @@ -20,7 +20,7 @@ namespace OCC { namespace Ui { -class ProxyAuthDialog; + class ProxyAuthDialog; } /** @@ -36,7 +36,7 @@ public: explicit ProxyAuthDialog(QWidget *parent = 0); ~ProxyAuthDialog(); - void setProxyAddress(const QString& address); + void setProxyAddress(const QString &address); QString username() const; QString password() const; diff --git a/src/gui/proxyauthhandler.cpp b/src/gui/proxyauthhandler.cpp index 479b3f224..5b7d7382d 100644 --- a/src/gui/proxyauthhandler.cpp +++ b/src/gui/proxyauthhandler.cpp @@ -27,7 +27,7 @@ using namespace OCC; Q_LOGGING_CATEGORY(lcProxy, "gui.credentials.proxy", QtInfoMsg) -ProxyAuthHandler* ProxyAuthHandler::instance() +ProxyAuthHandler *ProxyAuthHandler::instance() { static ProxyAuthHandler inst; return &inst; @@ -53,8 +53,8 @@ ProxyAuthHandler::~ProxyAuthHandler() } void ProxyAuthHandler::handleProxyAuthenticationRequired( - const QNetworkProxy& proxy, - QAuthenticator* authenticator) + const QNetworkProxy &proxy, + QAuthenticator *authenticator) { if (!_dialog) { return; @@ -73,7 +73,7 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired( // If the user explicitly configured the proxy in the // network settings, don't ask about it. if (_configFile->proxyType() == QNetworkProxy::HttpProxy - || _configFile->proxyType() == QNetworkProxy::Socks5Proxy) { + || _configFile->proxyType() == QNetworkProxy::Socks5Proxy) { _blocked = true; } } @@ -83,9 +83,9 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired( } // Find the responsible QNAM if possible. - QNetworkAccessManager* sending_qnam = 0; + QNetworkAccessManager *sending_qnam = 0; QWeakPointer qnam_alive; - if (Account* account = qobject_cast(sender())) { + if (Account *account = qobject_cast(sender())) { // Since we go into an event loop, it's possible for the account's qnam // to be destroyed before we get back. We can use this to check for its // liveness. @@ -104,9 +104,8 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired( // isn't reliable, so we also invalidate credentials if we previously // gave presumably valid credentials to the same QNAM. bool invalidated = false; - if (!_waitingForDialog && !_waitingForKeychain && - (!authenticator->user().isEmpty() - || (sending_qnam && _gaveCredentialsTo.contains(sending_qnam)))) { + if (!_waitingForDialog && !_waitingForKeychain && (!authenticator->user().isEmpty() + || (sending_qnam && _gaveCredentialsTo.contains(sending_qnam)))) { qCInfo(lcProxy) << "invalidating old creds" << key; _username.clear(); _password.clear(); @@ -132,8 +131,8 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired( sending_qnam = qnam_alive.data(); if (sending_qnam) { _gaveCredentialsTo.insert(sending_qnam); - connect(sending_qnam, SIGNAL(destroyed(QObject*)), - SLOT(slotSenderDestroyed(QObject*))); + connect(sending_qnam, SIGNAL(destroyed(QObject *)), + SLOT(slotSenderDestroyed(QObject *))); } } @@ -142,7 +141,7 @@ void ProxyAuthHandler::slotKeychainJobDone() _keychainJobRunning = false; } -void ProxyAuthHandler::slotSenderDestroyed(QObject* obj) +void ProxyAuthHandler::slotSenderDestroyed(QObject *obj) { _gaveCredentialsTo.remove(obj); } @@ -195,8 +194,8 @@ bool ProxyAuthHandler::getCredsFromKeychain() _readPasswordJob->setInsecureFallback(false); _readPasswordJob->setKey(keychainPasswordKey()); _readPasswordJob->setAutoDelete(false); - connect(_readPasswordJob.data(), SIGNAL(finished(QKeychain::Job*)), - SLOT(slotKeychainJobDone())); + connect(_readPasswordJob.data(), SIGNAL(finished(QKeychain::Job *)), + SLOT(slotKeychainJobDone())); _keychainJobRunning = true; _readPasswordJob->start(); } @@ -237,13 +236,13 @@ void ProxyAuthHandler::storeCredsInKeychain() _settings->setValue(keychainUsernameKey(), _username); - WritePasswordJob* job = new WritePasswordJob(Theme::instance()->appName(), this); + WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName(), this); job->setSettings(_settings.data()); job->setInsecureFallback(false); job->setKey(keychainPasswordKey()); job->setTextData(_password); job->setAutoDelete(false); - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotKeychainJobDone())); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotKeychainJobDone())); _keychainJobRunning = true; job->start(); diff --git a/src/gui/proxyauthhandler.h b/src/gui/proxyauthhandler.h index b1fc3d0f8..3d5afedd3 100644 --- a/src/gui/proxyauthhandler.h +++ b/src/gui/proxyauthhandler.h @@ -47,18 +47,18 @@ class ProxyAuthHandler : public QObject Q_OBJECT public: - static ProxyAuthHandler* instance(); + static ProxyAuthHandler *instance(); virtual ~ProxyAuthHandler(); public slots: /// Intended for QNetworkAccessManager::proxyAuthenticationRequired() - void handleProxyAuthenticationRequired(const QNetworkProxy& proxy, - QAuthenticator* authenticator); + void handleProxyAuthenticationRequired(const QNetworkProxy &proxy, + QAuthenticator *authenticator); private slots: void slotKeychainJobDone(); - void slotSenderDestroyed(QObject*); + void slotSenderDestroyed(QObject *); private: ProxyAuthHandler(); @@ -107,7 +107,7 @@ private: /// To distinguish between a new QNAM asking for credentials and credentials /// failing for an existing QNAM, we keep track of the senders of the /// proxyAuthRequired signal here. - QSet _gaveCredentialsTo; + QSet _gaveCredentialsTo; }; } // namespace OCC diff --git a/src/gui/quotainfo.cpp b/src/gui/quotainfo.cpp index f2ccb2c55..1eb1066cc 100644 --- a/src/gui/quotainfo.cpp +++ b/src/gui/quotainfo.cpp @@ -25,8 +25,8 @@ namespace OCC { namespace { -static const int defaultIntervalT = 30*1000; -static const int failIntervalT = 5*1000; + static const int defaultIntervalT = 30 * 1000; + static const int failIntervalT = 5 * 1000; } QuotaInfo::QuotaInfo(AccountState *accountState, QObject *parent) @@ -37,7 +37,7 @@ QuotaInfo::QuotaInfo(AccountState *accountState, QObject *parent) , _active(false) { connect(accountState, SIGNAL(stateChanged(int)), - SLOT(slotAccountStateChanged())); + SLOT(slotAccountStateChanged())); connect(&_jobRestartTimer, SIGNAL(timeout()), SLOT(slotCheckQuota())); _jobRestartTimer.setSingleShot(true); } @@ -72,7 +72,7 @@ void QuotaInfo::slotRequestFailed() bool QuotaInfo::canGetQuota() const { - if (! _accountState || !_active) { + if (!_accountState || !_active) { return false; } AccountPtr account = _accountState->account(); @@ -88,7 +88,7 @@ QString QuotaInfo::quotaBaseFolder() const void QuotaInfo::slotCheckQuota() { - if (! canGetQuota()) { + if (!canGetQuota()) { return; } @@ -99,9 +99,10 @@ void QuotaInfo::slotCheckQuota() AccountPtr account = _accountState->account(); _job = new PropfindJob(account, quotaBaseFolder(), this); - _job->setProperties(QList() << "quota-available-bytes" << "quota-used-bytes"); + _job->setProperties(QList() << "quota-available-bytes" + << "quota-used-bytes"); connect(_job, SIGNAL(result(QVariantMap)), SLOT(slotUpdateLastQuota(QVariantMap))); - connect(_job, SIGNAL(networkError(QNetworkReply*)), SLOT(slotRequestFailed())); + connect(_job, SIGNAL(networkError(QNetworkReply *)), SLOT(slotRequestFailed())); _job->start(); } @@ -117,5 +118,4 @@ void QuotaInfo::slotUpdateLastQuota(const QVariantMap &result) _jobRestartTimer.start(defaultIntervalT); _lastQuotaRecieved = QDateTime::currentDateTime(); } - } diff --git a/src/gui/quotainfo.h b/src/gui/quotainfo.h index 90725e081..4fef65a95 100644 --- a/src/gui/quotainfo.h +++ b/src/gui/quotainfo.h @@ -43,10 +43,11 @@ class PropfindJob; * * @ingroup gui */ -class QuotaInfo : public QObject { +class QuotaInfo : public QObject +{ Q_OBJECT public: - explicit QuotaInfo(OCC::AccountState* accountState, QObject* parent = 0); + explicit QuotaInfo(OCC::AccountState *accountState, QObject *parent = 0); qint64 lastQuotaTotalBytes() const { return _lastQuotaTotalBytes; } qint64 lastQuotaUsedBytes() const { return _lastQuotaUsedBytes; } @@ -85,7 +86,6 @@ private: }; - } // namespace OCC #endif //QUOTAINFO_H diff --git a/src/gui/selectivesyncdialog.cpp b/src/gui/selectivesyncdialog.cpp index c10331723..1663ca481 100644 --- a/src/gui/selectivesyncdialog.cpp +++ b/src/gui/selectivesyncdialog.cpp @@ -34,24 +34,34 @@ namespace OCC { -class SelectiveSyncTreeViewItem : public QTreeWidgetItem { +class SelectiveSyncTreeViewItem : public QTreeWidgetItem +{ public: SelectiveSyncTreeViewItem(int type = QTreeWidgetItem::Type) - : QTreeWidgetItem(type) { } + : QTreeWidgetItem(type) + { + } SelectiveSyncTreeViewItem(const QStringList &strings, int type = QTreeWidgetItem::Type) - : QTreeWidgetItem(strings, type) { } + : QTreeWidgetItem(strings, type) + { + } SelectiveSyncTreeViewItem(QTreeWidget *view, int type = QTreeWidgetItem::Type) - : QTreeWidgetItem(view, type) { } + : QTreeWidgetItem(view, type) + { + } SelectiveSyncTreeViewItem(QTreeWidgetItem *parent, int type = QTreeWidgetItem::Type) - : QTreeWidgetItem(parent, type) { } + : QTreeWidgetItem(parent, type) + { + } private: - bool operator<(const QTreeWidgetItem &other)const { + bool operator<(const QTreeWidgetItem &other) const + { int column = treeWidget()->sortColumn(); if (column == 1) { return data(1, Qt::UserRole).toLongLong() < other.data(1, Qt::UserRole).toLongLong(); } - return QTreeWidgetItem::operator <(other); + return QTreeWidgetItem::operator<(other); } }; @@ -73,10 +83,10 @@ SelectiveSyncWidget::SelectiveSyncWidget(AccountPtr account, QWidget *parent) layout->addWidget(_folderTree); - connect(_folderTree, SIGNAL(itemExpanded(QTreeWidgetItem*)), - SLOT(slotItemExpanded(QTreeWidgetItem*))); - connect(_folderTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)), - SLOT(slotItemChanged(QTreeWidgetItem*,int))); + connect(_folderTree, SIGNAL(itemExpanded(QTreeWidgetItem *)), + SLOT(slotItemExpanded(QTreeWidgetItem *))); + connect(_folderTree, SIGNAL(itemChanged(QTreeWidgetItem *, int)), + SLOT(slotItemChanged(QTreeWidgetItem *, int))); _folderTree->setSortingEnabled(true); _folderTree->sortByColumn(0, Qt::AscendingOrder); _folderTree->setColumnCount(2); @@ -84,7 +94,7 @@ SelectiveSyncWidget::SelectiveSyncWidget(AccountPtr account, QWidget *parent) _folderTree->header()->setSectionResizeMode(0, QHeaderView::QHeaderView::ResizeToContents); _folderTree->header()->setSectionResizeMode(1, QHeaderView::QHeaderView::ResizeToContents); #else - _folderTree->header()->resizeSection(0, sizeHint().width()/2); + _folderTree->header()->resizeSection(0, sizeHint().width() / 2); #endif _folderTree->header()->setStretchLastSection(true); _folderTree->headerItem()->setText(0, tr("Name")); @@ -99,18 +109,19 @@ QSize SelectiveSyncWidget::sizeHint() const void SelectiveSyncWidget::refreshFolders() { LsColJob *job = new LsColJob(_account, _folderPath, this); - job->setProperties(QList() << "resourcetype" << "http://owncloud.org/ns:size"); + job->setProperties(QList() << "resourcetype" + << "http://owncloud.org/ns:size"); connect(job, SIGNAL(directoryListingSubfolders(QStringList)), - this, SLOT(slotUpdateDirectories(QStringList))); - connect(job, SIGNAL(finishedWithError(QNetworkReply*)), - this, SLOT(slotLscolFinishedWithError(QNetworkReply*))); + this, SLOT(slotUpdateDirectories(QStringList))); + connect(job, SIGNAL(finishedWithError(QNetworkReply *)), + this, SLOT(slotLscolFinishedWithError(QNetworkReply *))); job->start(); _folderTree->clear(); _loading->show(); _loading->move(10, _folderTree->header()->height() + 10); } -void SelectiveSyncWidget::setFolderInfo(const QString& folderPath, const QString& rootName, const QStringList& oldBlackList) +void SelectiveSyncWidget::setFolderInfo(const QString &folderPath, const QString &rootName, const QStringList &oldBlackList) { _folderPath = folderPath; if (_folderPath.startsWith(QLatin1Char('/'))) { @@ -122,7 +133,7 @@ void SelectiveSyncWidget::setFolderInfo(const QString& folderPath, const QString refreshFolders(); } -static QTreeWidgetItem* findFirstChild(QTreeWidgetItem *parent, const QString& text) +static QTreeWidgetItem *findFirstChild(QTreeWidgetItem *parent, const QString &text) { for (int i = 0; i < parent->childCount(); ++i) { QTreeWidgetItem *child = parent->child(i); @@ -133,7 +144,7 @@ static QTreeWidgetItem* findFirstChild(QTreeWidgetItem *parent, const QString& t return 0; } -void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem* parent, QStringList pathTrail, QString path, qint64 size) +void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path, qint64 size) { QFileIconProvider prov; QIcon folderIcon = prov.icon(QFileIconProvider::Folder); @@ -144,13 +155,13 @@ void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem* parent, QStringList p parent->setToolTip(0, path); parent->setData(0, Qt::UserRole, path); } else { - SelectiveSyncTreeViewItem *item = static_cast(findFirstChild(parent, pathTrail.first())); + SelectiveSyncTreeViewItem *item = static_cast(findFirstChild(parent, pathTrail.first())); if (!item) { item = new SelectiveSyncTreeViewItem(parent); if (parent->checkState(0) == Qt::Checked - || parent->checkState(0) == Qt::PartiallyChecked) { + || parent->checkState(0) == Qt::PartiallyChecked) { item->setCheckState(0, Qt::Checked); - foreach(const QString &str , _oldBlackList) { + foreach (const QString &str, _oldBlackList) { if (str == path || str == QLatin1String("/")) { item->setCheckState(0, Qt::Unchecked); break; @@ -167,7 +178,7 @@ void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem* parent, QStringList p item->setText(1, Utility::octetsToString(size)); item->setData(1, Qt::UserRole, size); } -// item->setData(0, Qt::UserRole, pathTrail.first()); + // item->setData(0, Qt::UserRole, pathTrail.first()); item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator); } @@ -182,7 +193,7 @@ void SelectiveSyncWidget::slotUpdateDirectories(QStringList list) QScopedValueRollback isInserting(_inserting); _inserting = true; - SelectiveSyncTreeViewItem *root = static_cast(_folderTree->topLevelItem(0)); + SelectiveSyncTreeViewItem *root = static_cast(_folderTree->topLevelItem(0)); QUrl url = _account->davUrl(); QString pathToRemove = url.path(); @@ -240,7 +251,8 @@ void SelectiveSyncWidget::slotUpdateDirectories(QStringList list) auto size = job ? job->_sizes.value(path) : 0; path.remove(pathToRemove); QStringList paths = path.split('/'); - if (paths.last().isEmpty()) paths.removeLast(); + if (paths.last().isEmpty()) + paths.removeLast(); if (paths.isEmpty()) continue; if (!path.endsWith('/')) { @@ -274,15 +286,17 @@ void SelectiveSyncWidget::slotLscolFinishedWithError(QNetworkReply *r) void SelectiveSyncWidget::slotItemExpanded(QTreeWidgetItem *item) { QString dir = item->data(0, Qt::UserRole).toString(); - if (dir.isEmpty()) return; + if (dir.isEmpty()) + return; QString prefix; if (!_folderPath.isEmpty()) { prefix = _folderPath + QLatin1Char('/'); } LsColJob *job = new LsColJob(_account, prefix + dir, this); - job->setProperties(QList() << "resourcetype" << "http://owncloud.org/ns:size"); + job->setProperties(QList() << "resourcetype" + << "http://owncloud.org/ns:size"); connect(job, SIGNAL(directoryListingSubfolders(QStringList)), - SLOT(slotUpdateDirectories(QStringList))); + SLOT(slotUpdateDirectories(QStringList))); job->start(); } @@ -344,17 +358,18 @@ void SelectiveSyncWidget::slotItemChanged(QTreeWidgetItem *item, int col) } } -QStringList SelectiveSyncWidget::createBlackList(QTreeWidgetItem* root) const +QStringList SelectiveSyncWidget::createBlackList(QTreeWidgetItem *root) const { if (!root) { root = _folderTree->topLevelItem(0); } - if (!root) return QStringList(); + if (!root) + return QStringList(); - switch(root->checkState(0)) { + switch (root->checkState(0)) { case Qt::Unchecked: return QStringList(root->data(0, Qt::UserRole).toString() + "/"); - case Qt::Checked: + case Qt::Checked: return QStringList(); case Qt::PartiallyChecked: break; @@ -368,7 +383,7 @@ QStringList SelectiveSyncWidget::createBlackList(QTreeWidgetItem* root) const } else { // We did not load from the server so we re-use the one from the old black list QString path = root->data(0, Qt::UserRole).toString(); - foreach (const QString & it, _oldBlackList) { + foreach (const QString &it, _oldBlackList) { if (it.startsWith(path)) result += it; } @@ -381,28 +396,30 @@ QStringList SelectiveSyncWidget::oldBlackList() const return _oldBlackList; } -qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem* root) +qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem *root) { if (!root) { root = _folderTree->topLevelItem(0); } - if (!root) return -1; + if (!root) + return -1; - switch(root->checkState(0)) { - case Qt::Unchecked: - return 0; - case Qt::Checked: - return root->data(1, Qt::UserRole).toLongLong(); - case Qt::PartiallyChecked: - break; + switch (root->checkState(0)) { + case Qt::Unchecked: + return 0; + case Qt::Checked: + return root->data(1, Qt::UserRole).toLongLong(); + case Qt::PartiallyChecked: + break; } qint64 result = 0; if (root->childCount()) { for (int i = 0; i < root->childCount(); ++i) { auto r = estimatedSize(root->child(i)); - if (r < 0) return r; + if (r < 0) + return r; result += r; } } else { @@ -413,25 +430,27 @@ qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem* root) } -SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, Folder* folder, QWidget* parent, Qt::WindowFlags f) - : QDialog(parent, f), _folder(folder), - _okButton(0) // defined in init() +SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget *parent, Qt::WindowFlags f) + : QDialog(parent, f) + , _folder(folder) + , _okButton(0) // defined in init() { bool ok; init(account); QStringList selectiveSyncList = _folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok); - if( ok ) { - _selectiveSync->setFolderInfo(_folder->remotePath(), _folder->alias(),selectiveSyncList); + if (ok) { + _selectiveSync->setFolderInfo(_folder->remotePath(), _folder->alias(), selectiveSyncList); } else { _okButton->setEnabled(false); } // Make sure we don't get crashes if the folder is destroyed while we are still open - connect(_folder, SIGNAL(destroyed(QObject*)), this, SLOT(deleteLater())); + connect(_folder, SIGNAL(destroyed(QObject *)), this, SLOT(deleteLater())); } SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, const QString &folder, - const QStringList& blacklist, QWidget* parent, Qt::WindowFlags f) - : QDialog(parent, f), _folder(0) + const QStringList &blacklist, QWidget *parent, Qt::WindowFlags f) + : QDialog(parent, f) + , _folder(0) { init(account); _selectiveSync->setFolderInfo(folder, folder, blacklist); @@ -457,7 +476,7 @@ void SelectiveSyncDialog::accept() if (_folder) { bool ok; auto oldBlackListSet = _folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok).toSet(); - if( ! ok ) { + if (!ok) { return; } QStringList blackList = _selectiveSync->createBlackList(); @@ -472,7 +491,7 @@ void SelectiveSyncDialog::accept() // (the ones that are no longer in the blacklist) auto blackListSet = blackList.toSet(); auto changes = (oldBlackListSet - blackListSet) + (blackListSet - oldBlackListSet); - foreach(const auto &it, changes) { + foreach (const auto &it, changes) { _folder->journalDb()->avoidReadFromDbOnNextSync(it); } @@ -495,6 +514,4 @@ qint64 SelectiveSyncDialog::estimatedSize() { return _selectiveSync->estimatedSize(); } - } - diff --git a/src/gui/selectivesyncdialog.h b/src/gui/selectivesyncdialog.h index e49dfee97..15e4d7d33 100644 --- a/src/gui/selectivesyncdialog.h +++ b/src/gui/selectivesyncdialog.h @@ -29,13 +29,14 @@ class Folder; * @brief The SelectiveSyncWidget contains a folder tree with labels * @ingroup gui */ -class SelectiveSyncWidget : public QWidget { +class SelectiveSyncWidget : public QWidget +{ Q_OBJECT public: - explicit SelectiveSyncWidget(AccountPtr account, QWidget* parent = 0); + explicit SelectiveSyncWidget(AccountPtr account, QWidget *parent = 0); /// Returns a list of blacklisted paths, each including the trailing / - QStringList createBlackList(QTreeWidgetItem* root = 0) const; + QStringList createBlackList(QTreeWidgetItem *root = 0) const; /** Returns the oldBlackList passed into setFolderInfo(), except that * a "/" entry is expanded to all top-level folder names. @@ -47,18 +48,19 @@ public: // oldBlackList is a list of excluded paths, each including a trailing / void setFolderInfo(const QString &folderPath, const QString &rootName, - const QStringList &oldBlackList = QStringList()); + const QStringList &oldBlackList = QStringList()); QSize sizeHint() const Q_DECL_OVERRIDE; private slots: void slotUpdateDirectories(QStringList); void slotItemExpanded(QTreeWidgetItem *); - void slotItemChanged(QTreeWidgetItem*,int); - void slotLscolFinishedWithError(QNetworkReply*); + void slotItemChanged(QTreeWidgetItem *, int); + void slotLscolFinishedWithError(QNetworkReply *); + private: void refreshFolders(); - void recursiveInsert(QTreeWidgetItem* parent, QStringList pathTrail, QString path, qint64 size); + void recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path, qint64 size); AccountPtr _account; @@ -76,14 +78,15 @@ private: * @brief The SelectiveSyncDialog class * @ingroup gui */ -class SelectiveSyncDialog : public QDialog { +class SelectiveSyncDialog : public QDialog +{ Q_OBJECT public: // Dialog for a specific folder (used from the account settings button) - explicit SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget *parent = 0, Qt::WindowFlags f = 0); // Dialog for the whole account (Used from the wizard) - explicit SelectiveSyncDialog(AccountPtr account, const QString &folder, const QStringList &blacklist, QWidget* parent = 0, Qt::WindowFlags f = 0); + explicit SelectiveSyncDialog(AccountPtr account, const QString &folder, const QStringList &blacklist, QWidget *parent = 0, Qt::WindowFlags f = 0); virtual void accept() Q_DECL_OVERRIDE; @@ -94,7 +97,6 @@ public: qint64 estimatedSize(); private: - void init(const AccountPtr &account); SelectiveSyncWidget *_selectiveSync; @@ -102,5 +104,4 @@ private: Folder *_folder; QPushButton *_okButton; }; - } diff --git a/src/gui/servernotificationhandler.cpp b/src/gui/servernotificationhandler.cpp index 62ba5e973..afbd66ddf 100644 --- a/src/gui/servernotificationhandler.cpp +++ b/src/gui/servernotificationhandler.cpp @@ -20,30 +20,26 @@ #include #include -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcServerNotification, "gui.servernotification", QtInfoMsg) ServerNotificationHandler::ServerNotificationHandler(QObject *parent) : QObject(parent) { - } void ServerNotificationHandler::slotFetchNotifications(AccountState *ptr) { // check connectivity and credentials - if( !( ptr && ptr->isConnected() && ptr->account() && - ptr->account()->credentials() && - ptr->account()->credentials()->ready() ) ) { + if (!(ptr && ptr->isConnected() && ptr->account() && ptr->account()->credentials() && ptr->account()->credentials()->ready())) { deleteLater(); return; } // check if the account has notifications enabled. If the capabilities are // not yet valid, its assumed that notifications are available. - if( ptr->account()->capabilities().isValid() ) { - if( ! ptr->account()->capabilities().notificationsAvailable() ) { + if (ptr->account()->capabilities().isValid()) { + if (!ptr->account()->capabilities().notificationsAvailable()) { qCInfo(lcServerNotification) << "Account" << ptr->account()->displayName() << "does not have notifications enabled."; deleteLater(); return; @@ -51,17 +47,17 @@ void ServerNotificationHandler::slotFetchNotifications(AccountState *ptr) } // if the previous notification job has finished, start next. - _notificationJob = new JsonApiJob( ptr->account(), QLatin1String("ocs/v2.php/apps/notifications/api/v1/notifications"), this ); + _notificationJob = new JsonApiJob(ptr->account(), QLatin1String("ocs/v2.php/apps/notifications/api/v1/notifications"), this); QObject::connect(_notificationJob.data(), SIGNAL(jsonReceived(QJsonDocument, int)), - this, SLOT(slotNotificationsReceived(QJsonDocument, int))); - _notificationJob->setProperty("AccountStatePtr", QVariant::fromValue(ptr)); + this, SLOT(slotNotificationsReceived(QJsonDocument, int))); + _notificationJob->setProperty("AccountStatePtr", QVariant::fromValue(ptr)); _notificationJob->start(); } -void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument& json, int statusCode) +void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument &json, int statusCode) { - if( statusCode != 200 ) { + if (statusCode != 200) { qCWarning(lcServerNotification) << "Notifications failed with status code " << statusCode; deleteLater(); return; @@ -69,40 +65,39 @@ void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument& j auto notifies = json.object().value("ocs").toObject().value("data").toArray(); - AccountState* ai = qvariant_cast(sender()->property("AccountStatePtr")); + AccountState *ai = qvariant_cast(sender()->property("AccountStatePtr")); ActivityList list; - foreach( auto element, notifies ) { + foreach (auto element, notifies) { Activity a; - auto json = element.toObject(); - a._type = Activity::NotificationType; - a._accName = ai->account()->displayName(); - a._id = json.value("notification_id").toInt(); - a._subject = json.value("subject").toString(); - a._message = json.value("message").toString(); - QString s = json.value("link").toString(); - if( !s.isEmpty() ) { - a._link = QUrl(s); + auto json = element.toObject(); + a._type = Activity::NotificationType; + a._accName = ai->account()->displayName(); + a._id = json.value("notification_id").toInt(); + a._subject = json.value("subject").toString(); + a._message = json.value("message").toString(); + QString s = json.value("link").toString(); + if (!s.isEmpty()) { + a._link = QUrl(s); } a._dateTime = QDateTime::fromString(json.value("datetime").toString(), Qt::ISODate); auto actions = json.value("actions").toArray(); - foreach( auto action, actions) { + foreach (auto action, actions) { auto actionJson = action.toObject(); ActivityLink al; al._label = QUrl::fromPercentEncoding(actionJson.value("label").toString().toUtf8()); - al._link = actionJson.value("link").toString(); - al._verb = actionJson.value("type").toString().toUtf8(); + al._link = actionJson.value("link").toString(); + al._verb = actionJson.value("type").toString().toUtf8(); al._isPrimary = actionJson.value("primary").toBool(); a._links.append(al); } list.append(a); } - emit newNotificationList( list ); + emit newNotificationList(list); deleteLater(); } - } diff --git a/src/gui/servernotificationhandler.h b/src/gui/servernotificationhandler.h index 8c8fef976..875c3189e 100644 --- a/src/gui/servernotificationhandler.h +++ b/src/gui/servernotificationhandler.h @@ -21,8 +21,7 @@ class QJsonDocument; -namespace OCC -{ +namespace OCC { class ServerNotificationHandler : public QObject { @@ -37,14 +36,11 @@ public slots: void slotFetchNotifications(AccountState *ptr); private slots: - void slotNotificationsReceived(const QJsonDocument& json, int statusCode); + void slotNotificationsReceived(const QJsonDocument &json, int statusCode); private: QPointer _notificationJob; - - }; - } #endif // SERVERNOTIFICATIONHANDLER_H diff --git a/src/gui/settingsdialog.cpp b/src/gui/settingsdialog.cpp index 6c9fc1b54..bb44a080a 100644 --- a/src/gui/settingsdialog.cpp +++ b/src/gui/settingsdialog.cpp @@ -43,19 +43,19 @@ #include namespace { - const char TOOLBAR_CSS[] = +const char TOOLBAR_CSS[] = "QToolBar { background: %1; margin: 0; padding: 0; border: none; border-bottom: 1px solid %2; spacing: 0; } " "QToolBar QToolButton { background: %1; border: none; border-bottom: 1px solid %2; margin: 0; padding: 5px; } " "QToolBar QToolBarExtension { padding:0; } " "QToolBar QToolButton:checked { background: %3; color: %4; }"; - static const float buttonSizeRatio = 1.618; // golden ratio +static const float buttonSizeRatio = 1.618; // golden ratio } namespace OCC { -static QIcon circleMask( const QImage& avatar ) +static QIcon circleMask(const QImage &avatar) { int dim = avatar.width(); @@ -76,9 +76,10 @@ static QIcon circleMask( const QImage& avatar ) // Whenever you change something here check both settingsdialog.cpp and settingsdialogmac.cpp ! // -SettingsDialog::SettingsDialog(ownCloudGui *gui, QWidget *parent) : - QDialog(parent) - , _ui(new Ui::SettingsDialog), _gui(gui) +SettingsDialog::SettingsDialog(ownCloudGui *gui, QWidget *parent) + : QDialog(parent) + , _ui(new Ui::SettingsDialog) + , _gui(gui) { ConfigFile cfg; @@ -108,9 +109,9 @@ SettingsDialog::SettingsDialog(ownCloudGui *gui, QWidget *parent) : _toolBar->addAction(_activityAction); _activitySettings = new ActivitySettings; _ui->stack->addWidget(_activitySettings); - connect( _activitySettings, SIGNAL(guiLog(QString,QString)), _gui, - SLOT(slotShowOptionalTrayMessage(QString,QString)) ); - _activitySettings->setNotificationRefreshInterval( cfg.notificationRefreshInterval()); + connect(_activitySettings, SIGNAL(guiLog(QString, QString)), _gui, + SLOT(slotShowOptionalTrayMessage(QString, QString))); + _activitySettings->setNotificationRefreshInterval(cfg.notificationRefreshInterval()); QAction *generalAction = createColorAwareAction(QLatin1String(":/client/resources/settings.png"), tr("General")); _actionGroup->addAction(generalAction); @@ -128,13 +129,13 @@ SettingsDialog::SettingsDialog(ownCloudGui *gui, QWidget *parent) : _actionGroupWidgets.insert(generalAction, generalSettings); _actionGroupWidgets.insert(networkAction, networkSettings); - connect(_actionGroup, SIGNAL(triggered(QAction*)), SLOT(slotSwitchPage(QAction*))); + connect(_actionGroup, SIGNAL(triggered(QAction *)), SLOT(slotSwitchPage(QAction *))); - connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)), - this, SLOT(accountAdded(AccountState*))); - connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)), - this, SLOT(accountRemoved(AccountState*))); - foreach (auto ai , AccountManager::instance()->accounts()) { + connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)), + this, SLOT(accountAdded(AccountState *))); + connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)), + this, SLOT(accountRemoved(AccountState *))); + foreach (auto ai, AccountManager::instance()->accounts()) { accountAdded(ai.data()); } @@ -159,13 +160,15 @@ SettingsDialog::~SettingsDialog() } // close event is not being called here -void SettingsDialog::reject() { +void SettingsDialog::reject() +{ ConfigFile cfg; cfg.saveGeometry(this); QDialog::reject(); } -void SettingsDialog::accept() { +void SettingsDialog::accept() +{ ConfigFile cfg; cfg.saveGeometry(this); QDialog::accept(); @@ -195,7 +198,7 @@ void SettingsDialog::slotSwitchPage(QAction *action) void SettingsDialog::showFirstPage() { - QList actions = _toolBar->actions(); + QList actions = _toolBar->actions(); if (!actions.empty()) { actions.first()->trigger(); } @@ -217,9 +220,9 @@ void SettingsDialog::accountAdded(AccountState *s) QAction *accountAction; QImage avatar = s->account()->avatar(); const QString actionText = brandingSingleAccount ? tr("Account") : s->account()->displayName(); - if(avatar.isNull()) { + if (avatar.isNull()) { accountAction = createColorAwareAction(QLatin1String(":/client/resources/account.png"), - actionText); + actionText); } else { QIcon icon = circleMask(avatar); accountAction = createActionWithIcon(icon, actionText); @@ -231,14 +234,14 @@ void SettingsDialog::accountAdded(AccountState *s) } _toolBar->insertAction(_toolBar->actions().at(0), accountAction); auto accountSettings = new AccountSettings(s, this); - _ui->stack->insertWidget(0 , accountSettings); + _ui->stack->insertWidget(0, accountSettings); _actionGroup->addAction(accountAction); _actionGroupWidgets.insert(accountAction, accountSettings); _actionForAccount.insert(s->account().data(), accountAction); - connect( accountSettings, SIGNAL(folderChanged()), _gui, SLOT(slotFoldersChanged())); - connect( accountSettings, SIGNAL(openFolderAlias(const QString&)), - _gui, SLOT(slotFolderOpenAction(QString))); + connect(accountSettings, SIGNAL(folderChanged()), _gui, SLOT(slotFoldersChanged())); + connect(accountSettings, SIGNAL(openFolderAlias(const QString &)), + _gui, SLOT(slotFolderOpenAction(QString))); connect(s->account().data(), SIGNAL(accountChangedAvatar()), SLOT(slotAccountAvatarChanged())); slotRefreshActivity(s); @@ -246,13 +249,13 @@ void SettingsDialog::accountAdded(AccountState *s) void SettingsDialog::slotAccountAvatarChanged() { - Account *account = static_cast(sender()); - if( account && _actionForAccount.contains(account)) { + Account *account = static_cast(sender()); + if (account && _actionForAccount.contains(account)) { QAction *action = _actionForAccount[account]; - if( action ) { + if (action) { QImage pix = account->avatar(); - if( !pix.isNull() ) { - action->setIcon( circleMask(pix) ); + if (!pix.isNull()) { + action->setIcon(circleMask(pix)); } } } @@ -279,7 +282,7 @@ void SettingsDialog::accountRemoved(AccountState *s) } } - if( _actionForAccount.contains(s->account().data()) ) { + if (_actionForAccount.contains(s->account().data())) { _actionForAccount.remove(s->account().data()); } _activitySettings->slotRemoveAccount(s); @@ -294,29 +297,28 @@ void SettingsDialog::accountRemoved(AccountState *s) void SettingsDialog::customizeStyle() { - QString highlightColor(palette().highlight().color().name()); + QString highlightColor(palette().highlight().color().name()); QString altBase(palette().alternateBase().color().name()); QString dark(palette().dark().color().name()); QString background(palette().base().color().name()); - _toolBar->setStyleSheet(QString::fromAscii(TOOLBAR_CSS).arg(background,dark,highlightColor,altBase)); + _toolBar->setStyleSheet(QString::fromAscii(TOOLBAR_CSS).arg(background, dark, highlightColor, altBase)); - Q_FOREACH(QAction *a, _actionGroup->actions()) { + Q_FOREACH (QAction *a, _actionGroup->actions()) { QIcon icon = createColorAwareIcon(a->property("iconPath").toString()); a->setIcon(icon); - QToolButton *btn = qobject_cast(_toolBar->widgetForAction(a)); + QToolButton *btn = qobject_cast(_toolBar->widgetForAction(a)); if (btn) { btn->setIcon(icon); } } - } QIcon SettingsDialog::createColorAwareIcon(const QString &name) { - QColor bg(palette().base().color()); + QColor bg(palette().base().color()); QImage img(name); // account for different sensitivity of the human eye to certain colors - double treshold = 1.0 - ( 0.299 * bg.red() + 0.587 * bg.green() + 0.114 * bg.blue())/255.0; + double treshold = 1.0 - (0.299 * bg.red() + 0.587 * bg.green() + 0.114 * bg.blue()) / 255.0; if (treshold > 0.5) { img.invertPixels(QImage::InvertRgb); } @@ -327,40 +329,40 @@ QIcon SettingsDialog::createColorAwareIcon(const QString &name) class ToolButtonAction : public QWidgetAction { public: - explicit ToolButtonAction(const QIcon &icon, const QString &text, QObject* parent) - : QWidgetAction(parent) { + explicit ToolButtonAction(const QIcon &icon, const QString &text, QObject *parent) + : QWidgetAction(parent) + { setText(text); setIcon(icon); } - QWidget* createWidget(QWidget* parent) Q_DECL_OVERRIDE { - - auto toolbar = qobject_cast(parent); + QWidget *createWidget(QWidget *parent) Q_DECL_OVERRIDE + { + auto toolbar = qobject_cast(parent); if (!toolbar) { // this means we are in the extention menu, no special action here return 0; } - QToolButton* btn = new QToolButton(parent); + QToolButton *btn = new QToolButton(parent); btn->setDefaultAction(this); btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); btn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); -// btn->setMinimumWidth(qMax(parent->sizeHint().height() * buttonSizeRatio, -// btn->sizeHint().width())); + // btn->setMinimumWidth(qMax(parent->sizeHint().height() * buttonSizeRatio, + // btn->sizeHint().width())); return btn; } }; -QAction *SettingsDialog::createActionWithIcon(const QIcon& icon, const QString& text, const QString& iconPath) +QAction *SettingsDialog::createActionWithIcon(const QIcon &icon, const QString &text, const QString &iconPath) { QAction *action = new ToolButtonAction(icon, text, this); action->setCheckable(true); - if(!iconPath.isEmpty()) { + if (!iconPath.isEmpty()) { action->setProperty("iconPath", iconPath); } return action; - } QAction *SettingsDialog::createColorAwareAction(const QString &iconPath, const QString &text) @@ -370,7 +372,7 @@ QAction *SettingsDialog::createColorAwareAction(const QString &iconPath, const Q return createActionWithIcon(coloredIcon, text, iconPath); } -void SettingsDialog::slotRefreshActivity( AccountState* accountState ) +void SettingsDialog::slotRefreshActivity(AccountState *accountState) { if (accountState) { _activitySettings->slotRefresh(accountState); diff --git a/src/gui/settingsdialog.h b/src/gui/settingsdialog.h index 39f2595a1..9d4459959 100644 --- a/src/gui/settingsdialog.h +++ b/src/gui/settingsdialog.h @@ -31,7 +31,7 @@ namespace OCC { class AccountState; namespace Ui { -class SettingsDialog; + class SettingsDialog; } class AccountSettings; class Application; @@ -57,7 +57,7 @@ public slots: void showFirstPage(); void showActivityPage(); void slotSwitchPage(QAction *action); - void slotRefreshActivity(AccountState *accountState ); + void slotRefreshActivity(AccountState *accountState); void slotAccountAvatarChanged(); protected: @@ -74,26 +74,25 @@ private: QIcon createColorAwareIcon(const QString &name); QAction *createColorAwareAction(const QString &iconName, const QString &fileName); - QAction *createActionWithIcon(const QIcon& icon, const QString& text, const QString& iconPath = QString()); + QAction *createActionWithIcon(const QIcon &icon, const QString &text, const QString &iconPath = QString()); - Ui::SettingsDialog * const _ui; + Ui::SettingsDialog *const _ui; - QActionGroup* _actionGroup; + QActionGroup *_actionGroup; // Maps the actions from the action group to the corresponding widgets - QHash _actionGroupWidgets; + QHash _actionGroupWidgets; // Maps the action in the dialog to their according account. Needed in // case the account avatar changes - QHash _actionForAccount; + QHash _actionForAccount; - QToolBar* _toolBar; + QToolBar *_toolBar; ActivitySettings *_activitySettings; - QAction * _activityAction; + QAction *_activityAction; ownCloudGui *_gui; }; - } #endif // SETTINGSDIALOG_H diff --git a/src/gui/settingsdialogmac.cpp b/src/gui/settingsdialogmac.cpp index 65ae6ac38..486bc7018 100644 --- a/src/gui/settingsdialogmac.cpp +++ b/src/gui/settingsdialogmac.cpp @@ -39,7 +39,7 @@ namespace OCC { // Duplicate in settingsdialog.cpp -static QIcon circleMask( const QImage& avatar ) +static QIcon circleMask(const QImage &avatar) { int dim = avatar.width(); @@ -61,12 +61,12 @@ static QIcon circleMask( const QImage& avatar ) // Whenever you change something here check both settingsdialog.cpp and settingsdialogmac.cpp ! // SettingsDialogMac::SettingsDialogMac(ownCloudGui *gui, QWidget *parent) - : MacPreferencesWindow(parent), _gui(gui) + : MacPreferencesWindow(parent) + , _gui(gui) { // do not show minimize button. There is no use, and restoring the // dialog from minimize is broken in MacPreferencesWindow - setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint | - Qt::WindowCloseButtonHint | Qt::WindowMaximizeButtonHint); + setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMaximizeButtonHint); // Emulate dialog behavior: Escape means close @@ -92,14 +92,14 @@ SettingsDialogMac::SettingsDialogMac(ownCloudGui *gui, QWidget *parent) QIcon activityIcon(QLatin1String(":/client/resources/activity.png")); _activitySettings = new ActivitySettings; addPreferencesPanel(activityIcon, tr("Activity"), _activitySettings); - connect( _activitySettings, SIGNAL(guiLog(QString,QString)), _gui, - SLOT(slotShowOptionalTrayMessage(QString,QString)) ); + connect(_activitySettings, SIGNAL(guiLog(QString, QString)), _gui, + SLOT(slotShowOptionalTrayMessage(QString, QString))); connect(AccountManager::instance(), &AccountManager::accountAdded, - this, &SettingsDialogMac::accountAdded); + this, &SettingsDialogMac::accountAdded); connect(AccountManager::instance(), &AccountManager::accountRemoved, - this, &SettingsDialogMac::accountRemoved); - foreach (auto ai , AccountManager::instance()->accounts()) { + this, &SettingsDialogMac::accountRemoved); + foreach (auto ai, AccountManager::instance()->accounts()) { accountAdded(ai.data()); } @@ -142,8 +142,8 @@ void SettingsDialogMac::accountAdded(AccountState *s) insertPreferencesPanel(0, accountIcon, displayName, accountSettings); - connect( accountSettings, &AccountSettings::folderChanged, _gui, &ownCloudGui::slotFoldersChanged); - connect( accountSettings, &AccountSettings::openFolderAlias, _gui, &ownCloudGui::slotFolderOpenAction); + connect(accountSettings, &AccountSettings::folderChanged, _gui, &ownCloudGui::slotFoldersChanged); + connect(accountSettings, &AccountSettings::openFolderAlias, _gui, &ownCloudGui::slotFolderOpenAction); connect(s->account().data(), SIGNAL(accountChangedAvatar()), this, SLOT(slotAccountAvatarChanged())); @@ -152,8 +152,8 @@ void SettingsDialogMac::accountAdded(AccountState *s) void SettingsDialogMac::accountRemoved(AccountState *s) { - auto list = findChildren(QString()); - foreach(auto p, list) { + auto list = findChildren(QString()); + foreach (auto p, list) { if (p->accountsState() == s) { removePreferencesPanel(p); } @@ -162,7 +162,7 @@ void SettingsDialogMac::accountRemoved(AccountState *s) _activitySettings->slotRemoveAccount(s); } -void SettingsDialogMac::slotRefreshActivity( AccountState* accountState ) +void SettingsDialogMac::slotRefreshActivity(AccountState *accountState) { if (accountState) { _activitySettings->slotRefresh(accountState); @@ -171,9 +171,9 @@ void SettingsDialogMac::slotRefreshActivity( AccountState* accountState ) void SettingsDialogMac::slotAccountAvatarChanged() { - Account *account = static_cast(sender()); - auto list = findChildren(QString()); - foreach(auto p, list) { + Account *account = static_cast(sender()); + auto list = findChildren(QString()); + foreach (auto p, list) { if (p->accountsState()->account() == account) { int idx = indexForPanel(p); QImage pix = account->avatar(); @@ -183,5 +183,4 @@ void SettingsDialogMac::slotAccountAvatarChanged() } } } - } diff --git a/src/gui/settingsdialogmac.h b/src/gui/settingsdialogmac.h index a00046153..f931f9009 100644 --- a/src/gui/settingsdialogmac.h +++ b/src/gui/settingsdialogmac.h @@ -47,22 +47,22 @@ public: public slots: void showActivityPage(); - void slotRefreshActivity(AccountState *accountState ); + void slotRefreshActivity(AccountState *accountState); private slots: void accountAdded(AccountState *); void accountRemoved(AccountState *); void slotAccountAvatarChanged(); + private: void closeEvent(QCloseEvent *event); - ProtocolWidget *_protocolWidget; + ProtocolWidget *_protocolWidget; ActivitySettings *_activitySettings; - ownCloudGui *_gui; + ownCloudGui *_gui; int _protocolIdx; }; - } #endif // SETTINGSDIALOGMAC_H diff --git a/src/gui/sharedialog.cpp b/src/gui/sharedialog.cpp index 3ad8eed32..60d6167d4 100644 --- a/src/gui/sharedialog.cpp +++ b/src/gui/sharedialog.cpp @@ -35,19 +35,19 @@ namespace OCC { static const int thumbnailSize = 40; ShareDialog::ShareDialog(QPointer accountState, - const QString &sharePath, - const QString &localPath, - SharePermissions maxSharingPermissions, - QWidget *parent) : - QDialog(parent), - _ui(new Ui::ShareDialog), - _accountState(accountState), - _sharePath(sharePath), - _localPath(localPath), - _maxSharingPermissions(maxSharingPermissions), - _linkWidget(NULL), - _userGroupWidget(NULL), - _progressIndicator(NULL) + const QString &sharePath, + const QString &localPath, + SharePermissions maxSharingPermissions, + QWidget *parent) + : QDialog(parent) + , _ui(new Ui::ShareDialog) + , _accountState(accountState) + , _sharePath(sharePath) + , _localPath(localPath) + , _maxSharingPermissions(maxSharingPermissions) + , _linkWidget(NULL) + , _userGroupWidget(NULL) + , _progressIndicator(NULL) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WA_DeleteOnClose); @@ -75,13 +75,13 @@ ShareDialog::ShareDialog(QPointer accountState, QFileInfo lPath(_localPath); QString fileName = lPath.fileName(); _ui->label_name->setText(tr("%1").arg(fileName)); - QFont f( _ui->label_name->font()); - f.setPointSize( f.pointSize() * 1.4 ); - _ui->label_name->setFont( f ); + QFont f(_ui->label_name->font()); + f.setPointSize(f.pointSize() * 1.4); + _ui->label_name->setFont(f); _ui->label_sharePath->setWordWrap(true); QString ocDir(_sharePath); - ocDir.truncate(ocDir.length()-fileName.length()); + ocDir.truncate(ocDir.length() - fileName.length()); ocDir.replace(QRegExp("^/*"), ""); ocDir.replace(QRegExp("/*$"), ""); @@ -90,7 +90,7 @@ ShareDialog::ShareDialog(QPointer accountState, // may be in use or not. _ui->gridLayout->removeWidget(_ui->label_sharePath); _ui->gridLayout->removeWidget(_ui->label_name); - if( ocDir.isEmpty() ) { + if (ocDir.isEmpty()) { _ui->gridLayout->addWidget(_ui->label_name, 0, 1, 2, 1); _ui->label_sharePath->setText(QString()); } else { @@ -124,7 +124,7 @@ ShareDialog::ShareDialog(QPointer accountState, job->setProperties(QList() << "http://open-collaboration-services.org/ns:share-permissions"); job->setTimeout(10 * 1000); connect(job, SIGNAL(result(QVariantMap)), SLOT(slotMaxSharingPermissionsReceived(QVariantMap))); - connect(job, SIGNAL(finishedWithError(QNetworkReply*)), SLOT(slotMaxSharingPermissionsError())); + connect(job, SIGNAL(finishedWithError(QNetworkReply *)), SLOT(slotMaxSharingPermissionsError())); job->start(); } @@ -133,13 +133,14 @@ ShareDialog::~ShareDialog() delete _ui; } -void ShareDialog::done( int r ) { +void ShareDialog::done(int r) +{ ConfigFile cfg; cfg.saveGeometry(this); QDialog::done(r); } -void ShareDialog::slotMaxSharingPermissionsReceived(const QVariantMap & result) +void ShareDialog::slotMaxSharingPermissionsReceived(const QVariantMap &result) { const QVariant receivedPermissions = result["share-permissions"]; if (!receivedPermissions.toString().isEmpty()) { @@ -179,8 +180,8 @@ void ShareDialog::showSharingUi() // We only do user/group sharing from 8.2.0 bool userGroupSharing = - theme->userGroupSharing() - && _accountState->account()->serverVersionInt() >= Account::makeServerVersion(8, 2, 0); + theme->userGroupSharing() + && _accountState->account()->serverVersionInt() >= Account::makeServerVersion(8, 2, 0); if (userGroupSharing) { _userGroupWidget = new ShareUserGroupWidget(_accountState->account(), _sharePath, _localPath, _maxSharingPermissions, this); @@ -218,7 +219,8 @@ void ShareDialog::slotThumbnailFetched(const int &statusCode, const QByteArray & _ui->label_icon->setPixmap(p); } -void ShareDialog::slotAccountStateChanged(int state) { +void ShareDialog::slotAccountStateChanged(int state) +{ bool enabled = (state == AccountState::State::Connected); qCDebug(lcSharing) << "Account connected?" << enabled; @@ -230,6 +232,4 @@ void ShareDialog::slotAccountStateChanged(int state) { _linkWidget->setEnabled(enabled); } } - } - diff --git a/src/gui/sharedialog.h b/src/gui/sharedialog.h index f7a3380d1..dac7b9841 100644 --- a/src/gui/sharedialog.h +++ b/src/gui/sharedialog.h @@ -28,7 +28,7 @@ class QProgressIndicator; namespace OCC { namespace Ui { -class ShareDialog; + class ShareDialog; } class ShareLinkWidget; @@ -40,21 +40,20 @@ class ShareDialog : public QDialog public: explicit ShareDialog(QPointer accountState, - const QString &sharePath, - const QString &localPath, - SharePermissions maxSharingPermissions, - QWidget *parent = 0); + const QString &sharePath, + const QString &localPath, + SharePermissions maxSharingPermissions, + QWidget *parent = 0); ~ShareDialog(); private slots: - void done( int r ); + void done(int r); void slotMaxSharingPermissionsReceived(const QVariantMap &result); void slotMaxSharingPermissionsError(); void slotThumbnailFetched(const int &statusCode, const QByteArray &reply); void slotAccountStateChanged(int state); private: - void showSharingUi(); Ui::ShareDialog *_ui; @@ -68,7 +67,6 @@ private: ShareUserGroupWidget *_userGroupWidget; QProgressIndicator *_progressIndicator; }; - } #endif // SHAREDIALOG_H diff --git a/src/gui/sharee.cpp b/src/gui/sharee.cpp index 1553a3069..2d1ca4d49 100644 --- a/src/gui/sharee.cpp +++ b/src/gui/sharee.cpp @@ -24,11 +24,11 @@ namespace OCC { Q_LOGGING_CATEGORY(lcSharing, "gui.sharing", QtInfoMsg) Sharee::Sharee(const QString shareWith, - const QString displayName, - const Type type) -: _shareWith(shareWith), - _displayName(displayName), - _type(type) + const QString displayName, + const Type type) + : _shareWith(shareWith) + , _displayName(displayName) + , _type(type) { } @@ -61,8 +61,11 @@ Sharee::Type Sharee::type() const } ShareeModel::ShareeModel(const AccountPtr &account, const QString &type, QObject *parent) - : QAbstractListModel(parent), _account(account), _type(type) -{ } + : QAbstractListModel(parent) + , _account(account) + , _type(type) +{ +} void ShareeModel::fetch(const QString &search, const ShareeSet &blacklist) { @@ -70,7 +73,7 @@ void ShareeModel::fetch(const QString &search, const ShareeSet &blacklist) _shareeBlacklist = blacklist; OcsShareeJob *job = new OcsShareeJob(_account); connect(job, SIGNAL(shareeJobFinished(QJsonDocument)), SLOT(shareesFetched(QJsonDocument))); - connect(job, SIGNAL(ocsError(int,QString)), SIGNAL(displayErrorMessage(int,QString))); + connect(job, SIGNAL(ocsError(int, QString)), SIGNAL(displayErrorMessage(int, QString))); job->getSharees(_search, _type, 1, 50); } @@ -86,45 +89,44 @@ void ShareeModel::shareesFetched(const QJsonDocument &reply) auto exact = data.value("exact").toObject(); { auto users = exact.value("users").toArray(); - foreach(auto user, users) { + foreach (auto user, users) { newSharees.append(parseSharee(user.toObject())); } auto groups = exact.value("groups").toArray(); - foreach(auto group, groups) { + foreach (auto group, groups) { newSharees.append(parseSharee(group.toObject())); } auto remotes = exact.value("remotes").toArray(); - foreach(auto remote, remotes) { + foreach (auto remote, remotes) { newSharees.append(parseSharee(remote.toObject())); } } { auto users = data.value("users").toArray(); - foreach(auto user, users) { + foreach (auto user, users) { newSharees.append(parseSharee(user.toObject())); } } { auto groups = data.value("groups").toArray(); - foreach(auto group, groups) { + foreach (auto group, groups) { newSharees.append(parseSharee(group.toObject())); } } { auto remotes = data.value("remotes").toArray(); - foreach(auto remote, remotes) { + foreach (auto remote, remotes) { newSharees.append(parseSharee(remote.toObject())); } } // Filter sharees that we have already shared with QVector> filteredSharees; - foreach(const auto &sharee, newSharees) { + foreach (const auto &sharee, newSharees) { bool found = false; - foreach(const auto &blacklistSharee, _shareeBlacklist) { - if (sharee->type() == blacklistSharee->type() && - sharee->shareWith() == blacklistSharee->shareWith()) { + foreach (const auto &blacklistSharee, _shareeBlacklist) { + if (sharee->type() == blacklistSharee->type() && sharee->shareWith() == blacklistSharee->shareWith()) { found = true; break; } @@ -151,11 +153,15 @@ QSharedPointer ShareeModel::parseSharee(const QJsonObject &data) // Helper function for setNewSharees (could be a lambda when we can use them) static QSharedPointer shareeFromModelIndex(const QModelIndex &idx) -{ return idx.data(Qt::UserRole).value>(); } +{ + return idx.data(Qt::UserRole).value>(); +} -struct FindShareeHelper { +struct FindShareeHelper +{ const QSharedPointer &sharee; - bool operator()(const QSharedPointer &s2) const { + bool operator()(const QSharedPointer &s2) const + { return s2->format() == sharee->format() && s2->displayName() == sharee->format(); } }; @@ -164,7 +170,7 @@ struct FindShareeHelper { Do that while preserving the model index so the selection stays */ -void ShareeModel::setNewSharees(const QVector>& newSharees) +void ShareeModel::setNewSharees(const QVector> &newSharees) { layoutAboutToBeChanged(); const auto persistent = persistentIndexList(); @@ -172,13 +178,13 @@ void ShareeModel::setNewSharees(const QVector>& newSharee oldPersistantSharee.reserve(persistent.size()); std::transform(persistent.begin(), persistent.end(), std::back_inserter(oldPersistantSharee), - shareeFromModelIndex); + shareeFromModelIndex); _sharees = newSharees; QModelIndexList newPersistant; newPersistant.reserve(persistent.size()); - foreach(const QSharedPointer &sharee, oldPersistantSharee) { + foreach (const QSharedPointer &sharee, oldPersistantSharee) { FindShareeHelper helper = { sharee }; auto it = std::find_if(_sharees.constBegin(), _sharees.constEnd(), helper); if (it == _sharees.constEnd()) { @@ -204,7 +210,7 @@ QVariant ShareeModel::data(const QModelIndex &index, int role) const return QVariant(); } - const auto & sharee = _sharees.at(index.row()); + const auto &sharee = _sharees.at(index.row()); if (role == Qt::DisplayRole) { return sharee->format(); @@ -218,16 +224,16 @@ QVariant ShareeModel::data(const QModelIndex &index, int role) const } else if (role == Qt::UserRole) { return QVariant::fromValue(sharee); } - + return QVariant(); } -QSharedPointer ShareeModel::getSharee(int at) { +QSharedPointer ShareeModel::getSharee(int at) +{ if (at < 0 || at > _sharees.size()) { return QSharedPointer(NULL); } return _sharees.at(at); } - } diff --git a/src/gui/sharee.h b/src/gui/sharee.h index 0391eae53..ec053d2a9 100644 --- a/src/gui/sharee.h +++ b/src/gui/sharee.h @@ -33,9 +33,9 @@ namespace OCC { Q_DECLARE_LOGGING_CATEGORY(lcSharing) -class Sharee { +class Sharee +{ public: - // Keep in sync with Share::ShareType enum Type { User = 0, @@ -44,8 +44,8 @@ public: }; explicit Sharee(const QString shareWith, - const QString displayName, - const Type type); + const QString displayName, + const Type type); QString format() const; QString shareWith() const; @@ -59,7 +59,8 @@ private: }; -class ShareeModel : public QAbstractListModel { +class ShareeModel : public QAbstractListModel +{ Q_OBJECT public: explicit ShareeModel(const AccountPtr &account, const QString &type, QObject *parent = 0); @@ -91,9 +92,8 @@ private: QVector> _sharees; QVector> _shareeBlacklist; }; - } Q_DECLARE_METATYPE(QSharedPointer) -#endif //SHAREE_H +#endif //SHAREE_H diff --git a/src/gui/sharelinkwidget.cpp b/src/gui/sharelinkwidget.cpp index dcdff486a..3988a9a83 100644 --- a/src/gui/sharelinkwidget.cpp +++ b/src/gui/sharelinkwidget.cpp @@ -34,19 +34,19 @@ namespace OCC { const char propertyShareC[] = "oc_share"; ShareLinkWidget::ShareLinkWidget(AccountPtr account, - const QString &sharePath, - const QString &localPath, - SharePermissions maxSharingPermissions, - QWidget *parent) : - QWidget(parent), - _ui(new Ui::ShareLinkWidget), - _account(account), - _sharePath(sharePath), - _localPath(localPath), - _manager(0), - _passwordRequired(false), - _expiryRequired(false), - _namesSupported(true) + const QString &sharePath, + const QString &localPath, + SharePermissions maxSharingPermissions, + QWidget *parent) + : QWidget(parent) + , _ui(new Ui::ShareLinkWidget) + , _account(account) + , _sharePath(sharePath) + , _localPath(localPath) + , _manager(0) + , _passwordRequired(false) + , _expiryRequired(false) + , _namesSupported(true) { _ui->setupUi(this); @@ -61,10 +61,10 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account, // the following progress indicator widgets are added to layouts which makes them // automatically deleted once the dialog dies. - _pi_create = new QProgressIndicator(); + _pi_create = new QProgressIndicator(); _pi_password = new QProgressIndicator(); - _pi_date = new QProgressIndicator(); - _pi_editing = new QProgressIndicator(); + _pi_date = new QProgressIndicator(); + _pi_editing = new QProgressIndicator(); _ui->horizontalLayout_create->addWidget(_pi_create); _ui->horizontalLayout_password->addWidget(_pi_password); _ui->horizontalLayout_editing->addWidget(_pi_editing); @@ -73,7 +73,7 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account, connect(_ui->nameLineEdit, SIGNAL(returnPressed()), SLOT(slotShareNameEntered())); connect(_ui->createShareButton, SIGNAL(clicked(bool)), SLOT(slotShareNameEntered())); connect(_ui->linkShares, SIGNAL(itemSelectionChanged()), SLOT(slotShareSelectionChanged())); - connect(_ui->linkShares, SIGNAL(itemChanged(QTableWidgetItem*)), SLOT(slotNameEdited(QTableWidgetItem*))); + connect(_ui->linkShares, SIGNAL(itemChanged(QTableWidgetItem *)), SLOT(slotNameEdited(QTableWidgetItem *))); connect(_ui->checkBox_password, SIGNAL(clicked()), this, SLOT(slotCheckBoxPasswordClicked())); connect(_ui->lineEdit_password, SIGNAL(returnPressed()), this, SLOT(slotPasswordReturnPressed())); connect(_ui->lineEdit_password, SIGNAL(textChanged(QString)), this, SLOT(slotPasswordChanged(QString))); @@ -86,7 +86,7 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account, displayError(tr("Link shares have been disabled")); _ui->nameLineEdit->setEnabled(false); _ui->createShareButton->setEnabled(false); - } else if ( !(maxSharingPermissions & SharePermissionShare) ) { + } else if (!(maxSharingPermissions & SharePermissionShare)) { displayError(tr("The file can not be shared because it was shared without sharing permission.")); _ui->nameLineEdit->setEnabled(false); _ui->createShareButton->setEnabled(false); @@ -111,7 +111,7 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account, _ui->calendar->setEnabled(false); // check if the file is already inside of a synced folder - if( sharePath.isEmpty() ) { + if (sharePath.isEmpty()) { // The file is not yet in an ownCloud synced folder. We could automatically // copy it over, but that is skipped as not all questions can be answered that // are involved in that, see https://github.com/owncloud/client/issues/2732 @@ -137,15 +137,14 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account, if (_account->capabilities().sharePublicLinkEnforceExpireDate()) { _ui->checkBox_expire->setEnabled(false); _ui->calendar->setMaximumDate(QDate::currentDate().addDays( - _account->capabilities().sharePublicLinkExpireDateDays() - )); + _account->capabilities().sharePublicLinkExpireDateDays())); _expiryRequired = true; } // File can't have public upload set. _ui->widget_editing->setVisible(!_isFile); _ui->checkBox_editing->setEnabled( - _account->capabilities().sharePublicLinkAllowUpload()); + _account->capabilities().sharePublicLinkAllowUpload()); // Prepare sharing menu @@ -165,7 +164,7 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account, connect(_manager, SIGNAL(sharesFetched(QList>)), SLOT(slotSharesFetched(QList>))); connect(_manager, SIGNAL(linkShareCreated(QSharedPointer)), SLOT(slotCreateShareFetched(const QSharedPointer))); connect(_manager, SIGNAL(linkShareRequiresPassword(QString)), SLOT(slotCreateShareRequiresPassword(QString))); - connect(_manager, SIGNAL(serverError(int, QString)), SLOT(slotServerError(int,QString))); + connect(_manager, SIGNAL(serverError(int, QString)), SLOT(slotServerError(int, QString))); } ShareLinkWidget::~ShareLinkWidget() @@ -199,7 +198,7 @@ void ShareLinkWidget::slotSharesFetched(const QList> &shar table->setRowCount(0); auto deleteIcon = QIcon::fromTheme(QLatin1String("user-trash"), - QIcon(QLatin1String(":/client/resources/delete.png"))); + QIcon(QLatin1String(":/client/resources/delete.png"))); foreach (auto share, shares) { if (share->getShareType() != Share::TypeLink) { @@ -208,12 +207,12 @@ void ShareLinkWidget::slotSharesFetched(const QList> &shar auto linkShare = qSharedPointerDynamicCast(share); // Connect all shares signals to gui slots - connect(share.data(), SIGNAL(serverError(int, QString)), SLOT(slotServerError(int,QString))); + connect(share.data(), SIGNAL(serverError(int, QString)), SLOT(slotServerError(int, QString))); connect(share.data(), SIGNAL(shareDeleted()), SLOT(slotDeleteShareFetched())); connect(share.data(), SIGNAL(expireDateSet()), SLOT(slotExpireSet())); connect(share.data(), SIGNAL(publicUploadSet()), SLOT(slotPublicUploadSet())); connect(share.data(), SIGNAL(passwordSet()), SLOT(slotPasswordSet())); - connect(share.data(), SIGNAL(passwordSetError(int, QString)), SLOT(slotPasswordSetError(int,QString))); + connect(share.data(), SIGNAL(passwordSetError(int, QString)), SLOT(slotPasswordSetError(int, QString))); // Build the table row auto row = table->rowCount(); @@ -238,7 +237,7 @@ void ShareLinkWidget::slotSharesFetched(const QList> &shar shareButton->setProperty(propertyShareC, QVariant::fromValue(linkShare)); shareButton->setMenu(_shareLinkMenu); shareButton->setPopupMode(QToolButton::InstantPopup); - connect(shareButton, SIGNAL(triggered(QAction*)), SLOT(slotShareLinkButtonTriggered(QAction*))); + connect(shareButton, SIGNAL(triggered(QAction *)), SLOT(slotShareLinkButtonTriggered(QAction *))); table->setCellWidget(row, 1, shareButton); auto deleteButton = new QToolButton; @@ -287,7 +286,7 @@ void ShareLinkWidget::slotShareSelectionChanged() _ui->checkBox_password->setEnabled(!_passwordRequired); _ui->checkBox_expire->setEnabled(!_expiryRequired); _ui->checkBox_editing->setEnabled( - _account->capabilities().sharePublicLinkAllowUpload()); + _account->capabilities().sharePublicLinkAllowUpload()); // Password state _ui->checkBox_password->setText(tr("P&assword protect")); @@ -362,13 +361,13 @@ void ShareLinkWidget::slotPasswordReturnPressed() _ui->lineEdit_password->clearFocus(); } -void ShareLinkWidget::slotPasswordChanged(const QString& newText) +void ShareLinkWidget::slotPasswordChanged(const QString &newText) { // disable the set-password button - _ui->pushButton_setPassword->setEnabled( newText.length() > 0 ); + _ui->pushButton_setPassword->setEnabled(newText.length() > 0); } -void ShareLinkWidget::slotNameEdited(QTableWidgetItem* item) +void ShareLinkWidget::slotNameEdited(QTableWidgetItem *item) { if (!_namesSupported) { return; @@ -429,7 +428,7 @@ void ShareLinkWidget::slotCreateShareFetched(const QSharedPointer sha getShares(); } -void ShareLinkWidget::slotCreateShareRequiresPassword(const QString& message) +void ShareLinkWidget::slotCreateShareRequiresPassword(const QString &message) { // Deselect existing shares _ui->linkShares->clearSelection(); @@ -471,16 +470,13 @@ void ShareLinkWidget::slotCheckBoxPasswordClicked() void ShareLinkWidget::slotCheckBoxExpireClicked() { - if (_ui->checkBox_expire->checkState() == Qt::Checked) - { + if (_ui->checkBox_expire->checkState() == Qt::Checked) { const QDate date = QDate::currentDate().addDays(1); setExpireDate(date); _ui->calendar->setDate(date); _ui->calendar->setMinimumDate(date); _ui->calendar->setEnabled(true); - } - else - { + } else { setExpireDate(QDate()); _ui->calendar->setEnabled(false); } @@ -505,11 +501,12 @@ void ShareLinkWidget::emailShareLink(const QUrl &url) QString fileName = _sharePath.mid(_sharePath.lastIndexOf('/') + 1); if (!QDesktopServices::openUrl(QUrl(QString( - "mailto: " - "?subject=I shared %1 with you" - "&body=%2").arg( - fileName, - url.toString()), + "mailto: " + "?subject=I shared %1 with you" + "&body=%2") + .arg( + fileName, + url.toString()), QUrl::TolerantMode))) { QMessageBox::warning( this, @@ -603,10 +600,9 @@ void ShareLinkWidget::slotPasswordSetError(int code, const QString &message) _ui->lineEdit_password->setFocus(); } -void ShareLinkWidget::displayError(const QString& errMsg) +void ShareLinkWidget::displayError(const QString &errMsg) { - _ui->errorLabel->setText( errMsg ); + _ui->errorLabel->setText(errMsg); _ui->errorLabel->show(); } - } diff --git a/src/gui/sharelinkwidget.h b/src/gui/sharelinkwidget.h index c919b86d5..78dcc596b 100644 --- a/src/gui/sharelinkwidget.h +++ b/src/gui/sharelinkwidget.h @@ -29,7 +29,7 @@ class QTableWidgetItem; namespace OCC { namespace Ui { -class ShareLinkWidget; + class ShareLinkWidget; } class AbstractCredentials; @@ -49,10 +49,10 @@ class ShareLinkWidget : public QWidget public: explicit ShareLinkWidget(AccountPtr account, - const QString &sharePath, - const QString &localPath, - SharePermissions maxSharingPermissions, - QWidget *parent = 0); + const QString &sharePath, + const QString &localPath, + SharePermissions maxSharingPermissions, + QWidget *parent = 0); ~ShareLinkWidget(); void getShares(); @@ -67,14 +67,14 @@ private slots: void slotPasswordReturnPressed(); void slotCheckBoxEditingClicked(); void slotExpireDateChanged(const QDate &date); - void slotPasswordChanged(const QString& newText); - void slotNameEdited(QTableWidgetItem* item); + void slotPasswordChanged(const QString &newText); + void slotNameEdited(QTableWidgetItem *item); - void slotShareLinkButtonTriggered(QAction* action); + void slotShareLinkButtonTriggered(QAction *action); void slotDeleteShareFetched(); void slotCreateShareFetched(const QSharedPointer share); - void slotCreateShareRequiresPassword(const QString& message); + void slotCreateShareRequiresPassword(const QString &message); void slotPasswordSet(); void slotExpireSet(); void slotPublicUploadSet(); @@ -83,7 +83,7 @@ private slots: void slotPasswordSetError(int code, const QString &message); private: - void displayError(const QString& errMsg); + void displayError(const QString &errMsg); void setPassword(const QString &password); void setExpireDate(const QDate &date); @@ -126,7 +126,6 @@ private: QAction *_emailLinkAction; QAction *_emailDirectLinkAction; }; - } #endif // SHARELINKWIDGET_H diff --git a/src/gui/sharemanager.cpp b/src/gui/sharemanager.cpp index 3993430fd..cc8233289 100644 --- a/src/gui/sharemanager.cpp +++ b/src/gui/sharemanager.cpp @@ -35,19 +35,18 @@ Q_DECLARE_METATYPE(CreateShare) namespace OCC { Share::Share(AccountPtr account, - const QString& id, - const QString& path, - const ShareType shareType, - const Permissions permissions, - const QSharedPointer shareWith) -: _account(account), - _id(id), - _path(path), - _shareType(shareType), - _permissions(permissions), - _shareWith(shareWith) + const QString &id, + const QString &path, + const ShareType shareType, + const Permissions permissions, + const QSharedPointer shareWith) + : _account(account) + , _id(id) + , _path(path) + , _shareType(shareType) + , _permissions(permissions) + , _shareWith(shareWith) { - } AccountPtr Share::account() const @@ -130,28 +129,26 @@ bool LinkShare::isPasswordSet() const } LinkShare::LinkShare(AccountPtr account, - const QString& id, - const QString& path, - const QString& name, - const QString& token, - Permissions permissions, - bool passwordSet, - const QUrl& url, - const QDate& expireDate) -: Share(account, id, path, Share::TypeLink, permissions), - _name(name), - _token(token), - _passwordSet(passwordSet), - _expireDate(expireDate), - _url(url) + const QString &id, + const QString &path, + const QString &name, + const QString &token, + Permissions permissions, + bool passwordSet, + const QUrl &url, + const QDate &expireDate) + : Share(account, id, path, Share::TypeLink, permissions) + , _name(name) + , _token(token) + , _passwordSet(passwordSet) + , _expireDate(expireDate) + , _url(url) { - } bool LinkShare::getPublicUpload() { - return ((_permissions & SharePermissionUpdate) && - (_permissions & SharePermissionCreate)); + return ((_permissions & SharePermissionUpdate) && (_permissions & SharePermissionCreate)); } void LinkShare::setPublicUpload(bool publicUpload) @@ -167,11 +164,11 @@ QString LinkShare::getName() const return _name; } -void LinkShare::setName(const QString& name) +void LinkShare::setName(const QString &name) { OcsShareJob *job = new OcsShareJob(_account); - connect(job, SIGNAL(shareJobFinished(QJsonDocument,QVariant)), SLOT(slotNameSet(QJsonDocument,QVariant))); - connect(job, SIGNAL(ocsError(int,QString)), SLOT(slotOcsError(int,QString))); + connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotNameSet(QJsonDocument, QVariant))); + connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotOcsError(int, QString))); job->setName(getId(), name); } @@ -180,7 +177,7 @@ QString LinkShare::getToken() const return _token; } -void LinkShare::slotPublicUploadSet(const QJsonDocument&, const QVariant &value) +void LinkShare::slotPublicUploadSet(const QJsonDocument &, const QVariant &value) { if (value.toBool()) { _permissions = SharePermissionRead | SharePermissionUpdate | SharePermissionCreate; @@ -195,11 +192,11 @@ void LinkShare::setPassword(const QString &password) { OcsShareJob *job = new OcsShareJob(_account); connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotPasswordSet(QJsonDocument, QVariant))); - connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotSetPasswordError(int,QString))); + connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotSetPasswordError(int, QString))); job->setPassword(getId(), password); } -void LinkShare::slotPasswordSet(const QJsonDocument&, const QVariant &value) +void LinkShare::slotPasswordSet(const QJsonDocument &, const QVariant &value) { _passwordSet = value.toString() == ""; emit passwordSet(); @@ -213,7 +210,7 @@ void LinkShare::setExpireDate(const QDate &date) job->setExpireDate(getId(), date); } -void LinkShare::slotExpireDateSet(const QJsonDocument& reply, const QVariant &value) +void LinkShare::slotExpireDateSet(const QJsonDocument &reply, const QVariant &value) { auto data = reply.object().value("ocs").toObject().value("data").toObject(); @@ -222,7 +219,7 @@ void LinkShare::slotExpireDateSet(const QJsonDocument& reply, const QVariant &va * they use this date. */ if (data.value("expiration").isString()) { - _expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00"); + _expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00"); } else { _expireDate = value.toDate(); } @@ -241,15 +238,14 @@ void LinkShare::slotNameSet(const QJsonDocument &, const QVariant &value) } ShareManager::ShareManager(AccountPtr account, QObject *parent) -: QObject(parent), - _account(account) + : QObject(parent) + , _account(account) { - } void ShareManager::createLinkShare(const QString &path, - const QString &name, - const QString &password) + const QString &name, + const QString &password) { OcsShareJob *job = new OcsShareJob(_account); connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotLinkShareCreated(QJsonDocument))); @@ -279,10 +275,10 @@ void ShareManager::slotLinkShareCreated(const QJsonDocument &reply) } -void ShareManager::createShare(const QString& path, - const Share::ShareType shareType, - const QString shareWith, - const Share::Permissions permissions) +void ShareManager::createShare(const QString &path, + const Share::ShareType shareType, + const QString shareWith, + const Share::Permissions permissions) { auto job = new OcsShareJob(_account); @@ -294,8 +290,8 @@ void ShareManager::createShare(const QString& path, continuation.permissions = permissions; _jobContinuation[job] = QVariant::fromValue(continuation); - connect(job, SIGNAL(shareJobFinished(QJsonDocument,QVariant)), SLOT(slotCreateShare(QJsonDocument))); - connect(job, SIGNAL(ocsError(int,QString)), SLOT(slotOcsError(int,QString))); + connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotCreateShare(QJsonDocument))); + connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotOcsError(int, QString))); job->getSharedWithMe(); } @@ -311,7 +307,7 @@ void ShareManager::slotCreateShare(const QJsonDocument &reply) // Find existing share permissions (if this was shared with us) Share::Permissions existingPermissions = SharePermissionDefault; - foreach (const QJsonValue & element, reply.object()["ocs"].toObject()["data"].toArray()) { + foreach (const QJsonValue &element, reply.object()["ocs"].toObject()["data"].toArray()) { auto map = element.toObject(); if (map["file_target"] == cont.path) existingPermissions = Share::Permissions(map["permissions"].toInt()); @@ -356,7 +352,7 @@ void ShareManager::slotSharesFetched(const QJsonDocument &reply) QList> shares; - foreach(const auto &share, tmpShares) { + foreach (const auto &share, tmpShares) { auto data = share.toObject(); auto shareType = data.value("share_type").toInt(); @@ -395,37 +391,36 @@ QSharedPointer ShareManager::parseLinkShare(const QJsonObject &data) QDate expireDate; if (data.value("expiration").isString()) { - expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00"); + expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00"); } return QSharedPointer(new LinkShare(_account, - data.value("id").toString(), - data.value("path").toString(), - data.value("name").toString(), - data.value("token").toString(), - (Share::Permissions)data.value("permissions").toInt(), - data.value("share_with").isString(), // has password? - url, - expireDate)); + data.value("id").toString(), + data.value("path").toString(), + data.value("name").toString(), + data.value("token").toString(), + (Share::Permissions)data.value("permissions").toInt(), + data.value("share_with").isString(), // has password? + url, + expireDate)); } QSharedPointer ShareManager::parseShare(const QJsonObject &data) { QSharedPointer sharee(new Sharee(data.value("share_with").toString(), - data.value("share_with_displayname").toString(), - (Sharee::Type)data.value("share_type").toInt())); + data.value("share_with_displayname").toString(), + (Sharee::Type)data.value("share_type").toInt())); return QSharedPointer(new Share(_account, - data.value("id").toString(), - data.value("path").toString(), - (Share::ShareType)data.value("share_type").toInt(), - (Share::Permissions)data.value("permissions").toInt(), - sharee)); + data.value("id").toString(), + data.value("path").toString(), + (Share::ShareType)data.value("share_type").toInt(), + (Share::Permissions)data.value("permissions").toInt(), + sharee)); } void ShareManager::slotOcsError(int statusCode, const QString &message) { emit serverError(statusCode, message); } - } diff --git a/src/gui/sharemanager.h b/src/gui/sharemanager.h index 72e3d73de..62ff6ee4c 100644 --- a/src/gui/sharemanager.h +++ b/src/gui/sharemanager.h @@ -31,19 +31,19 @@ class QJsonObject; namespace OCC { -class Share : public QObject { +class Share : public QObject +{ Q_OBJECT public: - /** * Possible share types * Need to be in sync with Sharee::Type */ enum ShareType { - TypeUser = Sharee::User, - TypeGroup = Sharee::Group, - TypeLink = 3, + TypeUser = Sharee::User, + TypeGroup = Sharee::Group, + TypeLink = 3, TypeRemote = Sharee::Federated }; @@ -53,11 +53,11 @@ public: * Constructor for shares */ explicit Share(AccountPtr account, - const QString& id, - const QString& path, - const ShareType shareType, - const Permissions permissions = SharePermissionDefault, - const QSharedPointer shareWith = QSharedPointer(NULL)); + const QString &id, + const QString &path, + const ShareType shareType, + const Permissions permissions = SharePermissionDefault, + const QSharedPointer shareWith = QSharedPointer(NULL)); /** * The account the share is defined on. @@ -119,7 +119,6 @@ protected slots: private slots: void slotDeleted(); void slotPermissionsSet(const QJsonDocument &, const QVariant &value); - }; /** @@ -127,19 +126,19 @@ private slots: * There are several methods in the API that either work differently for * link shares or are only available to link shares. */ -class LinkShare : public Share { +class LinkShare : public Share +{ Q_OBJECT public: - explicit LinkShare(AccountPtr account, - const QString& id, - const QString& path, - const QString& name, - const QString& token, - const Permissions permissions, - bool passwordSet, - const QUrl& url, - const QDate& expireDate); + const QString &id, + const QString &path, + const QString &name, + const QString &token, + const Permissions permissions, + bool passwordSet, + const QUrl &url, + const QDate &expireDate); /* * Get the share link @@ -175,7 +174,7 @@ public: * * Emits either nameSet() or serverError(). */ - void setName(const QString& name); + void setName(const QString &name); /* * Returns the token of the link share. @@ -188,7 +187,7 @@ public: * On success the passwordSet signal is emitted * In case of a server error the serverError signal is emitted. */ - void setPassword(const QString& password); + void setPassword(const QString &password); /* * Is the password set? @@ -206,7 +205,7 @@ public: * On success the expireDateSet signal is emitted * In case of a server error the serverError signal is emitted. */ - void setExpireDate(const QDate& expireDate); + void setExpireDate(const QDate &expireDate); signals: void expireDateSet(); @@ -216,11 +215,11 @@ signals: void nameSet(); private slots: - void slotPasswordSet(const QJsonDocument&, const QVariant &value); - void slotPublicUploadSet(const QJsonDocument&, const QVariant &value); - void slotExpireDateSet(const QJsonDocument& reply, const QVariant &value); + void slotPasswordSet(const QJsonDocument &, const QVariant &value); + void slotPublicUploadSet(const QJsonDocument &, const QVariant &value); + void slotExpireDateSet(const QJsonDocument &reply, const QVariant &value); void slotSetPasswordError(int statusCode, const QString &message); - void slotNameSet(const QJsonDocument&, const QVariant &value); + void slotNameSet(const QJsonDocument &, const QVariant &value); private: QString _name; @@ -235,7 +234,8 @@ private: * of shares. It abstracts away from the OCS Share API, all the usages * shares should talk to this manager and not use OCS Share Job directly */ -class ShareManager : public QObject { +class ShareManager : public QObject +{ Q_OBJECT public: explicit ShareManager(AccountPtr _account, QObject *parent = NULL); @@ -251,9 +251,9 @@ public: * For older server the linkShareRequiresPassword signal is emitted when it seems appropiate * In case of a server error the serverError signal is emitted */ - void createLinkShare(const QString& path, - const QString& name, - const QString& password); + void createLinkShare(const QString &path, + const QString &name, + const QString &password); /** * Tell the manager to create a new share @@ -265,10 +265,10 @@ public: * On success the signal shareCreated is emitted * In case of a server error the serverError signal is emitted */ - void createShare(const QString& path, - const Share::ShareType shareType, - const QString shareWith, - const Share::Permissions permissions); + void createShare(const QString &path, + const Share::ShareType shareType, + const QString shareWith, + const Share::Permissions permissions); /** * Fetch all the shares for path @@ -278,7 +278,7 @@ public: * On success the sharesFetched signal is emitted * In case of a server error the serverError signal is emitted */ - void fetchShares(const QString& path); + void fetchShares(const QString &path); signals: void shareCreated(const QSharedPointer &share); @@ -305,10 +305,9 @@ private: QSharedPointer parseLinkShare(const QJsonObject &data); QSharedPointer parseShare(const QJsonObject &data); - QMap _jobContinuation; + QMap _jobContinuation; AccountPtr _account; }; - } #endif // SHAREMANAGER_H diff --git a/src/gui/sharepermissions.h b/src/gui/sharepermissions.h index 8a8f906e9..5d1245912 100644 --- a/src/gui/sharepermissions.h +++ b/src/gui/sharepermissions.h @@ -23,11 +23,11 @@ namespace OCC { * Possible permissions, must match the server permission constants */ enum SharePermission { - SharePermissionRead = 1, - SharePermissionUpdate = 2, - SharePermissionCreate = 4, - SharePermissionDelete = 8, - SharePermissionShare = 16, + SharePermissionRead = 1, + SharePermissionUpdate = 2, + SharePermissionCreate = 4, + SharePermissionDelete = 8, + SharePermissionShare = 16, SharePermissionDefault = 1 << 30 }; Q_DECLARE_FLAGS(SharePermissions, SharePermission) diff --git a/src/gui/shareusergroupwidget.cpp b/src/gui/shareusergroupwidget.cpp index 66008b4d1..1351f888f 100644 --- a/src/gui/shareusergroupwidget.cpp +++ b/src/gui/shareusergroupwidget.cpp @@ -43,17 +43,17 @@ namespace OCC { ShareUserGroupWidget::ShareUserGroupWidget(AccountPtr account, - const QString &sharePath, - const QString &localPath, - SharePermissions maxSharingPermissions, - QWidget *parent) : - QWidget(parent), - _ui(new Ui::ShareUserGroupWidget), - _account(account), - _sharePath(sharePath), - _localPath(localPath), - _maxSharingPermissions(maxSharingPermissions), - _disableCompleterActivated(false) + const QString &sharePath, + const QString &localPath, + SharePermissions maxSharingPermissions, + QWidget *parent) + : QWidget(parent) + , _ui(new Ui::ShareUserGroupWidget) + , _account(account) + , _sharePath(sharePath) + , _localPath(localPath) + , _maxSharingPermissions(maxSharingPermissions) + , _disableCompleterActivated(false) { setAttribute(Qt::WA_DeleteOnClose); setObjectName("SharingDialogUG"); // required as group for saveGeometry call @@ -65,10 +65,10 @@ ShareUserGroupWidget::ShareUserGroupWidget(AccountPtr account, _completer = new QCompleter(this); _completerModel = new ShareeModel(_account, - _isFile ? QLatin1String("file") : QLatin1String("folder"), - _completer); + _isFile ? QLatin1String("file") : QLatin1String("folder"), + _completer); connect(_completerModel, SIGNAL(shareesReady()), this, SLOT(slotShareesReady())); - connect(_completerModel, SIGNAL(displayErrorMessage(int,QString)), this, SLOT(displayError(int,QString))); + connect(_completerModel, SIGNAL(displayErrorMessage(int, QString)), this, SLOT(displayError(int, QString))); _completer->setModel(_completerModel); _completer->setCaseSensitivity(Qt::CaseInsensitive); @@ -78,19 +78,19 @@ ShareUserGroupWidget::ShareUserGroupWidget(AccountPtr account, _manager = new ShareManager(_account, this); connect(_manager, SIGNAL(sharesFetched(QList>)), SLOT(slotSharesFetched(QList>))); connect(_manager, SIGNAL(shareCreated(QSharedPointer)), SLOT(getShares())); - connect(_manager, SIGNAL(serverError(int,QString)), this, SLOT(displayError(int,QString))); + connect(_manager, SIGNAL(serverError(int, QString)), this, SLOT(displayError(int, QString))); connect(_ui->shareeLineEdit, SIGNAL(returnPressed()), SLOT(slotLineEditReturn())); // By making the next two QueuedConnections we can override // the strings the completer sets on the line edit. connect(_completer, SIGNAL(activated(QModelIndex)), SLOT(slotCompleterActivated(QModelIndex)), - Qt::QueuedConnection); + Qt::QueuedConnection); connect(_completer, SIGNAL(highlighted(QModelIndex)), SLOT(slotCompleterHighlighted(QModelIndex)), - Qt::QueuedConnection); + Qt::QueuedConnection); // Queued connection so this signal is recieved after textChanged connect(_ui->shareeLineEdit, SIGNAL(textEdited(QString)), - this, SLOT(slotLineEditTextEdited(QString)), Qt::QueuedConnection); + this, SLOT(slotLineEditTextEdited(QString)), Qt::QueuedConnection); connect(&_completionTimer, SIGNAL(timeout()), this, SLOT(searchForSharees())); _completionTimer.setSingleShot(true); _completionTimer.setInterval(600); @@ -112,7 +112,7 @@ void ShareUserGroupWidget::on_shareeLineEdit_textChanged(const QString &) _completionTimer.stop(); } -void ShareUserGroupWidget::slotLineEditTextEdited(const QString& text) +void ShareUserGroupWidget::slotLineEditTextEdited(const QString &text) { _disableCompleterActivated = false; // First textChanged is called first and we stopped the timer when the text is changed, programatically or not @@ -130,8 +130,8 @@ void ShareUserGroupWidget::slotLineEditReturn() for (int i = 0; i < _completerModel->rowCount(); ++i) { const auto sharee = _completerModel->getSharee(i); if (sharee->format() == text - || sharee->displayName() == text - || sharee->shareWith() == text) { + || sharee->displayName() == text + || sharee->shareWith() == text) { slotCompleterActivated(_completerModel->index(i)); // make sure we do not send the same item twice (because return is called when we press // return to activate an item inthe completer) @@ -155,7 +155,7 @@ void ShareUserGroupWidget::searchForSharees() QSharedPointer currentUser(new Sharee(_account->credentials()->user(), "", Sharee::Type::User)); blacklist << currentUser; - foreach (auto sw, _ui->scrollArea->findChildren()) { + foreach (auto sw, _ui->scrollArea->findChildren()) { blacklist << sw->share()->getShareWith(); } _ui->errorLabel->hide(); @@ -180,7 +180,7 @@ void ShareUserGroupWidget::slotSharesFetched(const QList> if (shares.isEmpty()) { layout->addWidget(new QLabel(tr("The item is not shared with any users or groups"))); } else { - foreach(const auto &share, shares) { + foreach (const auto &share, shares) { // We don't handle link shares if (share->getShareType() == Share::TypeLink) { continue; @@ -213,7 +213,7 @@ void ShareUserGroupWidget::slotSharesFetched(const QList> void ShareUserGroupWidget::slotAdjustScrollWidgetSize() { QScrollArea *scrollArea = _ui->scrollArea; - if (scrollArea->findChildren().count() <= 3) { + if (scrollArea->findChildren().count() <= 3) { auto minimumSize = scrollArea->widget()->sizeHint(); auto spacing = scrollArea->widget()->layout()->spacing(); minimumSize.rwidth() += spacing; @@ -232,7 +232,7 @@ void ShareUserGroupWidget::slotShareesReady() _completer->complete(); } -void ShareUserGroupWidget::slotCompleterActivated(const QModelIndex & index) +void ShareUserGroupWidget::slotCompleterActivated(const QModelIndex &index) { if (_disableCompleterActivated) return; @@ -247,7 +247,7 @@ void ShareUserGroupWidget::slotCompleterActivated(const QModelIndex & index) * Add spinner to the bottom of the widget list */ auto viewPort = _ui->scrollArea->widget(); - auto layout = qobject_cast(viewPort->layout()); + auto layout = qobject_cast(viewPort->layout()); auto indicator = new QProgressIndicator(viewPort); indicator->startAnimation(); if (layout->count() == 1) { @@ -263,35 +263,35 @@ void ShareUserGroupWidget::slotCompleterActivated(const QModelIndex & index) * https://github.com/owncloud/client/issues/4996 */ if (sharee->type() == Sharee::Federated - && _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) { + && _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) { int permissions = SharePermissionRead | SharePermissionUpdate; if (!_isFile) { permissions |= SharePermissionCreate | SharePermissionDelete; } _manager->createShare(_sharePath, Share::ShareType(sharee->type()), - sharee->shareWith(), SharePermission(permissions)); + sharee->shareWith(), SharePermission(permissions)); } else { _manager->createShare(_sharePath, Share::ShareType(sharee->type()), - sharee->shareWith(), SharePermissionDefault); + sharee->shareWith(), SharePermissionDefault); } _ui->shareeLineEdit->setEnabled(false); _ui->shareeLineEdit->setText(QString()); } -void ShareUserGroupWidget::slotCompleterHighlighted(const QModelIndex & index) +void ShareUserGroupWidget::slotCompleterHighlighted(const QModelIndex &index) { // By default the completer would set the text to EditRole, // override that here. _ui->shareeLineEdit->setText(index.data(Qt::DisplayRole).toString()); } -void ShareUserGroupWidget::displayError(int code, const QString& message) +void ShareUserGroupWidget::displayError(int code, const QString &message) { _pi_sharee.stopAnimation(); // Also remove the spinner in the widget list, if any - foreach (auto pi, _ui->scrollArea->findChildren()) { + foreach (auto pi, _ui->scrollArea->findChildren()) { delete pi; } @@ -302,18 +302,18 @@ void ShareUserGroupWidget::displayError(int code, const QString& message) } ShareUserLine::ShareUserLine(QSharedPointer share, - SharePermissions maxSharingPermissions, - bool isFile, - QWidget *parent) : - QWidget(parent), - _ui(new Ui::ShareUserLine), - _share(share), - _isFile(isFile) + SharePermissions maxSharingPermissions, + bool isFile, + QWidget *parent) + : QWidget(parent) + , _ui(new Ui::ShareUserLine) + , _share(share) + , _isFile(isFile) { _ui->setupUi(this); _ui->sharedWith->setText(share->getShareWith()->format()); - + // Create detailed permissions menu QMenu *menu = new QMenu(this); _permissionCreate = new QAction(tr("create"), this); @@ -350,13 +350,13 @@ ShareUserLine::ShareUserLine(QSharedPointer share, _ui->permissionShare->setEnabled(maxSharingPermissions & SharePermissionShare); _ui->permissionsEdit->setEnabled(maxSharingPermissions - & (SharePermissionCreate | SharePermissionUpdate | SharePermissionDelete)); + & (SharePermissionCreate | SharePermissionUpdate | SharePermissionDelete)); connect(_permissionUpdate, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged())); connect(_permissionCreate, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged())); connect(_permissionDelete, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged())); - connect(_ui->permissionShare, SIGNAL(clicked(bool)), SLOT(slotPermissionsChanged())); - connect(_ui->permissionsEdit, SIGNAL(clicked(bool)), SLOT(slotEditPermissionsChanged())); + connect(_ui->permissionShare, SIGNAL(clicked(bool)), SLOT(slotPermissionsChanged())); + connect(_ui->permissionsEdit, SIGNAL(clicked(bool)), SLOT(slotEditPermissionsChanged())); /* * We don't show permssion share for federated shares with server <9.1 @@ -364,7 +364,7 @@ ShareUserLine::ShareUserLine(QSharedPointer share, * https://github.com/owncloud/client/issues/4996 */ if (share->getShareType() == Share::TypeRemote - && share->account()->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) { + && share->account()->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) { _ui->permissionShare->setVisible(false); _ui->permissionToolButton->setVisible(false); } @@ -373,7 +373,7 @@ ShareUserLine::ShareUserLine(QSharedPointer share, connect(share.data(), SIGNAL(shareDeleted()), SLOT(slotShareDeleted())); _ui->deleteShareButton->setIcon(QIcon::fromTheme(QLatin1String("user-trash"), - QIcon(QLatin1String(":/client/resources/delete.png")))); + QIcon(QLatin1String(":/client/resources/delete.png")))); if (!share->account()->capabilities().shareResharing()) { _ui->permissionShare->hide(); @@ -429,7 +429,7 @@ void ShareUserLine::slotEditPermissionsChanged() void ShareUserLine::slotPermissionsChanged() { setEnabled(false); - + Share::Permissions permissions = SharePermissionRead; if (_permissionUpdate->isChecked()) { @@ -460,7 +460,7 @@ void ShareUserLine::slotDeleteAnimationFinished() // There is a painting bug where a small line of this widget isn't // properly cleared. This explicit repaint() call makes sure any trace of // the share widget is removed once it's destroyed. #4189 - connect(this, SIGNAL(destroyed(QObject*)), parentWidget(), SLOT(repaint())); + connect(this, SIGNAL(destroyed(QObject *)), parentWidget(), SLOT(repaint())); } void ShareUserLine::slotShareDeleted() @@ -506,9 +506,9 @@ void ShareUserLine::displayPermissions() } if (perm & SharePermissionUpdate - && (_isFile - || (perm & SharePermissionCreate - && perm & SharePermissionDelete))) { + && (_isFile + || (perm & SharePermissionCreate + && perm & SharePermissionDelete))) { _ui->permissionsEdit->setCheckState(Qt::Checked); } else if (perm & (SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete)) { _ui->permissionsEdit->setCheckState(Qt::PartiallyChecked); @@ -521,5 +521,4 @@ void ShareUserLine::displayPermissions() _ui->permissionShare->setCheckState(Qt::Checked); } } - } diff --git a/src/gui/shareusergroupwidget.h b/src/gui/shareusergroupwidget.h index 6da721435..36639196d 100644 --- a/src/gui/shareusergroupwidget.h +++ b/src/gui/shareusergroupwidget.h @@ -32,8 +32,8 @@ class QModelIndex; namespace OCC { namespace Ui { -class ShareUserGroupWidget; -class ShareUserLine; + class ShareUserGroupWidget; + class ShareUserLine; } class AbstractCredentials; @@ -53,11 +53,11 @@ class ShareUserGroupWidget : public QWidget Q_OBJECT public: - explicit ShareUserGroupWidget(AccountPtr account, - const QString &sharePath, - const QString &localPath, - SharePermissions maxSharingPermissions, - QWidget *parent = 0); + explicit ShareUserGroupWidget(AccountPtr account, + const QString &sharePath, + const QString &localPath, + SharePermissions maxSharingPermissions, + QWidget *parent = 0); ~ShareUserGroupWidget(); public slots: @@ -71,11 +71,11 @@ private slots: void slotLineEditTextEdited(const QString &text); void slotLineEditReturn(); - void slotCompleterActivated(const QModelIndex & index); - void slotCompleterHighlighted(const QModelIndex & index); + void slotCompleterActivated(const QModelIndex &index); + void slotCompleterHighlighted(const QModelIndex &index); void slotShareesReady(); void slotAdjustScrollWidgetSize(); - void displayError(int code ,const QString &message); + void displayError(int code, const QString &message); private: Ui::ShareUserGroupWidget *_ui; @@ -104,9 +104,9 @@ class ShareUserLine : public QWidget public: explicit ShareUserLine(QSharedPointer Share, - SharePermissions maxSharingPermissions, - bool isFile, - QWidget *parent = 0); + SharePermissions maxSharingPermissions, + bool isFile, + QWidget *parent = 0); ~ShareUserLine(); QSharedPointer share() const; @@ -123,6 +123,7 @@ private slots: void slotShareDeleted(); void slotPermissionsSet(); + private: void displayPermissions(); @@ -134,7 +135,6 @@ private: QAction *_permissionUpdate; QAction *_permissionDelete; }; - } #endif // SHAREUSERGROUPWIDGET_H diff --git a/src/gui/socketapi.cpp b/src/gui/socketapi.cpp index a4973aeb8..82705c59a 100644 --- a/src/gui/socketapi.cpp +++ b/src/gui/socketapi.cpp @@ -61,19 +61,19 @@ static inline QString removeTrailingSlash(QString path) { Q_ASSERT(path.endsWith(QLatin1Char('/'))); - path.truncate(path.length()-1); + path.truncate(path.length() - 1); return path; } -static QString buildMessage(const QString& verb, const QString &path, const QString &status = QString::null ) +static QString buildMessage(const QString &verb, const QString &path, const QString &status = QString::null) { QString msg(verb); - if( !status.isEmpty() ) { + if (!status.isEmpty()) { msg.append(QLatin1Char(':')); msg.append(status); } - if( !path.isEmpty() ) { + if (!path.isEmpty()) { msg.append(QLatin1Char(':')); QFileInfo fi(path); msg.append(QDir::toNativeSeparators(fi.absoluteFilePath())); @@ -85,19 +85,25 @@ namespace OCC { Q_LOGGING_CATEGORY(lcSocketApi, "gui.socketapi", QtInfoMsg) -class BloomFilter { +class BloomFilter +{ // Initialize with m=1024 bits and k=2 (high and low 16 bits of a qHash). // For a client navigating in less than 100 directories, this gives us a probability less than (1-e^(-2*100/1024))^2 = 0.03147872136 false positives. const static int NumBits = 1024; public: - BloomFilter() : hashBits(NumBits) { } + BloomFilter() + : hashBits(NumBits) + { + } - void storeHash(uint hash) { + void storeHash(uint hash) + { hashBits.setBit((hash & 0xFFFF) % NumBits); hashBits.setBit((hash >> 16) % NumBits); } - bool isHashMaybeStored(uint hash) const { + bool isHashMaybeStored(uint hash) const + { return hashBits.testBit((hash & 0xFFFF) % NumBits) && hashBits.testBit((hash >> 16) % NumBits); } @@ -106,32 +112,35 @@ private: QBitArray hashBits; }; -class SocketListener { +class SocketListener +{ public: - QIODevice* socket; + QIODevice *socket; - SocketListener(QIODevice* socket = 0) : socket(socket) { } + SocketListener(QIODevice *socket = 0) + : socket(socket) + { + } - void sendMessage(const QString& message, bool doWait = false) const + void sendMessage(const QString &message, bool doWait = false) const { qCInfo(lcSocketApi) << "Sending SocketAPI message: " << message << "to" << socket; QString localMessage = message; - if( ! localMessage.endsWith(QLatin1Char('\n'))) { + if (!localMessage.endsWith(QLatin1Char('\n'))) { localMessage.append(QLatin1Char('\n')); } QByteArray bytesToSend = localMessage.toUtf8(); qint64 sent = socket->write(bytesToSend); - if( doWait ) { + if (doWait) { socket->waitForBytesWritten(1000); } - if( sent != bytesToSend.length() ) { + if (sent != bytesToSend.length()) { qCWarning(lcSocketApi) << "Could not send all data on socket for " << localMessage; } - } - void sendMessageIfDirectoryMonitored(const QString& message, uint systemDirectoryHash) const + void sendMessageIfDirectoryMonitored(const QString &message, uint systemDirectoryHash) const { if (_monitoredDirectoriesBloomFilter.isHashMaybeStored(systemDirectoryHash)) sendMessage(message, false); @@ -141,25 +150,30 @@ public: { _monitoredDirectoriesBloomFilter.storeHash(systemDirectoryHash); } + private: BloomFilter _monitoredDirectoriesBloomFilter; }; -struct ListenerHasSocketPred { +struct ListenerHasSocketPred +{ QIODevice *socket; - ListenerHasSocketPred(QIODevice *socket) : socket(socket) { } + ListenerHasSocketPred(QIODevice *socket) + : socket(socket) + { + } bool operator()(const SocketListener &listener) const { return listener.socket == socket; } }; -SocketApi::SocketApi(QObject* parent) +SocketApi::SocketApi(QObject *parent) : QObject(parent) { QString socketPath; if (Utility::isWindows()) { socketPath = QLatin1String("\\\\.\\pipe\\") - + QLatin1String("ownCloud-") - + QString::fromLocal8Bit(qgetenv("USERNAME")); + + QLatin1String("ownCloud-") + + QString::fromLocal8Bit(qgetenv("USERNAME")); // TODO: once the windows extension supports multiple // client connections, switch back to the theme name // See issue #2388 @@ -169,7 +183,7 @@ SocketApi::SocketApi(QObject* parent) // Example for developer builds (with ad-hoc signing identity): "" "com.owncloud.desktopclient" ".socketApi" // Example for official signed packages: "9B5WD74GWJ." "com.owncloud.desktopclient" ".socketApi" socketPath = SOCKETAPI_TEAM_IDENTIFIER_PREFIX APPLICATION_REV_DOMAIN ".socketApi"; - } else if( Utility::isLinux() || Utility::isBSD() ) { + } else if (Utility::isLinux() || Utility::isBSD()) { QString runtimeDir; #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) runtimeDir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation); @@ -183,7 +197,7 @@ SocketApi::SocketApi(QObject* parent) #endif socketPath = runtimeDir + "/" + Theme::instance()->appName() + "/socket"; } else { - qCWarning(lcSocketApi) << "An unexpected system detected, this probably won't work."; + qCWarning(lcSocketApi) << "An unexpected system detected, this probably won't work."; } SocketApiServer::removeServer(socketPath); @@ -191,12 +205,12 @@ SocketApi::SocketApi(QObject* parent) if (!info.dir().exists()) { bool result = info.dir().mkpath("."); qCDebug(lcSocketApi) << "creating" << info.dir().path() << result; - if( result ) { + if (result) { QFile::setPermissions(socketPath, - QFile::Permissions(QFile::ReadOwner+QFile::WriteOwner+QFile::ExeOwner)); + QFile::Permissions(QFile::ReadOwner + QFile::WriteOwner + QFile::ExeOwner)); } } - if(!_localServer.listen(socketPath)) { + if (!_localServer.listen(socketPath)) { qCWarning(lcSocketApi) << "can't start server" << socketPath; } else { qCInfo(lcSocketApi) << "server started, listening at " << socketPath; @@ -205,7 +219,7 @@ SocketApi::SocketApi(QObject* parent) connect(&_localServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection())); // folder watcher - connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder*)), this, SLOT(slotUpdateFolderView(Folder*))); + connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder *)), this, SLOT(slotUpdateFolderView(Folder *))); } SocketApi::~SocketApi() @@ -219,21 +233,21 @@ SocketApi::~SocketApi() void SocketApi::slotNewConnection() { - QIODevice* socket = _localServer.nextPendingConnection(); + QIODevice *socket = _localServer.nextPendingConnection(); - if( ! socket ) { + if (!socket) { return; } qCInfo(lcSocketApi) << "New connection" << socket; connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadSocket())); connect(socket, SIGNAL(disconnected()), this, SLOT(onLostConnection())); - connect(socket, SIGNAL(destroyed(QObject*)), this, SLOT(slotSocketDestroyed(QObject*))); + connect(socket, SIGNAL(destroyed(QObject *)), this, SLOT(slotSocketDestroyed(QObject *))); ASSERT(socket->readAll().isEmpty()); _listeners.append(SocketListener(socket)); SocketListener &listener = _listeners.last(); - foreach( Folder *f, FolderMan::instance()->map() ) { + foreach (Folder *f, FolderMan::instance()->map()) { if (f->canSync()) { QString message = buildRegisterPathMessage(removeTrailingSlash(f->path())); listener.sendMessage(message); @@ -247,19 +261,19 @@ void SocketApi::onLostConnection() sender()->deleteLater(); } -void SocketApi::slotSocketDestroyed(QObject* obj) +void SocketApi::slotSocketDestroyed(QObject *obj) { - QIODevice* socket = static_cast(obj); + QIODevice *socket = static_cast(obj); _listeners.erase(std::remove_if(_listeners.begin(), _listeners.end(), ListenerHasSocketPred(socket)), _listeners.end()); } void SocketApi::slotReadSocket() { - QIODevice* socket = qobject_cast(sender()); + QIODevice *socket = qobject_cast(sender()); ASSERT(socket); SocketListener *listener = &*std::find_if(_listeners.begin(), _listeners.end(), ListenerHasSocketPred(socket)); - while(socket->canReadLine()) { + while (socket->canReadLine()) { // Make sure to normalize the input from the socket to // make sure that the path will match, especially on OS X. QString line = QString::fromUtf8(socket->readLine()).normalized(QString::NormalizationForm_C); @@ -268,16 +282,16 @@ void SocketApi::slotReadSocket() QByteArray functionWithArguments = "command_" + command + "(QString,SocketListener*)"; int indexOfMethod = staticMetaObject.indexOfMethod(functionWithArguments); - QString argument = line.remove(0, command.length()+1); - if(indexOfMethod != -1) { - staticMetaObject.method(indexOfMethod).invoke(this, Q_ARG(QString, argument), Q_ARG(SocketListener*, listener)); + QString argument = line.remove(0, command.length() + 1); + if (indexOfMethod != -1) { + staticMetaObject.method(indexOfMethod).invoke(this, Q_ARG(QString, argument), Q_ARG(SocketListener *, listener)); } else { qCWarning(lcSocketApi) << "The command is not supported by this version of the client:" << command << "with argument:" << argument; } } } -void SocketApi::slotRegisterPath( const QString& alias ) +void SocketApi::slotRegisterPath(const QString &alias) { // Make sure not to register twice to each connected client if (_registeredAliases.contains(alias)) @@ -294,7 +308,7 @@ void SocketApi::slotRegisterPath( const QString& alias ) _registeredAliases.insert(alias); } -void SocketApi::slotUnregisterPath( const QString& alias ) +void SocketApi::slotUnregisterPath(const QString &alias) { if (!_registeredAliases.contains(alias)) return; @@ -314,13 +328,12 @@ void SocketApi::slotUpdateFolderView(Folder *f) if (f) { // do only send UPDATE_VIEW for a couple of status - if( f->syncResult().status() == SyncResult::SyncPrepare - || f->syncResult().status() == SyncResult::Success - || f->syncResult().status() == SyncResult::Paused - || f->syncResult().status() == SyncResult::Problem - || f->syncResult().status() == SyncResult::Error - || f->syncResult().status() == SyncResult::SetupError ) { - + if (f->syncResult().status() == SyncResult::SyncPrepare + || f->syncResult().status() == SyncResult::Success + || f->syncResult().status() == SyncResult::Paused + || f->syncResult().status() == SyncResult::Problem + || f->syncResult().status() == SyncResult::Error + || f->syncResult().status() == SyncResult::SetupError) { QString rootPath = removeTrailingSlash(f->path()); broadcastStatusPushMessage(rootPath, f->syncEngine().syncFileStatusTracker().fileStatus("")); @@ -331,14 +344,14 @@ void SocketApi::slotUpdateFolderView(Folder *f) } } -void SocketApi::broadcastMessage(const QString& msg, bool doWait) +void SocketApi::broadcastMessage(const QString &msg, bool doWait) { foreach (auto &listener, _listeners) { listener.sendMessage(msg, doWait); } } -void SocketApi::broadcastStatusPushMessage(const QString& systemPath, SyncFileStatus fileStatus) +void SocketApi::broadcastStatusPushMessage(const QString &systemPath, SyncFileStatus fileStatus) { QString msg = buildMessage(QLatin1String("STATUS"), systemPath, fileStatus.toSocketAPIString()); Q_ASSERT(!systemPath.endsWith('/')); @@ -348,26 +361,26 @@ void SocketApi::broadcastStatusPushMessage(const QString& systemPath, SyncFileSt } } -void SocketApi::command_RETRIEVE_FOLDER_STATUS(const QString& argument, SocketListener* listener) +void SocketApi::command_RETRIEVE_FOLDER_STATUS(const QString &argument, SocketListener *listener) { // This command is the same as RETRIEVE_FILE_STATUS command_RETRIEVE_FILE_STATUS(argument, listener); } -void SocketApi::command_RETRIEVE_FILE_STATUS(const QString& argument, SocketListener* listener) +void SocketApi::command_RETRIEVE_FILE_STATUS(const QString &argument, SocketListener *listener) { qCDebug(lcSocketApi) << argument; QString statusString; - Folder* syncFolder = FolderMan::instance()->folderForPath( argument ); + Folder *syncFolder = FolderMan::instance()->folderForPath(argument); if (!syncFolder) { // this can happen in offline mode e.g.: nothing to worry about statusString = QLatin1String("NOP"); } else { QString systemPath = QDir::cleanPath(argument); - if( systemPath.endsWith(QLatin1Char('/')) ) { - systemPath.truncate(systemPath.length()-1); + if (systemPath.endsWith(QLatin1Char('/'))) { + systemPath.truncate(systemPath.length() - 1); qCWarning(lcSocketApi) << "Removed trailing slash for directory: " << systemPath << "Status pushes won't have one."; } // The user probably visited this directory in the file shell. @@ -375,16 +388,16 @@ void SocketApi::command_RETRIEVE_FILE_STATUS(const QString& argument, SocketList QString directory = systemPath.left(systemPath.lastIndexOf('/')); listener->registerMonitoredDirectory(qHash(directory)); - QString relativePath = systemPath.mid(syncFolder->cleanPath().length()+1); + QString relativePath = systemPath.mid(syncFolder->cleanPath().length() + 1); SyncFileStatus fileStatus = syncFolder->syncEngine().syncFileStatusTracker().fileStatus(relativePath); statusString = fileStatus.toSocketAPIString(); } - const QString message = QLatin1String("STATUS:") % statusString % QLatin1Char(':') % QDir::toNativeSeparators(argument); + const QString message = QLatin1String("STATUS:") % statusString % QLatin1Char(':') % QDir::toNativeSeparators(argument); listener->sendMessage(message); } -void SocketApi::command_SHARE(const QString& localFile, SocketListener* listener) +void SocketApi::command_SHARE(const QString &localFile, SocketListener *listener) { qCDebug(lcSocketApi) << localFile; @@ -392,26 +405,24 @@ void SocketApi::command_SHARE(const QString& localFile, SocketListener* listener Folder *shareFolder = FolderMan::instance()->folderForPath(localFile); if (!shareFolder) { - const QString message = QLatin1String("SHARE:NOP:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE:NOP:") + QDir::toNativeSeparators(localFile); // files that are not within a sync folder are not synced. listener->sendMessage(message); } else if (!shareFolder->accountState()->isConnected()) { - const QString message = QLatin1String("SHARE:NOTCONNECTED:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE:NOTCONNECTED:") + QDir::toNativeSeparators(localFile); // if the folder isn't connected, don't open the share dialog listener->sendMessage(message); - } else if (!theme->linkSharing() && ( - !theme->userGroupSharing() || - shareFolder->accountState()->account()->serverVersionInt() < Account::makeServerVersion(8, 2, 0))) { - const QString message = QLatin1String("SHARE:NOP:")+QDir::toNativeSeparators(localFile); + } else if (!theme->linkSharing() && (!theme->userGroupSharing() || shareFolder->accountState()->account()->serverVersionInt() < Account::makeServerVersion(8, 2, 0))) { + const QString message = QLatin1String("SHARE:NOP:") + QDir::toNativeSeparators(localFile); listener->sendMessage(message); } else { const QString localFileClean = QDir::cleanPath(localFile); - const QString file = localFileClean.mid(shareFolder->cleanPath().length()+1); + const QString file = localFileClean.mid(shareFolder->cleanPath().length() + 1); SyncFileStatus fileStatus = shareFolder->syncEngine().syncFileStatusTracker().fileStatus(file); // Verify the file is on the server (to our knowledge of course) if (fileStatus.tag() != SyncFileStatus::StatusUpToDate) { - const QString message = QLatin1String("SHARE:NOTSYNCED:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE:NOTSYNCED:") + QDir::toNativeSeparators(localFile); listener->sendMessage(message); return; } @@ -420,7 +431,7 @@ void SocketApi::command_SHARE(const QString& localFile, SocketListener* listener // Can't share root folder if (remotePath == "/") { - const QString message = QLatin1String("SHARE:CANNOTSHAREROOT:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE:CANNOTSHAREROOT:") + QDir::toNativeSeparators(localFile); listener->sendMessage(message); return; } @@ -428,40 +439,40 @@ void SocketApi::command_SHARE(const QString& localFile, SocketListener* listener SyncJournalFileRecord rec = shareFolder->journalDb()->getFileRecord(localFileClean); bool allowReshare = true; // lets assume the good - if( rec.isValid() ) { + if (rec.isValid()) { // check the permission: Is resharing allowed? - if( !rec._remotePerm.contains('R') ) { + if (!rec._remotePerm.contains('R')) { allowReshare = false; } } - const QString message = QLatin1String("SHARE:OK:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE:OK:") + QDir::toNativeSeparators(localFile); listener->sendMessage(message); emit shareCommandReceived(remotePath, localFileClean, allowReshare); } } -void SocketApi::command_VERSION(const QString&, SocketListener* listener) +void SocketApi::command_VERSION(const QString &, SocketListener *listener) { listener->sendMessage(QLatin1String("VERSION:" MIRALL_VERSION_STRING ":" MIRALL_SOCKET_API_VERSION)); } -void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener* listener) +void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener *listener) { qCDebug(lcSocketApi) << localFile; Folder *shareFolder = FolderMan::instance()->folderForPath(localFile); if (!shareFolder) { - const QString message = QLatin1String("SHARE_STATUS:NOP:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE_STATUS:NOP:") + QDir::toNativeSeparators(localFile); listener->sendMessage(message); } else { - const QString file = QDir::cleanPath(localFile).mid(shareFolder->cleanPath().length()+1); + const QString file = QDir::cleanPath(localFile).mid(shareFolder->cleanPath().length() + 1); SyncFileStatus fileStatus = shareFolder->syncEngine().syncFileStatusTracker().fileStatus(file); // Verify the file is on the server (to our knowledge of course) if (fileStatus.tag() != SyncFileStatus::StatusUpToDate) { - const QString message = QLatin1String("SHARE_STATUS:NOTSYNCED:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE_STATUS:NOTSYNCED:") + QDir::toNativeSeparators(localFile); listener->sendMessage(message); return; } @@ -469,7 +480,7 @@ void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener* l const Capabilities capabilities = shareFolder->accountState()->account()->capabilities(); if (!capabilities.shareAPI()) { - const QString message = QLatin1String("SHARE_STATUS:DISABLED:")+QDir::toNativeSeparators(localFile); + const QString message = QLatin1String("SHARE_STATUS:DISABLED:") + QDir::toNativeSeparators(localFile); listener->sendMessage(message); } else { auto theme = Theme::instance(); @@ -498,12 +509,12 @@ void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener* l } } -void SocketApi::command_SHARE_MENU_TITLE(const QString &, SocketListener* listener) +void SocketApi::command_SHARE_MENU_TITLE(const QString &, SocketListener *listener) { listener->sendMessage(QLatin1String("SHARE_MENU_TITLE:") + tr("Share with %1", "parameter is ownCloud").arg(Theme::instance()->appNameGUI())); } -QString SocketApi::buildRegisterPathMessage(const QString& path) +QString SocketApi::buildRegisterPathMessage(const QString &path) { QFileInfo fi(path); QString message = QLatin1String("REGISTER_PATH:"); diff --git a/src/gui/socketapi.h b/src/gui/socketapi.h index 2c14cff27..e0b4c3ada 100644 --- a/src/gui/socketapi.h +++ b/src/gui/socketapi.h @@ -43,16 +43,16 @@ class SocketListener; */ class SocketApi : public QObject { -Q_OBJECT + Q_OBJECT public: - explicit SocketApi(QObject* parent = 0); + explicit SocketApi(QObject *parent = 0); virtual ~SocketApi(); public slots: void slotUpdateFolderView(Folder *f); - void slotUnregisterPath( const QString& alias ); - void slotRegisterPath( const QString& alias ); + void slotUnregisterPath(const QString &alias); + void slotRegisterPath(const QString &alias); signals: void shareCommandReceived(const QString &sharePath, const QString &localPath, bool resharingAllowed); @@ -61,27 +61,26 @@ signals: private slots: void slotNewConnection(); void onLostConnection(); - void slotSocketDestroyed(QObject* obj); + void slotSocketDestroyed(QObject *obj); void slotReadSocket(); - void broadcastStatusPushMessage(const QString& systemPath, SyncFileStatus fileStatus); + void broadcastStatusPushMessage(const QString &systemPath, SyncFileStatus fileStatus); private: - void broadcastMessage(const QString& msg, bool doWait = false); + void broadcastMessage(const QString &msg, bool doWait = false); - Q_INVOKABLE void command_RETRIEVE_FOLDER_STATUS(const QString& argument, SocketListener* listener); - Q_INVOKABLE void command_RETRIEVE_FILE_STATUS(const QString& argument, SocketListener* listener); - Q_INVOKABLE void command_SHARE(const QString& localFile, SocketListener* listener); + Q_INVOKABLE void command_RETRIEVE_FOLDER_STATUS(const QString &argument, SocketListener *listener); + Q_INVOKABLE void command_RETRIEVE_FILE_STATUS(const QString &argument, SocketListener *listener); + Q_INVOKABLE void command_SHARE(const QString &localFile, SocketListener *listener); - Q_INVOKABLE void command_VERSION(const QString& argument, SocketListener* listener); + Q_INVOKABLE void command_VERSION(const QString &argument, SocketListener *listener); - Q_INVOKABLE void command_SHARE_STATUS(const QString& localFile, SocketListener* listener); - Q_INVOKABLE void command_SHARE_MENU_TITLE(const QString& argument, SocketListener* listener); - QString buildRegisterPathMessage(const QString& path); + Q_INVOKABLE void command_SHARE_STATUS(const QString &localFile, SocketListener *listener); + Q_INVOKABLE void command_SHARE_MENU_TITLE(const QString &argument, SocketListener *listener); + QString buildRegisterPathMessage(const QString &path); QSet _registeredAliases; QList _listeners; SocketApiServer _localServer; }; - } #endif // SOCKETAPI_H diff --git a/src/gui/sslbutton.cpp b/src/gui/sslbutton.cpp index 8a6a4d503..89401c31e 100644 --- a/src/gui/sslbutton.cpp +++ b/src/gui/sslbutton.cpp @@ -29,20 +29,20 @@ namespace OCC { Q_LOGGING_CATEGORY(lcSsl, "gui.ssl", QtInfoMsg) -SslButton::SslButton(QWidget *parent) : - QToolButton(parent) +SslButton::SslButton(QWidget *parent) + : QToolButton(parent) { setPopupMode(QToolButton::InstantPopup); setAutoRaise(true); _menu = new QMenu(this); QObject::connect(_menu, SIGNAL(aboutToShow()), - this, SLOT(slotUpdateMenu())); + this, SLOT(slotUpdateMenu())); } QString SslButton::protoToString(QSsl::SslProtocol proto) { - switch(proto) { + switch (proto) { break; case QSsl::SslV2: return QLatin1String("SSL v2"); @@ -70,11 +70,11 @@ static QString addCertDetailsField(const QString &key, const QString &value) static bool isSelfSigned(const QSslCertificate &certificate) { return certificate.issuerInfo(QSslCertificate::CommonName) == certificate.subjectInfo(QSslCertificate::CommonName) - && certificate.issuerInfo(QSslCertificate::OrganizationalUnitName) == certificate.subjectInfo(QSslCertificate::OrganizationalUnitName); + && certificate.issuerInfo(QSslCertificate::OrganizationalUnitName) == certificate.subjectInfo(QSslCertificate::OrganizationalUnitName); } -QMenu* SslButton::buildCertMenu(QMenu *parent, const QSslCertificate& cert, - const QList& userApproved, int pos) +QMenu *SslButton::buildCertMenu(QMenu *parent, const QSslCertificate &cert, + const QList &userApproved, int pos) { QString cn = QStringList(cert.subjectInfo(QSslCertificate::CommonName)).join(QChar(';')); QString ou = QStringList(cert.subjectInfo(QSslCertificate::OrganizationalUnitName)).join(QChar(';')); @@ -90,9 +90,9 @@ QMenu* SslButton::buildCertMenu(QMenu *parent, const QSslCertificate& cert, #else QByteArray sha265hash = cert.digest(QCryptographicHash::Sha256).toHex(); QString sha256escaped = - Utility::escape(Utility::formatFingerprint(sha265hash.left(sha265hash.length()/2), false)) - + QLatin1String("
") - + Utility::escape(Utility::formatFingerprint(sha265hash.mid(sha265hash.length()/2), false)); + Utility::escape(Utility::formatFingerprint(sha265hash.left(sha265hash.length() / 2), false)) + + QLatin1String("
") + + Utility::escape(Utility::formatFingerprint(sha265hash.mid(sha265hash.length() / 2), false)); #endif QString serial = QString::fromUtf8(cert.serialNumber()); QString effectiveDate = cert.effectiveDate().date().toString(); @@ -108,8 +108,7 @@ QMenu* SslButton::buildCertMenu(QMenu *parent, const QSslCertificate& cert, stream << QLatin1String(""); stream << addCertDetailsField(tr("Common Name (CN):"), Utility::escape(cn)); - stream << addCertDetailsField(tr("Subject Alternative Names:"), Utility::escape(sna) - .replace(" ", "
")); + stream << addCertDetailsField(tr("Subject Alternative Names:"), Utility::escape(sna).replace(" ", "
")); stream << addCertDetailsField(tr("Organization (O):"), Utility::escape(org)); stream << addCertDetailsField(tr("Organizational Unit (OU):"), Utility::escape(ou)); stream << addCertDetailsField(tr("State/Province:"), Utility::escape(state)); @@ -143,7 +142,7 @@ QMenu* SslButton::buildCertMenu(QMenu *parent, const QSslCertificate& cert, QString txt; if (pos > 0) { - txt += QString(2*pos, ' '); + txt += QString(2 * pos, ' '); if (!Utility::isWindows()) { // doesn't seem to work reliably on Windows txt += QChar(0x21AA); // nicer '->' symbol @@ -178,7 +177,6 @@ QMenu* SslButton::buildCertMenu(QMenu *parent, const QSslCertificate& cert, menu->addAction(action); return menu; - } void SslButton::updateAccountState(AccountState *accountState) @@ -204,7 +202,8 @@ void SslButton::updateAccountState(AccountState *accountState) } } -void SslButton::slotUpdateMenu() { +void SslButton::slotUpdateMenu() +{ _menu->clear(); if (!_accountState) { @@ -215,9 +214,9 @@ void SslButton::slotUpdateMenu() { if (account->url().scheme() == QLatin1String("https")) { QString sslVersion = account->_sessionCipher.protocolString() - + ", " + account->_sessionCipher.authenticationMethod() - + ", " + account->_sessionCipher.keyExchangeMethod() - + ", " + account->_sessionCipher.encryptionMethod(); + + ", " + account->_sessionCipher.authenticationMethod() + + ", " + account->_sessionCipher.keyExchangeMethod() + + ", " + account->_sessionCipher.encryptionMethod(); _menu->addAction(sslVersion)->setEnabled(false); #if QT_VERSION > QT_VERSION_CHECK(5, 2, 0) @@ -236,7 +235,7 @@ void SslButton::slotUpdateMenu() { _menu->addAction(tr("Certificate information:"))->setEnabled(false); QList tmpChain; - foreach(QSslCertificate cert, chain) { + foreach (QSslCertificate cert, chain) { tmpChain << cert; if (QSslSocket::systemCaCertificates().contains(cert)) break; @@ -244,9 +243,9 @@ void SslButton::slotUpdateMenu() { chain = tmpChain; // find trust anchor (informational only, verification is done by QSslSocket!) - foreach(QSslCertificate rootCA, QSslSocket::systemCaCertificates()) { + foreach (QSslCertificate rootCA, QSslSocket::systemCaCertificates()) { if (rootCA.issuerInfo(QSslCertificate::CommonName) == chain.last().issuerInfo(QSslCertificate::CommonName) - && rootCA.issuerInfo(QSslCertificate::Organization) == chain.last().issuerInfo(QSslCertificate::Organization)) { + && rootCA.issuerInfo(QSslCertificate::Organization) == chain.last().issuerInfo(QSslCertificate::Organization)) { chain.append(rootCA); break; } diff --git a/src/gui/sslbutton.h b/src/gui/sslbutton.h index dec5e74f1..ffdafe52b 100644 --- a/src/gui/sslbutton.h +++ b/src/gui/sslbutton.h @@ -43,10 +43,10 @@ public slots: void slotUpdateMenu(); private: - QMenu* buildCertMenu(QMenu *parent, const QSslCertificate& cert, - const QList& userApproved, int pos); + QMenu *buildCertMenu(QMenu *parent, const QSslCertificate &cert, + const QList &userApproved, int pos); QPointer _accountState; - QMenu* _menu; + QMenu *_menu; }; } // namespace OCC diff --git a/src/gui/sslerrordialog.cpp b/src/gui/sslerrordialog.cpp index 53e90961e..4f6be75d6 100644 --- a/src/gui/sslerrordialog.cpp +++ b/src/gui/sslerrordialog.cpp @@ -24,8 +24,7 @@ #include "ui_sslerrordialog.h" -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcSslErrorDialog, "gui.sslerrordialog", QtInfoMsg) @@ -38,7 +37,7 @@ namespace Utility { bool SslDialogErrorHandler::handleErrors(QList errors, const QSslConfiguration &conf, QList *certs, AccountPtr account) { - (void) conf; + (void)conf; if (!certs) { qCCritical(lcSslErrorDialog) << "Certs parameter required but is NULL!"; return false; @@ -60,24 +59,27 @@ bool SslDialogErrorHandler::handleErrors(QList errors, const QSslConf return false; } -SslErrorDialog::SslErrorDialog(AccountPtr account, QWidget *parent) : - QDialog(parent), _allTrusted(false), _ui(new Ui::SslErrorDialog), _account(account) +SslErrorDialog::SslErrorDialog(AccountPtr account, QWidget *parent) + : QDialog(parent) + , _allTrusted(false) + , _ui(new Ui::SslErrorDialog) + , _account(account) { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - _ui->setupUi( this ); - setWindowTitle( tr("Untrusted Certificate") ); + _ui->setupUi(this); + setWindowTitle(tr("Untrusted Certificate")); QPushButton *okButton = - _ui->_dialogButtonBox->button( QDialogButtonBox::Ok ); + _ui->_dialogButtonBox->button(QDialogButtonBox::Ok); QPushButton *cancelButton = - _ui->_dialogButtonBox->button( QDialogButtonBox::Cancel ); + _ui->_dialogButtonBox->button(QDialogButtonBox::Cancel); okButton->setEnabled(false); connect(_ui->_cbTrustConnect, SIGNAL(clicked(bool)), - okButton, SLOT(setEnabled(bool))); + okButton, SLOT(setEnabled(bool))); - if( okButton ) { + if (okButton) { okButton->setDefault(true); - connect( okButton, SIGNAL(clicked()),SLOT(accept())); - connect( cancelButton, SIGNAL(clicked()),SLOT(reject())); + connect(okButton, SIGNAL(clicked()), SLOT(accept())); + connect(cancelButton, SIGNAL(clicked()), SLOT(reject())); } } @@ -90,19 +92,18 @@ SslErrorDialog::~SslErrorDialog() QString SslErrorDialog::styleSheet() const { const QString style = QLatin1String( - "#cert {margin-left: 5px;} " - "#ca_error { color:#a00011; margin-left:5px; margin-right:5px; }" - "#ca_error p { margin-top: 2px; margin-bottom:2px; }" - "#ccert { margin-left: 5px; }" - "#issuer { margin-left: 5px; }" - "tt { font-size: small; }" - ); + "#cert {margin-left: 5px;} " + "#ca_error { color:#a00011; margin-left:5px; margin-right:5px; }" + "#ca_error p { margin-top: 2px; margin-bottom:2px; }" + "#ccert { margin-left: 5px; }" + "#issuer { margin-left: 5px; }" + "tt { font-size: small; }"); return style; } #define QL(x) QLatin1String(x) -bool SslErrorDialog::checkFailingCertsKnown( const QList &errors ) +bool SslErrorDialog::checkFailingCertsKnown(const QList &errors) { // check if unknown certs caused errors. _unknownCerts.clear(); @@ -113,8 +114,7 @@ bool SslErrorDialog::checkFailingCertsKnown( const QList &errors ) for (int i = 0; i < errors.count(); ++i) { QSslError error = errors.at(i); - if (trustedCerts.contains(error.certificate()) || - _unknownCerts.contains(error.certificate() )) { + if (trustedCerts.contains(error.certificate()) || _unknownCerts.contains(error.certificate())) { continue; } errorStrings += error.errorString(); @@ -130,24 +130,24 @@ bool SslErrorDialog::checkFailingCertsKnown( const QList &errors ) } QString msg = QL(""); - msg += QL(""); - msg += QL(""); + msg += QL(""); + msg += QL(""); auto host = _account->url().host(); msg += QL("

") + tr("Cannot connect securely to %1:").arg(host) + QL("

"); // loop over the unknown certs and line up their errors. msg += QL("
"); - foreach( const QSslCertificate& cert, _unknownCerts ) { + foreach (const QSslCertificate &cert, _unknownCerts) { msg += QL("
"); // add the errors for this cert - foreach( QSslError err, errors ) { - if( err.certificate() == cert ) { + foreach (QSslError err, errors) { + if (err.certificate() == cert) { msg += QL("

") + err.errorString() + QL("

"); } } msg += QL("
"); - msg += certDiv( cert ); - if( _unknownCerts.count() > 1 ) { + msg += certDiv(cert); + if (_unknownCerts.count() > 1) { msg += QL("
"); } } @@ -155,30 +155,33 @@ bool SslErrorDialog::checkFailingCertsKnown( const QList &errors ) QTextDocument *doc = new QTextDocument(0); QString style = styleSheet(); - doc->addResource( QTextDocument::StyleSheetResource, QUrl( QL("format.css") ), style); - doc->setHtml( msg ); + doc->addResource(QTextDocument::StyleSheetResource, QUrl(QL("format.css")), style); + doc->setHtml(msg); - _ui->_tbErrors->setDocument( doc ); + _ui->_tbErrors->setDocument(doc); _ui->_tbErrors->show(); return false; } -QString SslErrorDialog::certDiv( QSslCertificate cert ) const +QString SslErrorDialog::certDiv(QSslCertificate cert) const { QString msg; msg += QL("
"); - msg += QL("

") + tr("with Certificate %1").arg( Utility::escape(cert.subjectInfo( QSslCertificate::CommonName ))) + QL("

"); + msg += QL("

") + tr("with Certificate %1").arg(Utility::escape(cert.subjectInfo(QSslCertificate::CommonName))) + QL("

"); msg += QL("
"); QStringList li; - QString org = Utility::escape(cert.subjectInfo( QSslCertificate::Organization)); - QString unit = Utility::escape(cert.subjectInfo( QSslCertificate::OrganizationalUnitName)); - QString country = Utility::escape(cert.subjectInfo( QSslCertificate::CountryName)); - if (unit.isEmpty()) unit = tr("<not specified>"); - if (org.isEmpty()) org = tr("<not specified>"); - if (country.isEmpty()) country = tr("<not specified>"); + QString org = Utility::escape(cert.subjectInfo(QSslCertificate::Organization)); + QString unit = Utility::escape(cert.subjectInfo(QSslCertificate::OrganizationalUnitName)); + QString country = Utility::escape(cert.subjectInfo(QSslCertificate::CountryName)); + if (unit.isEmpty()) + unit = tr("<not specified>"); + if (org.isEmpty()) + org = tr("<not specified>"); + if (country.isEmpty()) + country = tr("<not specified>"); li << tr("Organization: %1").arg(org); li << tr("Unit: %1").arg(unit); li << tr("Country: %1").arg(country); @@ -187,33 +190,34 @@ QString SslErrorDialog::certDiv( QSslCertificate cert ) const msg += QL("

"); QString md5sum = Utility::formatFingerprint(cert.digest(QCryptographicHash::Md5).toHex()); - QString sha1sum = Utility::formatFingerprint(cert.digest(QCryptographicHash::Sha1).toHex()); + QString sha1sum = Utility::formatFingerprint(cert.digest(QCryptographicHash::Sha1).toHex()); msg += tr("Fingerprint (MD5): %1").arg(md5sum) + QL("
"); msg += tr("Fingerprint (SHA1): %1").arg(sha1sum) + QL("
"); msg += QL("
"); - msg += tr("Effective Date: %1").arg( cert.effectiveDate().toString()) + QL("
"); - msg += tr("Expiration Date: %1").arg( cert.expiryDate().toString()) + QL("

"); + msg += tr("Effective Date: %1").arg(cert.effectiveDate().toString()) + QL("
"); + msg += tr("Expiration Date: %1").arg(cert.expiryDate().toString()) + QL("

"); - msg += QL("
" ); + msg += QL("
"); - msg += QL("

") + tr("Issuer: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::CommonName))) + QL("

"); + msg += QL("

") + tr("Issuer: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::CommonName))) + QL("

"); msg += QL("
"); li.clear(); - li << tr("Organization: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::Organization))); - li << tr("Unit: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::OrganizationalUnitName))); - li << tr("Country: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::CountryName))); + li << tr("Organization: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::Organization))); + li << tr("Unit: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::OrganizationalUnitName))); + li << tr("Country: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::CountryName))); msg += QL("

") + li.join(QL("
")) + QL("

"); - msg += QL("
" ); - msg += QL("
" ); + msg += QL(""); + msg += QL(""); return msg; } bool SslErrorDialog::trustConnection() { - if( _allTrusted ) return true; + if (_allTrusted) + return true; - bool stat = ( _ui->_cbTrustConnect->checkState() == Qt::Checked ); + bool stat = (_ui->_cbTrustConnect->checkState() == Qt::Checked); qCInfo(lcSslErrorDialog) << "SSL-Connection is trusted: " << stat; return stat; diff --git a/src/gui/sslerrordialog.h b/src/gui/sslerrordialog.h index e4de70ac8..d0bb40310 100644 --- a/src/gui/sslerrordialog.h +++ b/src/gui/sslerrordialog.h @@ -24,18 +24,18 @@ class QSslError; class QSslCertificate; -namespace OCC -{ +namespace OCC { namespace Ui { -class SslErrorDialog; + class SslErrorDialog; } /** * @brief The SslDialogErrorHandler class * @ingroup gui */ -class SslDialogErrorHandler : public AbstractSslErrorHandler { +class SslDialogErrorHandler : public AbstractSslErrorHandler +{ public: bool handleErrors(QList errors, const QSslConfiguration &conf, QList *certs, AccountPtr) Q_DECL_OVERRIDE; }; @@ -50,7 +50,7 @@ class SslErrorDialog : public QDialog public: explicit SslErrorDialog(AccountPtr account, QWidget *parent = 0); ~SslErrorDialog(); - bool checkFailingCertsKnown( const QList &errors ); + bool checkFailingCertsKnown(const QList &errors); bool trustConnection(); QList unknownCerts() const { return _unknownCerts; } @@ -58,12 +58,12 @@ private: QString styleSheet() const; bool _allTrusted; - QString certDiv( QSslCertificate ) const; + QString certDiv(QSslCertificate) const; QList _unknownCerts; - QString _customConfigHandle; - Ui::SslErrorDialog *_ui; - AccountPtr _account; + QString _customConfigHandle; + Ui::SslErrorDialog *_ui; + AccountPtr _account; }; } // end namespace diff --git a/src/gui/synclogdialog.cpp b/src/gui/synclogdialog.cpp index 885b61d42..d57f28851 100644 --- a/src/gui/synclogdialog.cpp +++ b/src/gui/synclogdialog.cpp @@ -27,27 +27,25 @@ namespace OCC { -SyncLogDialog::SyncLogDialog(QWidget *parent, ProtocolWidget *protoWidget) : - QDialog(parent), - _ui(new Ui::SyncLogDialog) +SyncLogDialog::SyncLogDialog(QWidget *parent, ProtocolWidget *protoWidget) + : QDialog(parent) + , _ui(new Ui::SyncLogDialog) { setObjectName("SyncLogDialog"); // required as group for saveGeometry call _ui->setupUi(this); - if( protoWidget) { + if (protoWidget) { _ui->logWidgetLayout->addWidget(protoWidget); } QPushButton *closeButton = _ui->buttonBox->button(QDialogButtonBox::Close); - if( closeButton ) { - connect( closeButton, SIGNAL(clicked()), this, SLOT(close()) ); + if (closeButton) { + connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); } } SyncLogDialog::~SyncLogDialog() { - } - } diff --git a/src/gui/synclogdialog.h b/src/gui/synclogdialog.h index 1ca0a3e54..c530c35ab 100644 --- a/src/gui/synclogdialog.h +++ b/src/gui/synclogdialog.h @@ -24,7 +24,7 @@ namespace OCC { namespace Ui { -class SyncLogDialog; + class SyncLogDialog; } @@ -43,10 +43,8 @@ public: private slots: private: - Ui::SyncLogDialog *_ui; }; - } #endif // SyncLogDialog_H diff --git a/src/gui/syncrunfilelog.cpp b/src/gui/syncrunfilelog.cpp index c0f5c142f..d0a5259f1 100644 --- a/src/gui/syncrunfilelog.cpp +++ b/src/gui/syncrunfilelog.cpp @@ -25,27 +25,27 @@ SyncRunFileLog::SyncRunFileLog() { } -QString SyncRunFileLog::dateTimeStr( const QDateTime& dt ) +QString SyncRunFileLog::dateTimeStr(const QDateTime &dt) { return dt.toString(Qt::ISODate); } -QString SyncRunFileLog::directionToStr( SyncFileItem::Direction dir ) +QString SyncRunFileLog::directionToStr(SyncFileItem::Direction dir) { QString re("N"); - if( dir == SyncFileItem::Up ) { + if (dir == SyncFileItem::Up) { re = QLatin1String("Up"); - } else if( dir == SyncFileItem::Down ) { + } else if (dir == SyncFileItem::Down) { re = QLatin1String("Down"); } return re; } -QString SyncRunFileLog::instructionToStr( csync_instructions_e inst ) +QString SyncRunFileLog::instructionToStr(csync_instructions_e inst) { QString re; - switch( inst ) { + switch (inst) { case CSYNC_INSTRUCTION_NONE: re = "INST_NONE"; break; @@ -93,7 +93,7 @@ QString SyncRunFileLog::instructionToStr( csync_instructions_e inst ) void SyncRunFileLog::start(const QString &folderPath) { - const qint64 logfileMaxSize = 1024*1024; // 1MiB + const qint64 logfileMaxSize = 1024 * 1024; // 1MiB // Note; this name is ignored in csync_exclude.c const QString filename = folderPath + QLatin1String(".owncloudsync.log"); @@ -110,7 +110,7 @@ void SyncRunFileLog::start(const QString &folderPath) _file.reset(new QFile(filename)); _file->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); - _out.setDevice( _file.data() ); + _out.setDevice(_file.data()); if (!exists) { @@ -118,7 +118,8 @@ void SyncRunFileLog::start(const QString &folderPath) _out << "# timestamp | duration | file | instruction | dir | modtime | etag | " "size | fileId | status | errorString | http result code | " "other size | other modtime | other etag | other fileId | " - "other instruction" << endl; + "other instruction" + << endl; FileSystem::setFileHidden(filename, true); } @@ -129,16 +130,16 @@ void SyncRunFileLog::start(const QString &folderPath) _out << "#=#=#=# Syncrun started " << dateTimeStr(QDateTime::currentDateTime()) << endl; } -void SyncRunFileLog::logItem( const SyncFileItem& item ) +void SyncRunFileLog::logItem(const SyncFileItem &item) { // don't log the directory items that are in the list - if( item._direction == SyncFileItem::None ) { + if (item._direction == SyncFileItem::None) { return; } - QString ts = QString::fromAscii(item._responseTimeStamp); - if( ts.length() > 6 ) { + QString ts = QString::fromAscii(item._responseTimeStamp); + if (ts.length() > 6) { QRegExp rx("(\\d\\d:\\d\\d:\\d\\d)"); - if( ts.contains(rx) ) { + if (ts.contains(rx)) { ts = rx.cap(0); } } @@ -146,13 +147,13 @@ void SyncRunFileLog::logItem( const SyncFileItem& item ) const QChar L = QLatin1Char('|'); _out << ts << L; _out << L; - if( item._instruction != CSYNC_INSTRUCTION_RENAME ) { + if (item._instruction != CSYNC_INSTRUCTION_RENAME) { _out << item._file << L; } else { _out << item._file << QLatin1String(" -> ") << item._renameTarget << L; } - _out << instructionToStr( item._instruction ) << L; - _out << directionToStr( item._direction ) << L; + _out << instructionToStr(item._instruction) << L; + _out << directionToStr(item._direction) << L; _out << QString::number(item._modtime) << L; _out << item._etag << L; _out << QString::number(item._size) << L; @@ -169,7 +170,7 @@ void SyncRunFileLog::logItem( const SyncFileItem& item ) _out << endl; } -void SyncRunFileLog::logLap(const QString& name) +void SyncRunFileLog::logLap(const QString &name) { _out << "#=#=#=#=# " << name << " " << dateTimeStr(QDateTime::currentDateTime()) << " (last step: " << _lapDuration.restart() << " msec" @@ -183,5 +184,4 @@ void SyncRunFileLog::finish() << ", total: " << _totalDuration.elapsed() << " msec)" << endl; _file->close(); } - } diff --git a/src/gui/syncrunfilelog.h b/src/gui/syncrunfilelog.h index 4f54a45c0..e31917e96 100644 --- a/src/gui/syncrunfilelog.h +++ b/src/gui/syncrunfilelog.h @@ -33,17 +33,16 @@ class SyncRunFileLog { public: SyncRunFileLog(); - void start( const QString& folderPath ); - void logItem( const SyncFileItem& item ); - void logLap( const QString& name ); + void start(const QString &folderPath); + void logItem(const SyncFileItem &item); + void logLap(const QString &name); void finish(); protected: - private: - QString dateTimeStr( const QDateTime& dt ); - QString instructionToStr( csync_instructions_e inst ); - QString directionToStr( SyncFileItem::Direction dir ); + QString dateTimeStr(const QDateTime &dt); + QString instructionToStr(csync_instructions_e inst); + QString directionToStr(SyncFileItem::Direction dir); QScopedPointer _file; QTextStream _out; diff --git a/src/gui/systray.cpp b/src/gui/systray.cpp index e1e72cb06..af6e933cc 100644 --- a/src/gui/systray.cpp +++ b/src/gui/systray.cpp @@ -27,20 +27,19 @@ namespace OCC { -void Systray::showMessage(const QString & title, const QString & message, MessageIcon icon, int millisecondsTimeoutHint) +void Systray::showMessage(const QString &title, const QString &message, MessageIcon icon, int millisecondsTimeoutHint) { - #ifdef USE_FDO_NOTIFICATIONS - if(QDBusInterface(NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE).isValid()) { + if (QDBusInterface(NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE).isValid()) { QList args = QList() << "owncloud" << quint32(0) << "owncloud" - << title << message << QStringList () << QVariantMap() << qint32(-1); + << title << message << QStringList() << QVariantMap() << qint32(-1); QDBusMessage method = QDBusMessage::createMethodCall(NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE, "Notify"); method.setArguments(args); QDBusConnection::sessionBus().asyncCall(method); } else #endif #ifdef Q_OS_OSX - if (canOsXSendUserNotification()) { + if (canOsXSendUserNotification()) { sendOsXUserNotification(title, message); } else #endif diff --git a/src/gui/systray.h b/src/gui/systray.h index 14e9607ab..523d4b689 100644 --- a/src/gui/systray.h +++ b/src/gui/systray.h @@ -34,7 +34,7 @@ class Systray : public QSystemTrayIcon { Q_OBJECT public: - void showMessage(const QString & title, const QString & message, MessageIcon icon = Information, int millisecondsTimeoutHint = 10000); + void showMessage(const QString &title, const QString &message, MessageIcon icon = Information, int millisecondsTimeoutHint = 10000); void setToolTip(const QString &tip); }; diff --git a/src/gui/thumbnailjob.cpp b/src/gui/thumbnailjob.cpp index 2f58fcded..81d631289 100644 --- a/src/gui/thumbnailjob.cpp +++ b/src/gui/thumbnailjob.cpp @@ -18,8 +18,8 @@ namespace OCC { -ThumbnailJob::ThumbnailJob(const QString &path, AccountPtr account, QObject* parent) -: AbstractNetworkJob(account, QLatin1String("index.php/apps/files/api/v1/thumbnail/150/150/") + path, parent) +ThumbnailJob::ThumbnailJob(const QString &path, AccountPtr account, QObject *parent) + : AbstractNetworkJob(account, QLatin1String("index.php/apps/files/api/v1/thumbnail/150/150/") + path, parent) { setIgnoreCredentialFailure(true); } @@ -35,5 +35,4 @@ bool ThumbnailJob::finished() emit jobFinished(reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), reply()->readAll()); return true; } - } diff --git a/src/gui/thumbnailjob.h b/src/gui/thumbnailjob.h index 13b754380..37c9ba922 100644 --- a/src/gui/thumbnailjob.h +++ b/src/gui/thumbnailjob.h @@ -27,10 +27,11 @@ namespace OCC { * Job that allows fetching a preview (of 150x150 for now) of a given file. * Once the job has finished the jobFinished signal will be emitted. */ -class ThumbnailJob : public AbstractNetworkJob { +class ThumbnailJob : public AbstractNetworkJob +{ Q_OBJECT public: - explicit ThumbnailJob(const QString& path, AccountPtr account, QObject* parent = 0); + explicit ThumbnailJob(const QString &path, AccountPtr account, QObject *parent = 0); public slots: void start() Q_DECL_OVERRIDE; signals: @@ -46,7 +47,6 @@ signals: private slots: virtual bool finished() Q_DECL_OVERRIDE; }; - } #endif // THUMBNAILJOB_H diff --git a/src/gui/tooltipupdater.cpp b/src/gui/tooltipupdater.cpp index 0f9b0510a..30f12a39c 100644 --- a/src/gui/tooltipupdater.cpp +++ b/src/gui/tooltipupdater.cpp @@ -20,28 +20,27 @@ using namespace OCC; -ToolTipUpdater::ToolTipUpdater(QTreeView* treeView) +ToolTipUpdater::ToolTipUpdater(QTreeView *treeView) : QObject(treeView) , _treeView(treeView) { - connect(_treeView->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector)), - SLOT(dataChanged(QModelIndex,QModelIndex,QVector))); + connect(_treeView->model(), SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector)), + SLOT(dataChanged(QModelIndex, QModelIndex, QVector))); _treeView->viewport()->installEventFilter(this); } -bool ToolTipUpdater::eventFilter(QObject* /*obj*/, QEvent* ev) +bool ToolTipUpdater::eventFilter(QObject * /*obj*/, QEvent *ev) { - if (ev->type() == QEvent::ToolTip) - { + if (ev->type() == QEvent::ToolTip) { QHelpEvent *helpEvent = static_cast(ev); _toolTipPos = helpEvent->globalPos(); } return false; } -void ToolTipUpdater::dataChanged(const QModelIndex& topLeft, - const QModelIndex& bottomRight, - const QVector& roles) +void ToolTipUpdater::dataChanged(const QModelIndex &topLeft, + const QModelIndex &bottomRight, + const QVector &roles) { if (!QToolTip::isVisible() || !roles.contains(Qt::ToolTipRole) || _toolTipPos.isNull()) { return; @@ -56,4 +55,3 @@ void ToolTipUpdater::dataChanged(const QModelIndex& topLeft, // Update the currently active tooltip QToolTip::showText(_toolTipPos, _treeView->model()->data(index, Qt::ToolTipRole).toString()); } - diff --git a/src/gui/tooltipupdater.h b/src/gui/tooltipupdater.h index e1eefb453..05144b04a 100644 --- a/src/gui/tooltipupdater.h +++ b/src/gui/tooltipupdater.h @@ -37,16 +37,16 @@ class ToolTipUpdater : public QObject { Q_OBJECT public: - ToolTipUpdater(QTreeView* treeView); + ToolTipUpdater(QTreeView *treeView); protected: - bool eventFilter(QObject* obj, QEvent* ev) Q_DECL_OVERRIDE; + bool eventFilter(QObject *obj, QEvent *ev) Q_DECL_OVERRIDE; private slots: - void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector& roles); + void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles); private: - QTreeView* _treeView; + QTreeView *_treeView; QPoint _toolTipPos; }; diff --git a/src/gui/updater/ocupdater.cpp b/src/gui/updater/ocupdater.cpp index 7bb94ad69..bac0da503 100644 --- a/src/gui/updater/ocupdater.cpp +++ b/src/gui/updater/ocupdater.cpp @@ -38,16 +38,16 @@ static const char autoUpdateFailedVersionC[] = "Updater/autoUpdateFailedVersion" static const char autoUpdateAttemptedC[] = "Updater/autoUpdateAttempted"; -UpdaterScheduler::UpdaterScheduler(QObject *parent) : - QObject(parent) +UpdaterScheduler::UpdaterScheduler(QObject *parent) + : QObject(parent) { - connect( &_updateCheckTimer, SIGNAL(timeout()), - this, SLOT(slotTimerFired()) ); + connect(&_updateCheckTimer, SIGNAL(timeout()), + this, SLOT(slotTimerFired())); // Note: the sparkle-updater is not an OCUpdater - if (OCUpdater *updater = qobject_cast(Updater::instance())) { - connect(updater, SIGNAL(newUpdateAvailable(QString,QString)), - this, SIGNAL(updaterAnnouncement(QString,QString)) ); + if (OCUpdater *updater = qobject_cast(Updater::instance())) { + connect(updater, SIGNAL(newUpdateAvailable(QString, QString)), + this, SIGNAL(updaterAnnouncement(QString, QString))); connect(updater, SIGNAL(requestRestart()), SIGNAL(requestRestart())); } @@ -65,13 +65,13 @@ void UpdaterScheduler::slotTimerFired() // re-set the check interval if it changed in the config file meanwhile auto checkInterval = cfg.updateCheckInterval(); - if( checkInterval != _updateCheckTimer.interval() ) { + if (checkInterval != _updateCheckTimer.interval()) { _updateCheckTimer.setInterval(checkInterval); qCInfo(lcUpdater) << "Setting new update check interval " << checkInterval; } // consider the skipUpdateCheck flag in the config. - if( cfg.skipUpdateCheck() ) { + if (cfg.skipUpdateCheck()) { qCInfo(lcUpdater) << "Skipping update check because of config file"; return; } @@ -85,14 +85,13 @@ void UpdaterScheduler::slotTimerFired() /* ----------------------------------------------------------------- */ -OCUpdater::OCUpdater(const QUrl &url) : - Updater() - , _updateUrl(url) - , _state(Unknown) - , _accessManager(new AccessManager(this)) - , _timeoutWatchdog(new QTimer(this)) +OCUpdater::OCUpdater(const QUrl &url) + : Updater() + , _updateUrl(url) + , _state(Unknown) + , _accessManager(new AccessManager(this)) + , _timeoutWatchdog(new QTimer(this)) { - } bool OCUpdater::performUpdate() @@ -101,11 +100,13 @@ bool OCUpdater::performUpdate() QSettings settings(cfg.configFile(), QSettings::IniFormat); QString updateFile = settings.value(updateAvailableC).toString(); if (!updateFile.isEmpty() && QFile(updateFile).exists() - && !updateSucceeded() /* Someone might have run the updater manually between restarts */ ) { + && !updateSucceeded() /* Someone might have run the updater manually between restarts */) { const QString name = Theme::instance()->appNameGUI(); if (QMessageBox::information(0, tr("New %1 Update Ready").arg(name), - tr("A new update for %1 is about to be installed. The updater may ask\n" - "for additional privileges during the process.").arg(name), QMessageBox::Ok)) { + tr("A new update for %1 is about to be installed. The updater may ask\n" + "for additional privileges during the process.") + .arg(name), + QMessageBox::Ok)) { slotStartInstaller(); return true; } @@ -118,7 +119,7 @@ void OCUpdater::backgroundCheckForUpdate() int dlState = downloadState(); // do the real update check depending on the internal state of updater. - switch( dlState ) { + switch (dlState) { case Unknown: case UpToDate: case DownloadFailed: @@ -155,7 +156,7 @@ QString OCUpdater::statusString() const case Unknown: return tr("Update status is unknown: Did not check for new updates."); case UpToDate: - // fall through + // fall through default: return tr("No updates available. Your installation is at the latest version."); } @@ -174,10 +175,9 @@ void OCUpdater::setDownloadState(DownloadState state) // show the notification if the download is complete (on every check) // or once for system based updates. - if( _state == OCUpdater::DownloadComplete || - (oldState != OCUpdater::UpdateOnlyAvailableThroughSystem - && _state == OCUpdater::UpdateOnlyAvailableThroughSystem) ) { - emit newUpdateAvailable(tr("Update Check"), statusString() ); + if (_state == OCUpdater::DownloadComplete || (oldState != OCUpdater::UpdateOnlyAvailableThroughSystem + && _state == OCUpdater::UpdateOnlyAvailableThroughSystem)) { + emit newUpdateAvailable(tr("Update Check"), statusString()); } } @@ -189,14 +189,15 @@ void OCUpdater::slotStartInstaller() settings.setValue(autoUpdateAttemptedC, true); settings.sync(); qCInfo(lcUpdater) << "Running updater" << updateFile; - QProcess::startDetached(updateFile, QStringList() << "/S" << "/launch"); + QProcess::startDetached(updateFile, QStringList() << "/S" + << "/launch"); } void OCUpdater::checkForUpdate() { QNetworkReply *reply = _accessManager->get(QNetworkRequest(_updateUrl)); connect(_timeoutWatchdog, SIGNAL(timeout()), this, SLOT(slotTimedOut())); - _timeoutWatchdog->start(30*1000); + _timeoutWatchdog->start(30 * 1000); connect(reply, SIGNAL(finished()), this, SLOT(slotVersionInfoArrived())); setDownloadState(CheckingServer); @@ -220,9 +221,9 @@ bool OCUpdater::updateSucceeded() const void OCUpdater::slotVersionInfoArrived() { _timeoutWatchdog->stop(); - QNetworkReply *reply = qobject_cast(sender()); + QNetworkReply *reply = qobject_cast(sender()); reply->deleteLater(); - if( reply->error() != QNetworkReply::NoError ) { + if (reply->error() != QNetworkReply::NoError) { qCWarning(lcUpdater) << "Failed to reach version check url: " << reply->errorString(); return; } @@ -230,8 +231,8 @@ void OCUpdater::slotVersionInfoArrived() QString xml = QString::fromUtf8(reply->readAll()); bool ok; - _updateInfo = UpdateInfo::parseString( xml, &ok ); - if( ok ) { + _updateInfo = UpdateInfo::parseString(xml, &ok); + if (ok) { versionInfoArrived(_updateInfo); } else { qCWarning(lcUpdater) << "Could not parse update information."; @@ -253,15 +254,15 @@ NSISUpdater::NSISUpdater(const QUrl &url) void NSISUpdater::slotWriteFile() { - QNetworkReply *reply = qobject_cast(sender()); - if(_file->isOpen()) { + QNetworkReply *reply = qobject_cast(sender()); + if (_file->isOpen()) { _file->write(reply->readAll()); } } void NSISUpdater::slotDownloadFinished() { - QNetworkReply *reply = qobject_cast(sender()); + QNetworkReply *reply = qobject_cast(sender()); reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { setDownloadState(DownloadFailed); @@ -286,16 +287,15 @@ void NSISUpdater::versionInfoArrived(const UpdateInfo &info) qint64 infoVersion = Helper::stringVersionToInt(info.version()); qint64 seenVersion = Helper::stringVersionToInt(settings.value(seenVersionC).toString()); qint64 currVersion = Helper::currentVersionToInt(); - if(info.version().isEmpty() - || infoVersion <= currVersion - || infoVersion <= seenVersion) - { + if (info.version().isEmpty() + || infoVersion <= currVersion + || infoVersion <= seenVersion) { qCInfo(lcUpdater) << "Client is on latest version!"; setDownloadState(UpToDate); } else { QString url = info.downloadUrl(); qint64 autoUpdateFailedVersion = - Helper::stringVersionToInt(settings.value(autoUpdateFailedVersionC).toString()); + Helper::stringVersionToInt(settings.value(autoUpdateFailedVersionC).toString()); if (url.isEmpty() || _showFallbackMessage || infoVersion == autoUpdateFailedVersion) { showDialog(info); } @@ -340,7 +340,7 @@ void NSISUpdater::showDialog(const UpdateInfo &info) QString txt = tr("

A new version of the %1 Client is available.

" "

%2 is available for download. The installed version is %3.

") .arg(Utility::escape(Theme::instance()->appNameGUI()), - Utility::escape(info.versionString()), Utility::escape(clientVersion())); + Utility::escape(info.versionString()), Utility::escape(clientVersion())); lbl->setText(txt); lbl->setTextFormat(Qt::RichText); @@ -353,7 +353,7 @@ void NSISUpdater::showDialog(const UpdateInfo &info) bb->setWindowFlags(bb->windowFlags() & ~Qt::WindowContextHelpButtonHint); QPushButton *skip = bb->addButton(tr("Skip this version"), QDialogButtonBox::ResetRole); QPushButton *reject = bb->addButton(tr("Skip this time"), QDialogButtonBox::AcceptRole); - QPushButton *getupdate = bb->addButton(tr("Get update"), QDialogButtonBox::AcceptRole); + QPushButton *getupdate = bb->addButton(tr("Get update"), QDialogButtonBox::AcceptRole); connect(skip, SIGNAL(clicked()), msgBox, SLOT(reject())); connect(reject, SIGNAL(clicked()), msgBox, SLOT(reject())); @@ -399,7 +399,7 @@ NSISUpdater::UpdateState NSISUpdater::updateStateOnStart() } } } - return NoUpdate; + return NoUpdate; } bool NSISUpdater::handleStartup() @@ -437,12 +437,11 @@ PassiveUpdateNotifier::PassiveUpdateNotifier(const QUrl &url) void PassiveUpdateNotifier::backgroundCheckForUpdate() { - - if( Utility::isLinux() ) { + if (Utility::isLinux()) { // on linux, check if the installed binary is still the same version // as the one that is running. If not, restart if possible. const QByteArray fsVersion = Utility::versionOfInstalledBinary(); - if( !(fsVersion.isEmpty() || _runningAppVersion.isEmpty()) && fsVersion != _runningAppVersion ) { + if (!(fsVersion.isEmpty() || _runningAppVersion.isEmpty()) && fsVersion != _runningAppVersion) { emit requestRestart(); } } @@ -455,8 +454,7 @@ void PassiveUpdateNotifier::versionInfoArrived(const UpdateInfo &info) qint64 currentVer = Helper::currentVersionToInt(); qint64 remoteVer = Helper::stringVersionToInt(info.version()); - if( info.version().isEmpty() || - currentVer >= remoteVer ) { + if (info.version().isEmpty() || currentVer >= remoteVer) { qCInfo(lcUpdater) << "Client is on latest version!"; setDownloadState(UpToDate); } else { diff --git a/src/gui/updater/ocupdater.h b/src/gui/updater/ocupdater.h index 170a03305..b157b93ce 100644 --- a/src/gui/updater/ocupdater.h +++ b/src/gui/updater/ocupdater.h @@ -71,7 +71,7 @@ public: UpdaterScheduler(QObject *parent); signals: - void updaterAnnouncement(const QString& title, const QString& msg); + void updaterAnnouncement(const QString &title, const QString &msg); void requestRestart(); private slots: @@ -79,7 +79,6 @@ private slots: private: QTimer _updateCheckTimer; /** Timer for the regular update check. */ - }; /** @@ -90,10 +89,14 @@ class OCUpdater : public Updater { Q_OBJECT public: - enum DownloadState { Unknown = 0, CheckingServer, UpToDate, - Downloading, DownloadComplete, - DownloadFailed, DownloadTimedOut, - UpdateOnlyAvailableThroughSystem }; + enum DownloadState { Unknown = 0, + CheckingServer, + UpToDate, + Downloading, + DownloadComplete, + DownloadFailed, + DownloadTimedOut, + UpdateOnlyAvailableThroughSystem }; explicit OCUpdater(const QUrl &url); bool performUpdate(); @@ -106,7 +109,7 @@ public: signals: void downloadStateChanged(); - void newUpdateAvailable(const QString& header, const QString& message); + void newUpdateAvailable(const QString &header, const QString &message); void requestRestart(); public slots: @@ -123,13 +126,14 @@ private slots: protected: virtual void versionInfoArrived(const UpdateInfo &info) = 0; bool updateSucceeded() const; - QNetworkAccessManager* qnam() const { return _accessManager; } + QNetworkAccessManager *qnam() const { return _accessManager; } UpdateInfo updateInfo() const { return _updateInfo; } + private: QUrl _updateUrl; int _state; QNetworkAccessManager *_accessManager; - QTimer *_timeoutWatchdog; /** Timer to guard the timeout of an individual network request */ + QTimer *_timeoutWatchdog; /** Timer to guard the timeout of an individual network request */ UpdateInfo _updateInfo; }; @@ -137,16 +141,20 @@ private: * @brief Windows Updater Using NSIS * @ingroup gui */ -class NSISUpdater : public OCUpdater { +class NSISUpdater : public OCUpdater +{ Q_OBJECT public: - enum UpdateState { NoUpdate = 0, UpdateAvailable, UpdateFailed }; + enum UpdateState { NoUpdate = 0, + UpdateAvailable, + UpdateFailed }; explicit NSISUpdater(const QUrl &url); bool handleStartup() Q_DECL_OVERRIDE; private slots: void slotSetSeenVersion(); void slotDownloadFinished(); void slotWriteFile(); + private: NSISUpdater::UpdateState updateStateOnStart(); void showDialog(const UpdateInfo &info); @@ -154,7 +162,6 @@ private: QScopedPointer _file; QString _targetFile; bool _showFallbackMessage; - }; /** @@ -164,7 +171,8 @@ private: * * @ingroup gui */ -class PassiveUpdateNotifier : public OCUpdater { +class PassiveUpdateNotifier : public OCUpdater +{ Q_OBJECT public: explicit PassiveUpdateNotifier(const QUrl &url); @@ -173,11 +181,8 @@ public: private: void versionInfoArrived(const UpdateInfo &info) Q_DECL_OVERRIDE; - QByteArray _runningAppVersion; + QByteArray _runningAppVersion; }; - - - } #endif // OC_UPDATER diff --git a/src/gui/updater/sparkleupdater.h b/src/gui/updater/sparkleupdater.h index 22c93d80f..e9a2c8882 100644 --- a/src/gui/updater/sparkleupdater.h +++ b/src/gui/updater/sparkleupdater.h @@ -21,15 +21,17 @@ namespace OCC { -class SparkleUpdater : public Updater { +class SparkleUpdater : public Updater +{ public: - SparkleUpdater(const QString& appCastUrl); + SparkleUpdater(const QString &appCastUrl); ~SparkleUpdater(); // unused in this updater void checkForUpdate() Q_DECL_OVERRIDE; void backgroundCheckForUpdate() Q_DECL_OVERRIDE; bool handleStartup() Q_DECL_OVERRIDE { return false; } + private: class Private; Private *d; diff --git a/src/gui/updater/updateinfo.cpp b/src/gui/updater/updateinfo.cpp index 225cdb69f..711daa942 100644 --- a/src/gui/updater/updateinfo.cpp +++ b/src/gui/updater/updateinfo.cpp @@ -12,158 +12,160 @@ namespace OCC { -void UpdateInfo::setVersion( const QString &v ) +void UpdateInfo::setVersion(const QString &v) { - mVersion = v; + mVersion = v; } QString UpdateInfo::version() const { - return mVersion; + return mVersion; } -void UpdateInfo::setVersionString( const QString &v ) +void UpdateInfo::setVersionString(const QString &v) { - mVersionString = v; + mVersionString = v; } QString UpdateInfo::versionString() const { - return mVersionString; + return mVersionString; } -void UpdateInfo::setWeb( const QString &v ) +void UpdateInfo::setWeb(const QString &v) { - mWeb = v; + mWeb = v; } QString UpdateInfo::web() const { - return mWeb; + return mWeb; } -void UpdateInfo::setDownloadUrl( const QString &v ) +void UpdateInfo::setDownloadUrl(const QString &v) { - mDownloadUrl = v; + mDownloadUrl = v; } QString UpdateInfo::downloadUrl() const { - return mDownloadUrl; + return mDownloadUrl; } -UpdateInfo UpdateInfo::parseElement( const QDomElement &element, bool *ok ) +UpdateInfo UpdateInfo::parseElement(const QDomElement &element, bool *ok) { - if ( element.tagName() != QLatin1String("owncloudclient") ) { - qCCritical(lcUpdater) << "Expected 'owncloudclient', got '" << element.tagName() << "'."; - if ( ok ) *ok = false; - return UpdateInfo(); - } - - UpdateInfo result = UpdateInfo(); - - QDomNode n; - for( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) { - QDomElement e = n.toElement(); - if ( e.tagName() == QLatin1String("version") ) { - result.setVersion( e.text() ); + if (element.tagName() != QLatin1String("owncloudclient")) { + qCCritical(lcUpdater) << "Expected 'owncloudclient', got '" << element.tagName() << "'."; + if (ok) + *ok = false; + return UpdateInfo(); } - else if ( e.tagName() == QLatin1String("versionstring") ) { - result.setVersionString( e.text() ); - } - else if ( e.tagName() == QLatin1String("web") ) { - result.setWeb( e.text() ); - } - else if ( e.tagName() == QLatin1String("downloadurl") ) { - result.setDownloadUrl( e.text() ); + + UpdateInfo result = UpdateInfo(); + + QDomNode n; + for (n = element.firstChild(); !n.isNull(); n = n.nextSibling()) { + QDomElement e = n.toElement(); + if (e.tagName() == QLatin1String("version")) { + result.setVersion(e.text()); + } else if (e.tagName() == QLatin1String("versionstring")) { + result.setVersionString(e.text()); + } else if (e.tagName() == QLatin1String("web")) { + result.setWeb(e.text()); + } else if (e.tagName() == QLatin1String("downloadurl")) { + result.setDownloadUrl(e.text()); + } } - } - if ( ok ) *ok = true; - return result; + if (ok) + *ok = true; + return result; } -void UpdateInfo::writeElement( QXmlStreamWriter &xml ) +void UpdateInfo::writeElement(QXmlStreamWriter &xml) { - xml.writeStartElement( QLatin1String("owncloudclient") ); - if ( !version().isEmpty() ) { - xml.writeTextElement( QLatin1String("version"), version() ); - } - if ( !versionString().isEmpty() ) { - xml.writeTextElement( QLatin1String("versionstring"), versionString() ); - } - if ( !web().isEmpty() ) { - xml.writeTextElement( QLatin1String("web"), web() ); - } - if ( !downloadUrl().isEmpty() ) { - xml.writeTextElement( QLatin1String("downloadurl"), web() ); - } - xml.writeEndElement(); + xml.writeStartElement(QLatin1String("owncloudclient")); + if (!version().isEmpty()) { + xml.writeTextElement(QLatin1String("version"), version()); + } + if (!versionString().isEmpty()) { + xml.writeTextElement(QLatin1String("versionstring"), versionString()); + } + if (!web().isEmpty()) { + xml.writeTextElement(QLatin1String("web"), web()); + } + if (!downloadUrl().isEmpty()) { + xml.writeTextElement(QLatin1String("downloadurl"), web()); + } + xml.writeEndElement(); } -UpdateInfo UpdateInfo::parseFile( const QString &filename, bool *ok ) +UpdateInfo UpdateInfo::parseFile(const QString &filename, bool *ok) { - QFile file( filename ); - if ( !file.open( QIODevice::ReadOnly ) ) { - qCCritical(lcUpdater) << "Unable to open file '" << filename << "'"; - if ( ok ) *ok = false; - return UpdateInfo(); - } - - QString errorMsg; - int errorLine, errorCol; - QDomDocument doc; - if ( !doc.setContent( &file, false, &errorMsg, &errorLine, &errorCol ) ) { - qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol; - if ( ok ) *ok = false; - return UpdateInfo(); - } - - bool documentOk; - UpdateInfo c = parseElement( doc.documentElement(), &documentOk ); - if ( ok ) { - *ok = documentOk; - } - return c; + QFile file(filename); + if (!file.open(QIODevice::ReadOnly)) { + qCCritical(lcUpdater) << "Unable to open file '" << filename << "'"; + if (ok) + *ok = false; + return UpdateInfo(); + } + + QString errorMsg; + int errorLine, errorCol; + QDomDocument doc; + if (!doc.setContent(&file, false, &errorMsg, &errorLine, &errorCol)) { + qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol; + if (ok) + *ok = false; + return UpdateInfo(); + } + + bool documentOk; + UpdateInfo c = parseElement(doc.documentElement(), &documentOk); + if (ok) { + *ok = documentOk; + } + return c; } -UpdateInfo UpdateInfo::parseString( const QString &xml, bool *ok ) +UpdateInfo UpdateInfo::parseString(const QString &xml, bool *ok) { - QString errorMsg; - int errorLine, errorCol; - QDomDocument doc; - if ( !doc.setContent( xml, false, &errorMsg, &errorLine, &errorCol ) ) { - qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol; - if ( ok ) *ok = false; - return UpdateInfo(); - } - - bool documentOk; - UpdateInfo c = parseElement( doc.documentElement(), &documentOk ); - if ( ok ) { - *ok = documentOk; - } - return c; + QString errorMsg; + int errorLine, errorCol; + QDomDocument doc; + if (!doc.setContent(xml, false, &errorMsg, &errorLine, &errorCol)) { + qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol; + if (ok) + *ok = false; + return UpdateInfo(); + } + + bool documentOk; + UpdateInfo c = parseElement(doc.documentElement(), &documentOk); + if (ok) { + *ok = documentOk; + } + return c; } -bool UpdateInfo::writeFile( const QString &filename ) +bool UpdateInfo::writeFile(const QString &filename) { - QFile file( filename ); - if ( !file.open( QIODevice::WriteOnly ) ) { - qCCritical(lcUpdater) << "Unable to open file '" << filename << "'"; - return false; - } - - QXmlStreamWriter xml( &file ); - xml.setAutoFormatting( true ); - xml.setAutoFormattingIndent( 2 ); - xml.writeStartDocument( QLatin1String("1.0") ); - writeElement( xml ); - xml.writeEndDocument(); - file.close(); - - return true; + QFile file(filename); + if (!file.open(QIODevice::WriteOnly)) { + qCCritical(lcUpdater) << "Unable to open file '" << filename << "'"; + return false; + } + + QXmlStreamWriter xml(&file); + xml.setAutoFormatting(true); + xml.setAutoFormattingIndent(2); + xml.writeStartDocument(QLatin1String("1.0")); + writeElement(xml); + xml.writeEndDocument(); + file.close(); + + return true; } } // namespace OCC diff --git a/src/gui/updater/updateinfo.h b/src/gui/updater/updateinfo.h index 4ed098579..af5e76b5a 100644 --- a/src/gui/updater/updateinfo.h +++ b/src/gui/updater/updateinfo.h @@ -11,25 +11,25 @@ namespace OCC { class UpdateInfo { - public: - void setVersion( const QString &v ); +public: + void setVersion(const QString &v); QString version() const; - void setVersionString( const QString &v ); + void setVersionString(const QString &v); QString versionString() const; - void setWeb( const QString &v ); + void setWeb(const QString &v); QString web() const; - void setDownloadUrl( const QString &v ); + void setDownloadUrl(const QString &v); QString downloadUrl() const; /** Parse XML object from DOM element. */ - static UpdateInfo parseElement( const QDomElement &element, bool *ok ); - void writeElement( QXmlStreamWriter &xml ); - static UpdateInfo parseFile( const QString &filename, bool *ok ); - static UpdateInfo parseString( const QString &xml, bool *ok ); - bool writeFile( const QString &filename ); + static UpdateInfo parseElement(const QDomElement &element, bool *ok); + void writeElement(QXmlStreamWriter &xml); + static UpdateInfo parseFile(const QString &filename, bool *ok); + static UpdateInfo parseString(const QString &xml, bool *ok); + bool writeFile(const QString &filename); - private: +private: QString mVersion; QString mVersionString; QString mWeb; diff --git a/src/gui/updater/updater.cpp b/src/gui/updater/updater.cpp index de9e339c7..2529b261a 100644 --- a/src/gui/updater/updater.cpp +++ b/src/gui/updater/updater.cpp @@ -31,9 +31,9 @@ Q_LOGGING_CATEGORY(lcUpdater, "gui.updater", QtInfoMsg) Updater *Updater::_instance = 0; -Updater * Updater::instance() +Updater *Updater::instance() { - if(!_instance) { + if (!_instance) { _instance = create(); } return _instance; @@ -47,7 +47,7 @@ QUrl Updater::addQueryParams(const QUrl &url) if (Utility::isLinux()) { platform = QLatin1String("linux"); } else if (Utility::isBSD()) { - platform = QLatin1String("bsd"); + platform = QLatin1String("bsd"); } else if (Utility::isWindows()) { platform = QLatin1String("win32"); } else if (Utility::isMac()) { @@ -55,12 +55,12 @@ QUrl Updater::addQueryParams(const QUrl &url) } QString sysInfo = getSystemInfo(); - if( !sysInfo.isEmpty() ) { - paramUrl.addQueryItem(QLatin1String("client"), sysInfo ); + if (!sysInfo.isEmpty()) { + paramUrl.addQueryItem(QLatin1String("client"), sysInfo); } - paramUrl.addQueryItem( QLatin1String("version"), clientVersion() ); - paramUrl.addQueryItem( QLatin1String("platform"), platform ); - paramUrl.addQueryItem( QLatin1String("oem"), theme->appName() ); + paramUrl.addQueryItem(QLatin1String("version"), clientVersion()); + paramUrl.addQueryItem(QLatin1String("platform"), platform); + paramUrl.addQueryItem(QLatin1String("oem"), theme->appName()); return paramUrl; } @@ -69,13 +69,14 @@ QString Updater::getSystemInfo() { #ifdef Q_OS_LINUX QProcess process; - process.start( QLatin1String("lsb_release -a") ); + process.start(QLatin1String("lsb_release -a")); process.waitForFinished(); QByteArray output = process.readAllStandardOutput(); qCDebug(lcUpdater) << "Sys Info size: " << output.length(); - if( output.length() > 1024 ) output.clear(); // don't send too much. + if (output.length() > 1024) + output.clear(); // don't send too much. - return QString::fromLocal8Bit( output.toBase64() ); + return QString::fromLocal8Bit(output.toBase64()); #else return QString::null; #endif @@ -94,15 +95,14 @@ Updater *Updater::create() } updateBaseUrl = addQueryParams(updateBaseUrl); #if defined(Q_OS_MAC) && defined(HAVE_SPARKLE) - updateBaseUrl.addQueryItem( QLatin1String("sparkle"), QLatin1String("true")); + updateBaseUrl.addQueryItem(QLatin1String("sparkle"), QLatin1String("true")); return new SparkleUpdater(updateBaseUrl.toString()); -#elif defined (Q_OS_WIN32) +#elif defined(Q_OS_WIN32) // the best we can do is notify about updates return new NSISUpdater(updateBaseUrl); #else return new PassiveUpdateNotifier(QUrl(updateBaseUrl)); #endif - } @@ -114,10 +114,10 @@ qint64 Updater::Helper::versionToInt(qint64 major, qint64 minor, qint64 patch, q qint64 Updater::Helper::currentVersionToInt() { return versionToInt(MIRALL_VERSION_MAJOR, MIRALL_VERSION_MINOR, - MIRALL_VERSION_PATCH, MIRALL_VERSION_BUILD); + MIRALL_VERSION_PATCH, MIRALL_VERSION_BUILD); } -qint64 Updater::Helper::stringVersionToInt(const QString& version) +qint64 Updater::Helper::stringVersionToInt(const QString &version) { if (version.isEmpty()) return 0; diff --git a/src/gui/updater/updater.h b/src/gui/updater/updater.h index 07c6528bf..77f322638 100644 --- a/src/gui/updater/updater.h +++ b/src/gui/updater/updater.h @@ -24,11 +24,13 @@ namespace OCC { Q_DECLARE_LOGGING_CATEGORY(lcUpdater) -class Updater : public QObject { +class Updater : public QObject +{ Q_OBJECT public: - struct Helper { - static qint64 stringVersionToInt(const QString& version); + struct Helper + { + static qint64 stringVersionToInt(const QString &version); static qint64 currentVersionToInt(); static qint64 versionToInt(qint64 major, qint64 minor, qint64 patch, qint64 build); }; @@ -41,7 +43,10 @@ public: protected: static QString clientVersion(); - Updater() : QObject(0) {} + Updater() + : QObject(0) + { + } private: static QString getSystemInfo(); diff --git a/src/gui/wizard/abstractcredswizardpage.cpp b/src/gui/wizard/abstractcredswizardpage.cpp index ce5a4fdf4..696e98e09 100644 --- a/src/gui/wizard/abstractcredswizardpage.cpp +++ b/src/gui/wizard/abstractcredswizardpage.cpp @@ -26,7 +26,7 @@ void AbstractCredentialsWizardPage::cleanupPage() { // Reset the credentials when the 'Back' button is used. - AccountPtr account = static_cast(wizard())->account(); + AccountPtr account = static_cast(wizard())->account(); AbstractCredentials *creds = account->credentials(); if (creds) { if (!creds->inherits("DummyCredentials")) { @@ -34,5 +34,4 @@ void AbstractCredentialsWizardPage::cleanupPage() } } } - } diff --git a/src/gui/wizard/abstractcredswizardpage.h b/src/gui/wizard/abstractcredswizardpage.h index 82d61ac42..87e50620b 100644 --- a/src/gui/wizard/abstractcredswizardpage.h +++ b/src/gui/wizard/abstractcredswizardpage.h @@ -17,8 +17,7 @@ #include -namespace OCC -{ +namespace OCC { class AbstractCredentials; @@ -30,7 +29,7 @@ class AbstractCredentialsWizardPage : public QWizardPage { public: void cleanupPage() Q_DECL_OVERRIDE; - virtual AbstractCredentials* getCredentials() const = 0; + virtual AbstractCredentials *getCredentials() const = 0; }; } // namespace OCC diff --git a/src/gui/wizard/owncloudadvancedsetuppage.cpp b/src/gui/wizard/owncloudadvancedsetuppage.cpp index 3c9dd6979..9bc1b60c3 100644 --- a/src/gui/wizard/owncloudadvancedsetuppage.cpp +++ b/src/gui/wizard/owncloudadvancedsetuppage.cpp @@ -31,17 +31,16 @@ #include "creds/abstractcredentials.h" #include "networkjobs.h" -namespace OCC -{ +namespace OCC { OwncloudAdvancedSetupPage::OwncloudAdvancedSetupPage() - : QWizardPage(), - _ui(), - _checking(false), - _created(false), - _localFolderValid(false), - _progressIndi(new QProgressIndicator (this)), - _remoteFolder() + : QWizardPage() + , _ui() + , _checking(false) + , _created(false) + , _localFolderValid(false) + , _progressIndi(new QProgressIndicator(this)) + , _remoteFolder() { _ui.setupUi(this); @@ -49,18 +48,18 @@ OwncloudAdvancedSetupPage::OwncloudAdvancedSetupPage() setTitle(WizardCommon::titleTemplate().arg(tr("Connect to %1").arg(theme->appNameGUI()))); setSubTitle(WizardCommon::subTitleTemplate().arg(tr("Setup local folder options"))); - registerField( QLatin1String("OCSyncFromScratch"), _ui.cbSyncFromScratch); + registerField(QLatin1String("OCSyncFromScratch"), _ui.cbSyncFromScratch); - _ui.resultLayout->addWidget( _progressIndi ); + _ui.resultLayout->addWidget(_progressIndi); stopSpinner(); setupCustomization(); - connect( _ui.pbSelectLocalFolder, SIGNAL(clicked()), SLOT(slotSelectFolder())); + connect(_ui.pbSelectLocalFolder, SIGNAL(clicked()), SLOT(slotSelectFolder())); setButtonText(QWizard::NextButton, tr("Connect...")); - connect( _ui.rSyncEverything, SIGNAL(clicked()), SLOT(slotSyncEverythingClicked())); - connect( _ui.rSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked())); - connect( _ui.bSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked())); + connect(_ui.rSyncEverything, SIGNAL(clicked()), SLOT(slotSyncEverythingClicked())); + connect(_ui.rSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked())); + connect(_ui.bSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked())); QIcon appIcon = theme->applicationIcon(); _ui.lServerIcon->setText(QString()); @@ -85,13 +84,13 @@ void OwncloudAdvancedSetupPage::setupCustomization() _ui.bottomLabel->hide(); Theme *theme = Theme::instance(); - QVariant variant = theme->customMedia( Theme::oCSetupTop ); - if( !variant.isNull() ) { - WizardCommon::setupCustomMedia( variant, _ui.topLabel ); + QVariant variant = theme->customMedia(Theme::oCSetupTop); + if (!variant.isNull()) { + WizardCommon::setupCustomMedia(variant, _ui.topLabel); } - variant = theme->customMedia( Theme::oCSetupBottom ); - WizardCommon::setupCustomMedia( variant, _ui.bottomLabel ); + variant = theme->customMedia(Theme::oCSetupBottom); + WizardCommon::setupCustomMedia(variant, _ui.bottomLabel); } bool OwncloudAdvancedSetupPage::isComplete() const @@ -103,7 +102,7 @@ void OwncloudAdvancedSetupPage::initializePage() { WizardCommon::initErrorLabel(_ui.errorLabel); - _checking = false; + _checking = false; _ui.lSelectiveSyncSizeLabel->setText(QString()); _ui.lSyncEverythingSizeLabel->setText(QString()); @@ -151,17 +150,17 @@ void OwncloudAdvancedSetupPage::updateStatus() _ui.pbSelectLocalFolder->setText(QDir::toNativeSeparators(locFolder)); if (dataChanged()) { - if( _remoteFolder.isEmpty() || _remoteFolder == QLatin1String("/") ) { + if (_remoteFolder.isEmpty() || _remoteFolder == QLatin1String("/")) { t = ""; } else { t = Utility::escape(tr("%1 folder '%2' is synced to local folder '%3'") .arg(Theme::instance()->appName(), _remoteFolder, - QDir::toNativeSeparators(locFolder))); + QDir::toNativeSeparators(locFolder))); _ui.rSyncEverything->setText(tr("Sync the folder '%1'").arg(_remoteFolder)); } const bool dirNotEmpty(QDir(locFolder).entryList(QDir::AllEntries | QDir::NoDotAndDotDot).count() > 0); - if(dirNotEmpty) { + if (dirNotEmpty) { t += tr("

Warning: The local folder is not empty. " "Pick a resolution!

"); } @@ -230,7 +229,7 @@ bool OwncloudAdvancedSetupPage::isConfirmBigFolderChecked() const bool OwncloudAdvancedSetupPage::validatePage() { - if(!_created) { + if (!_created) { setErrorString(QString::null); _checking = true; startSpinner(); @@ -239,7 +238,7 @@ bool OwncloudAdvancedSetupPage::validatePage() if (_ui.rSyncEverything->isChecked()) { ConfigFile cfgFile; cfgFile.setNewBigFolderSizeLimit(_ui.confCheckBoxSize->isChecked(), - _ui.confSpinBox->value()); + _ui.confSpinBox->value()); cfgFile.setConfirmExternalStorage(_ui.confCheckBoxExternal->isChecked()); } @@ -254,9 +253,9 @@ bool OwncloudAdvancedSetupPage::validatePage() } } -void OwncloudAdvancedSetupPage::setErrorString( const QString& err ) +void OwncloudAdvancedSetupPage::setErrorString(const QString &err) { - if( err.isEmpty()) { + if (err.isEmpty()) { _ui.errorLabel->setVisible(false); } else { _ui.errorLabel->setVisible(true); @@ -274,9 +273,9 @@ void OwncloudAdvancedSetupPage::directoriesCreated() emit completeChanged(); } -void OwncloudAdvancedSetupPage::setRemoteFolder( const QString& remoteFolder ) +void OwncloudAdvancedSetupPage::setRemoteFolder(const QString &remoteFolder) { - if( !remoteFolder.isEmpty() ) { + if (!remoteFolder.isEmpty()) { _remoteFolder = remoteFolder; } } @@ -284,7 +283,7 @@ void OwncloudAdvancedSetupPage::setRemoteFolder( const QString& remoteFolder ) void OwncloudAdvancedSetupPage::slotSelectFolder() { QString dir = QFileDialog::getExistingDirectory(0, tr("Local Sync Folder"), QDir::homePath()); - if( !dir.isEmpty() ) { + if (!dir.isEmpty()) { _ui.pbSelectLocalFolder->setText(dir); wizard()->setProperty("localFolder", dir); updateStatus(); @@ -321,7 +320,7 @@ void OwncloudAdvancedSetupPage::slotSelectiveSyncClicked() _ui.rSelectiveSync->setChecked(true); _ui.rSelectiveSync->blockSignals(false); auto s = dlg->estimatedSize(); - if (s > 0 ) { + if (s > 0) { _ui.lSelectiveSyncSizeLabel->setText(tr("(%1)").arg(Utility::octetsToString(s))); } else { _ui.lSelectiveSyncSizeLabel->setText(QString()); @@ -344,8 +343,6 @@ void OwncloudAdvancedSetupPage::slotSyncEverythingClicked() void OwncloudAdvancedSetupPage::slotQuotaRetrieved(const QVariantMap &result) { _ui.lSyncEverythingSizeLabel->setText(tr("(%1)").arg(Utility::octetsToString(result["size"].toDouble()))); - } } // namespace OCC - diff --git a/src/gui/wizard/owncloudadvancedsetuppage.h b/src/gui/wizard/owncloudadvancedsetuppage.h index 5d1c82ed2..a51c51b1b 100644 --- a/src/gui/wizard/owncloudadvancedsetuppage.h +++ b/src/gui/wizard/owncloudadvancedsetuppage.h @@ -29,50 +29,50 @@ namespace OCC { * @brief The OwncloudAdvancedSetupPage class * @ingroup gui */ -class OwncloudAdvancedSetupPage: public QWizardPage +class OwncloudAdvancedSetupPage : public QWizardPage { Q_OBJECT public: - OwncloudAdvancedSetupPage(); + OwncloudAdvancedSetupPage(); - virtual bool isComplete() const Q_DECL_OVERRIDE; - virtual void initializePage() Q_DECL_OVERRIDE; - virtual int nextId() const Q_DECL_OVERRIDE; - bool validatePage() Q_DECL_OVERRIDE; - QString localFolder() const; - QStringList selectiveSyncBlacklist() const; - bool isConfirmBigFolderChecked() const; - void setRemoteFolder( const QString& remoteFolder); - void setMultipleFoldersExist( bool exist ); - void directoriesCreated(); + virtual bool isComplete() const Q_DECL_OVERRIDE; + virtual void initializePage() Q_DECL_OVERRIDE; + virtual int nextId() const Q_DECL_OVERRIDE; + bool validatePage() Q_DECL_OVERRIDE; + QString localFolder() const; + QStringList selectiveSyncBlacklist() const; + bool isConfirmBigFolderChecked() const; + void setRemoteFolder(const QString &remoteFolder); + void setMultipleFoldersExist(bool exist); + void directoriesCreated(); signals: - void createLocalAndRemoteFolders(const QString&, const QString&); + void createLocalAndRemoteFolders(const QString &, const QString &); public slots: - void setErrorString( const QString& ); + void setErrorString(const QString &); private slots: - void slotSelectFolder(); - void slotSyncEverythingClicked(); - void slotSelectiveSyncClicked(); - void slotQuotaRetrieved(const QVariantMap& result); + void slotSelectFolder(); + void slotSyncEverythingClicked(); + void slotSelectiveSyncClicked(); + void slotQuotaRetrieved(const QVariantMap &result); private: - void setupCustomization(); - void updateStatus(); - bool dataChanged(); - void startSpinner(); - void stopSpinner(); - QUrl serverUrl() const; + void setupCustomization(); + void updateStatus(); + bool dataChanged(); + void startSpinner(); + void stopSpinner(); + QUrl serverUrl() const; - Ui_OwncloudAdvancedSetupPage _ui; - bool _checking; - bool _created; - bool _localFolderValid; - QProgressIndicator* _progressIndi; - QString _remoteFolder; - QStringList _selectiveSyncBlacklist; + Ui_OwncloudAdvancedSetupPage _ui; + bool _checking; + bool _created; + bool _localFolderValid; + QProgressIndicator *_progressIndi; + QString _remoteFolder; + QStringList _selectiveSyncBlacklist; }; } // namespace OCC diff --git a/src/gui/wizard/owncloudconnectionmethoddialog.cpp b/src/gui/wizard/owncloudconnectionmethoddialog.cpp index 1312da562..f0d670480 100644 --- a/src/gui/wizard/owncloudconnectionmethoddialog.cpp +++ b/src/gui/wizard/owncloudconnectionmethoddialog.cpp @@ -19,9 +19,9 @@ namespace OCC { -OwncloudConnectionMethodDialog::OwncloudConnectionMethodDialog(QWidget *parent) : - QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint), - ui(new Ui::OwncloudConnectionMethodDialog) +OwncloudConnectionMethodDialog::OwncloudConnectionMethodDialog(QWidget *parent) + : QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint) + , ui(new Ui::OwncloudConnectionMethodDialog) { ui->setupUi(this); @@ -40,9 +40,9 @@ void OwncloudConnectionMethodDialog::setUrl(const QUrl &url) { ui->label->setText(tr("

Failed to connect to the secure server address %1. How do you wish to proceed?

") #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) - .arg(OCC::Utility::escape(url.toString()))); + .arg(OCC::Utility::escape(url.toString()))); #else - .arg(url.toDisplayString().toHtmlEscaped())); + .arg(url.toDisplayString().toHtmlEscaped())); #endif } @@ -66,5 +66,4 @@ OwncloudConnectionMethodDialog::~OwncloudConnectionMethodDialog() { delete ui; } - } diff --git a/src/gui/wizard/owncloudconnectionmethoddialog.h b/src/gui/wizard/owncloudconnectionmethoddialog.h index b08076f59..c3e3412c1 100644 --- a/src/gui/wizard/owncloudconnectionmethoddialog.h +++ b/src/gui/wizard/owncloudconnectionmethoddialog.h @@ -23,7 +23,7 @@ namespace OCC { namespace Ui { -class OwncloudConnectionMethodDialog; + class OwncloudConnectionMethodDialog; } /** @@ -43,7 +43,7 @@ public: Client_Side_TLS, Back }; - + // The URL that was tried void setUrl(const QUrl &); @@ -55,7 +55,6 @@ public slots: private: Ui::OwncloudConnectionMethodDialog *ui; }; - } #endif // OWNCLOUDCONNECTIONMETHODDIALOG_H diff --git a/src/gui/wizard/owncloudhttpcredspage.cpp b/src/gui/wizard/owncloudhttpcredspage.cpp index 4c8bbd5a1..265d3bf3c 100644 --- a/src/gui/wizard/owncloudhttpcredspage.cpp +++ b/src/gui/wizard/owncloudhttpcredspage.cpp @@ -23,26 +23,25 @@ #include "wizard/owncloudwizardcommon.h" #include "wizard/owncloudwizard.h" -namespace OCC -{ +namespace OCC { -OwncloudHttpCredsPage::OwncloudHttpCredsPage(QWidget* parent) - : AbstractCredentialsWizardPage(), - _ui(), - _connected(false), - _progressIndi(new QProgressIndicator (this)) +OwncloudHttpCredsPage::OwncloudHttpCredsPage(QWidget *parent) + : AbstractCredentialsWizardPage() + , _ui() + , _connected(false) + , _progressIndi(new QProgressIndicator(this)) { _ui.setupUi(this); - if(parent){ + if (parent) { _ocWizard = qobject_cast(parent); } - registerField( QLatin1String("OCUser*"), _ui.leUsername); - registerField( QLatin1String("OCPasswd*"), _ui.lePassword); + registerField(QLatin1String("OCUser*"), _ui.leUsername); + registerField(QLatin1String("OCPasswd*"), _ui.lePassword); Theme *theme = Theme::instance(); - switch(theme->userIDType()) { + switch (theme->userIDType()) { case Theme::UserIDUserName: // default, handled in ui file break; @@ -60,7 +59,7 @@ OwncloudHttpCredsPage::OwncloudHttpCredsPage(QWidget* parent) setTitle(WizardCommon::titleTemplate().arg(tr("Connect to %1").arg(Theme::instance()->appNameGUI()))); setSubTitle(WizardCommon::subTitleTemplate().arg(tr("Enter user credentials"))); - _ui.resultLayout->addWidget( _progressIndi ); + _ui.resultLayout->addWidget(_progressIndi); stopSpinner(); setupCustomization(); } @@ -72,22 +71,22 @@ void OwncloudHttpCredsPage::setupCustomization() _ui.bottomLabel->hide(); Theme *theme = Theme::instance(); - QVariant variant = theme->customMedia( Theme::oCSetupTop ); - if( !variant.isNull() ) { - WizardCommon::setupCustomMedia( variant, _ui.topLabel ); + QVariant variant = theme->customMedia(Theme::oCSetupTop); + if (!variant.isNull()) { + WizardCommon::setupCustomMedia(variant, _ui.topLabel); } - variant = theme->customMedia( Theme::oCSetupBottom ); - WizardCommon::setupCustomMedia( variant, _ui.bottomLabel ); + variant = theme->customMedia(Theme::oCSetupBottom); + WizardCommon::setupCustomMedia(variant, _ui.bottomLabel); } void OwncloudHttpCredsPage::initializePage() { WizardCommon::initErrorLabel(_ui.errorLabel); - OwncloudWizard* ocWizard = qobject_cast< OwncloudWizard* >(wizard()); + OwncloudWizard *ocWizard = qobject_cast(wizard()); AbstractCredentials *cred = ocWizard->account()->credentials(); - HttpCredentials *httpCreds = qobject_cast(cred); + HttpCredentials *httpCreds = qobject_cast(cred); if (httpCreds) { const QString user = httpCreds->fetchUser(); if (!user.isEmpty()) { @@ -106,10 +105,10 @@ void OwncloudHttpCredsPage::initializePage() const QString user = url.userName(); const QString password = url.password(); - if(!user.isEmpty()) { + if (!user.isEmpty()) { _ui.leUsername->setText(user); } - if(!password.isEmpty()) { + if (!password.isEmpty()) { _ui.lePassword->setText(password); } } @@ -135,7 +134,7 @@ bool OwncloudHttpCredsPage::validatePage() startSpinner(); // Reset cookies to ensure the username / password is actually used - OwncloudWizard* ocWizard = qobject_cast< OwncloudWizard* >(wizard()); + OwncloudWizard *ocWizard = qobject_cast(wizard()); ocWizard->account()->clearCookieJar(); emit completeChanged(); @@ -161,7 +160,7 @@ int OwncloudHttpCredsPage::nextId() const void OwncloudHttpCredsPage::setConnected() { _connected = true; - stopSpinner (); + stopSpinner(); } void OwncloudHttpCredsPage::startSpinner() @@ -178,9 +177,9 @@ void OwncloudHttpCredsPage::stopSpinner() _progressIndi->stopAnimation(); } -void OwncloudHttpCredsPage::setErrorString(const QString& err) +void OwncloudHttpCredsPage::setErrorString(const QString &err) { - if( err.isEmpty()) { + if (err.isEmpty()) { _ui.errorLabel->setVisible(false); } else { _ui.errorLabel->setVisible(true); @@ -190,7 +189,7 @@ void OwncloudHttpCredsPage::setErrorString(const QString& err) stopSpinner(); } -AbstractCredentials* OwncloudHttpCredsPage::getCredentials() const +AbstractCredentials *OwncloudHttpCredsPage::getCredentials() const { return new HttpCredentialsGui(_ui.leUsername->text(), _ui.lePassword->text(), _ocWizard->_clientSslCertificate, _ocWizard->_clientSslKey); } diff --git a/src/gui/wizard/owncloudhttpcredspage.h b/src/gui/wizard/owncloudhttpcredspage.h index f339b23ec..3fce61e1a 100644 --- a/src/gui/wizard/owncloudhttpcredspage.h +++ b/src/gui/wizard/owncloudhttpcredspage.h @@ -30,31 +30,31 @@ namespace OCC { */ class OwncloudHttpCredsPage : public AbstractCredentialsWizardPage { - Q_OBJECT + Q_OBJECT public: - OwncloudHttpCredsPage(QWidget* parent); + OwncloudHttpCredsPage(QWidget *parent); - AbstractCredentials* getCredentials() const Q_DECL_OVERRIDE; + AbstractCredentials *getCredentials() const Q_DECL_OVERRIDE; - void initializePage() Q_DECL_OVERRIDE; - void cleanupPage() Q_DECL_OVERRIDE; - bool validatePage() Q_DECL_OVERRIDE; - int nextId() const Q_DECL_OVERRIDE; - void setConnected(); - void setErrorString( const QString& err ); + void initializePage() Q_DECL_OVERRIDE; + void cleanupPage() Q_DECL_OVERRIDE; + bool validatePage() Q_DECL_OVERRIDE; + int nextId() const Q_DECL_OVERRIDE; + void setConnected(); + void setErrorString(const QString &err); Q_SIGNALS: - void connectToOCUrl(const QString&); + void connectToOCUrl(const QString &); private: - void startSpinner(); - void stopSpinner(); - void setupCustomization(); - - Ui_OwncloudHttpCredsPage _ui; - bool _connected; - QProgressIndicator* _progressIndi; - OwncloudWizard* _ocWizard; + void startSpinner(); + void stopSpinner(); + void setupCustomization(); + + Ui_OwncloudHttpCredsPage _ui; + bool _connected; + QProgressIndicator *_progressIndi; + OwncloudWizard *_ocWizard; }; } // namespace OCC diff --git a/src/gui/wizard/owncloudsetuppage.cpp b/src/gui/wizard/owncloudsetuppage.cpp index 8e67d6f8c..39710e892 100644 --- a/src/gui/wizard/owncloudsetuppage.cpp +++ b/src/gui/wizard/owncloudsetuppage.cpp @@ -31,18 +31,17 @@ #include "theme.h" #include "account.h" -namespace OCC -{ +namespace OCC { OwncloudSetupPage::OwncloudSetupPage(QWidget *parent) - : QWizardPage(), - _ui(), - _oCUrl(), - _ocUser(), - _authTypeKnown(false), - _checking(false), - _authType(WizardCommon::HttpCreds), - _progressIndi(new QProgressIndicator (this)) + : QWizardPage() + , _ui() + , _oCUrl() + , _ocUser() + , _authTypeKnown(false) + , _checking(false) + , _authType(WizardCommon::HttpCreds) + , _progressIndi(new QProgressIndicator(this)) { _ui.setupUi(this); _ocWizard = qobject_cast(parent); @@ -59,9 +58,9 @@ OwncloudSetupPage::OwncloudSetupPage(QWidget *parent) } - registerField( QLatin1String("OCUrl*"), _ui.leUrl ); + registerField(QLatin1String("OCUrl*"), _ui.leUrl); - _ui.resultLayout->addWidget( _progressIndi ); + _ui.resultLayout->addWidget(_progressIndi); stopSpinner(); setupCustomization(); @@ -73,15 +72,15 @@ OwncloudSetupPage::OwncloudSetupPage(QWidget *parent) addCertDial = new AddCertificateDialog(this); } -void OwncloudSetupPage::setServerUrl( const QString& newUrl ) +void OwncloudSetupPage::setServerUrl(const QString &newUrl) { _oCUrl = newUrl; - if( _oCUrl.isEmpty() ) { + if (_oCUrl.isEmpty()) { _ui.leUrl->clear(); return; } - _ui.leUrl->setText( _oCUrl ); + _ui.leUrl->setText(_oCUrl); } void OwncloudSetupPage::setupCustomization() @@ -91,17 +90,17 @@ void OwncloudSetupPage::setupCustomization() _ui.bottomLabel->hide(); Theme *theme = Theme::instance(); - QVariant variant = theme->customMedia( Theme::oCSetupTop ); - if( !variant.isNull() ) { - WizardCommon::setupCustomMedia( variant, _ui.topLabel ); + QVariant variant = theme->customMedia(Theme::oCSetupTop); + if (!variant.isNull()) { + WizardCommon::setupCustomMedia(variant, _ui.topLabel); } - variant = theme->customMedia( Theme::oCSetupBottom ); - WizardCommon::setupCustomMedia( variant, _ui.bottomLabel ); + variant = theme->customMedia(Theme::oCSetupBottom); + WizardCommon::setupCustomMedia(variant, _ui.bottomLabel); } // slot hit from textChanged of the url entry field. -void OwncloudSetupPage::slotUrlChanged(const QString& url) +void OwncloudSetupPage::slotUrlChanged(const QString &url) { _authTypeKnown = false; @@ -109,14 +108,14 @@ void OwncloudSetupPage::slotUrlChanged(const QString& url) if (url.endsWith("index.php")) { newUrl.chop(9); } - if( _ocWizard && _ocWizard->account() ) { + if (_ocWizard && _ocWizard->account()) { QString webDavPath = _ocWizard->account()->davPath(); if (url.endsWith(webDavPath)) { - newUrl.chop( webDavPath.length() ); + newUrl.chop(webDavPath.length()); } - if( webDavPath.endsWith(QLatin1Char('/')) ) { + if (webDavPath.endsWith(QLatin1Char('/'))) { webDavPath.chop(1); // cut off the slash - if( url.endsWith(webDavPath)) { + if (url.endsWith(webDavPath)) { newUrl.chop(webDavPath.length()); } } @@ -155,10 +154,10 @@ void OwncloudSetupPage::initializePage() WizardCommon::initErrorLabel(_ui.errorLabel); _authTypeKnown = false; - _checking = false; + _checking = false; QAbstractButton *nextButton = wizard()->button(QWizard::NextButton); - QPushButton *pushButton = qobject_cast(nextButton); + QPushButton *pushButton = qobject_cast(nextButton); if (pushButton) pushButton->setDefault(true); @@ -181,19 +180,19 @@ bool OwncloudSetupPage::urlHasChanged() bool change = false; const QChar slash('/'); - QUrl currentUrl( url() ); - QUrl initialUrl( _oCUrl ); + QUrl currentUrl(url()); + QUrl initialUrl(_oCUrl); QString currentPath = currentUrl.path(); QString initialPath = initialUrl.path(); // add a trailing slash. - if( ! currentPath.endsWith( slash )) currentPath += slash; - if( ! initialPath.endsWith( slash )) initialPath += slash; + if (!currentPath.endsWith(slash)) + currentPath += slash; + if (!initialPath.endsWith(slash)) + initialPath += slash; - if( currentUrl.host() != initialUrl.host() || - currentUrl.port() != initialUrl.port() || - currentPath != initialPath ) { + if (currentUrl.host() != initialUrl.host() || currentUrl.port() != initialUrl.port() || currentPath != initialPath) { change = true; } @@ -217,10 +216,10 @@ QString OwncloudSetupPage::url() const bool OwncloudSetupPage::validatePage() { - if( ! _authTypeKnown) { + if (!_authTypeKnown) { setErrorString(QString::null, false); _checking = true; - startSpinner (); + startSpinner(); emit completeChanged(); emit determineAuthType(url()); @@ -234,16 +233,16 @@ bool OwncloudSetupPage::validatePage() } } -void OwncloudSetupPage::setAuthType (WizardCommon::AuthType type) +void OwncloudSetupPage::setAuthType(WizardCommon::AuthType type) { - _authTypeKnown = true; - _authType = type; - stopSpinner(); + _authTypeKnown = true; + _authType = type; + stopSpinner(); } -void OwncloudSetupPage::setErrorString( const QString& err, bool retryHTTPonly ) +void OwncloudSetupPage::setErrorString(const QString &err, bool retryHTTPonly) { - if( err.isEmpty()) { + if (err.isEmpty()) { _ui.errorLabel->setVisible(false); } else { if (retryHTTPonly) { @@ -259,18 +258,16 @@ void OwncloudSetupPage::setErrorString( const QString& err, bool retryHTTPonly ) int retVal = dialog.exec(); switch (retVal) { - case OwncloudConnectionMethodDialog::No_TLS: - { - url.setScheme("http"); - _ui.leUrl->setFullText(url.toString()); - // skip ahead to next page, since the user would expect us to retry automatically - wizard()->next(); - } - break; + case OwncloudConnectionMethodDialog::No_TLS: { + url.setScheme("http"); + _ui.leUrl->setFullText(url.toString()); + // skip ahead to next page, since the user would expect us to retry automatically + wizard()->next(); + } break; case OwncloudConnectionMethodDialog::Client_Side_TLS: #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) addCertDial->show(); - connect(addCertDial, SIGNAL(accepted()),this,SLOT(slotCertificateAccepted())); + connect(addCertDial, SIGNAL(accepted()), this, SLOT(slotCertificateAccepted())); #endif break; case OwncloudConnectionMethodDialog::Closed: @@ -304,9 +301,9 @@ void OwncloudSetupPage::stopSpinner() _progressIndi->stopAnimation(); } -QString subjectInfoHelper(const QSslCertificate& cert, const QByteArray &qa) +QString subjectInfoHelper(const QSslCertificate &cert, const QByteArray &qa) { -#if QT_VERSION < QT_VERSION_CHECK(5,0,0) +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) return cert.subjectInfo(qa); #else return cert.subjectInfo(qa).join(QLatin1Char('/')); @@ -320,10 +317,10 @@ void OwncloudSetupPage::slotCertificateAccepted() QList clientCaCertificates; QFile certFile(addCertDial->getCertificatePath()); certFile.open(QFile::ReadOnly); - if(QSslCertificate::importPkcs12(&certFile, - &_ocWizard->_clientSslKey, &_ocWizard->_clientSslCertificate, - &clientCaCertificates, - addCertDial->getCertificatePasswd().toLocal8Bit())){ + if (QSslCertificate::importPkcs12(&certFile, + &_ocWizard->_clientSslKey, &_ocWizard->_clientSslCertificate, + &clientCaCertificates, + addCertDial->getCertificatePasswd().toLocal8Bit())) { AccountPtr acc = _ocWizard->account(); // to re-create the session ticket because we added a key/cert diff --git a/src/gui/wizard/owncloudsetuppage.h b/src/gui/wizard/owncloudsetuppage.h index e0b1ba852..accd39989 100644 --- a/src/gui/wizard/owncloudsetuppage.h +++ b/src/gui/wizard/owncloudsetuppage.h @@ -36,57 +36,57 @@ namespace OCC { * @brief The OwncloudSetupPage class * @ingroup gui */ -class OwncloudSetupPage: public QWizardPage +class OwncloudSetupPage : public QWizardPage { Q_OBJECT public: - OwncloudSetupPage(QWidget *parent=0); - ~OwncloudSetupPage(); - - virtual bool isComplete() const Q_DECL_OVERRIDE; - virtual void initializePage() Q_DECL_OVERRIDE; - virtual int nextId() const Q_DECL_OVERRIDE; - void setServerUrl( const QString& ); - void setAllowPasswordStorage( bool ); - bool validatePage() Q_DECL_OVERRIDE; - QString url() const; - QString localFolder() const; - void setRemoteFolder( const QString& remoteFolder); - void setMultipleFoldersExist( bool exist ); - void setAuthType(WizardCommon::AuthType type); + OwncloudSetupPage(QWidget *parent = 0); + ~OwncloudSetupPage(); + + virtual bool isComplete() const Q_DECL_OVERRIDE; + virtual void initializePage() Q_DECL_OVERRIDE; + virtual int nextId() const Q_DECL_OVERRIDE; + void setServerUrl(const QString &); + void setAllowPasswordStorage(bool); + bool validatePage() Q_DECL_OVERRIDE; + QString url() const; + QString localFolder() const; + void setRemoteFolder(const QString &remoteFolder); + void setMultipleFoldersExist(bool exist); + void setAuthType(WizardCommon::AuthType type); public slots: - void setErrorString( const QString&, bool retryHTTPonly ); - void startSpinner(); - void stopSpinner(); - void slotCertificateAccepted(); + void setErrorString(const QString &, bool retryHTTPonly); + void startSpinner(); + void stopSpinner(); + void slotCertificateAccepted(); protected slots: - void slotUrlChanged(const QString&); - void slotUrlEditFinished(); + void slotUrlChanged(const QString &); + void slotUrlEditFinished(); - void setupCustomization(); + void setupCustomization(); signals: - void determineAuthType(const QString&); + void determineAuthType(const QString &); private: - bool urlHasChanged(); - - Ui_OwncloudSetupPage _ui; - - QString _oCUrl; - QString _ocUser; - bool _authTypeKnown; - bool _checking; - bool _multipleFoldersExist; - WizardCommon::AuthType _authType; - - QProgressIndicator* _progressIndi; - QButtonGroup* _selectiveSyncButtons; - QString _remoteFolder; - AddCertificateDialog* addCertDial; - OwncloudWizard* _ocWizard; + bool urlHasChanged(); + + Ui_OwncloudSetupPage _ui; + + QString _oCUrl; + QString _ocUser; + bool _authTypeKnown; + bool _checking; + bool _multipleFoldersExist; + WizardCommon::AuthType _authType; + + QProgressIndicator *_progressIndi; + QButtonGroup *_selectiveSyncButtons; + QString _remoteFolder; + AddCertificateDialog *addCertDial; + OwncloudWizard *_ocWizard; }; } // namespace OCC diff --git a/src/gui/wizard/owncloudshibbolethcredspage.cpp b/src/gui/wizard/owncloudshibbolethcredspage.cpp index 9b031c064..9d88555a6 100644 --- a/src/gui/wizard/owncloudshibbolethcredspage.cpp +++ b/src/gui/wizard/owncloudshibbolethcredspage.cpp @@ -23,21 +23,21 @@ #include "creds/shibbolethcredentials.h" #include "creds/shibboleth/shibbolethwebview.h" -namespace OCC -{ +namespace OCC { OwncloudShibbolethCredsPage::OwncloudShibbolethCredsPage() - : AbstractCredentialsWizardPage(), - _browser(0), - _afterInitialSetup(false) -{} + : AbstractCredentialsWizardPage() + , _browser(0) + , _afterInitialSetup(false) +{ +} void OwncloudShibbolethCredsPage::setupBrowser() { if (!_browser.isNull()) { return; } - OwncloudWizard *ocWizard = qobject_cast(wizard()); + OwncloudWizard *ocWizard = qobject_cast(wizard()); AccountPtr account = ocWizard->account(); // we need to reset the cookie jar to drop temporary cookies (like the shib cookie) @@ -49,10 +49,10 @@ void OwncloudShibbolethCredsPage::setupBrowser() qnam->setCookieJar(jar); _browser = new ShibbolethWebView(account); - connect(_browser, SIGNAL(shibbolethCookieReceived(const QNetworkCookie&)), - this, SLOT(slotShibbolethCookieReceived(const QNetworkCookie&)), Qt::QueuedConnection); + connect(_browser, SIGNAL(shibbolethCookieReceived(const QNetworkCookie &)), + this, SLOT(slotShibbolethCookieReceived(const QNetworkCookie &)), Qt::QueuedConnection); connect(_browser, SIGNAL(rejected()), - this, SLOT(slotBrowserRejected())); + this, SLOT(slotBrowserRejected())); _browser->move(ocWizard->x(), ocWizard->y()); _browser->show(); @@ -84,7 +84,7 @@ void OwncloudShibbolethCredsPage::initializePage() int OwncloudShibbolethCredsPage::nextId() const { - return WizardCommon::Page_AdvancedSetup; + return WizardCommon::Page_AdvancedSetup; } void OwncloudShibbolethCredsPage::setConnected() @@ -92,7 +92,7 @@ void OwncloudShibbolethCredsPage::setConnected() wizard()->show(); } -AbstractCredentials* OwncloudShibbolethCredsPage::getCredentials() const +AbstractCredentials *OwncloudShibbolethCredsPage::getCredentials() const { return new ShibbolethCredentials(_cookie); } diff --git a/src/gui/wizard/owncloudshibbolethcredspage.h b/src/gui/wizard/owncloudshibbolethcredspage.h index 75584674d..daa9817a9 100644 --- a/src/gui/wizard/owncloudshibbolethcredspage.h +++ b/src/gui/wizard/owncloudshibbolethcredspage.h @@ -34,32 +34,32 @@ class ShibbolethWebView; */ class OwncloudShibbolethCredsPage : public AbstractCredentialsWizardPage { - Q_OBJECT + Q_OBJECT public: - OwncloudShibbolethCredsPage(); + OwncloudShibbolethCredsPage(); - AbstractCredentials* getCredentials() const Q_DECL_OVERRIDE; + AbstractCredentials *getCredentials() const Q_DECL_OVERRIDE; - void initializePage() Q_DECL_OVERRIDE; - int nextId() const Q_DECL_OVERRIDE; - void setConnected(); + void initializePage() Q_DECL_OVERRIDE; + int nextId() const Q_DECL_OVERRIDE; + void setConnected(); Q_SIGNALS: - void connectToOCUrl(const QString&); + void connectToOCUrl(const QString &); public Q_SLOTS: - void setVisible(bool visible) Q_DECL_OVERRIDE; + void setVisible(bool visible) Q_DECL_OVERRIDE; private Q_SLOTS: - void slotShibbolethCookieReceived(const QNetworkCookie&); - void slotBrowserRejected(); + void slotShibbolethCookieReceived(const QNetworkCookie &); + void slotBrowserRejected(); private: - void setupBrowser(); + void setupBrowser(); - QPointer _browser; - bool _afterInitialSetup; - QNetworkCookie _cookie; + QPointer _browser; + bool _afterInitialSetup; + QNetworkCookie _cookie; }; } // namespace OCC diff --git a/src/gui/wizard/owncloudwizard.cpp b/src/gui/wizard/owncloudwizard.cpp index c611a4e66..84068ddd5 100644 --- a/src/gui/wizard/owncloudwizard.cpp +++ b/src/gui/wizard/owncloudwizard.cpp @@ -33,23 +33,24 @@ #include -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcWizard, "gui.wizard", QtInfoMsg) OwncloudWizard::OwncloudWizard(QWidget *parent) - : QWizard(parent), - _account(0), - _setupPage(new OwncloudSetupPage(this)), - _httpCredsPage(new OwncloudHttpCredsPage(this)), + : QWizard(parent) + , _account(0) + , _setupPage(new OwncloudSetupPage(this)) + , _httpCredsPage(new OwncloudHttpCredsPage(this)) + , #ifndef NO_SHIBBOLETH - _shibbolethCredsPage(new OwncloudShibbolethCredsPage), + _shibbolethCredsPage(new OwncloudShibbolethCredsPage) + , #endif - _advancedSetupPage(new OwncloudAdvancedSetupPage), - _resultPage(new OwncloudWizardResultPage), - _credentialsPage(0), - _setupLog() + _advancedSetupPage(new OwncloudAdvancedSetupPage) + , _resultPage(new OwncloudWizardResultPage) + , _credentialsPage(0) + , _setupLog() { setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setPage(WizardCommon::Page_ServerSetup, _setupPage); @@ -64,27 +65,27 @@ OwncloudWizard::OwncloudWizard(QWidget *parent) // note: start Id is set by the calling class depending on if the // welcome text is to be shown or not. - setWizardStyle( QWizard::ModernStyle ); + setWizardStyle(QWizard::ModernStyle); - connect( this, SIGNAL(currentIdChanged(int)), SLOT(slotCurrentPageChanged(int))); - connect( _setupPage, SIGNAL(determineAuthType(QString)), SIGNAL(determineAuthType(QString))); - connect( _httpCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString))); + connect(this, SIGNAL(currentIdChanged(int)), SLOT(slotCurrentPageChanged(int))); + connect(_setupPage, SIGNAL(determineAuthType(QString)), SIGNAL(determineAuthType(QString))); + connect(_httpCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString))); #ifndef NO_SHIBBOLETH - connect( _shibbolethCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString))); + connect(_shibbolethCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString))); #endif - connect( _advancedSetupPage, SIGNAL(createLocalAndRemoteFolders(QString, QString)), - SIGNAL(createLocalAndRemoteFolders(QString, QString))); + connect(_advancedSetupPage, SIGNAL(createLocalAndRemoteFolders(QString, QString)), + SIGNAL(createLocalAndRemoteFolders(QString, QString))); connect(this, SIGNAL(customButtonClicked(int)), this, SIGNAL(skipFolderConfiguration())); Theme *theme = Theme::instance(); - setWindowTitle( tr("%1 Connection Wizard").arg(theme->appNameGUI())); + setWindowTitle(tr("%1 Connection Wizard").arg(theme->appNameGUI())); setWizardStyle(QWizard::ModernStyle); - setPixmap( QWizard::BannerPixmap, theme->wizardHeaderBanner() ); - setPixmap( QWizard::LogoPixmap, theme->wizardHeaderLogo() ); - setOption( QWizard::NoBackButtonOnStartPage ); - setOption( QWizard::NoBackButtonOnLastPage ); - setOption( QWizard::NoCancelButton ); + setPixmap(QWizard::BannerPixmap, theme->wizardHeaderBanner()); + setPixmap(QWizard::LogoPixmap, theme->wizardHeaderLogo()); + setOption(QWizard::NoBackButtonOnStartPage); + setOption(QWizard::NoBackButtonOnLastPage); + setOption(QWizard::NoCancelButton); setTitleFormat(Qt::RichText); setSubTitleFormat(Qt::RichText); setButtonText(QWizard::CustomButton1, tr("Skip folders configuration")); @@ -102,7 +103,7 @@ AccountPtr OwncloudWizard::account() const QString OwncloudWizard::localFolder() const { - return(_advancedSetupPage->localFolder()); + return (_advancedSetupPage->localFolder()); } QStringList OwncloudWizard::selectiveSyncBlacklist() const @@ -126,10 +127,10 @@ void OwncloudWizard::enableFinishOnResultWidget(bool enable) _resultPage->setComplete(enable); } -void OwncloudWizard::setRemoteFolder( const QString& remoteFolder ) +void OwncloudWizard::setRemoteFolder(const QString &remoteFolder) { - _advancedSetupPage->setRemoteFolder( remoteFolder ); - _resultPage->setRemoteFolder( remoteFolder ); + _advancedSetupPage->setRemoteFolder(remoteFolder); + _resultPage->setRemoteFolder(remoteFolder); } void OwncloudWizard::successfulStep() @@ -162,31 +163,31 @@ void OwncloudWizard::successfulStep() void OwncloudWizard::setAuthType(WizardCommon::AuthType type) { - _setupPage->setAuthType(type); + _setupPage->setAuthType(type); #ifndef NO_SHIBBOLETH - if (type == WizardCommon::Shibboleth) { - _credentialsPage = _shibbolethCredsPage; - } else + if (type == WizardCommon::Shibboleth) { + _credentialsPage = _shibbolethCredsPage; + } else #endif - { - _credentialsPage = _httpCredsPage; - } - next(); + { + _credentialsPage = _httpCredsPage; + } + next(); } // TODO: update this function -void OwncloudWizard::slotCurrentPageChanged( int id ) +void OwncloudWizard::slotCurrentPageChanged(int id) { qCDebug(lcWizard) << "Current Wizard page changed to " << id; - if( id == WizardCommon::Page_ServerSetup ) { + if (id == WizardCommon::Page_ServerSetup) { emit clearPendingRequests(); } - if( id == WizardCommon::Page_Result ) { + if (id == WizardCommon::Page_Result) { disconnect(this, SIGNAL(finished(int)), this, SIGNAL(basicSetupFinished(int))); emit basicSetupFinished(QDialog::Accepted); - appendToConfigurationLog( QString::null ); + appendToConfigurationLog(QString::null); // Immediately close on show, we currently don't want this page anymore done(Accepted); } @@ -194,11 +195,11 @@ void OwncloudWizard::slotCurrentPageChanged( int id ) setOption(QWizard::HaveCustomButton1, id == WizardCommon::Page_AdvancedSetup); } -void OwncloudWizard::displayError( const QString& msg, bool retryHTTPonly ) +void OwncloudWizard::displayError(const QString &msg, bool retryHTTPonly) { switch (currentId()) { case WizardCommon::Page_ServerSetup: - _setupPage->setErrorString( msg, retryHTTPonly ); + _setupPage->setErrorString(msg, retryHTTPonly); break; case WizardCommon::Page_HttpCreds: @@ -211,24 +212,24 @@ void OwncloudWizard::displayError( const QString& msg, bool retryHTTPonly ) } } -void OwncloudWizard::appendToConfigurationLog( const QString& msg, LogType /*type*/ ) +void OwncloudWizard::appendToConfigurationLog(const QString &msg, LogType /*type*/) { _setupLog << msg; qCDebug(lcWizard) << "Setup-Log: " << msg; } -void OwncloudWizard::setOCUrl( const QString& url ) +void OwncloudWizard::setOCUrl(const QString &url) { - _setupPage->setServerUrl( url ); + _setupPage->setServerUrl(url); } -AbstractCredentials* OwncloudWizard::getCredentials() const +AbstractCredentials *OwncloudWizard::getCredentials() const { - if (_credentialsPage) { - return _credentialsPage->getCredentials(); - } + if (_credentialsPage) { + return _credentialsPage->getCredentials(); + } - return 0; + return 0; } } // end namespace diff --git a/src/gui/wizard/owncloudwizard.h b/src/gui/wizard/owncloudwizard.h index 93391a2b5..4b9097f74 100644 --- a/src/gui/wizard/owncloudwizard.h +++ b/src/gui/wizard/owncloudwizard.h @@ -46,19 +46,18 @@ class OwncloudWizard : public QWizard { Q_OBJECT public: - enum LogType { - LogPlain, - LogParagraph + LogPlain, + LogParagraph }; OwncloudWizard(QWidget *parent = 0); void setAccount(AccountPtr account); AccountPtr account() const; - void setOCUrl( const QString& ); + void setOCUrl(const QString &); - void setupCustomMedia( QVariant, QLabel* ); + void setupCustomMedia(QVariant, QLabel *); QString ocUrl() const; QString localFolder() const; QStringList selectiveSyncBlacklist() const; @@ -66,8 +65,8 @@ public: void enableFinishOnResultWidget(bool enable); - void displayError( const QString&, bool retryHTTPonly); - AbstractCredentials* getCredentials() const; + void displayError(const QString &, bool retryHTTPonly); + AbstractCredentials *getCredentials() const; // FIXME: Can those be local variables? // Set from the OwncloudSetupPage, later used from OwncloudHttpCredsPage @@ -76,31 +75,31 @@ public: public slots: void setAuthType(WizardCommon::AuthType type); - void setRemoteFolder( const QString& ); - void appendToConfigurationLog( const QString& msg, LogType type = LogParagraph ); - void slotCurrentPageChanged( int ); + void setRemoteFolder(const QString &); + void appendToConfigurationLog(const QString &msg, LogType type = LogParagraph); + void slotCurrentPageChanged(int); void successfulStep(); signals: void clearPendingRequests(); - void determineAuthType(const QString&); - void connectToOCUrl( const QString& ); - void createLocalAndRemoteFolders(const QString&, const QString&); + void determineAuthType(const QString &); + void connectToOCUrl(const QString &); + void createLocalAndRemoteFolders(const QString &, const QString &); // make sure to connect to this, rather than finished(int)!! - void basicSetupFinished( int ); + void basicSetupFinished(int); void skipFolderConfiguration(); void needCertificate(); private: AccountPtr _account; - OwncloudSetupPage* _setupPage; - OwncloudHttpCredsPage* _httpCredsPage; + OwncloudSetupPage *_setupPage; + OwncloudHttpCredsPage *_httpCredsPage; #ifndef NO_SHIBBOLETH - OwncloudShibbolethCredsPage* _shibbolethCredsPage; + OwncloudShibbolethCredsPage *_shibbolethCredsPage; #endif - OwncloudAdvancedSetupPage* _advancedSetupPage; - OwncloudWizardResultPage* _resultPage; - AbstractCredentialsWizardPage* _credentialsPage; + OwncloudAdvancedSetupPage *_advancedSetupPage; + OwncloudWizardResultPage *_resultPage; + AbstractCredentialsWizardPage *_credentialsPage; QStringList _setupLog; }; diff --git a/src/gui/wizard/owncloudwizardcommon.cpp b/src/gui/wizard/owncloudwizardcommon.cpp index 0c4bcc07b..229987ece 100644 --- a/src/gui/wizard/owncloudwizardcommon.cpp +++ b/src/gui/wizard/owncloudwizardcommon.cpp @@ -20,51 +20,50 @@ #include "wizard/owncloudwizardcommon.h" #include "theme.h" -namespace OCC -{ +namespace OCC { -namespace WizardCommon -{ +namespace WizardCommon { -void setupCustomMedia( const QVariant& variant, QLabel *label ) -{ - if( !label ) return; + void setupCustomMedia(const QVariant &variant, QLabel *label) + { + if (!label) + return; - QPixmap pix = variant.value(); - if( !pix.isNull() ) { - label->setPixmap(pix); - label->setAlignment( Qt::AlignTop | Qt::AlignRight ); - label->setVisible(true); - } else { - QString str = variant.toString(); - if( !str.isEmpty() ) { - label->setText( str ); - label->setTextFormat( Qt::RichText ); + QPixmap pix = variant.value(); + if (!pix.isNull()) { + label->setPixmap(pix); + label->setAlignment(Qt::AlignTop | Qt::AlignRight); label->setVisible(true); - label->setOpenExternalLinks(true); + } else { + QString str = variant.toString(); + if (!str.isEmpty()) { + label->setText(str); + label->setTextFormat(Qt::RichText); + label->setVisible(true); + label->setOpenExternalLinks(true); + } } } -} -QString titleTemplate() -{ - return QString::fromLatin1("").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1"); -} + QString titleTemplate() + { + return QString::fromLatin1("").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1"); + } -QString subTitleTemplate() -{ - return QString::fromLatin1("").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1"); -} + QString subTitleTemplate() + { + return QString::fromLatin1("").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1"); + } -void initErrorLabel(QLabel* errorLabel) -{ - QString style = QLatin1String("border: 1px solid #eed3d7; border-radius: 5px; padding: 3px;" - "background-color: #f2dede; color: #b94a48;"); + void initErrorLabel(QLabel *errorLabel) + { + QString style = QLatin1String("border: 1px solid #eed3d7; border-radius: 5px; padding: 3px;" + "background-color: #f2dede; color: #b94a48;"); - errorLabel->setStyleSheet(style); - errorLabel->setWordWrap(true); - errorLabel->setVisible(false); -} + errorLabel->setStyleSheet(style); + errorLabel->setWordWrap(true); + errorLabel->setVisible(false); + } } // ns WizardCommon diff --git a/src/gui/wizard/owncloudwizardcommon.h b/src/gui/wizard/owncloudwizardcommon.h index 1eeeef006..bf6248c2c 100644 --- a/src/gui/wizard/owncloudwizardcommon.h +++ b/src/gui/wizard/owncloudwizardcommon.h @@ -19,34 +19,32 @@ class QVariant; class QLabel; -namespace OCC -{ - -namespace WizardCommon -{ - -void setupCustomMedia( const QVariant& variant, QLabel *label ); -QString titleTemplate(); -QString subTitleTemplate(); -void initErrorLabel(QLabel* errorLabel); - -enum AuthType { - HttpCreds, - Shibboleth -}; - -enum SyncMode { - SelectiveMode, - BoxMode -}; - -enum Pages { - Page_ServerSetup, - Page_HttpCreds, - Page_ShibbolethCreds, - Page_AdvancedSetup, - Page_Result -}; +namespace OCC { + +namespace WizardCommon { + + void setupCustomMedia(const QVariant &variant, QLabel *label); + QString titleTemplate(); + QString subTitleTemplate(); + void initErrorLabel(QLabel *errorLabel); + + enum AuthType { + HttpCreds, + Shibboleth + }; + + enum SyncMode { + SelectiveMode, + BoxMode + }; + + enum Pages { + Page_ServerSetup, + Page_HttpCreds, + Page_ShibbolethCreds, + Page_AdvancedSetup, + Page_Result + }; } // ns WizardCommon diff --git a/src/gui/wizard/owncloudwizardresultpage.cpp b/src/gui/wizard/owncloudwizardresultpage.cpp index 891417387..4610b409d 100644 --- a/src/gui/wizard/owncloudwizardresultpage.cpp +++ b/src/gui/wizard/owncloudwizardresultpage.cpp @@ -21,22 +21,21 @@ #include "wizard/owncloudwizardcommon.h" #include "theme.h" -namespace OCC -{ +namespace OCC { OwncloudWizardResultPage::OwncloudWizardResultPage() - : QWizardPage(), - _localFolder(), - _remoteFolder(), - _complete(false), - _ui() + : QWizardPage() + , _localFolder() + , _remoteFolder() + , _complete(false) + , _ui() { _ui.setupUi(this); // no fields to register. setTitle(WizardCommon::subTitleTemplate().arg(tr("Everything set up!"))); // required to show header in QWizard's modern style - setSubTitle( QLatin1String(" ") ); + setSubTitle(QLatin1String(" ")); _ui.pbOpenLocal->setText(tr("Open Local Folder")); _ui.pbOpenLocal->setIcon(QIcon(QLatin1String(":/client/resources/folder-sync.png"))); @@ -44,7 +43,7 @@ OwncloudWizardResultPage::OwncloudWizardResultPage() _ui.pbOpenLocal->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); connect(_ui.pbOpenLocal, SIGNAL(clicked()), SLOT(slotOpenLocal())); - Theme* theme = Theme::instance(); + Theme *theme = Theme::instance(); QIcon appIcon = theme->applicationIcon(); _ui.pbOpenServer->setText(tr("Open %1 in Browser").arg(theme->appNameGUI())); _ui.pbOpenServer->setIcon(appIcon.pixmap(48)); @@ -55,7 +54,8 @@ OwncloudWizardResultPage::OwncloudWizardResultPage() } OwncloudWizardResultPage::~OwncloudWizardResultPage() -{} +{ +} void OwncloudWizardResultPage::setComplete(bool complete) { @@ -70,7 +70,7 @@ bool OwncloudWizardResultPage::isComplete() const void OwncloudWizardResultPage::initializePage() { - _ui.localFolderLabel->setText( QString::null ); + _ui.localFolderLabel->setText(QString::null); } void OwncloudWizardResultPage::setRemoteFolder(const QString &remoteFolder) @@ -81,11 +81,11 @@ void OwncloudWizardResultPage::setRemoteFolder(const QString &remoteFolder) void OwncloudWizardResultPage::setupCustomization() { // set defaults for the customize labels. - _ui.topLabel->setText( QString::null ); + _ui.topLabel->setText(QString::null); _ui.topLabel->hide(); - QVariant variant = Theme::instance()->customMedia( Theme::oCSetupResultTop ); - WizardCommon::setupCustomMedia( variant, _ui.topLabel ); + QVariant variant = Theme::instance()->customMedia(Theme::oCSetupResultTop); + WizardCommon::setupCustomMedia(variant, _ui.topLabel); } void OwncloudWizardResultPage::slotOpenLocal() @@ -96,7 +96,7 @@ void OwncloudWizardResultPage::slotOpenLocal() void OwncloudWizardResultPage::slotOpenServer() { - Theme* theme = Theme::instance(); + Theme *theme = Theme::instance(); QUrl url = QUrl(field("OCUrl").toString() + theme->wizardUrlPostfix()); QDesktopServices::openUrl(url); } diff --git a/src/gui/wizard/owncloudwizardresultpage.h b/src/gui/wizard/owncloudwizardresultpage.h index 0e318b680..8d309f625 100644 --- a/src/gui/wizard/owncloudwizardresultpage.h +++ b/src/gui/wizard/owncloudwizardresultpage.h @@ -28,31 +28,31 @@ namespace OCC { */ class OwncloudWizardResultPage : public QWizardPage { - Q_OBJECT + Q_OBJECT public: - OwncloudWizardResultPage(); - ~OwncloudWizardResultPage(); + OwncloudWizardResultPage(); + ~OwncloudWizardResultPage(); - bool isComplete() const Q_DECL_OVERRIDE; - void initializePage() Q_DECL_OVERRIDE; - void setRemoteFolder( const QString& remoteFolder); + bool isComplete() const Q_DECL_OVERRIDE; + void initializePage() Q_DECL_OVERRIDE; + void setRemoteFolder(const QString &remoteFolder); public slots: - void setComplete(bool complete); + void setComplete(bool complete); protected slots: - void slotOpenLocal(); - void slotOpenServer(); + void slotOpenLocal(); + void slotOpenServer(); protected: - void setupCustomization(); + void setupCustomization(); private: - QString _localFolder; - QString _remoteFolder; - bool _complete; + QString _localFolder; + QString _remoteFolder; + bool _complete; - Ui_OwncloudWizardResultPage _ui; + Ui_OwncloudWizardResultPage _ui; }; } // namespace OCC diff --git a/src/gui/wizard/postfixlineedit.cpp b/src/gui/wizard/postfixlineedit.cpp index 5e4171c32..1cc44a248 100644 --- a/src/gui/wizard/postfixlineedit.cpp +++ b/src/gui/wizard/postfixlineedit.cpp @@ -23,7 +23,7 @@ const int horizontalMargin(4); const int verticalMargin(4); PostfixLineEdit::PostfixLineEdit(QWidget *parent) - : QLineEdit(parent) + : QLineEdit(parent) { } @@ -32,7 +32,7 @@ void PostfixLineEdit::setPostfix(const QString &postfix) _postfix = postfix; QFontMetricsF fm(font()); QMargins tm = textMargins(); - tm.setRight(tm.right()+fm.width(_postfix)+verticalMargin); + tm.setRight(tm.right() + fm.width(_postfix) + verticalMargin); setTextMargins(tm); } @@ -57,21 +57,20 @@ void PostfixLineEdit::setFullText(const QString &text) void PostfixLineEdit::paintEvent(QPaintEvent *pe) { - QLineEdit::paintEvent(pe); QPainter p(this); // p.setPen(palette().color(QPalette::Disabled, QPalette::Text)); QFontMetricsF fm(font()); - int start = rect().right()-fm.width(_postfix); + int start = rect().right() - fm.width(_postfix); QStyleOptionFrame panel; initStyleOption(&panel); QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this); - r.setTop(r.top()+horizontalMargin-1); + r.setTop(r.top() + horizontalMargin - 1); QRect postfixRect(r); - postfixRect.setLeft(start-verticalMargin); + postfixRect.setLeft(start - verticalMargin); p.drawText(postfixRect, _postfix); } diff --git a/src/gui/wizard/postfixlineedit.h b/src/gui/wizard/postfixlineedit.h index 2d0d29775..09855f373 100644 --- a/src/gui/wizard/postfixlineedit.h +++ b/src/gui/wizard/postfixlineedit.h @@ -34,7 +34,7 @@ public: PostfixLineEdit(QWidget *parent); /** @brief sets an optional postfix shown greyed out */ - void setPostfix(const QString& postfix); + void setPostfix(const QString &postfix); /** @brief retrives the postfix */ QString postfix() const; /** @brief retrieves combined text() and postfix() */ @@ -45,6 +45,7 @@ public: protected: void paintEvent(QPaintEvent *pe); + private: QString _postfix; }; diff --git a/src/libsync/abstractnetworkjob.cpp b/src/libsync/abstractnetworkjob.cpp index 5f6d7aa82..25fe28ce3 100644 --- a/src/libsync/abstractnetworkjob.cpp +++ b/src/libsync/abstractnetworkjob.cpp @@ -33,7 +33,7 @@ #include "creds/abstractcredentials.h" -Q_DECLARE_METATYPE(QTimer*) +Q_DECLARE_METATYPE(QTimer *) namespace OCC { @@ -106,21 +106,21 @@ void AbstractNetworkJob::setupConnections(QNetworkReply *reply) #if QT_VERSION >= QT_VERSION_CHECK(5, 1, 0) connect(reply, SIGNAL(encrypted()), SIGNAL(networkActivity())); #endif - connect(reply->manager(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), SIGNAL(networkActivity())); + connect(reply->manager(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)), SIGNAL(networkActivity())); connect(reply, SIGNAL(sslErrors(QList)), SIGNAL(networkActivity())); connect(reply, SIGNAL(metaDataChanged()), SIGNAL(networkActivity())); - connect(reply, SIGNAL(downloadProgress(qint64,qint64)), SIGNAL(networkActivity())); - connect(reply, SIGNAL(uploadProgress(qint64,qint64)), SIGNAL(networkActivity())); + connect(reply, SIGNAL(downloadProgress(qint64, qint64)), SIGNAL(networkActivity())); + connect(reply, SIGNAL(uploadProgress(qint64, qint64)), SIGNAL(networkActivity())); } -QNetworkReply* AbstractNetworkJob::addTimer(QNetworkReply *reply) +QNetworkReply *AbstractNetworkJob::addTimer(QNetworkReply *reply) { reply->setProperty("timer", QVariant::fromValue(&_timer)); return reply; } QNetworkReply *AbstractNetworkJob::sendRequest(const QByteArray &verb, const QUrl &url, - QNetworkRequest req, QIODevice *requestBody) + QNetworkRequest req, QIODevice *requestBody) { auto reply = _account->sendRequest(verb, url, req, requestBody); _requestBody = requestBody; @@ -133,12 +133,12 @@ QNetworkReply *AbstractNetworkJob::sendRequest(const QByteArray &verb, const QUr return reply; } -QUrl AbstractNetworkJob::makeAccountUrl(const QString& relativePath) const +QUrl AbstractNetworkJob::makeAccountUrl(const QString &relativePath) const { return Utility::concatUrlPath(_account->url(), relativePath); } -QUrl AbstractNetworkJob::makeDavUrl(const QString& relativePath) const +QUrl AbstractNetworkJob::makeDavUrl(const QString &relativePath) const { return Utility::concatUrlPath(_account->davUrl(), relativePath); } @@ -147,13 +147,13 @@ void AbstractNetworkJob::slotFinished() { _timer.stop(); - if( _reply->error() == QNetworkReply::SslHandshakeFailedError ) { + if (_reply->error() == QNetworkReply::SslHandshakeFailedError) { qCWarning(lcNetworkJob) << "SslHandshakeFailedError: " << errorString() << " : can be caused by a webserver wanting SSL client certificates"; } - if( _reply->error() != QNetworkReply::NoError ) { + if (_reply->error() != QNetworkReply::NoError) { qCWarning(lcNetworkJob) << _reply->error() << errorString() - << _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + << _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (_reply->error() == QNetworkReply::ProxyAuthenticationRequiredError) { qCWarning(lcNetworkJob) << _reply->rawHeader("Proxy-Authenticate"); } @@ -171,8 +171,7 @@ void AbstractNetworkJob::slotFinished() // ### some of the qWarnings here should be exported via displayErrors() so they // ### can be presented to the user if the job executor has a GUI QByteArray verb = requestVerb(*reply()); - if (requestedUrl.scheme() == QLatin1String("https") && - redirectUrl.scheme() == QLatin1String("http")) { + if (requestedUrl.scheme() == QLatin1String("https") && redirectUrl.scheme() == QLatin1String("http")) { qCWarning(lcNetworkJob) << this << "HTTPS->HTTP downgrade detected!"; } else if (requestedUrl == redirectUrl || _redirectCount >= maxRedirects()) { qCWarning(lcNetworkJob) << this << "Redirect loop detected!"; @@ -188,16 +187,16 @@ void AbstractNetworkJob::slotFinished() _requestBody->seek(0); } sendRequest( - verb, - redirectUrl, - reply()->request(), - _requestBody); + verb, + redirectUrl, + reply()->request(), + _requestBody); return; } } AbstractCredentials *creds = _account->credentials(); - if (!creds->stillValid(_reply) && ! _ignoreCredentialFailure) { + if (!creds->stillValid(_reply) && !_ignoreCredentialFailure) { _account->handleInvalidCredentials(); } @@ -226,7 +225,7 @@ QString AbstractNetworkJob::errorString() const } } -QString AbstractNetworkJob::errorStringParsingBody(QByteArray* body) +QString AbstractNetworkJob::errorStringParsingBody(QByteArray *body) { QString base = errorString(); if (base.isEmpty() || !reply()) { @@ -257,7 +256,7 @@ void AbstractNetworkJob::start() _timer.start(); const QUrl url = account()->url(); - const QString displayUrl = QString( "%1://%2%3").arg(url.scheme()).arg(url.host()).arg(url.path()); + const QString displayUrl = QString("%1://%2%3").arg(url.scheme()).arg(url.host()).arg(url.path()); QString parentMetaObjectName = parent() ? parent()->metaObject()->className() : ""; qCInfo(lcNetworkJob) << metaObject()->className() << "created for" << displayUrl << "+" << path() << parentMetaObjectName; @@ -282,20 +281,20 @@ void AbstractNetworkJob::onTimedOut() NetworkJobTimeoutPauser::NetworkJobTimeoutPauser(QNetworkReply *reply) { - _timer = reply->property("timer").value(); - if(!_timer.isNull()) { + _timer = reply->property("timer").value(); + if (!_timer.isNull()) { _timer->stop(); } } NetworkJobTimeoutPauser::~NetworkJobTimeoutPauser() { - if(!_timer.isNull()) { + if (!_timer.isNull()) { _timer->start(); } } -QString extractErrorMessage(const QByteArray& errorResponse) +QString extractErrorMessage(const QByteArray &errorResponse) { QXmlStreamReader reader(errorResponse); reader.readNextStartElement(); @@ -314,13 +313,12 @@ QString extractErrorMessage(const QByteArray& errorResponse) } else if (reader.name() == QLatin1String("exception")) { exception = reader.readElementText(); } - } // Fallback, if message could not be found return exception; } -QString errorMessage(const QString& baseError, const QByteArray& body) +QString errorMessage(const QString &baseError, const QByteArray &body) { QString msg = baseError; QString extra = extractErrorMessage(body); @@ -330,7 +328,7 @@ QString errorMessage(const QString& baseError, const QByteArray& body) return msg; } -QByteArray requestVerb(const QNetworkReply& reply) +QByteArray requestVerb(const QNetworkReply &reply) { switch (reply.operation()) { case QNetworkAccessManager::HeadOperation: @@ -351,7 +349,7 @@ QByteArray requestVerb(const QNetworkReply& reply) return QByteArray(); } -QString networkReplyErrorString(const QNetworkReply& reply) +QString networkReplyErrorString(const QNetworkReply &reply) { QString base = reply.errorString(); int httpStatus = reply.attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); @@ -362,14 +360,11 @@ QString networkReplyErrorString(const QNetworkReply& reply) return base; } - return AbstractNetworkJob::tr("Server replied \"%1 %2\" to \"%3 %4\"").arg( - QString::number(httpStatus), - httpReason, - requestVerb(reply), + return AbstractNetworkJob::tr("Server replied \"%1 %2\" to \"%3 %4\"").arg(QString::number(httpStatus), httpReason, requestVerb(reply), #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) - reply.request().url().toString() + reply.request().url().toString() #else - reply.request().url().toDisplayString() + reply.request().url().toDisplayString() #endif ); } diff --git a/src/libsync/abstractnetworkjob.h b/src/libsync/abstractnetworkjob.h index 73e77fec1..36a5113ff 100644 --- a/src/libsync/abstractnetworkjob.h +++ b/src/libsync/abstractnetworkjob.h @@ -35,10 +35,11 @@ class AbstractSslErrorHandler; * @brief The AbstractNetworkJob class * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT AbstractNetworkJob : public QObject { +class OWNCLOUDSYNC_EXPORT AbstractNetworkJob : public QObject +{ Q_OBJECT public: - explicit AbstractNetworkJob(AccountPtr account, const QString &path, QObject* parent = 0); + explicit AbstractNetworkJob(AccountPtr account, const QString &path, QObject *parent = 0); virtual ~AbstractNetworkJob(); virtual void start(); @@ -49,7 +50,7 @@ public: QString path() const { return _path; } void setReply(QNetworkReply *reply); - QNetworkReply* reply() const { return _reply; } + QNetworkReply *reply() const { return _reply; } void setIgnoreCredentialFailure(bool ignore); bool ignoreCredentialFailure() const { return _ignoreCredentialFailure; } @@ -84,7 +85,7 @@ public: * * Warning: Needs to call reply()->readAll(). */ - QString errorStringParsingBody(QByteArray* body = 0); + QString errorStringParsingBody(QByteArray *body = 0); public slots: void setTimeout(qint64 msec); @@ -96,6 +97,7 @@ signals: */ void networkError(QNetworkReply *reply); void networkActivity(); + protected: void setupConnections(QNetworkReply *reply); @@ -105,22 +107,22 @@ protected: * * Takes ownership of the requestBody (to allow redirects). */ - QNetworkReply* sendRequest(const QByteArray& verb, const QUrl &url, - QNetworkRequest req = QNetworkRequest(), - QIODevice *requestBody = 0); + QNetworkReply *sendRequest(const QByteArray &verb, const QUrl &url, + QNetworkRequest req = QNetworkRequest(), + QIODevice *requestBody = 0); // sendRequest does not take a relative path instead of an url, // but the old API allowed that. We have this undefined overload // to help catch usage errors - QNetworkReply* sendRequest(const QByteArray& verb, const QString &relativePath, - QNetworkRequest req = QNetworkRequest(), - QIODevice *requestBody = 0); + QNetworkReply *sendRequest(const QByteArray &verb, const QString &relativePath, + QNetworkRequest req = QNetworkRequest(), + QIODevice *requestBody = 0); /// Creates a url for the account from a relative path - QUrl makeAccountUrl(const QString& relativePath) const; + QUrl makeAccountUrl(const QString &relativePath) const; /// Like makeAccountUrl() but uses the account's dav base path - QUrl makeDavUrl(const QString& relativePath) const; + QUrl makeDavUrl(const QString &relativePath) const; int maxRedirects() const { return 10; } @@ -136,12 +138,12 @@ protected: */ virtual void onTimedOut(); - QByteArray _responseTimestamp; - bool _timedout; // set to true when the timeout slot is received + QByteArray _responseTimestamp; + bool _timedout; // set to true when the timeout slot is received // Automatically follows redirects. Note that this only works for // GET requests that don't set up any HTTP body or other flags. - bool _followRedirects; + bool _followRedirects; private slots: void slotFinished(); @@ -151,7 +153,7 @@ protected: AccountPtr _account; private: - QNetworkReply* addTimer(QNetworkReply *reply); + QNetworkReply *addTimer(QNetworkReply *reply); bool _ignoreCredentialFailure; QPointer _reply; // (QPointer because the NetworkManager may be destroyed before the jobs at exit) QString _path; @@ -168,10 +170,12 @@ private: /** * @brief Internal Helper class */ -class NetworkJobTimeoutPauser { +class NetworkJobTimeoutPauser +{ public: NetworkJobTimeoutPauser(QNetworkReply *reply); ~NetworkJobTimeoutPauser(); + private: QPointer _timer; }; @@ -184,16 +188,16 @@ private: * * Returns a null string if no message was found. */ -QString OWNCLOUDSYNC_EXPORT extractErrorMessage(const QByteArray& errorResponse); +QString OWNCLOUDSYNC_EXPORT extractErrorMessage(const QByteArray &errorResponse); /** Builds a error message based on the error and the reply body. */ -QString OWNCLOUDSYNC_EXPORT errorMessage(const QString& baseError, const QByteArray& body); +QString OWNCLOUDSYNC_EXPORT errorMessage(const QString &baseError, const QByteArray &body); /** Helper to construct the HTTP verb used in the request * * Returns an empty QByteArray for UnknownOperation. */ -QByteArray OWNCLOUDSYNC_EXPORT requestVerb(const QNetworkReply& reply); +QByteArray OWNCLOUDSYNC_EXPORT requestVerb(const QNetworkReply &reply); /** Nicer errorString() for QNetworkReply * @@ -204,8 +208,6 @@ QByteArray OWNCLOUDSYNC_EXPORT requestVerb(const QNetworkReply& reply); * * This function produces clearer error messages for HTTP errors. */ -QString OWNCLOUDSYNC_EXPORT networkReplyErrorString(const QNetworkReply& reply); +QString OWNCLOUDSYNC_EXPORT networkReplyErrorString(const QNetworkReply &reply); } // namespace OCC - - diff --git a/src/libsync/accessmanager.cpp b/src/libsync/accessmanager.cpp index 62e403808..1d8e91d4c 100644 --- a/src/libsync/accessmanager.cpp +++ b/src/libsync/accessmanager.cpp @@ -26,13 +26,12 @@ #include "accessmanager.h" #include "utility.h" -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcAccessManager, "sync.accessmanager", QtInfoMsg) -AccessManager::AccessManager(QObject* parent) - : QNetworkAccessManager (parent) +AccessManager::AccessManager(QObject *parent) + : QNetworkAccessManager(parent) { #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) && defined(Q_OS_MAC) // FIXME Workaround http://stackoverflow.com/a/15707366/2941 https://bugreports.qt-project.org/browse/QTBUG-30434 @@ -48,10 +47,10 @@ AccessManager::AccessManager(QObject* parent) setCookieJar(new CookieJar); } -void AccessManager::setRawCookie(const QByteArray &rawCookie, const QUrl &url) +void AccessManager::setRawCookie(const QByteArray &rawCookie, const QUrl &url) { QNetworkCookie cookie(rawCookie.left(rawCookie.indexOf('=')), - rawCookie.mid(rawCookie.indexOf('=')+1)); + rawCookie.mid(rawCookie.indexOf('=') + 1)); qCDebug(lcAccessManager) << cookie.name() << cookie.value(); QList cookieList; cookieList.append(cookie); @@ -60,7 +59,7 @@ void AccessManager::setRawCookie(const QByteArray &rawCookie, const QUrl &url) jar->setCookiesFromUrl(cookieList, url); } -QNetworkReply* AccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest& request, QIODevice* outgoingData) +QNetworkReply *AccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData) { QNetworkRequest newRequest(request); @@ -78,7 +77,7 @@ QNetworkReply* AccessManager::createRequest(QNetworkAccessManager::Operation op, // For PROPFIND (assumed to be a WebDAV op), set xml/utf8 as content type/encoding // This needs extension if (verb == "PROPFIND") { - newRequest.setHeader( QNetworkRequest::ContentTypeHeader, QLatin1String("text/xml; charset=utf-8")); + newRequest.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("text/xml; charset=utf-8")); } return QNetworkAccessManager::createRequest(op, newRequest, outgoingData); } diff --git a/src/libsync/accessmanager.h b/src/libsync/accessmanager.h index bbe28ab96..d38a13487 100644 --- a/src/libsync/accessmanager.h +++ b/src/libsync/accessmanager.h @@ -21,8 +21,7 @@ class QByteArray; class QUrl; -namespace OCC -{ +namespace OCC { /** * @brief The AccessManager class @@ -33,12 +32,12 @@ class OWNCLOUDSYNC_EXPORT AccessManager : public QNetworkAccessManager Q_OBJECT public: - AccessManager(QObject* parent = 0); + AccessManager(QObject *parent = 0); - void setRawCookie(const QByteArray &rawCookie, const QUrl &url); + void setRawCookie(const QByteArray &rawCookie, const QUrl &url); protected: - QNetworkReply* createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) Q_DECL_OVERRIDE; + QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0) Q_DECL_OVERRIDE; }; } // namespace OCC diff --git a/src/libsync/account.cpp b/src/libsync/account.cpp index 7e183ecb6..39d15f971 100644 --- a/src/libsync/account.cpp +++ b/src/libsync/account.cpp @@ -40,7 +40,7 @@ Q_LOGGING_CATEGORY(lcAccount, "sync.account", QtInfoMsg) Account::Account(QObject *parent) : QObject(parent) , _capabilities(QVariantMap()) - , _davPath( Theme::instance()->webDavPath() ) + , _davPath(Theme::instance()->webDavPath()) { qRegisterMetaType("AccountPtr"); } @@ -64,7 +64,7 @@ QString Account::davPath() const } // make sure to have a trailing slash - if( !_davPath.endsWith('/') ) { + if (!_davPath.endsWith('/')) { QString dp(_davPath); dp.append('/'); return dp; @@ -145,14 +145,14 @@ void Account::setCredentials(AbstractCredentials *cred) if (jar) { _am->setCookieJar(jar); } - connect(_am.data(), SIGNAL(sslErrors(QNetworkReply*,QList)), - SLOT(slotHandleSslErrors(QNetworkReply*,QList))); - connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), - SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); + connect(_am.data(), SIGNAL(sslErrors(QNetworkReply *, QList)), + SLOT(slotHandleSslErrors(QNetworkReply *, QList))); + connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)), + SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *))); connect(_credentials.data(), SIGNAL(fetched()), - SLOT(slotCredentialsFetched())); + SLOT(slotCredentialsFetched())); connect(_credentials.data(), SIGNAL(asked()), - SLOT(slotCredentialsAsked())); + SLOT(slotCredentialsAsked())); } QUrl Account::davUrl() const @@ -165,7 +165,7 @@ QUrl Account::davUrl() const */ void Account::clearCookieJar() { - auto jar = qobject_cast(_am->cookieJar()); + auto jar = qobject_cast(_am->cookieJar()); ASSERT(jar); jar->setAllCookies(QList()); emit wantsAccountSaved(this); @@ -195,17 +195,17 @@ void Account::resetNetworkAccessManager() } qCDebug(lcAccount) << "Resetting QNAM"; - QNetworkCookieJar* jar = _am->cookieJar(); + QNetworkCookieJar *jar = _am->cookieJar(); // Use a QSharedPointer to allow locking the life of the QNAM on the stack. // Make it call deleteLater to make sure that we can return to any QNAM stack frames safely. _am = QSharedPointer(_credentials->getQNAM(), &QObject::deleteLater); _am->setCookieJar(jar); // takes ownership of the old cookie jar - connect(_am.data(), SIGNAL(sslErrors(QNetworkReply*,QList)), - SLOT(slotHandleSslErrors(QNetworkReply*,QList))); - connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), - SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); + connect(_am.data(), SIGNAL(sslErrors(QNetworkReply *, QList)), + SLOT(slotHandleSslErrors(QNetworkReply *, QList))); + connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)), + SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *))); } QNetworkAccessManager *Account::networkAccessManager() @@ -292,7 +292,7 @@ QVariant Account::credentialSetting(const QString &key) const { if (_credentials) { QString prefix = _credentials->authType(); - QString value = _settingsMap.value(prefix+"_"+key).toString(); + QString value = _settingsMap.value(prefix + "_" + key).toString(); if (value.isEmpty()) { value = _settingsMap.value(key).toString(); } @@ -305,18 +305,19 @@ void Account::setCredentialSetting(const QString &key, const QVariant &value) { if (_credentials) { QString prefix = _credentials->authType(); - _settingsMap.insert(prefix+"_"+key, value); + _settingsMap.insert(prefix + "_" + key, value); } } -void Account::slotHandleSslErrors(QNetworkReply *reply , QList errors) +void Account::slotHandleSslErrors(QNetworkReply *reply, QList errors) { NetworkJobTimeoutPauser pauser(reply); QString out; QDebug(&out) << "SSL-Errors happened for url " << reply->url().toString(); - foreach(const QSslError &error, errors) { + foreach (const QSslError &error, errors) { QDebug(&out) << "\tError in " << error.certificate() << ":" - << error.errorString() << "("<< error.error() << ")" << "\n"; + << error.errorString() << "(" << error.error() << ")" + << "\n"; } bool allPreviouslyRejected = true; @@ -327,13 +328,13 @@ void Account::slotHandleSslErrors(QNetworkReply *reply , QList errors } // If all certs have previously been rejected by the user, don't ask again. - if( allPreviouslyRejected ) { + if (allPreviouslyRejected) { qCInfo(lcAccount) << out << "Certs not trusted by user decision, returning."; return; } QList approvedCerts; - if (_sslErrorHandler.isNull() ) { + if (_sslErrorHandler.isNull()) { qCWarning(lcAccount) << out << "called without valid SSL error handler for account" << url(); return; } @@ -346,7 +347,8 @@ void Account::slotHandleSslErrors(QNetworkReply *reply , QList errors QPointer guard = reply; if (_sslErrorHandler->handleErrors(errors, reply->sslConfiguration(), &approvedCerts, sharedFromThis())) { - if (!guard) return; + if (!guard) + return; QSslSocket::addDefaultCaCertificates(approvedCerts); addApprovedCerts(approvedCerts); @@ -359,7 +361,8 @@ void Account::slotHandleSslErrors(QNetworkReply *reply , QList errors // certificate changes. reply->ignoreSslErrors(errors); } else { - if (!guard) return; + if (!guard) + return; // Mark all involved certificates as rejected, so we don't ask the user again. foreach (const QSslError &error, errors) { @@ -408,8 +411,8 @@ int Account::serverVersionInt() const // FIXME: Use Qt 5.5 QVersionNumber auto components = serverVersion().split('.'); return makeServerVersion(components.value(0).toInt(), - components.value(1).toInt(), - components.value(2).toInt()); + components.value(1).toInt(), + components.value(2).toInt()); } int Account::makeServerVersion(int majorVersion, int minorVersion, int patchVersion) @@ -426,7 +429,7 @@ bool Account::serverVersionUnsupported() const return serverVersionInt() < makeServerVersion(7, 0, 0); } -void Account::setServerVersion(const QString& version) +void Account::setServerVersion(const QString &version) { if (version == _serverVersion) { return; @@ -444,7 +447,7 @@ bool Account::rootEtagChangesNotOnlySubFolderEtags() void Account::setNonShib(bool nonShib) { - if( nonShib ) { + if (nonShib) { _davPath = Theme::instance()->webDavPathNonShib(); } else { _davPath = Theme::instance()->webDavPath(); @@ -452,5 +455,4 @@ void Account::setNonShib(bool nonShib) } - } // namespace OCC diff --git a/src/libsync/account.h b/src/libsync/account.h index 829439bf9..4e554e590 100644 --- a/src/libsync/account.h +++ b/src/libsync/account.h @@ -50,10 +50,11 @@ class AccessManager; * @brief Reimplement this to handle SSL errors from libsync * @ingroup libsync */ -class AbstractSslErrorHandler { +class AbstractSslErrorHandler +{ public: virtual ~AbstractSslErrorHandler() {} - virtual bool handleErrors(QList, const QSslConfiguration &conf, QList*, AccountPtr) = 0; + virtual bool handleErrors(QList, const QSslConfiguration &conf, QList *, AccountPtr) = 0; }; /** @@ -63,7 +64,8 @@ public: * The Account has a name and url. It also has information about credentials, * SSL errors and certificates. */ -class OWNCLOUDSYNC_EXPORT Account : public QObject { +class OWNCLOUDSYNC_EXPORT Account : public QObject +{ Q_OBJECT public: static AccountPtr create(); @@ -81,7 +83,7 @@ public: void setDavUser(const QString &newDavUser); QImage avatar() const; - void setAvatar(const QImage& img); + void setAvatar(const QImage &img); /// The name of the account as shown in the toolbar QString displayName() const; @@ -99,22 +101,22 @@ public: * @returns the (themeable) dav path for the account. */ QString davPath() const; - void setDavPath(const QString&s) { _davPath = s; } + void setDavPath(const QString &s) { _davPath = s; } void setNonShib(bool nonShib); /** Returns webdav entry URL, based on url() */ QUrl davUrl() const; /** Holds the accounts credentials */ - AbstractCredentials* credentials() const; + AbstractCredentials *credentials() const; void setCredentials(AbstractCredentials *cred); // For creating various network requests - QNetworkReply* sendRequest(const QByteArray &verb, - const QUrl &url, - QNetworkRequest req = QNetworkRequest(), - QIODevice *data = 0); + QNetworkReply *sendRequest(const QByteArray &verb, + const QUrl &url, + QNetworkRequest req = QNetworkRequest(), + QIODevice *data = 0); /** The ssl configuration during the first connection */ QSslConfiguration getOrCreateSslConfig(); @@ -140,8 +142,8 @@ public: void setSslErrorHandler(AbstractSslErrorHandler *handler); // To be called by credentials only, for storing username and the like - QVariant credentialSetting(const QString& key) const; - void setCredentialSetting(const QString& key, const QVariant &value); + QVariant credentialSetting(const QString &key) const; + void setCredentialSetting(const QString &key, const QVariant &value); /** Assign a client certificate */ void setCertificate(const QByteArray certficate = QByteArray(), const QString privateKey = QString()); @@ -189,7 +191,7 @@ public: QString cookieJarPath(); void resetNetworkAccessManager(); - QNetworkAccessManager* networkAccessManager(); + QNetworkAccessManager *networkAccessManager(); QSharedPointer sharedNetworkAccessManager(); /// Called by network jobs on credential errors, emits invalidCredentials() @@ -202,21 +204,21 @@ signals: /// Triggered by handleInvalidCredentials() void invalidCredentials(); - void credentialsFetched(AbstractCredentials* credentials); - void credentialsAsked(AbstractCredentials* credentials); + void credentialsFetched(AbstractCredentials *credentials); + void credentialsAsked(AbstractCredentials *credentials); /// Forwards from QNetworkAccessManager::proxyAuthenticationRequired(). - void proxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*); + void proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *); // e.g. when the approved SSL certificates changed - void wantsAccountSaved(Account* acc); + void wantsAccountSaved(Account *acc); - void serverVersionChanged(Account* account, const QString& newVersion, const QString& oldVersion); + void serverVersionChanged(Account *account, const QString &newVersion, const QString &oldVersion); void accountChangedAvatar(); protected Q_SLOTS: - void slotHandleSslErrors(QNetworkReply*,QList); + void slotHandleSslErrors(QNetworkReply *, QList); void slotCredentialsFetched(); void slotCredentialsAsked(); @@ -247,7 +249,6 @@ private: QString _davPath; // defaults to value from theme, might be overwritten in brandings friend class AccountManager; }; - } Q_DECLARE_METATYPE(OCC::AccountPtr) diff --git a/src/libsync/asserts.h b/src/libsync/asserts.h index 5e02cf730..e96e57bb9 100644 --- a/src/libsync/asserts.h +++ b/src/libsync/asserts.h @@ -11,38 +11,43 @@ // For overloading macros by argument count // See stackoverflow.com/questions/16683146/can-macros-be-overloaded-by-number-of-arguments -#define OC_ASSERT_CAT(A, B) A ## B -#define OC_ASSERT_SELECT(NAME, NUM) OC_ASSERT_CAT(NAME ## _, NUM) +#define OC_ASSERT_CAT(A, B) A##B +#define OC_ASSERT_SELECT(NAME, NUM) OC_ASSERT_CAT(NAME##_, NUM) #define OC_ASSERT_GET_COUNT(_1, _2, _3, COUNT, ...) COUNT #define OC_ASSERT_VA_SIZE(...) OC_ASSERT_GET_COUNT(__VA_ARGS__, 3, 2, 1, 0) -#define OC_ASSERT_OVERLOAD(NAME, ...) OC_ASSERT_SELECT(NAME, OC_ASSERT_VA_SIZE(__VA_ARGS__))(__VA_ARGS__) +#define OC_ASSERT_OVERLOAD(NAME, ...) OC_ASSERT_SELECT(NAME, OC_ASSERT_VA_SIZE(__VA_ARGS__)) \ + (__VA_ARGS__) // Default assert: If the condition is false in debug builds, terminate. // // Prints a message on failure, even in release builds. #define ASSERT(...) OC_ASSERT_OVERLOAD(ASSERT, __VA_ARGS__) -#define ASSERT_1(cond) \ - if (!(cond)) { \ +#define ASSERT_1(cond) \ + if (!(cond)) { \ OC_ASSERT_MSG("ASSERT: \"%s\" in file %s, line %d", #cond, __FILE__, __LINE__); \ - } else {} -#define ASSERT_2(cond, message) \ - if (!(cond)) { \ + } else { \ + } +#define ASSERT_2(cond, message) \ + if (!(cond)) { \ OC_ASSERT_MSG("ASSERT: \"%s\" in file %s, line %d with message: %s", #cond, __FILE__, __LINE__, message); \ - } else {} + } else { \ + } // Enforce condition to be true, even in release builds. // // Prints 'message' and aborts execution if 'cond' is false. #define ENFORCE(...) OC_ASSERT_OVERLOAD(ENFORCE, __VA_ARGS__) -#define ENFORCE_1(cond) \ - if (!(cond)) { \ +#define ENFORCE_1(cond) \ + if (!(cond)) { \ qFatal("ENFORCE: \"%s\" in file %s, line %d", #cond, __FILE__, __LINE__); \ - } else {} -#define ENFORCE_2(cond, message) \ - if (!(cond)) { \ + } else { \ + } +#define ENFORCE_2(cond, message) \ + if (!(cond)) { \ qFatal("ENFORCE: \"%s\" in file %s, line %d with message: %s", #cond, __FILE__, __LINE__, message); \ - } else {} + } else { \ + } // An assert that is only present in debug builds: typically used for // asserts that are too expensive for release mode. diff --git a/src/libsync/bandwidthmanager.cpp b/src/libsync/bandwidthmanager.cpp index 6e65d0b44..2cd8d70a6 100644 --- a/src/libsync/bandwidthmanager.cpp +++ b/src/libsync/bandwidthmanager.cpp @@ -34,7 +34,7 @@ Q_LOGGING_CATEGORY(lcBandwidthManager, "sync.bandwidthmanager", QtInfoMsg) // Because of the many layers of buffering inside Qt (and probably the OS and the network) // we cannot lower this value much more. If we do, the estimated bw will be very high // because the buffers fill fast while the actual network algorithms are not relevant yet. -static qint64 relativeLimitMeasuringTimerIntervalMsec = 1000*2; +static qint64 relativeLimitMeasuringTimerIntervalMsec = 1000 * 2; // See also WritingState in http://code.woboq.org/qt5/qtbase/src/network/access/qhttpprotocolhandler.cpp.html#_ZN20QHttpProtocolHandler11sendRequestEv // FIXME At some point: @@ -44,19 +44,20 @@ static qint64 relativeLimitMeasuringTimerIntervalMsec = 1000*2; // * For relative limiting, do less measuring and more delaying+giving quota // * For relative limiting, smoothen measurements -BandwidthManager::BandwidthManager(OwncloudPropagator *p) : QObject(), - _propagator(p), - _relativeLimitCurrentMeasuredDevice(0), - _relativeUploadLimitProgressAtMeasuringRestart(0), - _currentUploadLimit(0), - _relativeLimitCurrentMeasuredJob(0), - _currentDownloadLimit(0) +BandwidthManager::BandwidthManager(OwncloudPropagator *p) + : QObject() + , _propagator(p) + , _relativeLimitCurrentMeasuredDevice(0) + , _relativeUploadLimitProgressAtMeasuringRestart(0) + , _currentUploadLimit(0) + , _relativeLimitCurrentMeasuredJob(0) + , _currentDownloadLimit(0) { _currentUploadLimit = _propagator->_uploadLimit.fetchAndAddAcquire(0); _currentDownloadLimit = _propagator->_downloadLimit.fetchAndAddAcquire(0); QObject::connect(&_switchingTimer, SIGNAL(timeout()), this, SLOT(switchingTimerExpired())); - _switchingTimer.setInterval(10*1000); + _switchingTimer.setInterval(10 * 1000); _switchingTimer.start(); QMetaObject::invokeMethod(this, "switchingTimerExpired", Qt::QueuedConnection); @@ -66,23 +67,23 @@ BandwidthManager::BandwidthManager(OwncloudPropagator *p) : QObject(), _absoluteLimitTimer.start(); // Relative uploads - QObject::connect(&_relativeUploadMeasuringTimer,SIGNAL(timeout()), - this, SLOT(relativeUploadMeasuringTimerExpired())); + QObject::connect(&_relativeUploadMeasuringTimer, SIGNAL(timeout()), + this, SLOT(relativeUploadMeasuringTimerExpired())); _relativeUploadMeasuringTimer.setInterval(relativeLimitMeasuringTimerIntervalMsec); _relativeUploadMeasuringTimer.start(); _relativeUploadMeasuringTimer.setSingleShot(true); // will be restarted from the delay timer QObject::connect(&_relativeUploadDelayTimer, SIGNAL(timeout()), - this, SLOT(relativeUploadDelayTimerExpired())); + this, SLOT(relativeUploadDelayTimerExpired())); _relativeUploadDelayTimer.setSingleShot(true); // will be restarted from the measuring timer // Relative downloads - QObject::connect(&_relativeDownloadMeasuringTimer,SIGNAL(timeout()), - this, SLOT(relativeDownloadMeasuringTimerExpired())); + QObject::connect(&_relativeDownloadMeasuringTimer, SIGNAL(timeout()), + this, SLOT(relativeDownloadMeasuringTimerExpired())); _relativeDownloadMeasuringTimer.setInterval(relativeLimitMeasuringTimerIntervalMsec); _relativeDownloadMeasuringTimer.start(); _relativeDownloadMeasuringTimer.setSingleShot(true); // will be restarted from the delay timer QObject::connect(&_relativeDownloadDelayTimer, SIGNAL(timeout()), - this, SLOT(relativeDownloadDelayTimerExpired())); + this, SLOT(relativeDownloadDelayTimerExpired())); _relativeDownloadDelayTimer.setSingleShot(true); // will be restarted from the measuring timer } @@ -94,7 +95,7 @@ void BandwidthManager::registerUploadDevice(UploadDevice *p) { _absoluteUploadDeviceList.append(p); _relativeUploadDeviceList.append(p); - QObject::connect(p, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterUploadDevice(QObject*))); + QObject::connect(p, SIGNAL(destroyed(QObject *)), this, SLOT(unregisterUploadDevice(QObject *))); if (usingAbsoluteUploadLimit()) { p->setBandwidthLimited(true); @@ -110,13 +111,13 @@ void BandwidthManager::registerUploadDevice(UploadDevice *p) void BandwidthManager::unregisterUploadDevice(QObject *o) { - UploadDevice *p = qobject_cast(o); + UploadDevice *p = qobject_cast(o); if (p) { unregisterUploadDevice(p); } } -void BandwidthManager::unregisterUploadDevice(UploadDevice* p) +void BandwidthManager::unregisterUploadDevice(UploadDevice *p) { _absoluteUploadDeviceList.removeAll(p); _relativeUploadDeviceList.removeAll(p); @@ -126,10 +127,10 @@ void BandwidthManager::unregisterUploadDevice(UploadDevice* p) } } -void BandwidthManager::registerDownloadJob(GETFileJob* j) +void BandwidthManager::registerDownloadJob(GETFileJob *j) { _downloadJobList.append(j); - QObject::connect(j, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterDownloadJob(QObject*))); + QObject::connect(j, SIGNAL(destroyed(QObject *)), this, SLOT(unregisterDownloadJob(QObject *))); if (usingAbsoluteDownloadLimit()) { j->setBandwidthLimited(true); @@ -143,7 +144,7 @@ void BandwidthManager::registerDownloadJob(GETFileJob* j) } } -void BandwidthManager::unregisterDownloadJob(GETFileJob* j) +void BandwidthManager::unregisterDownloadJob(GETFileJob *j) { _downloadJobList.removeAll(j); if (_relativeLimitCurrentMeasuredJob == j) { @@ -152,9 +153,9 @@ void BandwidthManager::unregisterDownloadJob(GETFileJob* j) } } -void BandwidthManager::unregisterDownloadJob(QObject* o) +void BandwidthManager::unregisterDownloadJob(QObject *o) { - GETFileJob *p = qobject_cast(o); + GETFileJob *p = qobject_cast(o); if (p) { unregisterDownloadJob(p); } @@ -175,19 +176,21 @@ void BandwidthManager::relativeUploadMeasuringTimerExpired() return; } - qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting Delay"; + qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting Delay"; qint64 relativeLimitProgressMeasured = (_relativeLimitCurrentMeasuredDevice->_readWithProgress - + _relativeLimitCurrentMeasuredDevice->_read) / 2; + + _relativeLimitCurrentMeasuredDevice->_read) + / 2; qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeUploadLimitProgressAtMeasuringRestart; qCDebug(lcBandwidthManager) << _relativeUploadLimitProgressAtMeasuringRestart - << relativeLimitProgressMeasured << relativeLimitProgressDifference; + << relativeLimitProgressMeasured << relativeLimitProgressDifference; - qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0; - qCDebug(lcBandwidthManager) << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed (" - << _relativeLimitCurrentMeasuredDevice->_readWithProgress << _relativeLimitCurrentMeasuredDevice->_read - << qAbs(_relativeLimitCurrentMeasuredDevice->_readWithProgress - - _relativeLimitCurrentMeasuredDevice->_read) << ")"; + qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec * 1000.0) / 1024.0; + qCDebug(lcBandwidthManager) << relativeLimitProgressDifference / 1024 << "kB =>" << speedkBPerSec << "kB/sec on full speed (" + << _relativeLimitCurrentMeasuredDevice->_readWithProgress << _relativeLimitCurrentMeasuredDevice->_read + << qAbs(_relativeLimitCurrentMeasuredDevice->_readWithProgress + - _relativeLimitCurrentMeasuredDevice->_read) + << ")"; qint64 uploadLimitPercent = -_currentUploadLimit; // don't use too extreme values @@ -196,8 +199,7 @@ void BandwidthManager::relativeUploadMeasuringTimerExpired() qint64 wholeTimeMsec = (100.0 / uploadLimitPercent) * relativeLimitMeasuringTimerIntervalMsec; qint64 waitTimeMsec = wholeTimeMsec - relativeLimitMeasuringTimerIntervalMsec; qint64 realWaitTimeMsec = waitTimeMsec + wholeTimeMsec; - qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec << - " msec for " << uploadLimitPercent << "%"; + qCDebug(lcBandwidthManager) << waitTimeMsec << " - " << realWaitTimeMsec << " msec for " << uploadLimitPercent << "%"; // We want to wait twice as long since we want to give all // devices the same quota we used now since we don't want @@ -207,11 +209,11 @@ void BandwidthManager::relativeUploadMeasuringTimerExpired() int deviceCount = _relativeUploadDeviceList.count(); qint64 quotaPerDevice = relativeLimitProgressDifference * (uploadLimitPercent / 100.0) / deviceCount + 1.0; - Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) { + Q_FOREACH (UploadDevice *ud, _relativeUploadDeviceList) { ud->setBandwidthLimited(true); ud->setChoked(false); ud->giveBandwidthQuota(quotaPerDevice); - qCDebug(lcBandwidthManager) << "Gave" << quotaPerDevice/1024.0 << "kB to" << ud; + qCDebug(lcBandwidthManager) << "Gave" << quotaPerDevice / 1024.0 << "kB to" << ud; } _relativeLimitCurrentMeasuredDevice = 0; } @@ -236,12 +238,13 @@ void BandwidthManager::relativeUploadDelayTimerExpired() _relativeUploadDeviceList.append(_relativeLimitCurrentMeasuredDevice); _relativeUploadLimitProgressAtMeasuringRestart = (_relativeLimitCurrentMeasuredDevice->_readWithProgress - + _relativeLimitCurrentMeasuredDevice->_read) / 2; + + _relativeLimitCurrentMeasuredDevice->_read) + / 2; _relativeLimitCurrentMeasuredDevice->setBandwidthLimited(false); _relativeLimitCurrentMeasuredDevice->setChoked(false); // choke all other UploadDevices - Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) { + Q_FOREACH (UploadDevice *ud, _relativeUploadDeviceList) { if (ud != _relativeLimitCurrentMeasuredDevice) { ud->setBandwidthLimited(true); ud->setChoked(true); @@ -272,11 +275,11 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired() qint64 relativeLimitProgressMeasured = _relativeLimitCurrentMeasuredJob->currentDownloadPosition(); qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeDownloadLimitProgressAtMeasuringRestart; qCDebug(lcBandwidthManager) << _relativeDownloadLimitProgressAtMeasuringRestart - << relativeLimitProgressMeasured << relativeLimitProgressDifference; + << relativeLimitProgressMeasured << relativeLimitProgressDifference; - qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0; - qCDebug(lcBandwidthManager) << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed (" - << _relativeLimitCurrentMeasuredJob->currentDownloadPosition() ; + qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec * 1000.0) / 1024.0; + qCDebug(lcBandwidthManager) << relativeLimitProgressDifference / 1024 << "kB =>" << speedkBPerSec << "kB/sec on full speed (" + << _relativeLimitCurrentMeasuredJob->currentDownloadPosition(); qint64 downloadLimitPercent = -_currentDownloadLimit; // don't use too extreme values @@ -285,8 +288,7 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired() qint64 wholeTimeMsec = (100.0 / downloadLimitPercent) * relativeLimitMeasuringTimerIntervalMsec; qint64 waitTimeMsec = wholeTimeMsec - relativeLimitMeasuringTimerIntervalMsec; qint64 realWaitTimeMsec = waitTimeMsec + wholeTimeMsec; - qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec << - " msec for " << downloadLimitPercent << "%"; + qCDebug(lcBandwidthManager) << waitTimeMsec << " - " << realWaitTimeMsec << " msec for " << downloadLimitPercent << "%"; // We want to wait twice as long since we want to give all // devices the same quota we used now since we don't want @@ -296,16 +298,16 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired() int jobCount = _downloadJobList.count(); qint64 quota = relativeLimitProgressDifference * (downloadLimitPercent / 100.0); - if (quota > 20*1024) { - qCInfo(lcBandwidthManager) << "ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20*1024; - quota -= 20*1024; + if (quota > 20 * 1024) { + qCInfo(lcBandwidthManager) << "ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20 * 1024; + quota -= 20 * 1024; } qint64 quotaPerJob = quota / jobCount + 1.0; - Q_FOREACH(GETFileJob *gfj, _downloadJobList) { + Q_FOREACH (GETFileJob *gfj, _downloadJobList) { gfj->setBandwidthLimited(true); gfj->setChoked(false); gfj->giveBandwidthQuota(quotaPerJob); - qCDebug(lcBandwidthManager) << "Gave" << quotaPerJob/1024.0 << "kB to" << gfj; + qCDebug(lcBandwidthManager) << "Gave" << quotaPerJob / 1024.0 << "kB to" << gfj; } _relativeLimitCurrentMeasuredDevice = 0; } @@ -335,7 +337,7 @@ void BandwidthManager::relativeDownloadDelayTimerExpired() _relativeLimitCurrentMeasuredJob->setChoked(false); // choke all other download jobs - Q_FOREACH(GETFileJob *gfj, _downloadJobList) { + Q_FOREACH (GETFileJob *gfj, _downloadJobList) { if (gfj != _relativeLimitCurrentMeasuredJob) { gfj->setBandwidthLimited(true); gfj->setChoked(true); @@ -347,12 +349,13 @@ void BandwidthManager::relativeDownloadDelayTimerExpired() // end downloads -void BandwidthManager::switchingTimerExpired() { +void BandwidthManager::switchingTimerExpired() +{ qint64 newUploadLimit = _propagator->_uploadLimit.fetchAndAddAcquire(0); if (newUploadLimit != _currentUploadLimit) { qCInfo(lcBandwidthManager) << "Upload Bandwidth limit changed" << _currentUploadLimit << newUploadLimit; _currentUploadLimit = newUploadLimit; - Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) { + Q_FOREACH (UploadDevice *ud, _relativeUploadDeviceList) { if (newUploadLimit == 0) { ud->setBandwidthLimited(false); ud->setChoked(false); @@ -369,7 +372,7 @@ void BandwidthManager::switchingTimerExpired() { if (newDownloadLimit != _currentDownloadLimit) { qCInfo(lcBandwidthManager) << "Download Bandwidth limit changed" << _currentDownloadLimit << newDownloadLimit; _currentDownloadLimit = newDownloadLimit; - Q_FOREACH(GETFileJob *j, _downloadJobList) { + Q_FOREACH (GETFileJob *j, _downloadJobList) { if (usingAbsoluteDownloadLimit()) { j->setBandwidthLimited(true); j->setChoked(false); @@ -388,21 +391,19 @@ void BandwidthManager::absoluteLimitTimerExpired() { if (usingAbsoluteUploadLimit() && _absoluteUploadDeviceList.count() > 0) { qint64 quotaPerDevice = _currentUploadLimit / qMax(1, _absoluteUploadDeviceList.count()); - qCDebug(lcBandwidthManager) << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit; - Q_FOREACH(UploadDevice *device, _absoluteUploadDeviceList) { + qCDebug(lcBandwidthManager) << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit; + Q_FOREACH (UploadDevice *device, _absoluteUploadDeviceList) { device->giveBandwidthQuota(quotaPerDevice); - qCDebug(lcBandwidthManager) << "Gave " << quotaPerDevice/1024.0 << " kB to" << device; + qCDebug(lcBandwidthManager) << "Gave " << quotaPerDevice / 1024.0 << " kB to" << device; } } if (usingAbsoluteDownloadLimit() && _downloadJobList.count() > 0) { qint64 quotaPerJob = _currentDownloadLimit / qMax(1, _downloadJobList.count()); - qCDebug(lcBandwidthManager) << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit; - Q_FOREACH(GETFileJob *j, _downloadJobList) { + qCDebug(lcBandwidthManager) << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit; + Q_FOREACH (GETFileJob *j, _downloadJobList) { j->giveBandwidthQuota(quotaPerJob); - qCDebug(lcBandwidthManager) << "Gave " << quotaPerJob/1024.0 << " kB to" << j; + qCDebug(lcBandwidthManager) << "Gave " << quotaPerJob / 1024.0 << " kB to" << j; } } } - - } diff --git a/src/libsync/bandwidthmanager.h b/src/libsync/bandwidthmanager.h index a57ca073f..77a327287 100644 --- a/src/libsync/bandwidthmanager.h +++ b/src/libsync/bandwidthmanager.h @@ -30,7 +30,8 @@ class OwncloudPropagator; * @brief The BandwidthManager class * @ingroup libsync */ -class BandwidthManager : public QObject { +class BandwidthManager : public QObject +{ Q_OBJECT public: BandwidthManager(OwncloudPropagator *p); @@ -43,13 +44,13 @@ public: public slots: - void registerUploadDevice(UploadDevice*); - void unregisterUploadDevice(UploadDevice*); - void unregisterUploadDevice(QObject*); + void registerUploadDevice(UploadDevice *); + void unregisterUploadDevice(UploadDevice *); + void unregisterUploadDevice(QObject *); - void registerDownloadJob(GETFileJob*); - void unregisterDownloadJob(GETFileJob*); - void unregisterDownloadJob(QObject*); + void registerDownloadJob(GETFileJob *); + void unregisterDownloadJob(GETFileJob *); + void unregisterDownloadJob(QObject *); void absoluteLimitTimerExpired(); void switchingTimerExpired(); @@ -72,8 +73,8 @@ private: QTimer _absoluteLimitTimer; // FIXME merge these two lists - QLinkedList _absoluteUploadDeviceList; - QLinkedList _relativeUploadDeviceList; + QLinkedList _absoluteUploadDeviceList; + QLinkedList _relativeUploadDeviceList; QTimer _relativeUploadMeasuringTimer; @@ -87,7 +88,7 @@ private: qint64 _relativeUploadLimitProgressAtMeasuringRestart; qint64 _currentUploadLimit; - QLinkedList _downloadJobList; + QLinkedList _downloadJobList; QTimer _relativeDownloadMeasuringTimer; // for relative bw limiting, we need to wait this amount before measuring again @@ -101,7 +102,6 @@ private: qint64 _currentDownloadLimit; }; - } #endif diff --git a/src/libsync/capabilities.cpp b/src/libsync/capabilities.cpp index 95459051f..651b1981d 100644 --- a/src/libsync/capabilities.cpp +++ b/src/libsync/capabilities.cpp @@ -48,7 +48,7 @@ bool Capabilities::sharePublicLink() const bool Capabilities::sharePublicLinkAllowUpload() const { - return _capabilities["files_sharing"].toMap()["public"].toMap()["upload"].toBool(); + return _capabilities["files_sharing"].toMap()["public"].toMap()["upload"].toBool(); } bool Capabilities::sharePublicLinkEnforcePassword() const @@ -90,7 +90,7 @@ bool Capabilities::isValid() const QList Capabilities::supportedChecksumTypes() const { QList list; - foreach (const auto & t, _capabilities["checksums"].toMap()["supportedTypes"].toList()) { + foreach (const auto &t, _capabilities["checksums"].toMap()["supportedTypes"].toList()) { list.push_back(t.toByteArray()); } return list; @@ -115,8 +115,10 @@ QByteArray Capabilities::uploadChecksumType() const bool Capabilities::chunkingNg() const { static const auto chunkng = qgetenv("OWNCLOUD_CHUNKING_NG"); - if (chunkng == "0") return false; - if (chunkng == "1") return true; + if (chunkng == "0") + return false; + if (chunkng == "1") + return true; return _capabilities["dav"].toMap()["chunking"].toByteArray() >= "1.0"; } @@ -128,10 +130,9 @@ bool Capabilities::chunkingParallelUploadDisabled() const QList Capabilities::httpErrorCodesThatResetFailingChunkedUploads() const { QList list; - foreach (const auto & t, _capabilities["dav"].toMap()["httpErrorCodesThatResetFailingChunkedUploads"].toList()) { + foreach (const auto &t, _capabilities["dav"].toMap()["httpErrorCodesThatResetFailingChunkedUploads"].toList()) { list.push_back(t.toInt()); } return list; } - } diff --git a/src/libsync/capabilities.h b/src/libsync/capabilities.h index 56ef6f622..4044d8584 100644 --- a/src/libsync/capabilities.h +++ b/src/libsync/capabilities.h @@ -28,8 +28,8 @@ namespace OCC { * server * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT Capabilities { - +class OWNCLOUDSYNC_EXPORT Capabilities +{ public: Capabilities(const QVariantMap &capabilities); @@ -38,7 +38,7 @@ public: bool sharePublicLinkAllowUpload() const; bool sharePublicLinkEnforcePassword() const; bool sharePublicLinkEnforceExpireDate() const; - int sharePublicLinkExpireDateDays() const; + int sharePublicLinkExpireDateDays() const; bool sharePublicLinkMultiple() const; bool shareResharing() const; bool chunkingNg() const; @@ -104,7 +104,6 @@ public: private: QVariantMap _capabilities; }; - } #endif //CAPABILITIES_H diff --git a/src/libsync/checksums.cpp b/src/libsync/checksums.cpp index 4498b4b7b..00818442f 100644 --- a/src/libsync/checksums.cpp +++ b/src/libsync/checksums.cpp @@ -79,7 +79,7 @@ namespace OCC { Q_LOGGING_CATEGORY(lcChecksums, "sync.checksums", QtInfoMsg) -QByteArray makeChecksumHeader(const QByteArray& checksumType, const QByteArray& checksum) +QByteArray makeChecksumHeader(const QByteArray &checksumType, const QByteArray &checksum) { QByteArray header = checksumType; header.append(':'); @@ -87,7 +87,7 @@ QByteArray makeChecksumHeader(const QByteArray& checksumType, const QByteArray& return header; } -bool parseChecksumHeader(const QByteArray& header, QByteArray* type, QByteArray* checksum) +bool parseChecksumHeader(const QByteArray &header, QByteArray *type, QByteArray *checksum) { if (header.isEmpty()) { type->clear(); @@ -120,12 +120,12 @@ QByteArray contentChecksumType() return type; } -ComputeChecksum::ComputeChecksum(QObject* parent) +ComputeChecksum::ComputeChecksum(QObject *parent) : QObject(parent) { } -void ComputeChecksum::setChecksumType(const QByteArray& type) +void ComputeChecksum::setChecksumType(const QByteArray &type) { _checksumType = type; } @@ -135,29 +135,29 @@ QByteArray ComputeChecksum::checksumType() const return _checksumType; } -void ComputeChecksum::start(const QString& filePath) +void ComputeChecksum::start(const QString &filePath) { // Calculate the checksum in a different thread first. - connect( &_watcher, SIGNAL(finished()), - this, SLOT(slotCalculationDone()), - Qt::UniqueConnection ); + connect(&_watcher, SIGNAL(finished()), + this, SLOT(slotCalculationDone()), + Qt::UniqueConnection); _watcher.setFuture(QtConcurrent::run(ComputeChecksum::computeNow, filePath, checksumType())); } -QByteArray ComputeChecksum::computeNow(const QString& filePath, const QByteArray& checksumType) +QByteArray ComputeChecksum::computeNow(const QString &filePath, const QByteArray &checksumType) { - if( checksumType == checkSumMD5C ) { + if (checksumType == checkSumMD5C) { return FileSystem::calcMd5(filePath); - } else if( checksumType == checkSumSHA1C ) { + } else if (checksumType == checkSumSHA1C) { return FileSystem::calcSha1(filePath); } #ifdef ZLIB_FOUND - else if( checksumType == checkSumAdlerC) { + else if (checksumType == checkSumAdlerC) { return FileSystem::calcAdler32(filePath); } #endif // for an unknown checksum or no checksum, we're done right now - if( !checksumType.isEmpty() ) { + if (!checksumType.isEmpty()) { qCWarning(lcChecksums) << "Unknown checksum type:" << checksumType; } return QByteArray(); @@ -179,15 +179,15 @@ ValidateChecksumHeader::ValidateChecksumHeader(QObject *parent) { } -void ValidateChecksumHeader::start(const QString& filePath, const QByteArray& checksumHeader) +void ValidateChecksumHeader::start(const QString &filePath, const QByteArray &checksumHeader) { // If the incoming header is empty no validation can happen. Just continue. - if( checksumHeader.isEmpty() ) { + if (checksumHeader.isEmpty()) { emit validated(QByteArray(), QByteArray()); return; } - if( !parseChecksumHeader(checksumHeader, &_expectedChecksumType, &_expectedChecksum) ) { + if (!parseChecksumHeader(checksumHeader, &_expectedChecksumType, &_expectedChecksum)) { qCWarning(lcChecksums) << "Checksum header malformed:" << checksumHeader; emit validationFailed(tr("The checksum header is malformed.")); return; @@ -195,20 +195,19 @@ void ValidateChecksumHeader::start(const QString& filePath, const QByteArray& ch auto calculator = new ComputeChecksum(this); calculator->setChecksumType(_expectedChecksumType); - connect(calculator, SIGNAL(done(QByteArray,QByteArray)), - SLOT(slotChecksumCalculated(QByteArray,QByteArray))); + connect(calculator, SIGNAL(done(QByteArray, QByteArray)), + SLOT(slotChecksumCalculated(QByteArray, QByteArray))); calculator->start(filePath); } -void ValidateChecksumHeader::slotChecksumCalculated(const QByteArray& checksumType, - const QByteArray& checksum) +void ValidateChecksumHeader::slotChecksumCalculated(const QByteArray &checksumType, + const QByteArray &checksum) { - if( checksumType != _expectedChecksumType ) { - emit validationFailed(tr("The checksum header contained an unknown checksum type '%1'").arg( - QString::fromLatin1(_expectedChecksumType))); + if (checksumType != _expectedChecksumType) { + emit validationFailed(tr("The checksum header contained an unknown checksum type '%1'").arg(QString::fromLatin1(_expectedChecksumType))); return; } - if( checksum != _expectedChecksum ) { + if (checksum != _expectedChecksum) { emit validationFailed(tr("The downloaded file does not match the checksum, it will be resumed.")); return; } @@ -220,21 +219,21 @@ CSyncChecksumHook::CSyncChecksumHook(SyncJournalDb *journal) { } -const char* CSyncChecksumHook::hook(const char* path, uint32_t checksumTypeId, void *this_obj) +const char *CSyncChecksumHook::hook(const char *path, uint32_t checksumTypeId, void *this_obj) { - CSyncChecksumHook* checksumHook = static_cast(this_obj); + CSyncChecksumHook *checksumHook = static_cast(this_obj); QByteArray checksum = checksumHook->compute(QString::fromUtf8(path), checksumTypeId); if (checksum.isNull()) { return NULL; } - char* result = (char*)malloc(checksum.size() + 1); + char *result = (char *)malloc(checksum.size() + 1); memcpy(result, checksum.constData(), checksum.size()); result[checksum.size()] = 0; return result; } -QByteArray CSyncChecksumHook::compute(const QString& path, int checksumTypeId) +QByteArray CSyncChecksumHook::compute(const QString &path, int checksumTypeId) { QByteArray checksumType = _journal->getChecksumType(checksumTypeId); if (checksumType.isEmpty()) { @@ -250,6 +249,4 @@ QByteArray CSyncChecksumHook::compute(const QString& path, int checksumTypeId) return checksum; } - - } diff --git a/src/libsync/checksums.h b/src/libsync/checksums.h index eb2bd275f..5d88b0bcb 100644 --- a/src/libsync/checksums.h +++ b/src/libsync/checksums.h @@ -26,10 +26,10 @@ namespace OCC { class SyncJournalDb; /// Creates a checksum header from type and value. -QByteArray makeChecksumHeader(const QByteArray& checksumType, const QByteArray& checksum); +QByteArray makeChecksumHeader(const QByteArray &checksumType, const QByteArray &checksum); /// Parses a checksum header -bool parseChecksumHeader(const QByteArray& header, QByteArray* type, QByteArray* checksum); +bool parseChecksumHeader(const QByteArray &header, QByteArray *type, QByteArray *checksum); /// Checks OWNCLOUD_DISABLE_CHECKSUM_UPLOAD bool uploadChecksumEnabled(); @@ -46,12 +46,12 @@ class OWNCLOUDSYNC_EXPORT ComputeChecksum : public QObject { Q_OBJECT public: - explicit ComputeChecksum(QObject* parent = 0); + explicit ComputeChecksum(QObject *parent = 0); /** * Sets the checksum type to be used. The default is empty. */ - void setChecksumType(const QByteArray& type); + void setChecksumType(const QByteArray &type); QByteArray checksumType() const; @@ -60,15 +60,15 @@ public: * * done() is emitted when the calculation finishes. */ - void start(const QString& filePath); + void start(const QString &filePath); /** * Computes the checksum synchronously. */ - static QByteArray computeNow(const QString& filePath, const QByteArray& checksumType); + static QByteArray computeNow(const QString &filePath, const QByteArray &checksumType); signals: - void done(const QByteArray& checksumType, const QByteArray& checksum); + void done(const QByteArray &checksumType, const QByteArray &checksum); private slots: void slotCalculationDone(); @@ -97,14 +97,14 @@ public: * will be emitted. In case of any kind of error, the signal validationFailed() will * be emitted. */ - void start(const QString& filePath, const QByteArray& checksumHeader); + void start(const QString &filePath, const QByteArray &checksumHeader); signals: - void validated(const QByteArray& checksumType, const QByteArray& checksum); - void validationFailed( const QString& errMsg ); + void validated(const QByteArray &checksumType, const QByteArray &checksum); + void validationFailed(const QString &errMsg); private slots: - void slotChecksumCalculated(const QByteArray& checksumType, const QByteArray& checksum); + void slotChecksumCalculated(const QByteArray &checksumType, const QByteArray &checksum); private: QByteArray _expectedChecksumType; @@ -119,7 +119,7 @@ class OWNCLOUDSYNC_EXPORT CSyncChecksumHook : public QObject { Q_OBJECT public: - explicit CSyncChecksumHook(SyncJournalDb* journal); + explicit CSyncChecksumHook(SyncJournalDb *journal); /** * Returns the checksum value for \a path for the given \a checksumTypeId. @@ -128,12 +128,11 @@ public: * to be set as userdata. * The return value will be owned by csync. */ - static const char* hook(const char* path, uint32_t checksumTypeId, void* this_obj); + static const char *hook(const char *path, uint32_t checksumTypeId, void *this_obj); - QByteArray compute(const QString& path, int checksumTypeId); + QByteArray compute(const QString &path, int checksumTypeId); private: - SyncJournalDb* _journal; + SyncJournalDb *_journal; }; - } diff --git a/src/libsync/clientproxy.cpp b/src/libsync/clientproxy.cpp index c78c59db6..e87f04b7c 100644 --- a/src/libsync/clientproxy.cpp +++ b/src/libsync/clientproxy.cpp @@ -23,12 +23,12 @@ namespace OCC { Q_LOGGING_CATEGORY(lcClientProxy, "sync.clientproxy", QtInfoMsg) -ClientProxy::ClientProxy(QObject *parent) : - QObject(parent) +ClientProxy::ClientProxy(QObject *parent) + : QObject(parent) { } -static QNetworkProxy proxyFromConfig(const ConfigFile& cfg) +static QNetworkProxy proxyFromConfig(const ConfigFile &cfg) { QNetworkProxy proxy; @@ -44,11 +44,12 @@ static QNetworkProxy proxyFromConfig(const ConfigFile& cfg) return proxy; } -bool ClientProxy::isUsingSystemDefault() { +bool ClientProxy::isUsingSystemDefault() +{ OCC::ConfigFile cfg; // if there is no config file, default to system proxy. - if( cfg.exists() ) { + if (cfg.exists()) { return cfg.proxyType() == QNetworkProxy::DefaultProxy; } @@ -67,12 +68,12 @@ void ClientProxy::setupQtProxyFromConfig() QNetworkProxy proxy; // if there is no config file, default to system proxy. - if( cfg.exists() ) { + if (cfg.exists()) { proxyType = cfg.proxyType(); - proxy = proxyFromConfig(cfg); + proxy = proxyFromConfig(cfg); } - switch(proxyType) { + switch (proxyType) { case QNetworkProxy::NoProxy: qCInfo(lcClientProxy) << "Set proxy configuration to use NO proxy"; QNetworkProxyFactory::setUseSystemConfiguration(false); @@ -99,7 +100,7 @@ void ClientProxy::setupQtProxyFromConfig() } } -const char* ClientProxy::proxyTypeToCStr(QNetworkProxy::ProxyType type) +const char *ClientProxy::proxyTypeToCStr(QNetworkProxy::ProxyType type) { switch (type) { case QNetworkProxy::NoProxy: @@ -126,9 +127,11 @@ void ClientProxy::lookupSystemProxyAsync(const QUrl &url, QObject *dst, const ch QThreadPool::globalInstance()->start(runnable); // takes ownership and deletes } -SystemProxyRunnable::SystemProxyRunnable(const QUrl &url) : QObject(), QRunnable(), _url(url) +SystemProxyRunnable::SystemProxyRunnable(const QUrl &url) + : QObject() + , QRunnable() + , _url(url) { - } void SystemProxyRunnable::run() @@ -143,6 +146,4 @@ void SystemProxyRunnable::run() // FIXME Would we really ever return more? } } - - } diff --git a/src/libsync/clientproxy.h b/src/libsync/clientproxy.h index 77884feff..923f060f7 100644 --- a/src/libsync/clientproxy.h +++ b/src/libsync/clientproxy.h @@ -44,23 +44,23 @@ public slots: void setupQtProxyFromConfig(); private: - const char* proxyTypeToCStr(QNetworkProxy::ProxyType type); + const char *proxyTypeToCStr(QNetworkProxy::ProxyType type); }; -class SystemProxyRunnable : public QObject, public QRunnable { +class SystemProxyRunnable : public QObject, public QRunnable +{ Q_OBJECT public: SystemProxyRunnable(const QUrl &url); void run(); signals: void systemProxyLookedUp(const QNetworkProxy &url); + private: QUrl _url; }; OWNCLOUDSYNC_EXPORT QString printQNetworkProxy(const QNetworkProxy &proxy); - - } #endif // CLIENTPROXY_H diff --git a/src/libsync/configfile.cpp b/src/libsync/configfile.cpp index 22a500e5c..a3bab5f1c 100644 --- a/src/libsync/configfile.cpp +++ b/src/libsync/configfile.cpp @@ -66,10 +66,10 @@ static const char proxyUserC[] = "Proxy/user"; static const char proxyPassC[] = "Proxy/pass"; static const char proxyNeedsAuthC[] = "Proxy/needsAuth"; -static const char useUploadLimitC[] = "BWLimit/useUploadLimit"; +static const char useUploadLimitC[] = "BWLimit/useUploadLimit"; static const char useDownloadLimitC[] = "BWLimit/useDownloadLimit"; -static const char uploadLimitC[] = "BWLimit/uploadLimit"; -static const char downloadLimitC[] = "BWLimit/downloadLimit"; +static const char uploadLimitC[] = "BWLimit/uploadLimit"; +static const char downloadLimitC[] = "BWLimit/downloadLimit"; static const char newBigFolderSizeLimitC[] = "newBigFolderSizeLimit"; static const char useNewBigFolderSizeLimitC[] = "useNewBigFolderSizeLimit"; @@ -80,12 +80,12 @@ static const char maxLogLinesC[] = "Logging/maxLogLines"; const char certPath[] = "http_certificatePath"; const char certPasswd[] = "http_certificatePasswd"; QString ConfigFile::_confDir = QString::null; -bool ConfigFile::_askedUser = false; +bool ConfigFile::_askedUser = false; ConfigFile::ConfigFile() { // QDesktopServices uses the application name to create a config path - qApp->setApplicationName( Theme::instance()->appNameGUI() ); + qApp->setApplicationName(Theme::instance()->appNameGUI()); QSettings::setDefaultFormat(QSettings::IniFormat); @@ -93,23 +93,24 @@ ConfigFile::ConfigFile() QSettings settings(config, QSettings::IniFormat); - settings.beginGroup( defaultConnection() ); + settings.beginGroup(defaultConnection()); } bool ConfigFile::setConfDir(const QString &value) { QString dirPath = value; - if( dirPath.isEmpty() ) return false; + if (dirPath.isEmpty()) + return false; QFileInfo fi(dirPath); - if ( !fi.exists() ) { + if (!fi.exists()) { QDir().mkpath(dirPath); fi.setFile(dirPath); } - if( fi.exists() && fi.isDir() ) { + if (fi.exists() && fi.isDir()) { dirPath = fi.absoluteFilePath(); qCInfo(lcConfigFile) << "Using custom config dir " << dirPath; - _confDir=dirPath; + _confDir = dirPath; return true; } return false; @@ -130,25 +131,25 @@ int ConfigFile::timeout() const quint64 ConfigFile::chunkSize() const { QSettings settings(configFile(), QSettings::IniFormat); - return settings.value(QLatin1String(chunkSizeC), 10*1000*1000).toLongLong(); // default to 10 MB + return settings.value(QLatin1String(chunkSizeC), 10 * 1000 * 1000).toLongLong(); // default to 10 MB } quint64 ConfigFile::maxChunkSize() const { QSettings settings(configFile(), QSettings::IniFormat); - return settings.value(QLatin1String(maxChunkSizeC), 100*1000*1000).toLongLong(); // default to 100 MB + return settings.value(QLatin1String(maxChunkSizeC), 100 * 1000 * 1000).toLongLong(); // default to 100 MB } quint64 ConfigFile::minChunkSize() const { QSettings settings(configFile(), QSettings::IniFormat); - return settings.value(QLatin1String(minChunkSizeC), 1000*1000).toLongLong(); // default to 1 MB + return settings.value(QLatin1String(minChunkSizeC), 1000 * 1000).toLongLong(); // default to 1 MB } quint64 ConfigFile::targetChunkUploadDuration() const { QSettings settings(configFile(), QSettings::IniFormat); - return settings.value(QLatin1String(targetChunkUploadDurationC), 60*1000).toLongLong(); // default to 1 minute + return settings.value(QLatin1String(targetChunkUploadDurationC), 60 * 1000).toLongLong(); // default to 1 minute } void ConfigFile::setOptionalDesktopNotifications(bool show) @@ -179,7 +180,8 @@ void ConfigFile::restoreGeometry(QWidget *w) void ConfigFile::saveGeometryHeader(QHeaderView *header) { #ifndef TOKEN_AUTH_ONLY - if(!header) return; + if (!header) + return; ASSERT(!header->objectName().isEmpty()); QSettings settings(configFile(), QSettings::IniFormat); @@ -192,7 +194,8 @@ void ConfigFile::saveGeometryHeader(QHeaderView *header) void ConfigFile::restoreGeometryHeader(QHeaderView *header) { #ifndef TOKEN_AUTH_ONLY - if(!header) return; + if (!header) + return; ASSERT(!header->objectName().isNull()); QSettings settings(configFile(), QSettings::IniFormat); @@ -201,21 +204,21 @@ void ConfigFile::restoreGeometryHeader(QHeaderView *header) #endif } -QVariant ConfigFile::getPolicySetting(const QString &setting, const QVariant& defaultValue) const +QVariant ConfigFile::getPolicySetting(const QString &setting, const QVariant &defaultValue) const { if (Utility::isWindows()) { // check for policies first and return immediately if a value is found. QSettings userPolicy(QString::fromLatin1("HKEY_CURRENT_USER\\Software\\Policies\\%1\\%2") - .arg(APPLICATION_VENDOR, Theme::instance()->appName()), - QSettings::NativeFormat); - if(userPolicy.contains(setting)) { + .arg(APPLICATION_VENDOR, Theme::instance()->appName()), + QSettings::NativeFormat); + if (userPolicy.contains(setting)) { return userPolicy.value(setting); } QSettings machinePolicy(QString::fromLatin1("HKEY_LOCAL_MACHINE\\Software\\Policies\\%1\\%2") - .arg(APPLICATION_VENDOR, APPLICATION_NAME), - QSettings::NativeFormat); - if(machinePolicy.contains(setting)) { + .arg(APPLICATION_VENDOR, APPLICATION_NAME), + QSettings::NativeFormat); + if (machinePolicy.contains(setting)) { return machinePolicy.value(setting); } } @@ -224,23 +227,24 @@ QVariant ConfigFile::getPolicySetting(const QString &setting, const QVariant& de QString ConfigFile::configPath() const { - #ifndef TOKEN_AUTH_ONLY - if( _confDir.isEmpty() ) { +#ifndef TOKEN_AUTH_ONLY + if (_confDir.isEmpty()) { // Qt 5's QStandardPaths::writableLocation gives us wrong results (without /data/), // so we'll have to use the deprecated version for now _confDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); } - #endif +#endif QString dir = _confDir; - if( !dir.endsWith(QLatin1Char('/')) ) dir.append(QLatin1Char('/')); + if (!dir.endsWith(QLatin1Char('/'))) + dir.append(QLatin1Char('/')); return dir; } QString ConfigFile::configPathWithAppName() const { //HACK - return QFileInfo( configFile() ).dir().absolutePath().append("/"); + return QFileInfo(configFile()).dir().absolutePath().append("/"); } static const QLatin1String exclFile("sync-exclude.lst"); @@ -254,13 +258,13 @@ QString ConfigFile::excludeFile(Scope scope) const switch (scope) { case UserScope: - fi.setFile( configPath(), exclFile ); + fi.setFile(configPath(), exclFile); - if( ! fi.isReadable() ) { - fi.setFile( configPath(), QLatin1String("exclude.lst") ); + if (!fi.isReadable()) { + fi.setFile(configPath(), QLatin1String("exclude.lst")); } - if( ! fi.isReadable() ) { - fi.setFile( configPath(), exclFile ); + if (!fi.isReadable()) { + fi.setFile(configPath(), exclFile); } return fi.absoluteFilePath(); case SystemScope: @@ -275,14 +279,14 @@ QString ConfigFile::excludeFileFromSystem() { QFileInfo fi; #ifdef Q_OS_WIN - fi.setFile( QCoreApplication::applicationDirPath(), exclFile ); + fi.setFile(QCoreApplication::applicationDirPath(), exclFile); #endif #ifdef Q_OS_UNIX fi.setFile(QString(SYSCONFDIR "/" + Theme::instance()->appName()), exclFile); - if ( ! fi.exists() ) { + if (!fi.exists()) { // Prefer to return the preferred path! Only use the fallback location // if the other path does not exist and the fallback is valid. - QFileInfo nextToBinary( QCoreApplication::applicationDirPath(), exclFile ); + QFileInfo nextToBinary(QCoreApplication::applicationDirPath(), exclFile); if (nextToBinary.exists()) { fi = nextToBinary; } @@ -290,10 +294,10 @@ QString ConfigFile::excludeFileFromSystem() #endif #ifdef Q_OS_MAC // exec path is inside the bundle - fi.setFile( QCoreApplication::applicationDirPath(), - QLatin1String("../Resources/") + exclFile ); + fi.setFile(QCoreApplication::applicationDirPath(), + QLatin1String("../Resources/") + exclFile); #endif - + return fi.absoluteFilePath(); } @@ -304,7 +308,7 @@ QString ConfigFile::configFile() const bool ConfigFile::exists() { - QFile file( configFile() ); + QFile file(configFile()); return file.exists(); } @@ -313,7 +317,7 @@ QString ConfigFile::defaultConnection() const return Theme::instance()->appName(); } -void ConfigFile::storeData(const QString& group, const QString& key, const QVariant& value) +void ConfigFile::storeData(const QString &group, const QString &key, const QVariant &value) { const QString con(group.isEmpty() ? defaultConnection() : group); QSettings settings(configFile(), QSettings::IniFormat); @@ -323,7 +327,7 @@ void ConfigFile::storeData(const QString& group, const QString& key, const QVari settings.sync(); } -QVariant ConfigFile::retrieveData(const QString& group, const QString& key) const +QVariant ConfigFile::retrieveData(const QString &group, const QString &key) const { const QString con(group.isEmpty() ? defaultConnection() : group); QSettings settings(configFile(), QSettings::IniFormat); @@ -332,7 +336,7 @@ QVariant ConfigFile::retrieveData(const QString& group, const QString& key) cons return settings.value(key); } -void ConfigFile::removeData(const QString& group, const QString& key) +void ConfigFile::removeData(const QString &group, const QString &key) { const QString con(group.isEmpty() ? defaultConnection() : group); QSettings settings(configFile(), QSettings::IniFormat); @@ -341,7 +345,7 @@ void ConfigFile::removeData(const QString& group, const QString& key) settings.remove(key); } -bool ConfigFile::dataExists(const QString& group, const QString& key) const +bool ConfigFile::dataExists(const QString &group, const QString &key) const { const QString con(group.isEmpty() ? defaultConnection() : group); QSettings settings(configFile(), QSettings::IniFormat); @@ -350,93 +354,99 @@ bool ConfigFile::dataExists(const QString& group, const QString& key) const return settings.contains(key); } -int ConfigFile::remotePollInterval( const QString& connection ) const +int ConfigFile::remotePollInterval(const QString &connection) const { - QString con( connection ); - if( connection.isEmpty() ) con = defaultConnection(); + QString con(connection); + if (connection.isEmpty()) + con = defaultConnection(); - QSettings settings(configFile(), QSettings::IniFormat); - settings.beginGroup( con ); + QSettings settings(configFile(), QSettings::IniFormat); + settings.beginGroup(con); - int remoteInterval = settings.value( QLatin1String(remotePollIntervalC), DEFAULT_REMOTE_POLL_INTERVAL ).toInt(); - if( remoteInterval < 5000) { - qCWarning(lcConfigFile) << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL; - remoteInterval = DEFAULT_REMOTE_POLL_INTERVAL; - } - return remoteInterval; + int remoteInterval = settings.value(QLatin1String(remotePollIntervalC), DEFAULT_REMOTE_POLL_INTERVAL).toInt(); + if (remoteInterval < 5000) { + qCWarning(lcConfigFile) << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL; + remoteInterval = DEFAULT_REMOTE_POLL_INTERVAL; + } + return remoteInterval; } -void ConfigFile::setRemotePollInterval(int interval, const QString &connection ) +void ConfigFile::setRemotePollInterval(int interval, const QString &connection) { - QString con( connection ); - if( connection.isEmpty() ) con = defaultConnection(); + QString con(connection); + if (connection.isEmpty()) + con = defaultConnection(); - if( interval < 5000 ) { + if (interval < 5000) { qCWarning(lcConfigFile) << "Remote Poll interval of " << interval << " is below five seconds."; return; } QSettings settings(configFile(), QSettings::IniFormat); - settings.beginGroup( con ); - settings.setValue(QLatin1String(remotePollIntervalC), interval ); + settings.beginGroup(con); + settings.setValue(QLatin1String(remotePollIntervalC), interval); settings.sync(); } -quint64 ConfigFile::forceSyncInterval(const QString& connection) const +quint64 ConfigFile::forceSyncInterval(const QString &connection) const { uint pollInterval = remotePollInterval(connection); - QString con( connection ); - if( connection.isEmpty() ) con = defaultConnection(); + QString con(connection); + if (connection.isEmpty()) + con = defaultConnection(); QSettings settings(configFile(), QSettings::IniFormat); - settings.beginGroup( con ); + settings.beginGroup(con); quint64 defaultInterval = 2 * 60 * 60 * 1000ull; // 2h - quint64 interval = settings.value( QLatin1String(forceSyncIntervalC), defaultInterval ).toULongLong(); - if( interval < pollInterval) { + quint64 interval = settings.value(QLatin1String(forceSyncIntervalC), defaultInterval).toULongLong(); + if (interval < pollInterval) { qCWarning(lcConfigFile) << "Force sync interval is less than the remote poll inteval, reverting to" << pollInterval; interval = pollInterval; } return interval; } -quint64 ConfigFile::notificationRefreshInterval(const QString& connection) const +quint64 ConfigFile::notificationRefreshInterval(const QString &connection) const { - QString con( connection ); - if( connection.isEmpty() ) con = defaultConnection(); + QString con(connection); + if (connection.isEmpty()) + con = defaultConnection(); QSettings settings(configFile(), QSettings::IniFormat); - settings.beginGroup( con ); + settings.beginGroup(con); quint64 defaultInterval = 5 * 60 * 1000ull; // 5 minutes - quint64 interval = settings.value( QLatin1String(notificationRefreshIntervalC), defaultInterval ).toULongLong(); - if( interval < 60*1000ull) { + quint64 interval = settings.value(QLatin1String(notificationRefreshIntervalC), defaultInterval).toULongLong(); + if (interval < 60 * 1000ull) { qCWarning(lcConfigFile) << "Notification refresh interval smaller than one minute, setting to one minute"; - interval = 60*1000ull; + interval = 60 * 1000ull; } return interval; } -int ConfigFile::updateCheckInterval( const QString& connection ) const +int ConfigFile::updateCheckInterval(const QString &connection) const { - QString con( connection ); - if( connection.isEmpty() ) con = defaultConnection(); + QString con(connection); + if (connection.isEmpty()) + con = defaultConnection(); QSettings settings(configFile(), QSettings::IniFormat); - settings.beginGroup( con ); + settings.beginGroup(con); - int defaultInterval = 1000*60*60*10; // ten hours - int interval = settings.value( QLatin1String(updateCheckIntervalC), defaultInterval ).toInt(); + int defaultInterval = 1000 * 60 * 60 * 10; // ten hours + int interval = settings.value(QLatin1String(updateCheckIntervalC), defaultInterval).toInt(); - int minInterval = 1000*60*5; - if( interval < minInterval) { + int minInterval = 1000 * 60 * 5; + if (interval < minInterval) { qCWarning(lcConfigFile) << "Update check interval less than five minutes, setting " << minInterval; interval = minInterval; } return interval; } -bool ConfigFile::skipUpdateCheck( const QString& connection ) const +bool ConfigFile::skipUpdateCheck(const QString &connection) const { - QString con( connection ); - if( connection.isEmpty() ) con = defaultConnection(); + QString con(connection); + if (connection.isEmpty()) + con = defaultConnection(); QVariant fallback = getValue(QLatin1String(skipUpdateCheckC), con, false); fallback = getValue(QLatin1String(skipUpdateCheckC), QString(), fallback); @@ -445,26 +455,26 @@ bool ConfigFile::skipUpdateCheck( const QString& connection ) const return value.toBool(); } -void ConfigFile::setSkipUpdateCheck( bool skip, const QString& connection ) +void ConfigFile::setSkipUpdateCheck(bool skip, const QString &connection) { - QString con( connection ); - if( connection.isEmpty() ) con = defaultConnection(); + QString con(connection); + if (connection.isEmpty()) + con = defaultConnection(); QSettings settings(configFile(), QSettings::IniFormat); - settings.beginGroup( con ); + settings.beginGroup(con); - settings.setValue( QLatin1String(skipUpdateCheckC), QVariant(skip) ); + settings.setValue(QLatin1String(skipUpdateCheckC), QVariant(skip)); settings.sync(); - } int ConfigFile::maxLogLines() const { QSettings settings(configFile(), QSettings::IniFormat); - return settings.value( QLatin1String(maxLogLinesC), DEFAULT_MAX_LOG_LINES ).toInt(); + return settings.value(QLatin1String(maxLogLinesC), DEFAULT_MAX_LOG_LINES).toInt(); } -void ConfigFile::setMaxLogLines( int lines ) +void ConfigFile::setMaxLogLines(int lines) { QSettings settings(configFile(), QSettings::IniFormat); settings.setValue(QLatin1String(maxLogLinesC), lines); @@ -472,17 +482,16 @@ void ConfigFile::setMaxLogLines( int lines ) } void ConfigFile::setProxyType(int proxyType, - const QString& host, - int port, bool needsAuth, - const QString& user, - const QString& pass) + const QString &host, + int port, bool needsAuth, + const QString &user, + const QString &pass) { QSettings settings(configFile(), QSettings::IniFormat); settings.setValue(QLatin1String(proxyTypeC), proxyType); - if (proxyType == QNetworkProxy::HttpProxy || - proxyType == QNetworkProxy::Socks5Proxy) { + if (proxyType == QNetworkProxy::HttpProxy || proxyType == QNetworkProxy::Socks5Proxy) { settings.setValue(QLatin1String(proxyHostC), host); settings.setValue(QLatin1String(proxyPortC), port); settings.setValue(QLatin1String(proxyNeedsAuthC), needsAuth); @@ -492,18 +501,18 @@ void ConfigFile::setProxyType(int proxyType, settings.sync(); } -QVariant ConfigFile::getValue(const QString& param, const QString& group, - const QVariant& defaultValue) const +QVariant ConfigFile::getValue(const QString ¶m, const QString &group, + const QVariant &defaultValue) const { QVariant systemSetting; if (Utility::isMac()) { - QSettings systemSettings(QLatin1String("/Library/Preferences/" APPLICATION_REV_DOMAIN ".plist"), QSettings::NativeFormat); - if (!group.isEmpty()) { - systemSettings.beginGroup(group); - } - systemSetting = systemSettings.value(param, defaultValue); + QSettings systemSettings(QLatin1String("/Library/Preferences/" APPLICATION_REV_DOMAIN ".plist"), QSettings::NativeFormat); + if (!group.isEmpty()) { + systemSettings.beginGroup(group); + } + systemSetting = systemSettings.value(param, defaultValue); } else if (Utility::isUnix()) { - QSettings systemSettings(QString( SYSCONFDIR "/%1/%1.conf").arg(Theme::instance()->appName()), QSettings::NativeFormat); + QSettings systemSettings(QString(SYSCONFDIR "/%1/%1.conf").arg(Theme::instance()->appName()), QSettings::NativeFormat); if (!group.isEmpty()) { systemSettings.beginGroup(group); } @@ -511,7 +520,7 @@ QVariant ConfigFile::getValue(const QString& param, const QString& group, } else { // Windows QSettings systemSettings(QString::fromLatin1("HKEY_LOCAL_MACHINE\\Software\\%1\\%2") .arg(APPLICATION_VENDOR, Theme::instance()->appName()), - QSettings::NativeFormat); + QSettings::NativeFormat); if (!group.isEmpty()) { systemSettings.beginGroup(group); } @@ -519,12 +528,13 @@ QVariant ConfigFile::getValue(const QString& param, const QString& group, } QSettings settings(configFile(), QSettings::IniFormat); - if (!group.isEmpty()) settings.beginGroup(group); + if (!group.isEmpty()) + settings.beginGroup(group); return settings.value(param, systemSetting); } -void ConfigFile::setValue(const QString& key, const QVariant &value) +void ConfigFile::setValue(const QString &key, const QVariant &value) { QSettings settings(configFile(), QSettings::IniFormat); @@ -647,7 +657,7 @@ bool ConfigFile::monoIcons() const bool monoDefault = false; // On Mac we want bw by default #ifdef Q_OS_MAC // OEM themes are not obliged to ship mono icons - monoDefault = (0 == (strcmp("ownCloud",APPLICATION_NAME))); + monoDefault = (0 == (strcmp("ownCloud", APPLICATION_NAME))); #endif return settings.value(QLatin1String(monoIconsC), monoDefault).toBool(); } @@ -675,11 +685,11 @@ QString ConfigFile::certificatePath() const return retrieveData(QString(), QLatin1String(certPath)).toString(); } -void ConfigFile::setCertificatePath(const QString& cPath) +void ConfigFile::setCertificatePath(const QString &cPath) { - QSettings settings(configFile(), QSettings::IniFormat); - settings.setValue( QLatin1String(certPath), cPath); - settings.sync(); + QSettings settings(configFile(), QSettings::IniFormat); + settings.setValue(QLatin1String(certPath), cPath); + settings.sync(); } QString ConfigFile::certificatePasswd() const @@ -687,11 +697,10 @@ QString ConfigFile::certificatePasswd() const return retrieveData(QString(), QLatin1String(certPasswd)).toString(); } -void ConfigFile::setCertificatePasswd(const QString& cPasswd) +void ConfigFile::setCertificatePasswd(const QString &cPasswd) { - QSettings settings(configFile(), QSettings::IniFormat); - settings.setValue( QLatin1String(certPasswd), cPasswd); - settings.sync(); + QSettings settings(configFile(), QSettings::IniFormat); + settings.setValue(QLatin1String(certPasswd), cPasswd); + settings.sync(); } - } diff --git a/src/libsync/configfile.h b/src/libsync/configfile.h index 2f3a6becc..912b66a04 100644 --- a/src/libsync/configfile.h +++ b/src/libsync/configfile.h @@ -36,7 +36,8 @@ class OWNCLOUDSYNC_EXPORT ConfigFile public: ConfigFile(); - enum Scope { UserScope, SystemScope }; + enum Scope { UserScope, + SystemScope }; QString configPath() const; QString configPathWithAppName() const; @@ -50,21 +51,21 @@ public: // the certs do not depend on a connection. QByteArray caCerts(); - void setCaCerts( const QByteArray& ); + void setCaCerts(const QByteArray &); - bool passwordStorageAllowed(const QString &connection = QString::null ); + bool passwordStorageAllowed(const QString &connection = QString::null); // max count of lines in the log window - int maxLogLines() const; + int maxLogLines() const; void setMaxLogLines(int); /* Server poll interval in milliseconds */ - int remotePollInterval( const QString& connection = QString() ) const; + int remotePollInterval(const QString &connection = QString()) const; /* Set poll interval. Value in milliseconds has to be larger than 5000 */ - void setRemotePollInterval(int interval, const QString& connection = QString() ); + void setRemotePollInterval(int interval, const QString &connection = QString()); /* Interval to check for new notifications */ - quint64 notificationRefreshInterval(const QString& connection = QString()) const; + quint64 notificationRefreshInterval(const QString &connection = QString()) const; /* Force sync interval, in milliseconds */ quint64 forceSyncInterval(const QString &connection = QString()) const; @@ -80,10 +81,10 @@ public: // proxy settings void setProxyType(int proxyType, - const QString& host = QString(), - int port = 0, bool needsAuth = false, - const QString& user = QString(), - const QString& pass = QString()); + const QString &host = QString(), + int port = 0, bool needsAuth = false, + const QString &user = QString(), + const QString &pass = QString()); int proxyType() const; QString proxyHostName() const; @@ -91,7 +92,7 @@ public: bool proxyNeedsAuth() const; QString proxyUser() const; QString proxyPassword() const; - + /** 0: no limit, 1: manual, >0: automatic */ int useUploadLimit() const; int useDownloadLimit() const; @@ -123,38 +124,37 @@ public: void restoreGeometry(QWidget *w); // how often the check about new versions runs, default two hours - int updateCheckInterval( const QString& connection = QString() ) const; + int updateCheckInterval(const QString &connection = QString()) const; - bool skipUpdateCheck( const QString& connection = QString() ) const; - void setSkipUpdateCheck( bool, const QString& ); + bool skipUpdateCheck(const QString &connection = QString()) const; + void setSkipUpdateCheck(bool, const QString &); void saveGeometryHeader(QHeaderView *header); void restoreGeometryHeader(QHeaderView *header); QString certificatePath() const; - void setCertificatePath(const QString& cPath); + void setCertificatePath(const QString &cPath); QString certificatePasswd() const; - void setCertificatePasswd(const QString& cPasswd); + void setCertificatePasswd(const QString &cPasswd); protected: - QVariant getPolicySetting(const QString& policy, const QVariant& defaultValue = QVariant()) const; - void storeData(const QString& group, const QString& key, const QVariant& value); - QVariant retrieveData(const QString& group, const QString& key) const; - void removeData(const QString& group, const QString& key); - bool dataExists(const QString& group, const QString& key) const; + QVariant getPolicySetting(const QString &policy, const QVariant &defaultValue = QVariant()) const; + void storeData(const QString &group, const QString &key, const QVariant &value); + QVariant retrieveData(const QString &group, const QString &key) const; + void removeData(const QString &group, const QString &key); + bool dataExists(const QString &group, const QString &key) const; private: - QVariant getValue(const QString& param, const QString& group = QString::null, - const QVariant& defaultValue = QVariant()) const; - void setValue(const QString& key, const QVariant &value); + QVariant getValue(const QString ¶m, const QString &group = QString::null, + const QVariant &defaultValue = QVariant()) const; + void setValue(const QString &key, const QVariant &value); private: - typedef QSharedPointer< AbstractCredentials > SharedCreds; + typedef QSharedPointer SharedCreds; - static bool _askedUser; + static bool _askedUser; static QString _oCVersion; static QString _confDir; }; - } #endif // CONFIGFILE_H diff --git a/src/libsync/connectionvalidator.cpp b/src/libsync/connectionvalidator.cpp index bac43e3aa..c39f3cd7e 100644 --- a/src/libsync/connectionvalidator.cpp +++ b/src/libsync/connectionvalidator.cpp @@ -31,18 +31,18 @@ Q_LOGGING_CATEGORY(lcConnectionValidator, "sync.connectionvalidator", QtInfoMsg) // Make sure the timeout for this job is less than how often we get called // This makes sure we get tried often enough without "ConnectionValidator already running" -static qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5*1000); +static qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5 * 1000); ConnectionValidator::ConnectionValidator(AccountPtr account, QObject *parent) - : QObject(parent), - _account(account), - _isCheckingServerAndAuth(false) + : QObject(parent) + , _account(account) + , _isCheckingServerAndAuth(false) { } -QString ConnectionValidator::statusString( Status stat ) +QString ConnectionValidator::statusString(Status stat) { - switch( stat ) { + switch (stat) { case Undefined: return QLatin1String("Undefined"); case Connected: @@ -69,9 +69,9 @@ QString ConnectionValidator::statusString( Status stat ) void ConnectionValidator::checkServerAndAuth() { - if( !_account ) { + if (!_account) { _errors << tr("No ownCloud account configured"); - reportResult( NotConfigured ); + reportResult(NotConfigured); return; } qCDebug(lcConnectionValidator) << "Checking server and authentication"; @@ -82,7 +82,7 @@ void ConnectionValidator::checkServerAndAuth() if (ClientProxy::isUsingSystemDefault()) { qCDebug(lcConnectionValidator) << "Trying to look up system proxy"; ClientProxy::lookupSystemProxyAsync(_account->url(), - this, SLOT(systemProxyLookupDone(QNetworkProxy))); + this, SLOT(systemProxyLookupDone(QNetworkProxy))); } else { // We want to reset the QNAM proxy so that the global proxy settings are used (via ClientProxy settings) _account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy)); @@ -91,7 +91,8 @@ void ConnectionValidator::checkServerAndAuth() } } -void ConnectionValidator::systemProxyLookupDone(const QNetworkProxy &proxy) { +void ConnectionValidator::systemProxyLookupDone(const QNetworkProxy &proxy) +{ if (!_account) { qCWarning(lcConnectionValidator) << "Bailing out, Account had been deleted"; return; @@ -113,13 +114,13 @@ void ConnectionValidator::slotCheckServerAndAuth() CheckServerJob *checkJob = new CheckServerJob(_account, this); checkJob->setTimeout(timeoutToUseMsec); checkJob->setIgnoreCredentialFailure(true); - connect(checkJob, SIGNAL(instanceFound(QUrl,QJsonObject)), SLOT(slotStatusFound(QUrl,QJsonObject))); - connect(checkJob, SIGNAL(instanceNotFound(QNetworkReply*)), SLOT(slotNoStatusFound(QNetworkReply*))); + connect(checkJob, SIGNAL(instanceFound(QUrl, QJsonObject)), SLOT(slotStatusFound(QUrl, QJsonObject))); + connect(checkJob, SIGNAL(instanceNotFound(QNetworkReply *)), SLOT(slotNoStatusFound(QNetworkReply *))); connect(checkJob, SIGNAL(timeout(QUrl)), SLOT(slotJobTimeout(QUrl))); checkJob->start(); } -void ConnectionValidator::slotStatusFound(const QUrl&url, const QJsonObject &info) +void ConnectionValidator::slotStatusFound(const QUrl &url, const QJsonObject &info) { // Newer servers don't disclose any version in status.php anymore // https://github.com/owncloud/core/pull/27473/files @@ -128,24 +129,24 @@ void ConnectionValidator::slotStatusFound(const QUrl&url, const QJsonObject &inf // status.php was found. qCInfo(lcConnectionValidator) << "** Application: ownCloud found: " - << url << " with version " - << CheckServerJob::versionString(info) - << "(" << serverVersion << ")"; + << url << " with version " + << CheckServerJob::versionString(info) + << "(" << serverVersion << ")"; if (!serverVersion.isEmpty() && !setAndCheckServerVersion(serverVersion)) { return; } if (info["maintenance"].toBool()) { - reportResult( MaintenanceMode ); + reportResult(MaintenanceMode); return; } // now check the authentication if (_account->credentials()->ready()) - QTimer::singleShot( 0, this, SLOT( checkAuthentication() )); + QTimer::singleShot(0, this, SLOT(checkAuthentication())); else - reportResult( CredentialsMissingOrWrong ); + reportResult(CredentialsMissingOrWrong); } // status.php could not be loaded (network or server issue!). @@ -156,14 +157,14 @@ void ConnectionValidator::slotNoStatusFound(QNetworkReply *reply) if (!_account->credentials()->ready()) { // This could be needed for SSL client certificates // We need to load them from keychain and try - reportResult( CredentialsMissingOrWrong ); - } else if (! _account->credentials()->stillValid(reply)) { + reportResult(CredentialsMissingOrWrong); + } else if (!_account->credentials()->stillValid(reply)) { _errors.append(tr("Authentication error: Either username or password are wrong.")); } else { //_errors.append(tr("Unable to connect to %1").arg(_account->url().toString())); - _errors.append( job->errorString() ); + _errors.append(job->errorString()); } - reportResult( StatusNotFound ); + reportResult(StatusNotFound); } void ConnectionValidator::slotJobTimeout(const QUrl &url) @@ -171,7 +172,7 @@ void ConnectionValidator::slotJobTimeout(const QUrl &url) Q_UNUSED(url); //_errors.append(tr("Unable to connect to %1").arg(url.toString())); _errors.append(tr("timeout")); - reportResult( Timeout ); + reportResult(Timeout); } @@ -190,7 +191,7 @@ void ConnectionValidator::checkAuthentication() job->setTimeout(timeoutToUseMsec); job->setProperties(QList() << "getlastmodified"); connect(job, SIGNAL(result(QVariantMap)), SLOT(slotAuthSuccess())); - connect(job, SIGNAL(finishedWithError(QNetworkReply*)), SLOT(slotAuthFailed(QNetworkReply*))); + connect(job, SIGNAL(finishedWithError(QNetworkReply *)), SLOT(slotAuthFailed(QNetworkReply *))); job->start(); } @@ -199,24 +200,23 @@ void ConnectionValidator::slotAuthFailed(QNetworkReply *reply) auto job = qobject_cast(sender()); Status stat = Timeout; - if( reply->error() == QNetworkReply::AuthenticationRequiredError || - !_account->credentials()->stillValid(reply)) { + if (reply->error() == QNetworkReply::AuthenticationRequiredError || !_account->credentials()->stillValid(reply)) { qCWarning(lcConnectionValidator) << "******** Password is wrong!" << reply->error() << job->errorString(); _errors << tr("The provided credentials are not correct"); stat = CredentialsMissingOrWrong; - } else if( reply->error() != QNetworkReply::NoError ) { + } else if (reply->error() != QNetworkReply::NoError) { _errors << job->errorStringParsingBody(); const int httpStatus = - reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if ( httpStatus == 503 ) { + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + if (httpStatus == 503) { _errors.clear(); stat = ServiceUnavailable; } } - reportResult( stat ); + reportResult(stat); } void ConnectionValidator::slotAuthSuccess() @@ -254,24 +254,23 @@ void ConnectionValidator::slotCapabilitiesRecieved(const QJsonDocument &json) void ConnectionValidator::fetchUser() { - JsonApiJob *job = new JsonApiJob(_account, QLatin1String("ocs/v1.php/cloud/user"), this); job->setTimeout(timeoutToUseMsec); QObject::connect(job, SIGNAL(jsonReceived(QJsonDocument, int)), this, SLOT(slotUserFetched(QJsonDocument))); job->start(); } -bool ConnectionValidator::setAndCheckServerVersion(const QString& version) +bool ConnectionValidator::setAndCheckServerVersion(const QString &version) { qCInfo(lcConnectionValidator) << _account->url() << "has server version" << version; _account->setServerVersion(version); // We cannot deal with servers < 5.0.0 if (_account->serverVersionInt() - && _account->serverVersionInt() < Account::makeServerVersion(5, 0, 0)) { - _errors.append( tr("The configured server for this client is too old") ); - _errors.append( tr("Please update to the latest server and restart the client.") ); - reportResult( ServerVersionMismatch ); + && _account->serverVersionInt() < Account::makeServerVersion(5, 0, 0)) { + _errors.append(tr("The configured server for this client is too old")); + _errors.append(tr("Please update to the latest server and restart the client.")); + reportResult(ServerVersionMismatch); return false; } @@ -288,14 +287,14 @@ void ConnectionValidator::slotUserFetched(const QJsonDocument &json) _account->setDavUser(user); AvatarJob *job = new AvatarJob(_account, this); - job->setTimeout(20*1000); + job->setTimeout(20 * 1000); QObject::connect(job, SIGNAL(avatarPixmap(QImage)), this, SLOT(slotAvatarImage(QImage))); job->start(); } } -void ConnectionValidator::slotAvatarImage(const QImage& img) +void ConnectionValidator::slotAvatarImage(const QImage &img) { _account->setAvatar(img); reportResult(Connected); diff --git a/src/libsync/connectionvalidator.h b/src/libsync/connectionvalidator.h index e4e729701..7254c9bcf 100644 --- a/src/libsync/connectionvalidator.h +++ b/src/libsync/connectionvalidator.h @@ -94,7 +94,7 @@ public: Timeout // actually also used for other errors on the authed request }; - static QString statusString( Status ); + static QString statusString(Status); // How often should the Application ask this object to check for the connection? enum { DefaultCallingIntervalMsec = 32 * 1000 }; @@ -108,19 +108,19 @@ public slots: void checkAuthentication(); signals: - void connectionResult( ConnectionValidator::Status status, QStringList errors ); + void connectionResult(ConnectionValidator::Status status, QStringList errors); protected slots: void slotCheckServerAndAuth(); - void slotStatusFound(const QUrl&url, const QJsonObject &info); + void slotStatusFound(const QUrl &url, const QJsonObject &info); void slotNoStatusFound(QNetworkReply *reply); - void slotJobTimeout(const QUrl& url); + void slotJobTimeout(const QUrl &url); void slotAuthFailed(QNetworkReply *reply); void slotAuthSuccess(); - void slotCapabilitiesRecieved(const QJsonDocument&); + void slotCapabilitiesRecieved(const QJsonDocument &); void slotUserFetched(const QJsonDocument &); void slotAvatarImage(const QImage &img); @@ -133,13 +133,12 @@ private: * * Returns false and reports ServerVersionMismatch for very old servers. */ - bool setAndCheckServerVersion(const QString& version); + bool setAndCheckServerVersion(const QString &version); QStringList _errors; - AccountPtr _account; + AccountPtr _account; bool _isCheckingServerAndAuth; }; - } #endif // CONNECTIONVALIDATOR_H diff --git a/src/libsync/cookiejar.cpp b/src/libsync/cookiejar.cpp index 836b5d1ba..4af34d5e7 100644 --- a/src/libsync/cookiejar.cpp +++ b/src/libsync/cookiejar.cpp @@ -27,7 +27,7 @@ namespace OCC { Q_LOGGING_CATEGORY(lcCookieJar, "sync.cookiejar", QtInfoMsg) namespace { - const unsigned int JAR_VERSION = 23; + const unsigned int JAR_VERSION = 23; } QDataStream &operator<<(QDataStream &stream, const QList &list) @@ -51,8 +51,7 @@ QDataStream &operator>>(QDataStream &stream, QList &list) quint32 count; stream >> count; - for(quint32 i = 0; i < count; ++i) - { + for (quint32 i = 0; i < count; ++i) { QByteArray value; stream >> value; QList newCookies = QNetworkCookie::parseCookies(value); @@ -67,8 +66,8 @@ QDataStream &operator>>(QDataStream &stream, QList &list) return stream; } -CookieJar::CookieJar(QObject *parent) : - QNetworkCookieJar(parent) +CookieJar::CookieJar(QObject *parent) + : QNetworkCookieJar(parent) { } @@ -76,14 +75,14 @@ CookieJar::~CookieJar() { } -bool CookieJar::setCookiesFromUrl(const QList& cookieList, const QUrl& url) +bool CookieJar::setCookiesFromUrl(const QList &cookieList, const QUrl &url) { - if (QNetworkCookieJar::setCookiesFromUrl(cookieList, url)) { - Q_EMIT newCookiesForUrl(cookieList, url); - return true; - } + if (QNetworkCookieJar::setCookiesFromUrl(cookieList, url)) { + Q_EMIT newCookiesForUrl(cookieList, url); + return true; + } - return false; + return false; } QList CookieJar::cookiesForUrl(const QUrl &url) const @@ -124,7 +123,7 @@ void CookieJar::restore(const QString &fileName) QList CookieJar::removeExpired(const QList &cookies) { QList updatedList; - foreach(const QNetworkCookie &cookie, cookies) { + foreach (const QNetworkCookie &cookie, cookies) { if (cookie.expirationDate() > QDateTime::currentDateTime() && !cookie.isSessionCookie()) { updatedList << cookie; } diff --git a/src/libsync/cookiejar.h b/src/libsync/cookiejar.h index 9759676b3..83d9e3c50 100644 --- a/src/libsync/cookiejar.h +++ b/src/libsync/cookiejar.h @@ -43,7 +43,8 @@ public: void restore(const QString &fileName); signals: - void newCookiesForUrl(const QList& cookieList, const QUrl& url); + void newCookiesForUrl(const QList &cookieList, const QUrl &url); + private: QList removeExpired(const QList &cookies); }; diff --git a/src/libsync/creds/abstractcredentials.cpp b/src/libsync/creds/abstractcredentials.cpp index 4fe154184..9fdef3173 100644 --- a/src/libsync/creds/abstractcredentials.cpp +++ b/src/libsync/creds/abstractcredentials.cpp @@ -18,8 +18,7 @@ #include "asserts.h" #include "creds/abstractcredentials.h" -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcCredentials, "sync.credentials", QtInfoMsg) @@ -37,20 +36,20 @@ void AbstractCredentials::setAccount(Account *account) QString AbstractCredentials::keychainKey(const QString &url, const QString &user) { QString u(url); - if( u.isEmpty() ) { + if (u.isEmpty()) { qCWarning(lcCredentials) << "Empty url in keyChain, error!"; return QString::null; } - if( user.isEmpty() ) { + if (user.isEmpty()) { qCWarning(lcCredentials) << "Error: User is empty!"; return QString::null; } - if( !u.endsWith(QChar('/')) ) { + if (!u.endsWith(QChar('/'))) { u.append(QChar('/')); } - QString key = user+QLatin1Char(':')+u; + QString key = user + QLatin1Char(':') + u; return key; } } // namespace OCC diff --git a/src/libsync/creds/abstractcredentials.h b/src/libsync/creds/abstractcredentials.h index 93047e2fc..d73d4534e 100644 --- a/src/libsync/creds/abstractcredentials.h +++ b/src/libsync/creds/abstractcredentials.h @@ -23,8 +23,7 @@ class QNetworkAccessManager; class QNetworkReply; -namespace OCC -{ +namespace OCC { class OWNCLOUDSYNC_EXPORT AbstractCredentials : public QObject { @@ -40,11 +39,11 @@ public: * Calling Account::setCredentials() will call this function. * Credentials only live as long as the underlying account object. */ - virtual void setAccount(Account* account); + virtual void setAccount(Account *account); virtual QString authType() const = 0; virtual QString user() const = 0; - virtual QNetworkAccessManager* getQNAM() const = 0; + virtual QNetworkAccessManager *getQNAM() const = 0; virtual bool ready() const = 0; virtual void fetchFromKeychain() = 0; virtual void askFromUser() = 0; @@ -75,7 +74,7 @@ Q_SIGNALS: void asked(); protected: - Account* _account; + Account *_account; }; } // namespace OCC diff --git a/src/libsync/creds/credentialscommon.cpp b/src/libsync/creds/credentialscommon.cpp index 34181a8b0..58b3cc24f 100644 --- a/src/libsync/creds/credentialscommon.cpp +++ b/src/libsync/creds/credentialscommon.cpp @@ -25,8 +25,7 @@ #include "account.h" #include "syncengine.h" -namespace OCC -{ +namespace OCC { } // namespace OCC diff --git a/src/libsync/creds/credentialscommon.h b/src/libsync/creds/credentialscommon.h index 9a66fbd54..e2cf1a6ff 100644 --- a/src/libsync/creds/credentialscommon.h +++ b/src/libsync/creds/credentialscommon.h @@ -18,8 +18,7 @@ #include "owncloudlib.h" -namespace OCC -{ +namespace OCC { } // namespace OCC diff --git a/src/libsync/creds/dummycredentials.cpp b/src/libsync/creds/dummycredentials.cpp index 8caad01d5..1e34c72e1 100644 --- a/src/libsync/creds/dummycredentials.cpp +++ b/src/libsync/creds/dummycredentials.cpp @@ -15,8 +15,7 @@ #include "creds/dummycredentials.h" #include "accessmanager.h" -namespace OCC -{ +namespace OCC { QString DummyCredentials::authType() const { @@ -28,7 +27,7 @@ QString DummyCredentials::user() const return _user; } -QNetworkAccessManager* DummyCredentials::getQNAM() const +QNetworkAccessManager *DummyCredentials::getQNAM() const { return new AccessManager; } @@ -55,6 +54,7 @@ void DummyCredentials::askFromUser() } void DummyCredentials::persist() -{} +{ +} } // namespace OCC diff --git a/src/libsync/creds/dummycredentials.h b/src/libsync/creds/dummycredentials.h index 650da7a9c..ad56a08dd 100644 --- a/src/libsync/creds/dummycredentials.h +++ b/src/libsync/creds/dummycredentials.h @@ -17,27 +17,25 @@ #include "creds/abstractcredentials.h" -namespace OCC -{ +namespace OCC { class OWNCLOUDSYNC_EXPORT DummyCredentials : public AbstractCredentials { Q_OBJECT public: - QString _user; QString _password; QString authType() const Q_DECL_OVERRIDE; QString user() const Q_DECL_OVERRIDE; - QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE; + QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE; bool ready() const Q_DECL_OVERRIDE; bool stillValid(QNetworkReply *reply) Q_DECL_OVERRIDE; void fetchFromKeychain() Q_DECL_OVERRIDE; void askFromUser() Q_DECL_OVERRIDE; void persist() Q_DECL_OVERRIDE; void invalidateToken() Q_DECL_OVERRIDE {} - void forgetSensitiveData() Q_DECL_OVERRIDE {}; + void forgetSensitiveData() Q_DECL_OVERRIDE{}; }; } // namespace OCC diff --git a/src/libsync/creds/httpcredentials.cpp b/src/libsync/creds/httpcredentials.cpp index 6355d4788..5f5e880cc 100644 --- a/src/libsync/creds/httpcredentials.cpp +++ b/src/libsync/creds/httpcredentials.cpp @@ -31,26 +31,30 @@ using namespace QKeychain; -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcHttpCredentials, "sync.credentials.http", QtInfoMsg) -namespace -{ -const char userC[] = "user"; -const char clientCertificatePEMC[] = "_clientCertificatePEM"; -const char clientKeyPEMC[] = "_clientKeyPEM"; -const char authenticationFailedC[] = "owncloud-authentication-failed"; +namespace { + const char userC[] = "user"; + const char clientCertificatePEMC[] = "_clientCertificatePEM"; + const char clientKeyPEMC[] = "_clientKeyPEM"; + const char authenticationFailedC[] = "owncloud-authentication-failed"; } // ns -class HttpCredentialsAccessManager : public AccessManager { +class HttpCredentialsAccessManager : public AccessManager +{ public: - HttpCredentialsAccessManager(const HttpCredentials *cred, QObject* parent = 0) - : AccessManager(parent), _cred(cred) {} + HttpCredentialsAccessManager(const HttpCredentials *cred, QObject *parent = 0) + : AccessManager(parent) + , _cred(cred) + { + } + protected: - QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) Q_DECL_OVERRIDE { - QByteArray credHash = QByteArray(_cred->user().toUtf8()+":"+_cred->password().toUtf8()).toBase64(); + QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) Q_DECL_OVERRIDE + { + QByteArray credHash = QByteArray(_cred->user().toUtf8() + ":" + _cred->password().toUtf8()).toBase64(); QNetworkRequest req(request); req.setRawHeader(QByteArray("Authorization"), QByteArray("Basic ") + credHash); @@ -65,6 +69,7 @@ protected: return AccessManager::createRequest(op, req, outgoingData); } + private: const HttpCredentials *_cred; }; @@ -84,12 +89,12 @@ HttpCredentials::HttpCredentials() } // From wizard -HttpCredentials::HttpCredentials(const QString& user, const QString& password, const QSslCertificate& certificate, const QSslKey& key) - : _user(user), - _password(password), - _ready(true), - _clientSslKey(key), - _clientSslCertificate(certificate) +HttpCredentials::HttpCredentials(const QString &user, const QString &password, const QSslCertificate &certificate, const QSslKey &key) + : _user(user) + , _password(password) + , _ready(true) + , _clientSslKey(key) + , _clientSslCertificate(certificate) { } @@ -108,7 +113,7 @@ QString HttpCredentials::password() const return _password; } -void HttpCredentials::setAccount(Account* account) +void HttpCredentials::setAccount(Account *account) { AbstractCredentials::setAccount(account); if (_user.isEmpty()) { @@ -116,12 +121,12 @@ void HttpCredentials::setAccount(Account* account) } } -QNetworkAccessManager* HttpCredentials::getQNAM() const +QNetworkAccessManager *HttpCredentials::getQNAM() const { - AccessManager* qnam = new HttpCredentialsAccessManager(this); + AccessManager *qnam = new HttpCredentialsAccessManager(this); - connect( qnam, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), - this, SLOT(slotAuthentication(QNetworkReply*,QAuthenticator*))); + connect(qnam, SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)), + this, SLOT(slotAuthentication(QNetworkReply *, QAuthenticator *))); return qnam; } @@ -142,7 +147,7 @@ void HttpCredentials::fetchFromKeychain() // User must be fetched from config file fetchUser(); - const QString kck = keychainKey(_account->url().toString(), _user ); + const QString kck = keychainKey(_account->url().toString(), _user); if (_ready) { Q_EMIT fetched(); @@ -155,18 +160,18 @@ void HttpCredentials::fetchFromKeychain() job->setKey(kck); qCDebug(lcHttpCredentials) << "-------- ----->" << _clientSslCertificate << _clientSslKey; - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadClientCertPEMJobDone(QKeychain::Job*))); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadClientCertPEMJobDone(QKeychain::Job *))); job->start(); } } -void HttpCredentials::slotReadClientCertPEMJobDone(QKeychain::Job* incoming) +void HttpCredentials::slotReadClientCertPEMJobDone(QKeychain::Job *incoming) { // Store PEM in memory - ReadPasswordJob *readJob = static_cast(incoming); + ReadPasswordJob *readJob = static_cast(incoming); if (readJob->error() == NoError && readJob->binaryData().length() > 0) { QList sslCertificateList = QSslCertificate::fromData(readJob->binaryData(), QSsl::Pem); - if(sslCertificateList.length() >= 1) { + if (sslCertificateList.length() >= 1) { _clientSslCertificate = sslCertificateList.at(0); } } @@ -178,14 +183,14 @@ void HttpCredentials::slotReadClientCertPEMJobDone(QKeychain::Job* incoming) job->setInsecureFallback(false); job->setKey(kck); - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadClientKeyPEMJobDone(QKeychain::Job*))); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadClientKeyPEMJobDone(QKeychain::Job *))); job->start(); } -void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job* incoming) +void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job *incoming) { // Store key in memory - ReadPasswordJob *readJob = static_cast(incoming); + ReadPasswordJob *readJob = static_cast(incoming); if (readJob->error() == NoError && readJob->binaryData().length() > 0) { QByteArray clientKeyPEM = readJob->binaryData(); @@ -207,13 +212,13 @@ void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job* incoming) } // Now fetch the actual server password - const QString kck = keychainKey(_account->url().toString(), _user ); + const QString kck = keychainKey(_account->url().toString(), _user); ReadPasswordJob *job = new ReadPasswordJob(Theme::instance()->appName()); addSettingsToJob(_account, job); job->setInsecureFallback(false); job->setKey(kck); - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadJobDone(QKeychain::Job*))); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadJobDone(QKeychain::Job *))); job->start(); } @@ -221,23 +226,23 @@ void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job* incoming) bool HttpCredentials::stillValid(QNetworkReply *reply) { return ((reply->error() != QNetworkReply::AuthenticationRequiredError) - // returned if user or password is incorrect - && (reply->error() != QNetworkReply::OperationCanceledError - || !reply->property(authenticationFailedC).toBool())); + // returned if user or password is incorrect + && (reply->error() != QNetworkReply::OperationCanceledError + || !reply->property(authenticationFailedC).toBool())); } void HttpCredentials::slotReadJobDone(QKeychain::Job *incomingJob) { - QKeychain::ReadPasswordJob *job = static_cast(incomingJob); + QKeychain::ReadPasswordJob *job = static_cast(incomingJob); _password = job->textData(); - if( _user.isEmpty()) { + if (_user.isEmpty()) { qCWarning(lcHttpCredentials) << "Strange: User is empty!"; } QKeychain::Error error = job->error(); - if( !_password.isEmpty() && error == NoError ) { + if (!_password.isEmpty() && error == NoError) { // All cool, the keychain did not come back with error. // Still, the password can be empty which indicates a problem and // the password dialog has to be opened. @@ -257,7 +262,7 @@ void HttpCredentials::slotReadJobDone(QKeychain::Job *incomingJob) void HttpCredentials::invalidateToken() { - if (! _password.isEmpty()) { + if (!_password.isEmpty()) { _previousPassword = _password; } _password = QString(); @@ -267,7 +272,7 @@ void HttpCredentials::invalidateToken() fetchUser(); const QString kck = keychainKey(_account->url().toString(), _user); - if( kck.isEmpty() ) { + if (kck.isEmpty()) { qCWarning(lcHttpCredentials) << "InvalidateToken: User is empty, bailing out!"; return; } @@ -325,7 +330,7 @@ void HttpCredentials::persist() WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName()); addSettingsToJob(_account, job); job->setInsecureFallback(false); - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteClientCertPEMJobDone(QKeychain::Job*))); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotWriteClientCertPEMJobDone(QKeychain::Job *))); job->setKey(keychainKey(_account->url().toString(), _user + clientCertificatePEMC)); job->setBinaryData(_clientSslCertificate.toPem()); job->start(); @@ -335,10 +340,10 @@ void HttpCredentials::slotWriteClientCertPEMJobDone(Job *incomingJob) { Q_UNUSED(incomingJob); // write ssl key - WritePasswordJob* job = new WritePasswordJob(Theme::instance()->appName()); + WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName()); addSettingsToJob(_account, job); job->setInsecureFallback(false); - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteClientKeyPEMJobDone(QKeychain::Job*))); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotWriteClientKeyPEMJobDone(QKeychain::Job *))); job->setKey(keychainKey(_account->url().toString(), _user + clientKeyPEMC)); job->setBinaryData(_clientSslKey.toPem()); job->start(); @@ -347,10 +352,10 @@ void HttpCredentials::slotWriteClientCertPEMJobDone(Job *incomingJob) void HttpCredentials::slotWriteClientKeyPEMJobDone(Job *incomingJob) { Q_UNUSED(incomingJob); - WritePasswordJob* job = new WritePasswordJob(Theme::instance()->appName()); + WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName()); addSettingsToJob(_account, job); job->setInsecureFallback(false); - connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteJobDone(QKeychain::Job*))); + connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotWriteJobDone(QKeychain::Job *))); job->setKey(keychainKey(_account->url().toString(), _user)); job->setTextData(_password); job->start(); @@ -365,11 +370,11 @@ void HttpCredentials::slotWriteJobDone(QKeychain::Job *job) default: qCWarning(lcHttpCredentials) << "Error while writing password" << job->errorString(); } - WritePasswordJob *wjob = qobject_cast(job); + WritePasswordJob *wjob = qobject_cast(job); wjob->deleteLater(); } -void HttpCredentials::slotAuthentication(QNetworkReply* reply, QAuthenticator* authenticator) +void HttpCredentials::slotAuthentication(QNetworkReply *reply, QAuthenticator *authenticator) { Q_UNUSED(authenticator) // Because of issue #4326, we need to set the login and password manually at every requests diff --git a/src/libsync/creds/httpcredentials.h b/src/libsync/creds/httpcredentials.h index 860329d9b..14118e924 100644 --- a/src/libsync/creds/httpcredentials.h +++ b/src/libsync/creds/httpcredentials.h @@ -30,19 +30,19 @@ class WritePasswordJob; class ReadPasswordJob; } -namespace OCC -{ +namespace OCC { class OWNCLOUDSYNC_EXPORT HttpCredentials : public AbstractCredentials { Q_OBJECT friend class HttpCredentialsAccessManager; + public: explicit HttpCredentials(); - HttpCredentials(const QString& user, const QString& password, const QSslCertificate& certificate = QSslCertificate(), const QSslKey& key = QSslKey()); + HttpCredentials(const QString &user, const QString &password, const QSslCertificate &certificate = QSslCertificate(), const QSslKey &key = QSslKey()); QString authType() const Q_DECL_OVERRIDE; - QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE; + QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE; bool ready() const Q_DECL_OVERRIDE; void fetchFromKeychain() Q_DECL_OVERRIDE; bool stillValid(QNetworkReply *reply) Q_DECL_OVERRIDE; @@ -55,18 +55,18 @@ public: virtual bool sslIsTrusted() { return false; } // To fetch the user name as early as possible - void setAccount(Account* account) Q_DECL_OVERRIDE; + void setAccount(Account *account) Q_DECL_OVERRIDE; private Q_SLOTS: - void slotAuthentication(QNetworkReply*, QAuthenticator*); + void slotAuthentication(QNetworkReply *, QAuthenticator *); - void slotReadClientCertPEMJobDone(QKeychain::Job*); - void slotReadClientKeyPEMJobDone(QKeychain::Job*); - void slotReadJobDone(QKeychain::Job*); + void slotReadClientCertPEMJobDone(QKeychain::Job *); + void slotReadClientKeyPEMJobDone(QKeychain::Job *); + void slotReadJobDone(QKeychain::Job *); - void slotWriteClientCertPEMJobDone(QKeychain::Job*); - void slotWriteClientKeyPEMJobDone(QKeychain::Job*); - void slotWriteJobDone(QKeychain::Job*); + void slotWriteClientCertPEMJobDone(QKeychain::Job *); + void slotWriteClientKeyPEMJobDone(QKeychain::Job *); + void slotWriteJobDone(QKeychain::Job *); void clearQNAMCache(); protected: diff --git a/src/libsync/creds/tokencredentials.cpp b/src/libsync/creds/tokencredentials.cpp index 53b2cbc89..9e5e5b39e 100644 --- a/src/libsync/creds/tokencredentials.cpp +++ b/src/libsync/creds/tokencredentials.cpp @@ -27,32 +27,36 @@ #include "creds/tokencredentials.h" -namespace OCC -{ +namespace OCC { Q_LOGGING_CATEGORY(lcTokenCredentials, "sync.credentials.token", QtInfoMsg) -namespace -{ +namespace { -const char authenticationFailedC[] = "owncloud-authentication-failed"; + const char authenticationFailedC[] = "owncloud-authentication-failed"; } // ns -class TokenCredentialsAccessManager : public AccessManager { +class TokenCredentialsAccessManager : public AccessManager +{ public: friend class TokenCredentials; - TokenCredentialsAccessManager(const TokenCredentials *cred, QObject* parent = 0) - : AccessManager(parent), _cred(cred) {} + TokenCredentialsAccessManager(const TokenCredentials *cred, QObject *parent = 0) + : AccessManager(parent) + , _cred(cred) + { + } + protected: - QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) { + QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) + { if (_cred->user().isEmpty() || _cred->password().isEmpty()) { qCWarning(lcTokenCredentials) << "Empty user/password provided!"; } QNetworkRequest req(request); - QByteArray credHash = QByteArray(_cred->user().toUtf8()+":"+_cred->password().toUtf8()).toBase64(); + QByteArray credHash = QByteArray(_cred->user().toUtf8() + ":" + _cred->password().toUtf8()).toBase64(); req.setRawHeader(QByteArray("Authorization"), QByteArray("Basic ") + credHash); // A pre-authenticated cookie @@ -63,22 +67,23 @@ protected: return AccessManager::createRequest(op, req, outgoingData); } + private: const TokenCredentials *_cred; }; TokenCredentials::TokenCredentials() - : _user(), - _password(), - _ready(false) + : _user() + , _password() + , _ready(false) { } -TokenCredentials::TokenCredentials(const QString& user, const QString& password, const QString &token) - : _user(user), - _password(password), - _token(token), - _ready(true) +TokenCredentials::TokenCredentials(const QString &user, const QString &password, const QString &token) + : _user(user) + , _password(password) + , _token(token) + , _ready(true) { } @@ -97,12 +102,12 @@ QString TokenCredentials::password() const return _password; } -QNetworkAccessManager* TokenCredentials::getQNAM() const +QNetworkAccessManager *TokenCredentials::getQNAM() const { - AccessManager* qnam = new TokenCredentialsAccessManager(this); + AccessManager *qnam = new TokenCredentialsAccessManager(this); - connect( qnam, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), - this, SLOT(slotAuthentication(QNetworkReply*,QAuthenticator*))); + connect(qnam, SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)), + this, SLOT(slotAuthentication(QNetworkReply *, QAuthenticator *))); return qnam; } @@ -126,9 +131,9 @@ void TokenCredentials::askFromUser() bool TokenCredentials::stillValid(QNetworkReply *reply) { return ((reply->error() != QNetworkReply::AuthenticationRequiredError) - // returned if user/password or token are incorrect - && (reply->error() != QNetworkReply::OperationCanceledError - || !reply->property(authenticationFailedC).toBool())); + // returned if user/password or token are incorrect + && (reply->error() != QNetworkReply::OperationCanceledError + || !reply->property(authenticationFailedC).toBool())); } void TokenCredentials::invalidateToken() @@ -151,7 +156,7 @@ void TokenCredentials::persist() } -void TokenCredentials::slotAuthentication(QNetworkReply* reply, QAuthenticator* authenticator) +void TokenCredentials::slotAuthentication(QNetworkReply *reply, QAuthenticator *authenticator) { Q_UNUSED(authenticator) // we cannot use QAuthenticator, because it sends username and passwords with latin1 diff --git a/src/libsync/creds/tokencredentials.h b/src/libsync/creds/tokencredentials.h index 27da7b852..e170ea9db 100644 --- a/src/libsync/creds/tokencredentials.h +++ b/src/libsync/creds/tokencredentials.h @@ -27,8 +27,7 @@ namespace QKeychain { class Job; } -namespace OCC -{ +namespace OCC { class TokenCredentialsAccessManager; class OWNCLOUDSYNC_EXPORT TokenCredentials : public AbstractCredentials @@ -38,10 +37,10 @@ class OWNCLOUDSYNC_EXPORT TokenCredentials : public AbstractCredentials public: friend class TokenCredentialsAccessManager; TokenCredentials(); - TokenCredentials(const QString& user, const QString& password, const QString &token); + TokenCredentials(const QString &user, const QString &password, const QString &token); QString authType() const Q_DECL_OVERRIDE; - QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE; + QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE; bool ready() const Q_DECL_OVERRIDE; void askFromUser() Q_DECL_OVERRIDE; void fetchFromKeychain() Q_DECL_OVERRIDE; @@ -53,7 +52,7 @@ public: QString password() const; private Q_SLOTS: - void slotAuthentication(QNetworkReply*, QAuthenticator*); + void slotAuthentication(QNetworkReply *, QAuthenticator *); private: QString _user; diff --git a/src/libsync/discoveryphase.cpp b/src/libsync/discoveryphase.cpp index 9a8be41aa..c4c3c8743 100644 --- a/src/libsync/discoveryphase.cpp +++ b/src/libsync/discoveryphase.cpp @@ -85,12 +85,11 @@ bool DiscoveryJob::isInSelectiveSyncBlackList(const char *path) const int DiscoveryJob::isInSelectiveSyncBlackListCallback(void *data, const char *path) { - return static_cast(data)->isInSelectiveSyncBlackList(path); + return static_cast(data)->isInSelectiveSyncBlackList(path); } -bool DiscoveryJob::checkSelectiveSyncNewFolder(const QString& path, const char *remotePerm) +bool DiscoveryJob::checkSelectiveSyncNewFolder(const QString &path, const char *remotePerm) { - if (_syncOptions._confirmExternalStorage && std::strchr(remotePerm, 'M')) { // 'M' in the permission means external storage. @@ -107,7 +106,7 @@ bool DiscoveryJob::checkSelectiveSyncNewFolder(const QString& path, const char * return true; } - // If this path or the parent is in the white list, then we do not block this file + // If this path or the parent is in the white list, then we do not block this file if (findPathInList(_selectiveSyncWhiteList, path)) { return false; } @@ -135,9 +134,12 @@ bool DiscoveryJob::checkSelectiveSyncNewFolder(const QString& path, const char * // it is not too big, put it in the white list (so we will not do more query for the children) // and and do not block. auto p = path; - if (!p.endsWith(QLatin1Char('/'))) { p += QLatin1Char('/'); } + if (!p.endsWith(QLatin1Char('/'))) { + p += QLatin1Char('/'); + } _selectiveSyncWhiteList.insert(std::upper_bound(_selectiveSyncWhiteList.begin(), - _selectiveSyncWhiteList.end(), p), p); + _selectiveSyncWhiteList.end(), p), + p); return false; } @@ -145,15 +147,15 @@ bool DiscoveryJob::checkSelectiveSyncNewFolder(const QString& path, const char * int DiscoveryJob::checkSelectiveSyncNewFolderCallback(void *data, const char *path, const char *remotePerm) { - return static_cast(data)->checkSelectiveSyncNewFolder(QString::fromUtf8(path), remotePerm); + return static_cast(data)->checkSelectiveSyncNewFolder(QString::fromUtf8(path), remotePerm); } -void DiscoveryJob::update_job_update_callback (bool local, - const char *dirUrl, - void *userdata) +void DiscoveryJob::update_job_update_callback(bool local, + const char *dirUrl, + void *userdata) { - DiscoveryJob *updateJob = static_cast(userdata); + DiscoveryJob *updateJob = static_cast(userdata); if (updateJob) { // Don't wanna overload the UI if (!updateJob->_lastUpdateProgressCallbackCall.isValid()) { @@ -166,69 +168,70 @@ void DiscoveryJob::update_job_update_callback (bool local, QByteArray pPath(dirUrl); int indx = pPath.lastIndexOf('/'); - if(indx>-1) { - const QString path = QUrl::fromPercentEncoding( pPath.mid(indx+1)); + if (indx > -1) { + const QString path = QUrl::fromPercentEncoding(pPath.mid(indx + 1)); emit updateJob->folderDiscovered(local, path); } } } // Only use for error cases! It will always set an error errno -int get_errno_from_http_errcode( int err, const QString & reason ) { +int get_errno_from_http_errcode(int err, const QString &reason) +{ int new_errno = EIO; - switch(err) { - case 401: /* Unauthorized */ - case 402: /* Payment Required */ - case 407: /* Proxy Authentication Required */ + switch (err) { + case 401: /* Unauthorized */ + case 402: /* Payment Required */ + case 407: /* Proxy Authentication Required */ case 405: new_errno = EPERM; break; - case 301: /* Moved Permanently */ - case 303: /* See Other */ - case 404: /* Not Found */ - case 410: /* Gone */ + case 301: /* Moved Permanently */ + case 303: /* See Other */ + case 404: /* Not Found */ + case 410: /* Gone */ new_errno = ENOENT; break; - case 408: /* Request Timeout */ - case 504: /* Gateway Timeout */ + case 408: /* Request Timeout */ + case 504: /* Gateway Timeout */ new_errno = EAGAIN; break; - case 423: /* Locked */ + case 423: /* Locked */ new_errno = EACCES; break; - case 403: /* Forbidden */ + case 403: /* Forbidden */ new_errno = ERRNO_FORBIDDEN; break; - case 400: /* Bad Request */ - case 409: /* Conflict */ - case 411: /* Length Required */ - case 412: /* Precondition Failed */ - case 414: /* Request-URI Too Long */ - case 415: /* Unsupported Media Type */ - case 424: /* Failed Dependency */ - case 501: /* Not Implemented */ + case 400: /* Bad Request */ + case 409: /* Conflict */ + case 411: /* Length Required */ + case 412: /* Precondition Failed */ + case 414: /* Request-URI Too Long */ + case 415: /* Unsupported Media Type */ + case 424: /* Failed Dependency */ + case 501: /* Not Implemented */ new_errno = EINVAL; break; - case 507: /* Insufficient Storage */ + case 507: /* Insufficient Storage */ new_errno = ENOSPC; break; - case 206: /* Partial Content */ - case 300: /* Multiple Choices */ - case 302: /* Found */ - case 305: /* Use Proxy */ - case 306: /* (Unused) */ - case 307: /* Temporary Redirect */ - case 406: /* Not Acceptable */ - case 416: /* Requested Range Not Satisfiable */ - case 417: /* Expectation Failed */ - case 422: /* Unprocessable Entity */ - case 500: /* Internal Server Error */ - case 502: /* Bad Gateway */ - case 505: /* HTTP Version Not Supported */ + case 206: /* Partial Content */ + case 300: /* Multiple Choices */ + case 302: /* Found */ + case 305: /* Use Proxy */ + case 306: /* (Unused) */ + case 307: /* Temporary Redirect */ + case 406: /* Not Acceptable */ + case 416: /* Requested Range Not Satisfiable */ + case 417: /* Expectation Failed */ + case 422: /* Unprocessable Entity */ + case 500: /* Internal Server Error */ + case 502: /* Bad Gateway */ + case 505: /* HTTP Version Not Supported */ new_errno = EIO; break; - case 503: /* Service Unavailable */ + case 503: /* Service Unavailable */ // https://github.com/owncloud/core/pull/26145/files if (reason == "Storage not available" || reason == "Storage is temporarily not available") { new_errno = ERRNO_STORAGE_UNAVAILABLE; @@ -236,7 +239,7 @@ int get_errno_from_http_errcode( int err, const QString & reason ) { new_errno = ERRNO_SERVICE_UNAVAILABLE; } break; - case 413: /* Request Entity too Large */ + case 413: /* Request Entity too Large */ new_errno = EFBIG; break; default: @@ -246,9 +249,13 @@ int get_errno_from_http_errcode( int err, const QString & reason ) { } - DiscoverySingleDirectoryJob::DiscoverySingleDirectoryJob(const AccountPtr &account, const QString &path, QObject *parent) - : QObject(parent), _subPath(path), _account(account), _ignoredFirst(false), _isRootPath(false), _isExternalStorage(false) + : QObject(parent) + , _subPath(path) + , _account(account) + , _ignoredFirst(false) + , _isRootPath(false) + , _isExternalStorage(false) { } @@ -258,17 +265,22 @@ void DiscoverySingleDirectoryJob::start() LsColJob *lsColJob = new LsColJob(_account, _subPath, this); QList props; - props << "resourcetype" << "getlastmodified" << "getcontentlength" << "getetag" - << "http://owncloud.org/ns:id" << "http://owncloud.org/ns:downloadURL" - << "http://owncloud.org/ns:dDC" << "http://owncloud.org/ns:permissions"; + props << "resourcetype" + << "getlastmodified" + << "getcontentlength" + << "getetag" + << "http://owncloud.org/ns:id" + << "http://owncloud.org/ns:downloadURL" + << "http://owncloud.org/ns:dDC" + << "http://owncloud.org/ns:permissions"; if (_isRootPath) props << "http://owncloud.org/ns:data-fingerprint"; lsColJob->setProperties(props); - QObject::connect(lsColJob, SIGNAL(directoryListingIterated(QString,QMap)), - this, SLOT(directoryListingIteratedSlot(QString,QMap))); - QObject::connect(lsColJob, SIGNAL(finishedWithError(QNetworkReply*)), this, SLOT(lsJobFinishedWithErrorSlot(QNetworkReply*))); + QObject::connect(lsColJob, SIGNAL(directoryListingIterated(QString, QMap)), + this, SLOT(directoryListingIteratedSlot(QString, QMap))); + QObject::connect(lsColJob, SIGNAL(finishedWithError(QNetworkReply *)), this, SLOT(lsJobFinishedWithErrorSlot(QNetworkReply *))); QObject::connect(lsColJob, SIGNAL(finishedWithoutError()), this, SLOT(lsJobFinishedWithoutErrorSlot())); lsColJob->start(); @@ -282,9 +294,9 @@ void DiscoverySingleDirectoryJob::abort() } } -static csync_vio_file_stat_t* propertyMapToFileStat(const QMap &map) +static csync_vio_file_stat_t *propertyMapToFileStat(const QMap &map) { - csync_vio_file_stat_t* file_stat = csync_vio_file_stat_new(); + csync_vio_file_stat_t *file_stat = csync_vio_file_stat_new(); for (auto it = map.constBegin(); it != map.constEnd(); ++it) { QString property = it.key(); @@ -296,7 +308,7 @@ static csync_vio_file_stat_t* propertyMapToFileStat(const QMap file_stat->type = CSYNC_VIO_FILE_TYPE_REGULAR; } file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE; - } else if (property == "getlastmodified") { + } else if (property == "getlastmodified") { file_stat->mtime = oc_httpdate_parse(value.toUtf8()); file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_MTIME; } else if (property == "getcontentlength") { @@ -337,7 +349,7 @@ static csync_vio_file_stat_t* propertyMapToFileStat(const QMap return file_stat; } -void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap &map) +void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap &map) { if (!_ignoredFirst) { // The first entry is for the folder itself, we should process it differently. @@ -373,24 +385,24 @@ void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, con purposes in the desktop client, we only need to know about the mount points. So replace the 'M' by a 'm' for every sub entries in an external storage */ std::replace(file_stat->remotePerm, file_stat->remotePerm + strlen(file_stat->remotePerm), - 'M', 'm'); + 'M', 'm'); } QStringRef fileRef(&file); int slashPos = file.lastIndexOf(QLatin1Char('/')); - if( slashPos > -1 ) { - fileRef = file.midRef(slashPos+1); + if (slashPos > -1) { + fileRef = file.midRef(slashPos + 1); } _results.append(file_stat); } //This works in concerto with the RequestEtagJob and the Folder object to check if the remote folder changed. if (map.contains("getetag")) { - _etagConcatenation += map.value("getetag"); + _etagConcatenation += map.value("getetag"); - if (_firstEtag.isEmpty()) { - _firstEtag = map.value("getetag"); // for directory itself - } + if (_firstEtag.isEmpty()) { + _firstEtag = map.value("getetag"); // for directory itself + } } } @@ -437,12 +449,12 @@ void DiscoveryMainThread::setupHooks(DiscoveryJob *discoveryJob, const QString & _discoveryJob = discoveryJob; _pathPrefix = pathPrefix; - connect(discoveryJob, SIGNAL(doOpendirSignal(QString,DiscoveryDirectoryResult*)), - this, SLOT(doOpendirSlot(QString,DiscoveryDirectoryResult*)), - Qt::QueuedConnection); - connect(discoveryJob, SIGNAL(doGetSizeSignal(QString,qint64*)), - this, SLOT(doGetSizeSlot(QString,qint64*)), - Qt::QueuedConnection); + connect(discoveryJob, SIGNAL(doOpendirSignal(QString, DiscoveryDirectoryResult *)), + this, SLOT(doOpendirSlot(QString, DiscoveryDirectoryResult *)), + Qt::QueuedConnection); + connect(discoveryJob, SIGNAL(doGetSizeSignal(QString, qint64 *)), + this, SLOT(doGetSizeSlot(QString, qint64 *)), + Qt::QueuedConnection); } // Coming from owncloud_opendir -> DiscoveryJob::vio_opendir_hook -> doOpendirSignal @@ -459,7 +471,7 @@ void DiscoveryMainThread::doOpendirSlot(const QString &subPath, DiscoveryDirecto } // emit _discoveryJob->folderDiscovered(false, subPath); - _discoveryJob->update_job_update_callback (false, subPath.toUtf8(), _discoveryJob); + _discoveryJob->update_job_update_callback(false, subPath.toUtf8(), _discoveryJob); // Result gets written in there _currentDiscoveryDirectoryResult = r; @@ -468,15 +480,15 @@ void DiscoveryMainThread::doOpendirSlot(const QString &subPath, DiscoveryDirecto // Schedule the DiscoverySingleDirectoryJob _singleDirJob = new DiscoverySingleDirectoryJob(_account, fullPath, this); QObject::connect(_singleDirJob, SIGNAL(finishedWithResult(const QList &)), - this, SLOT(singleDirectoryJobResultSlot(const QList &))); - QObject::connect(_singleDirJob, SIGNAL(finishedWithError(int,QString)), - this, SLOT(singleDirectoryJobFinishedWithErrorSlot(int,QString))); + this, SLOT(singleDirectoryJobResultSlot(const QList &))); + QObject::connect(_singleDirJob, SIGNAL(finishedWithError(int, QString)), + this, SLOT(singleDirectoryJobFinishedWithErrorSlot(int, QString))); QObject::connect(_singleDirJob, SIGNAL(firstDirectoryPermissions(QString)), - this, SLOT(singleDirectoryJobFirstDirectoryPermissionsSlot(QString))); + this, SLOT(singleDirectoryJobFirstDirectoryPermissionsSlot(QString))); QObject::connect(_singleDirJob, SIGNAL(etagConcatenation(QString)), - this, SIGNAL(etagConcatenation(QString))); + this, SIGNAL(etagConcatenation(QString))); QObject::connect(_singleDirJob, SIGNAL(etag(QString)), - this, SIGNAL(etag(QString))); + this, SIGNAL(etag(QString))); if (!_firstFolderProcessed) { _singleDirJob->setIsRootPath(); @@ -486,7 +498,7 @@ void DiscoveryMainThread::doOpendirSlot(const QString &subPath, DiscoveryDirecto } -void DiscoveryMainThread::singleDirectoryJobResultSlot(const QList & result) +void DiscoveryMainThread::singleDirectoryJobResultSlot(const QList &result) { if (!_currentDiscoveryDirectoryResult) { return; // possibly aborted @@ -516,9 +528,9 @@ void DiscoveryMainThread::singleDirectoryJobFinishedWithErrorSlot(int csyncErrno } qCDebug(lcDiscovery) << csyncErrnoCode << msg; - _currentDiscoveryDirectoryResult->code = csyncErrnoCode; - _currentDiscoveryDirectoryResult->msg = msg; - _currentDiscoveryDirectoryResult = 0; // the sync thread owns it now + _currentDiscoveryDirectoryResult->code = csyncErrnoCode; + _currentDiscoveryDirectoryResult->msg = msg; + _currentDiscoveryDirectoryResult = 0; // the sync thread owns it now _discoveryJob->_vioMutex.lock(); _discoveryJob->_vioWaitCondition.wakeAll(); @@ -534,7 +546,7 @@ void DiscoveryMainThread::singleDirectoryJobFirstDirectoryPermissionsSlot(const } } -void DiscoveryMainThread::doGetSizeSlot(const QString& path, qint64* result) +void DiscoveryMainThread::doGetSizeSlot(const QString &path, qint64 *result) { QString fullPath = _pathPrefix; if (!_pathPrefix.endsWith('/')) { @@ -550,17 +562,18 @@ void DiscoveryMainThread::doGetSizeSlot(const QString& path, qint64* result) // Schedule the DiscoverySingleDirectoryJob auto propfindJob = new PropfindJob(_account, fullPath, this); - propfindJob->setProperties(QList() << "resourcetype" << "http://owncloud.org/ns:size"); + propfindJob->setProperties(QList() << "resourcetype" + << "http://owncloud.org/ns:size"); QObject::connect(propfindJob, SIGNAL(finishedWithError()), - this, SLOT(slotGetSizeFinishedWithError())); + this, SLOT(slotGetSizeFinishedWithError())); QObject::connect(propfindJob, SIGNAL(result(QVariantMap)), - this, SLOT(slotGetSizeResult(QVariantMap))); + this, SLOT(slotGetSizeResult(QVariantMap))); propfindJob->start(); } void DiscoveryMainThread::slotGetSizeFinishedWithError() { - if (! _currentGetSizeResult) { + if (!_currentGetSizeResult) { return; // possibly aborted } @@ -569,12 +582,11 @@ void DiscoveryMainThread::slotGetSizeFinishedWithError() _currentGetSizeResult = 0; QMutexLocker locker(&_discoveryJob->_vioMutex); _discoveryJob->_vioWaitCondition.wakeAll(); - } void DiscoveryMainThread::slotGetSizeResult(const QVariantMap &map) { - if (! _currentGetSizeResult) { + if (!_currentGetSizeResult) { return; // possibly aborted } @@ -586,12 +598,11 @@ void DiscoveryMainThread::slotGetSizeResult(const QVariantMap &map) } - - // called from SyncEngine -void DiscoveryMainThread::abort() { +void DiscoveryMainThread::abort() +{ if (_singleDirJob) { - _singleDirJob->disconnect(SIGNAL(finishedWithError(int,QString)), this); + _singleDirJob->disconnect(SIGNAL(finishedWithError(int, QString)), this); _singleDirJob->disconnect(SIGNAL(firstDirectoryPermissions(QString)), this); _singleDirJob->disconnect(SIGNAL(finishedWithResult(const QList &)), this); _singleDirJob->abort(); @@ -612,10 +623,10 @@ void DiscoveryMainThread::abort() { } } -csync_vio_handle_t* DiscoveryJob::remote_vio_opendir_hook (const char *url, - void *userdata) +csync_vio_handle_t *DiscoveryJob::remote_vio_opendir_hook(const char *url, + void *userdata) { - DiscoveryJob *discoveryJob = static_cast(userdata); + DiscoveryJob *discoveryJob = static_cast(userdata); if (discoveryJob) { qCDebug(lcDiscovery) << discoveryJob << url << "Calling into main thread..."; @@ -635,7 +646,7 @@ csync_vio_handle_t* DiscoveryJob::remote_vio_opendir_hook (const char *url, qCDebug(lcDiscovery) << directoryResult->code << "when opening" << url << "msg=" << directoryResult->msg; errno = directoryResult->code; // save the error string to the context - discoveryJob->_csync_ctx->error_string = qstrdup( directoryResult->msg.toUtf8().constData() ); + discoveryJob->_csync_ctx->error_string = qstrdup(directoryResult->msg.toUtf8().constData()); return NULL; } @@ -645,12 +656,12 @@ csync_vio_handle_t* DiscoveryJob::remote_vio_opendir_hook (const char *url, } -csync_vio_file_stat_t* DiscoveryJob::remote_vio_readdir_hook (csync_vio_handle_t *dhandle, - void *userdata) +csync_vio_file_stat_t *DiscoveryJob::remote_vio_readdir_hook(csync_vio_handle_t *dhandle, + void *userdata) { - DiscoveryJob *discoveryJob = static_cast(userdata); + DiscoveryJob *discoveryJob = static_cast(userdata); if (discoveryJob) { - DiscoveryDirectoryResult *directoryResult = static_cast(dhandle); + DiscoveryDirectoryResult *directoryResult = static_cast(dhandle); if (directoryResult->listIndex < directoryResult->list.size()) { csync_vio_file_stat_t *file_stat = directoryResult->list.at(directoryResult->listIndex++).data(); // Make a copy, csync_update will delete the copy @@ -660,19 +671,20 @@ csync_vio_file_stat_t* DiscoveryJob::remote_vio_readdir_hook (csync_vio_handle_t return NULL; } -void DiscoveryJob::remote_vio_closedir_hook (csync_vio_handle_t *dhandle, void *userdata) +void DiscoveryJob::remote_vio_closedir_hook(csync_vio_handle_t *dhandle, void *userdata) { - DiscoveryJob *discoveryJob = static_cast(userdata); + DiscoveryJob *discoveryJob = static_cast(userdata); if (discoveryJob) { - DiscoveryDirectoryResult *directoryResult = static_cast (dhandle); + DiscoveryDirectoryResult *directoryResult = static_cast(dhandle); QString path = directoryResult->path; qCDebug(lcDiscovery) << discoveryJob << path; - // just deletes the struct and the iterator, the data itself is owned by the SyncEngine/DiscoveryMainThread + // just deletes the struct and the iterator, the data itself is owned by the SyncEngine/DiscoveryMainThread delete directoryResult; } } -void DiscoveryJob::start() { +void DiscoveryJob::start() +{ _selectiveSyncBlackList.sort(); _selectiveSyncWhiteList.sort(); _csync_ctx->callbacks.update_callback_userdata = this; @@ -698,5 +710,4 @@ void DiscoveryJob::start() { emit finished(ret); deleteLater(); } - } diff --git a/src/libsync/discoveryphase.h b/src/libsync/discoveryphase.h index c59134093..9603c39ab 100644 --- a/src/libsync/discoveryphase.h +++ b/src/libsync/discoveryphase.h @@ -34,7 +34,8 @@ class Account; * if the files are new, or changed. */ -struct SyncOptions { +struct SyncOptions +{ SyncOptions() : _newBigFolderSizeLimit(-1) , _confirmExternalStorage(false) @@ -42,7 +43,8 @@ struct SyncOptions { , _minChunkSize(1 * 1000 * 1000) // 1 MB , _maxChunkSize(100 * 1000 * 1000) // 100 MB , _targetChunkUploadDuration(60 * 1000) // 1 minute - {} + { + } /** Maximum size (in Bytes) a folder can have without asking for confirmation. * -1 means infinite */ @@ -77,18 +79,23 @@ struct SyncOptions { * @brief The FileStatPointer class * @ingroup libsync */ -class FileStatPointer { +class FileStatPointer +{ public: FileStatPointer(csync_vio_file_stat_t *stat) : _stat(stat) - { } + { + } FileStatPointer(const FileStatPointer &other) : _stat(csync_vio_file_stat_copy(other._stat)) - { } - ~FileStatPointer() { + { + } + ~FileStatPointer() + { csync_vio_file_stat_destroy(_stat); } - FileStatPointer &operator=(const FileStatPointer &other) { + FileStatPointer &operator=(const FileStatPointer &other) + { csync_vio_file_stat_destroy(_stat); _stat = csync_vio_file_stat_copy(other._stat); return *this; @@ -100,13 +107,18 @@ private: csync_vio_file_stat_t *_stat; }; -struct DiscoveryDirectoryResult { +struct DiscoveryDirectoryResult +{ QString path; QString msg; int code; QList list; int listIndex; - DiscoveryDirectoryResult() : code(EIO), listIndex(0) { } + DiscoveryDirectoryResult() + : code(EIO) + , listIndex(0) + { + } }; /** @@ -116,7 +128,8 @@ struct DiscoveryDirectoryResult { * * @ingroup libsync */ -class DiscoverySingleDirectoryJob : public QObject { +class DiscoverySingleDirectoryJob : public QObject +{ Q_OBJECT public: explicit DiscoverySingleDirectoryJob(const AccountPtr &account, const QString &path, QObject *parent = 0); @@ -132,9 +145,10 @@ signals: void finishedWithResult(const QList &); void finishedWithError(int csyncErrnoCode, const QString &msg); private slots: - void directoryListingIteratedSlot(QString, const QMap&); + void directoryListingIteratedSlot(QString, const QMap &); void lsJobFinishedWithoutErrorSlot(); - void lsJobFinishedWithErrorSlot(QNetworkReply*); + void lsJobFinishedWithErrorSlot(QNetworkReply *); + private: QList _results; QString _subPath; @@ -156,7 +170,8 @@ public: // Lives in main thread. Deleted by the SyncEngine class DiscoveryJob; -class DiscoveryMainThread : public QObject { +class DiscoveryMainThread : public QObject +{ Q_OBJECT QPointer _discoveryJob; @@ -168,9 +183,14 @@ class DiscoveryMainThread : public QObject { bool _firstFolderProcessed; public: - DiscoveryMainThread(AccountPtr account) : QObject(), _account(account), - _currentDiscoveryDirectoryResult(0), _currentGetSizeResult(0), _firstFolderProcessed(false) - { } + DiscoveryMainThread(AccountPtr account) + : QObject() + , _account(account) + , _currentDiscoveryDirectoryResult(0) + , _currentGetSizeResult(0) + , _firstFolderProcessed(false) + { + } void abort(); QByteArray _dataFingerprint; @@ -178,21 +198,22 @@ public: public slots: // From DiscoveryJob: - void doOpendirSlot(const QString &url, DiscoveryDirectoryResult* ); - void doGetSizeSlot(const QString &path ,qint64 *result); + void doOpendirSlot(const QString &url, DiscoveryDirectoryResult *); + void doGetSizeSlot(const QString &path, qint64 *result); // From Job: void singleDirectoryJobResultSlot(const QList &); void singleDirectoryJobFinishedWithErrorSlot(int csyncErrnoCode, const QString &msg); - void singleDirectoryJobFirstDirectoryPermissionsSlot(const QString&); + void singleDirectoryJobFirstDirectoryPermissionsSlot(const QString &); void slotGetSizeFinishedWithError(); - void slotGetSizeResult(const QVariantMap&); + void slotGetSizeResult(const QVariantMap &); signals: void etag(const QString &); void etagConcatenation(const QString &); + public: - void setupHooks(DiscoveryJob* discoveryJob, const QString &pathPrefix); + void setupHooks(DiscoveryJob *discoveryJob, const QString &pathPrefix); }; /** @@ -202,42 +223,45 @@ public: * * @ingroup libsync */ -class DiscoveryJob : public QObject { +class DiscoveryJob : public QObject +{ Q_OBJECT friend class DiscoveryMainThread; - CSYNC *_csync_ctx; - csync_log_callback _log_callback; - int _log_level; - QElapsedTimer _lastUpdateProgressCallbackCall; + CSYNC *_csync_ctx; + csync_log_callback _log_callback; + int _log_level; + QElapsedTimer _lastUpdateProgressCallbackCall; /** * return true if the given path should be ignored, * false if the path should be synced */ - bool isInSelectiveSyncBlackList(const char* path) const; + bool isInSelectiveSyncBlackList(const char *path) const; static int isInSelectiveSyncBlackListCallback(void *, const char *); bool checkSelectiveSyncNewFolder(const QString &path, const char *remotePerm); - static int checkSelectiveSyncNewFolderCallback(void* data, const char* path, const char* remotePerm); + static int checkSelectiveSyncNewFolderCallback(void *data, const char *path, const char *remotePerm); // Just for progress - static void update_job_update_callback (bool local, - const char *dirname, - void *userdata); + static void update_job_update_callback(bool local, + const char *dirname, + void *userdata); // For using QNAM to get the directory listings - static csync_vio_handle_t* remote_vio_opendir_hook (const char *url, - void *userdata); - static csync_vio_file_stat_t* remote_vio_readdir_hook (csync_vio_handle_t *dhandle, - void *userdata); - static void remote_vio_closedir_hook (csync_vio_handle_t *dhandle, - void *userdata); + static csync_vio_handle_t *remote_vio_opendir_hook(const char *url, + void *userdata); + static csync_vio_file_stat_t *remote_vio_readdir_hook(csync_vio_handle_t *dhandle, + void *userdata); + static void remote_vio_closedir_hook(csync_vio_handle_t *dhandle, + void *userdata); QMutex _vioMutex; QWaitCondition _vioWaitCondition; public: - explicit DiscoveryJob(CSYNC *ctx, QObject* parent = 0) - : QObject(parent), _csync_ctx(ctx) { + explicit DiscoveryJob(CSYNC *ctx, QObject *parent = 0) + : QObject(parent) + , _csync_ctx(ctx) + { // We need to forward the log property as csync uses thread local // and updates run in another thread _log_callback = csync_get_log_callback(); @@ -253,11 +277,10 @@ signals: void folderDiscovered(bool local, QString folderUrl); // After the discovery job has been woken up again (_vioWaitCondition) - void doOpendirSignal(QString url, DiscoveryDirectoryResult*); + void doOpendirSignal(QString url, DiscoveryDirectoryResult *); void doGetSizeSignal(const QString &path, qint64 *result); // A new folder was discovered and was not synced because of the confirmation feature void newBigFolder(const QString &folder, bool isExternal); }; - } diff --git a/src/libsync/excludedfiles.cpp b/src/libsync/excludedfiles.cpp index d9793ce0f..7bd66ac9c 100644 --- a/src/libsync/excludedfiles.cpp +++ b/src/libsync/excludedfiles.cpp @@ -25,7 +25,7 @@ extern "C" { using namespace OCC; -ExcludedFiles::ExcludedFiles(c_strlist_t** excludesPtr) +ExcludedFiles::ExcludedFiles(c_strlist_t **excludesPtr) : _excludesPtr(excludesPtr) { } @@ -35,14 +35,14 @@ ExcludedFiles::~ExcludedFiles() c_strlist_destroy(*_excludesPtr); } -ExcludedFiles& ExcludedFiles::instance() +ExcludedFiles &ExcludedFiles::instance() { - static c_strlist_t* globalExcludes; + static c_strlist_t *globalExcludes; static ExcludedFiles inst(&globalExcludes); return inst; } -void ExcludedFiles::addExcludeFilePath(const QString& path) +void ExcludedFiles::addExcludeFilePath(const QString &path) { _excludeFiles.insert(path); } @@ -60,7 +60,7 @@ bool ExcludedFiles::reloadExcludes() *_excludesPtr = NULL; bool success = true; - foreach (const QString& file, _excludeFiles) { + foreach (const QString &file, _excludeFiles) { if (csync_exclude_load(file.toUtf8(), _excludesPtr) < 0) success = false; } @@ -68,22 +68,22 @@ bool ExcludedFiles::reloadExcludes() } bool ExcludedFiles::isExcluded( - const QString& filePath, - const QString& basePath, - bool excludeHidden) const + const QString &filePath, + const QString &basePath, + bool excludeHidden) const { if (!filePath.startsWith(basePath, Utility::fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive)) { // Mark paths we're not responsible for as excluded... return true; } - if( excludeHidden ) { + if (excludeHidden) { QString path = filePath; // Check all path subcomponents, but to *not* check the base path: // We do want to be able to sync with a hidden folder as the target. while (path.size() > basePath.size()) { QFileInfo fi(path); - if( fi.isHidden() || fi.fileName().startsWith(QLatin1Char('.')) ) { + if (fi.isHidden() || fi.fileName().startsWith(QLatin1Char('.'))) { return true; } diff --git a/src/libsync/excludedfiles.h b/src/libsync/excludedfiles.h index 97e3a98da..f8a18cd8d 100644 --- a/src/libsync/excludedfiles.h +++ b/src/libsync/excludedfiles.h @@ -35,9 +35,9 @@ class OWNCLOUDSYNC_EXPORT ExcludedFiles : public QObject { Q_OBJECT public: - static ExcludedFiles & instance(); + static ExcludedFiles &instance(); - ExcludedFiles(c_strlist_t** excludesPtr); + ExcludedFiles(c_strlist_t **excludesPtr); ~ExcludedFiles(); /** @@ -45,7 +45,7 @@ public: * * Does not load the file. Use reloadExcludes() afterwards. */ - void addExcludeFilePath(const QString& path); + void addExcludeFilePath(const QString &path); /** * Checks whether a file or directory should be excluded. @@ -54,9 +54,9 @@ public: * @param basePath folder path from which to apply exclude rules */ bool isExcluded( - const QString& filePath, - const QString& basePath, - bool excludeHidden) const; + const QString &filePath, + const QString &basePath, + bool excludeHidden) const; #ifdef WITH_TESTING void addExcludeExpr(const QString &expr); @@ -71,7 +71,7 @@ public slots: private: // This is a pointer to the csync exclude list, its is owned by this class // but the pointer can be in a csync_context so that it can itself also query the list. - c_strlist_t** _excludesPtr; + c_strlist_t **_excludesPtr; QSet _excludeFiles; }; diff --git a/src/libsync/filesystem.cpp b/src/libsync/filesystem.cpp index 21d9ccf5a..c068f4694 100644 --- a/src/libsync/filesystem.cpp +++ b/src/libsync/filesystem.cpp @@ -39,7 +39,7 @@ // We use some internals of csync: extern "C" int c_utimes(const char *, const struct timeval *); -extern "C" void csync_win32_set_file_hidden( const char *file, bool h ); +extern "C" void csync_win32_set_file_hidden(const char *file, bool h); extern "C" { #include "csync.h" @@ -52,17 +52,17 @@ namespace OCC { Q_LOGGING_CATEGORY(lcFileSystem, "sync.filesystem", QtInfoMsg) -QString FileSystem::longWinPath( const QString& inpath ) +QString FileSystem::longWinPath(const QString &inpath) { QString path(inpath); #ifdef Q_OS_WIN - path = QString::fromWCharArray( static_cast( c_utf8_path_to_locale(inpath.toUtf8() ) ) ); + path = QString::fromWCharArray(static_cast(c_utf8_path_to_locale(inpath.toUtf8()))); #endif return path; } -bool FileSystem::fileEquals(const QString& fn1, const QString& fn2) +bool FileSystem::fileEquals(const QString &fn1, const QString &fn2) { // compare two files with given filename and return true if they have the same content QFile f1(fn1); @@ -95,19 +95,19 @@ bool FileSystem::fileEquals(const QString& fn1, const QString& fn2) return false; } -void FileSystem::setFileHidden(const QString& filename, bool hidden) +void FileSystem::setFileHidden(const QString &filename, bool hidden) { #ifdef _WIN32 QString fName = longWinPath(filename); DWORD dwAttrs; - dwAttrs = GetFileAttributesW( (wchar_t*)fName.utf16() ); + dwAttrs = GetFileAttributesW((wchar_t *)fName.utf16()); if (dwAttrs != INVALID_FILE_ATTRIBUTES) { if (hidden && !(dwAttrs & FILE_ATTRIBUTE_HIDDEN)) { - SetFileAttributesW((wchar_t*)fName.utf16(), dwAttrs | FILE_ATTRIBUTE_HIDDEN ); + SetFileAttributesW((wchar_t *)fName.utf16(), dwAttrs | FILE_ATTRIBUTE_HIDDEN); } else if (!hidden && (dwAttrs & FILE_ATTRIBUTE_HIDDEN)) { - SetFileAttributesW((wchar_t*)fName.utf16(), dwAttrs & ~FILE_ATTRIBUTE_HIDDEN ); + SetFileAttributesW((wchar_t *)fName.utf16(), dwAttrs & ~FILE_ATTRIBUTE_HIDDEN); } } #else @@ -132,13 +132,13 @@ static QFile::Permissions getDefaultWritePermissions() return result; } -void FileSystem::setFileReadOnly(const QString& filename, bool readonly) +void FileSystem::setFileReadOnly(const QString &filename, bool readonly) { QFile file(filename); QFile::Permissions permissions = file.permissions(); QFile::Permissions allWritePermissions = - QFile::WriteUser | QFile::WriteGroup | QFile::WriteOther | QFile::WriteOwner; + QFile::WriteUser | QFile::WriteGroup | QFile::WriteOther | QFile::WriteOwner; static QFile::Permissions defaultWritePermissions = getDefaultWritePermissions(); permissions &= ~allWritePermissions; @@ -148,7 +148,7 @@ void FileSystem::setFileReadOnly(const QString& filename, bool readonly) file.setPermissions(permissions); } -void FileSystem::setFolderMinimumPermissions(const QString& filename) +void FileSystem::setFolderMinimumPermissions(const QString &filename) { #ifdef Q_OS_MAC QFile::Permissions perm = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner; @@ -160,7 +160,7 @@ void FileSystem::setFolderMinimumPermissions(const QString& filename) } -void FileSystem::setFileReadOnlyWeak(const QString& filename, bool readonly) +void FileSystem::setFileReadOnlyWeak(const QString &filename, bool readonly) { QFile file(filename); QFile::Permissions permissions = file.permissions(); @@ -174,21 +174,21 @@ void FileSystem::setFileReadOnlyWeak(const QString& filename, bool readonly) time_t FileSystem::getModTime(const QString &filename) { - csync_vio_file_stat_t* stat = csync_vio_file_stat_new(); + csync_vio_file_stat_t *stat = csync_vio_file_stat_new(); qint64 result = -1; if (csync_vio_local_stat(filename.toUtf8().data(), stat) != -1 - && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_MTIME)) { + && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_MTIME)) { result = stat->mtime; } else { qCWarning(lcFileSystem) << "Could not get modification time for" << filename - << "with csync, using QFileInfo"; + << "with csync, using QFileInfo"; result = Utility::qDateTimeToTime_t(QFileInfo(filename).lastModified()); } csync_vio_file_stat_destroy(stat); return result; } -bool FileSystem::setModTime(const QString& filename, time_t modTime) +bool FileSystem::setModTime(const QString &filename, time_t modTime) { struct timeval times[2]; times[0].tv_sec = times[1].tv_sec = modTime; @@ -196,22 +196,22 @@ bool FileSystem::setModTime(const QString& filename, time_t modTime) int rc = c_utimes(filename.toUtf8().data(), times); if (rc != 0) { qCWarning(lcFileSystem) << "Error setting mtime for" << filename - << "failed: rc" << rc << ", errno:" << errno; + << "failed: rc" << rc << ", errno:" << errno; return false; } return true; } #ifdef Q_OS_WIN -static bool isLnkFile(const QString& filename) +static bool isLnkFile(const QString &filename) { return filename.endsWith(".lnk"); } #endif bool FileSystem::rename(const QString &originFileName, - const QString &destinationFileName, - QString *errorString) + const QString &destinationFileName, + QString *errorString) { bool success = false; QString error; @@ -220,14 +220,14 @@ bool FileSystem::rename(const QString &originFileName, QString dest = longWinPath(destinationFileName); if (isLnkFile(originFileName) || isLnkFile(destinationFileName)) { - success = MoveFileEx((wchar_t*)orig.utf16(), - (wchar_t*)dest.utf16(), - MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH); + success = MoveFileEx((wchar_t *)orig.utf16(), + (wchar_t *)dest.utf16(), + MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH); if (!success) { wchar_t *string = 0; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPWSTR)&string, 0, NULL); + NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPWSTR)&string, 0, NULL); error = QString::fromWCharArray(string); LocalFree((HLOCAL)string); @@ -244,8 +244,8 @@ bool FileSystem::rename(const QString &originFileName, if (!success) { qCWarning(lcFileSystem) << "Error renaming file" << originFileName - << "to" << destinationFileName - << "failed: " << error; + << "to" << destinationFileName + << "failed: " << error; if (errorString) { *errorString = error; } @@ -253,40 +253,40 @@ bool FileSystem::rename(const QString &originFileName, return success; } -bool FileSystem::fileChanged(const QString& fileName, - qint64 previousSize, - time_t previousMtime) +bool FileSystem::fileChanged(const QString &fileName, + qint64 previousSize, + time_t previousMtime) { return getSize(fileName) != previousSize || getModTime(fileName) != previousMtime; } -bool FileSystem::verifyFileUnchanged(const QString& fileName, - qint64 previousSize, - time_t previousMtime) +bool FileSystem::verifyFileUnchanged(const QString &fileName, + qint64 previousSize, + time_t previousMtime) { const qint64 actualSize = getSize(fileName); const time_t actualMtime = getModTime(fileName); if (actualSize != previousSize || actualMtime != previousMtime) { qCInfo(lcFileSystem) << "File" << fileName << "has changed:" - << "size: " << previousSize << "<->" << actualSize - << ", mtime: " << previousMtime << "<->" << actualMtime; + << "size: " << previousSize << "<->" << actualSize + << ", mtime: " << previousMtime << "<->" << actualMtime; return false; } return true; } -bool FileSystem::renameReplace(const QString& originFileName, - const QString& destinationFileName, - qint64 destinationSize, - time_t destinationMtime, - QString* errorString) +bool FileSystem::renameReplace(const QString &originFileName, + const QString &destinationFileName, + qint64 destinationSize, + time_t destinationMtime, + QString *errorString) { if (fileExists(destinationFileName) - && fileChanged(destinationFileName, destinationSize, destinationMtime)) { + && fileChanged(destinationFileName, destinationSize, destinationMtime)) { if (errorString) { *errorString = qApp->translate("FileSystem", - "The destination file has an unexpected size or modification time"); + "The destination file has an unexpected size or modification time"); } return false; } @@ -294,9 +294,9 @@ bool FileSystem::renameReplace(const QString& originFileName, return uncheckedRenameReplace(originFileName, destinationFileName, errorString); } -bool FileSystem::uncheckedRenameReplace(const QString& originFileName, - const QString& destinationFileName, - QString* errorString) +bool FileSystem::uncheckedRenameReplace(const QString &originFileName, + const QString &destinationFileName, + QString *errorString) { #ifndef Q_OS_WIN bool success; @@ -309,18 +309,18 @@ bool FileSystem::uncheckedRenameReplace(const QString& originFileName, // ### FIXME success = true; bool destExists = fileExists(destinationFileName); - if( destExists && !QFile::remove(destinationFileName) ) { + if (destExists && !QFile::remove(destinationFileName)) { *errorString = orig.errorString(); qCWarning(lcFileSystem) << "Target file could not be removed."; success = false; } - if( success ) { + if (success) { success = orig.rename(destinationFileName); } #endif if (!success) { *errorString = orig.errorString(); - qCWarning(lcFileSystem) << "Renaming temp file to final failed: " << *errorString ; + qCWarning(lcFileSystem) << "Renaming temp file to final failed: " << *errorString; return false; } @@ -334,14 +334,14 @@ bool FileSystem::uncheckedRenameReplace(const QString& originFileName, QString orig = longWinPath(originFileName); QString dest = longWinPath(destinationFileName); - ok = MoveFileEx((wchar_t*)orig.utf16(), - (wchar_t*)dest.utf16(), - MOVEFILE_REPLACE_EXISTING+MOVEFILE_COPY_ALLOWED+MOVEFILE_WRITE_THROUGH); + ok = MoveFileEx((wchar_t *)orig.utf16(), + (wchar_t *)dest.utf16(), + MOVEFILE_REPLACE_EXISTING + MOVEFILE_COPY_ALLOWED + MOVEFILE_WRITE_THROUGH); if (!ok) { wchar_t *string = 0; - FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, - NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPWSTR)&string, 0, NULL); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPWSTR)&string, 0, NULL); *errorString = QString::fromWCharArray(string); qCWarning(lcFileSystem) << "Renaming temp file to final failed: " << *errorString; @@ -352,11 +352,11 @@ bool FileSystem::uncheckedRenameReplace(const QString& originFileName, return true; } -bool FileSystem::openAndSeekFileSharedRead(QFile* file, QString* errorOrNull, qint64 seek) +bool FileSystem::openAndSeekFileSharedRead(QFile *file, QString *errorOrNull, qint64 seek) { QString errorDummy; // avoid many if (errorOrNull) later. - QString& error = errorOrNull ? *errorOrNull : errorDummy; + QString &error = errorOrNull ? *errorOrNull : errorDummy; error.clear(); #ifdef Q_OS_WIN @@ -376,13 +376,13 @@ bool FileSystem::openAndSeekFileSharedRead(QFile* file, QString* errorOrNull, qi QString fName = longWinPath(file->fileName()); HANDLE fileHandle = CreateFileW( - (const wchar_t*)fName.utf16(), - accessRights, - shareMode, - &securityAtts, - creationDisp, - FILE_ATTRIBUTE_NORMAL, - NULL); + (const wchar_t *)fName.utf16(), + accessRights, + shareMode, + &securityAtts, + creationDisp, + FILE_ATTRIBUTE_NORMAL, + NULL); // Bail out on error. if (fileHandle == INVALID_HANDLE_VALUE) { @@ -404,7 +404,7 @@ bool FileSystem::openAndSeekFileSharedRead(QFile* file, QString* errorOrNull, qi } // Seek to the right spot - LARGE_INTEGER *li = reinterpret_cast(&seek); + LARGE_INTEGER *li = reinterpret_cast(&seek); DWORD newFilePointer = SetFilePointer(fileHandle, li->LowPart, &li->HighPart, FILE_BEGIN); if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) { error = qt_error_string(); @@ -426,12 +426,12 @@ bool FileSystem::openAndSeekFileSharedRead(QFile* file, QString* errorOrNull, qi } #ifdef Q_OS_WIN -static qint64 getSizeWithCsync(const QString& filename) +static qint64 getSizeWithCsync(const QString &filename) { qint64 result = 0; - csync_vio_file_stat_t* stat = csync_vio_file_stat_new(); + csync_vio_file_stat_t *stat = csync_vio_file_stat_new(); if (csync_vio_local_stat(filename.toUtf8().data(), stat) != -1 - && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_SIZE)) { + && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_SIZE)) { result = stat->size; } else { qCWarning(lcFileSystem) << "Could not get size for" << filename << "with csync"; @@ -441,7 +441,7 @@ static qint64 getSizeWithCsync(const QString& filename) } #endif -qint64 FileSystem::getSize(const QString& filename) +qint64 FileSystem::getSize(const QString &filename) { #ifdef Q_OS_WIN if (isLnkFile(filename)) { @@ -453,13 +453,13 @@ qint64 FileSystem::getSize(const QString& filename) } #ifdef Q_OS_WIN -static bool fileExistsWin(const QString& filename) +static bool fileExistsWin(const QString &filename) { WIN32_FIND_DATA FindFileData; HANDLE hFind; QString fName = FileSystem::longWinPath(filename); - hFind = FindFirstFileW( (wchar_t*)fName.utf16(), &FindFileData); + hFind = FindFirstFileW((wchar_t *)fName.utf16(), &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { return false; } @@ -468,7 +468,7 @@ static bool fileExistsWin(const QString& filename) } #endif -bool FileSystem::fileExists(const QString& filename, const QFileInfo& fileInfo) +bool FileSystem::fileExists(const QString &filename, const QFileInfo &fileInfo) { #ifdef Q_OS_WIN if (isLnkFile(filename)) { @@ -480,7 +480,7 @@ bool FileSystem::fileExists(const QString& filename, const QFileInfo& fileInfo) // if the filename is different from the filename in fileInfo, the fileInfo is // not valid. There needs to be one initialised here. Otherwise the incoming // fileInfo is re-used. - if( fileInfo.filePath() != filename ) { + if (fileInfo.filePath() != filename) { QFileInfo myFI(filename); re = myFI.exists(); } @@ -488,18 +488,18 @@ bool FileSystem::fileExists(const QString& filename, const QFileInfo& fileInfo) } #ifdef Q_OS_WIN -QString FileSystem::fileSystemForPath(const QString & path) +QString FileSystem::fileSystemForPath(const QString &path) { // See also QStorageInfo (Qt >=5.4) and GetVolumeInformationByHandleW (>= Vista) QString drive = path.left(2); - if (! drive.endsWith(":")) + if (!drive.endsWith(":")) return QString(); drive.append('\\'); const size_t fileSystemBufferSize = 4096; TCHAR fileSystemBuffer[fileSystemBufferSize]; - if (! GetVolumeInformationW( + if (!GetVolumeInformationW( reinterpret_cast(drive.utf16()), NULL, 0, NULL, NULL, NULL, @@ -510,21 +510,21 @@ QString FileSystem::fileSystemForPath(const QString & path) } #endif -#define BUFSIZE qint64(500*1024) // 500 KiB +#define BUFSIZE qint64(500 * 1024) // 500 KiB -static QByteArray readToCrypto( const QString& filename, QCryptographicHash::Algorithm algo ) +static QByteArray readToCrypto(const QString &filename, QCryptographicHash::Algorithm algo) { QFile file(filename); const qint64 bufSize = qMin(BUFSIZE, file.size() + 1); QByteArray buf(bufSize, Qt::Uninitialized); QByteArray arr; - QCryptographicHash crypto( algo ); + QCryptographicHash crypto(algo); if (file.open(QIODevice::ReadOnly)) { qint64 size; while (!file.atEnd()) { - size = file.read( buf.data(), bufSize ); - if( size > 0 ) { + size = file.read(buf.data(), bufSize); + if (size > 0) { crypto.addData(buf.data(), size); } } @@ -533,18 +533,18 @@ static QByteArray readToCrypto( const QString& filename, QCryptographicHash::Alg return arr; } -QByteArray FileSystem::calcMd5( const QString& filename ) +QByteArray FileSystem::calcMd5(const QString &filename) { - return readToCrypto( filename, QCryptographicHash::Md5 ); + return readToCrypto(filename, QCryptographicHash::Md5); } -QByteArray FileSystem::calcSha1( const QString& filename ) +QByteArray FileSystem::calcSha1(const QString &filename) { - return readToCrypto( filename, QCryptographicHash::Sha1 ); + return readToCrypto(filename, QCryptographicHash::Sha1); } #ifdef ZLIB_FOUND -QByteArray FileSystem::calcAdler32( const QString& filename ) +QByteArray FileSystem::calcAdler32(const QString &filename) { QFile file(filename); const qint64 bufSize = qMin(BUFSIZE, file.size() + 1); @@ -555,12 +555,12 @@ QByteArray FileSystem::calcAdler32( const QString& filename ) qint64 size; while (!file.atEnd()) { size = file.read(buf.data(), bufSize); - if( size > 0 ) - adler = adler32(adler, (const Bytef*) buf.data(), size); + if (size > 0) + adler = adler32(adler, (const Bytef *)buf.data(), size); } } - return QByteArray::number( adler, 16 ); + return QByteArray::number(adler, 16); } #endif @@ -580,7 +580,7 @@ QString FileSystem::makeConflictFileName(const QString &fn, const QDateTime &dt) if (conflictFileUserName.isEmpty()) conflictFileName.insert(dotLocation, "_conflict-" + timeString); else - conflictFileName.insert(dotLocation, "_conflict_" + QString::fromUtf8(conflictFileUserName) + "-" + timeString); + conflictFileName.insert(dotLocation, "_conflict_" + QString::fromUtf8(conflictFileUserName) + "-" + timeString); return conflictFileName; } @@ -604,7 +604,7 @@ bool FileSystem::remove(const QString &fileName, QString *errorString) return true; } -bool FileSystem::isFileLocked(const QString& fileName) +bool FileSystem::isFileLocked(const QString &fileName) { #ifdef Q_OS_WIN mbchar_t *wuri = c_utf8_path_to_locale(fileName.toUtf8()); @@ -614,12 +614,12 @@ bool FileSystem::isFileLocked(const QString& fileName) if (attr != INVALID_FILE_ATTRIBUTES) { // Try to open the file with as much access as possible.. HANDLE win_h = CreateFileW( - wuri, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, - NULL); + wuri, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, + NULL); c_free_locale_string(wuri); if (win_h == INVALID_HANDLE_VALUE) { diff --git a/src/libsync/filesystem.h b/src/libsync/filesystem.h index 36ac8d599..7494bdbd4 100644 --- a/src/libsync/filesystem.h +++ b/src/libsync/filesystem.h @@ -38,25 +38,25 @@ namespace OCC { */ namespace FileSystem { -/** + /** * @brief compare two files with given filename and return true if they have the same content */ -bool fileEquals(const QString &fn1, const QString &fn2); + bool fileEquals(const QString &fn1, const QString &fn2); -/** + /** * @brief Mark the file as hidden (only has effects on windows) */ -void OWNCLOUDSYNC_EXPORT setFileHidden(const QString& filename, bool hidden); + void OWNCLOUDSYNC_EXPORT setFileHidden(const QString &filename, bool hidden); -/** + /** * @brief Marks the file as read-only. * * On linux this either revokes all 'w' permissions or restores permissions * according to the umask. */ -void OWNCLOUDSYNC_EXPORT setFileReadOnly(const QString& filename, bool readonly); + void OWNCLOUDSYNC_EXPORT setFileReadOnly(const QString &filename, bool readonly); -/** + /** * @brief Marks the file as read-only. * * It's like setFileReadOnly(), but weaker: if readonly is false and the user @@ -65,71 +65,71 @@ void OWNCLOUDSYNC_EXPORT setFileReadOnly(const QString& filename, bool readonly) * This means that it will preserve explicitly set rw-r--r-- permissions even * when the umask is 0002. (setFileReadOnly() would adjust to rw-rw-r--) */ -void OWNCLOUDSYNC_EXPORT setFileReadOnlyWeak(const QString& filename, bool readonly); + void OWNCLOUDSYNC_EXPORT setFileReadOnlyWeak(const QString &filename, bool readonly); -/** + /** * @brief Try to set permissions so that other users on the local machine can not * go into the folder. */ -void OWNCLOUDSYNC_EXPORT setFolderMinimumPermissions(const QString& filename); + void OWNCLOUDSYNC_EXPORT setFolderMinimumPermissions(const QString &filename); -/** convert a "normal" windows path into a path that can be 32k chars long. */ -QString OWNCLOUDSYNC_EXPORT longWinPath( const QString& inpath ); + /** convert a "normal" windows path into a path that can be 32k chars long. */ + QString OWNCLOUDSYNC_EXPORT longWinPath(const QString &inpath); -/** + /** * @brief Get the mtime for a filepath * * Use this over QFileInfo::lastModified() to avoid timezone related bugs. See * owncloud/core#9781 for details. */ -time_t OWNCLOUDSYNC_EXPORT getModTime(const QString& filename); + time_t OWNCLOUDSYNC_EXPORT getModTime(const QString &filename); -bool OWNCLOUDSYNC_EXPORT setModTime(const QString &filename, time_t modTime); + bool OWNCLOUDSYNC_EXPORT setModTime(const QString &filename, time_t modTime); -/** + /** * @brief Get the size for a file * * Use this over QFileInfo::size() to avoid bugs with lnk files on Windows. * See https://bugreports.qt.io/browse/QTBUG-24831. */ -qint64 OWNCLOUDSYNC_EXPORT getSize(const QString& filename); + qint64 OWNCLOUDSYNC_EXPORT getSize(const QString &filename); -/** + /** * @brief Checks whether a file exists. * * Use this over QFileInfo::exists() and QFile::exists() to avoid bugs with lnk * files, see above. */ -bool OWNCLOUDSYNC_EXPORT fileExists(const QString& filename, const QFileInfo& = QFileInfo() ); + bool OWNCLOUDSYNC_EXPORT fileExists(const QString &filename, const QFileInfo & = QFileInfo()); -/** + /** * @brief Rename the file \a originFileName to \a destinationFileName. * * It behaves as QFile::rename() but handles .lnk files correctly on Windows. */ -bool OWNCLOUDSYNC_EXPORT rename(const QString& originFileName, - const QString& destinationFileName, - QString* errorString = NULL); + bool OWNCLOUDSYNC_EXPORT rename(const QString &originFileName, + const QString &destinationFileName, + QString *errorString = NULL); -/** + /** * @brief Check if \a fileName has changed given previous size and mtime * * Nonexisting files are covered through mtime: they have an mtime of -1. * * @return true if the file's mtime or size are not what is expected. */ -bool OWNCLOUDSYNC_EXPORT fileChanged(const QString& fileName, - qint64 previousSize, - time_t previousMtime); + bool OWNCLOUDSYNC_EXPORT fileChanged(const QString &fileName, + qint64 previousSize, + time_t previousMtime); -/** + /** * @brief Like !fileChanged() but with verbose logging if the file *did* change. */ -bool verifyFileUnchanged(const QString& fileName, - qint64 previousSize, - time_t previousMtime); + bool verifyFileUnchanged(const QString &fileName, + qint64 previousSize, + time_t previousMtime); -/** + /** * @brief renames a file, overriding the target if it exists * * Rename the file \a originFileName to \a destinationFileName, and @@ -140,62 +140,60 @@ bool verifyFileUnchanged(const QString& fileName, * If the destination file does not exist, the given size and mtime are * ignored. */ -bool renameReplace(const QString &originFileName, - const QString &destinationFileName, - qint64 destinationSize, - time_t destinationMtime, - QString *errorString); + bool renameReplace(const QString &originFileName, + const QString &destinationFileName, + qint64 destinationSize, + time_t destinationMtime, + QString *errorString); -/** + /** * Rename the file \a originFileName to \a destinationFileName, and * overwrite the destination if it already exists - without extra checks. */ -bool uncheckedRenameReplace(const QString &originFileName, - const QString &destinationFileName, - QString *errorString); + bool uncheckedRenameReplace(const QString &originFileName, + const QString &destinationFileName, + QString *errorString); -/** + /** * Removes a file. * * Equivalent to QFile::remove(), except on Windows, where it will also * successfully remove read-only files. */ -bool OWNCLOUDSYNC_EXPORT remove(const QString &fileName, QString *errorString = 0); + bool OWNCLOUDSYNC_EXPORT remove(const QString &fileName, QString *errorString = 0); -/** + /** * Replacement for QFile::open(ReadOnly) followed by a seek(). * This version sets a more permissive sharing mode on Windows. * * Warning: The resulting file may have an empty fileName and be unsuitable for use * with QFileInfo! Calling seek() on the QFile with >32bit signed values will fail! */ -bool openAndSeekFileSharedRead(QFile* file, QString* error, qint64 seek); + bool openAndSeekFileSharedRead(QFile *file, QString *error, qint64 seek); #ifdef Q_OS_WIN -/** + /** * Returns the file system used at the given path. */ -QString fileSystemForPath(const QString & path); + QString fileSystemForPath(const QString &path); #endif -QByteArray OWNCLOUDSYNC_EXPORT calcMd5( const QString& fileName ); -QByteArray OWNCLOUDSYNC_EXPORT calcSha1( const QString& fileName ); + QByteArray OWNCLOUDSYNC_EXPORT calcMd5(const QString &fileName); + QByteArray OWNCLOUDSYNC_EXPORT calcSha1(const QString &fileName); #ifdef ZLIB_FOUND -QByteArray OWNCLOUDSYNC_EXPORT calcAdler32( const QString& fileName ); + QByteArray OWNCLOUDSYNC_EXPORT calcAdler32(const QString &fileName); #endif -/** + /** * Returns a file name based on \a fn that's suitable for a conflict. */ -QString OWNCLOUDSYNC_EXPORT makeConflictFileName(const QString &fn, const QDateTime &dt); + QString OWNCLOUDSYNC_EXPORT makeConflictFileName(const QString &fn, const QDateTime &dt); -/** + /** * Returns true when a file is locked. (Windows only) */ -bool OWNCLOUDSYNC_EXPORT isFileLocked(const QString& fileName); - + bool OWNCLOUDSYNC_EXPORT isFileLocked(const QString &fileName); } /** @} */ - } diff --git a/src/libsync/logger.cpp b/src/libsync/logger.cpp index 47b731eba..46c2e95ba 100644 --- a/src/libsync/logger.cpp +++ b/src/libsync/logger.cpp @@ -30,32 +30,35 @@ Q_LOGGING_CATEGORY(lcCsync, "sync.csync", QtInfoMsg) // logging handler. static void mirallLogCatcher(QtMsgType type, const char *msg) { - Q_UNUSED(type) - // qDebug() exports to local8Bit, which is not always UTF-8 - Logger::instance()->mirallLog( QString::fromLocal8Bit(msg) ); + Q_UNUSED(type) + // qDebug() exports to local8Bit, which is not always UTF-8 + Logger::instance()->mirallLog(QString::fromLocal8Bit(msg)); } -static void qInstallMessageHandler(QtMsgHandler h) { +static void qInstallMessageHandler(QtMsgHandler h) +{ qInstallMsgHandler(h); } #elif QT_VERSION < QT_VERSION_CHECK(5, 4, 0) -static void mirallLogCatcher(QtMsgType, const QMessageLogContext &ctx, const QString &message) { +static void mirallLogCatcher(QtMsgType, const QMessageLogContext &ctx, const QString &message) +{ QByteArray file = ctx.file; file = file.mid(file.lastIndexOf('/') + 1); - Logger::instance()->mirallLog( QString::fromLocal8Bit(file) + QLatin1Char(':') + QString::number(ctx.line) - + QLatin1Char(' ') + message) ; + Logger::instance()->mirallLog(QString::fromLocal8Bit(file) + QLatin1Char(':') + QString::number(ctx.line) + + QLatin1Char(' ') + message); } #else -static void mirallLogCatcher(QtMsgType type, const QMessageLogContext &ctx, const QString &message) { +static void mirallLogCatcher(QtMsgType type, const QMessageLogContext &ctx, const QString &message) +{ auto logger = Logger::instance(); if (!logger->isNoop()) { - logger->doLog( qFormatLogMessage(type, ctx, message) ) ; + logger->doLog(qFormatLogMessage(type, ctx, message)); } } #endif static void csyncLogCatcher(int verbosity, - const char *function, - const char *buffer) + const char *function, + const char *buffer) { if (verbosity <= CSYNC_LOG_PRIORITY_FATAL) { QMessageLogger(0, 0, function, lcCsync().categoryName()).fatal("%s", buffer); @@ -80,8 +83,13 @@ Logger *Logger::instance() return &log; } -Logger::Logger( QObject* parent) : QObject(parent), - _showTime(true), _logWindowActivated(false), _doFileFlush(false), _logExpire(0), _logDebug(false) +Logger::Logger(QObject *parent) + : QObject(parent) + , _showTime(true) + , _logWindowActivated(false) + , _doFileFlush(false) + , _logExpire(0) + , _logDebug(false) { #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) qSetMessagePattern("%{time MM-dd hh:mm:ss:zzz} [ %{type} %{category} ]%{if-debug}\t[ %{function} ]%{endif}:\t%{message}"); @@ -98,7 +106,8 @@ Logger::Logger( QObject* parent) : QObject(parent), csync_set_log_callback(csyncLogCatcher); } -Logger::~Logger() { +Logger::~Logger() +{ #ifndef NO_MSG_HANDLER qInstallMessageHandler(0); #endif @@ -123,16 +132,16 @@ void Logger::postGuiMessage(const QString &title, const QString &message) void Logger::log(Log log) { QString msg; - if( _showTime ) { + if (_showTime) { msg = log.timeStamp.toString(QLatin1String("MM-dd hh:mm:ss:zzz")) + QLatin1Char(' '); } - if( log.source == Log::CSync ) { + if (log.source == Log::CSync) { // msg += "csync - "; } else { // msg += "ownCloud - "; } - msg += QString().sprintf("%p ", (void*)QThread::currentThread()); + msg += QString().sprintf("%p ", (void *)QThread::currentThread()); msg += log.message; // _logs.append(log); // std::cout << qPrintable(log.message) << std::endl; @@ -154,26 +163,27 @@ bool Logger::isNoop() const } -void Logger::doLog(const QString& msg) +void Logger::doLog(const QString &msg) { { QMutexLocker lock(&_mutex); - if( _logstream ) { + if (_logstream) { (*_logstream) << msg << endl; - if( _doFileFlush ) _logstream->flush(); + if (_doFileFlush) + _logstream->flush(); } } emit logWindowLog(msg); } -void Logger::mirallLog( const QString& message ) +void Logger::mirallLog(const QString &message) { Log log_; log_.source = Log::Occ; log_.timeStamp = QDateTime::currentDateTime(); log_.message = message; - Logger::instance()->log( log_ ); + Logger::instance()->log(log_); } void Logger::setLogWindowActivated(bool activated) @@ -185,18 +195,18 @@ void Logger::setLogWindowActivated(bool activated) _logWindowActivated = activated; } -void Logger::setLogFile(const QString & name) +void Logger::setLogFile(const QString &name) { QMutexLocker locker(&_mutex); csync_set_log_level(11); - - if( _logstream ) { + + if (_logstream) { _logstream.reset(0); _logFile.close(); } - if( name.isEmpty() ) { + if (name.isEmpty()) { return; } @@ -204,38 +214,38 @@ void Logger::setLogFile(const QString & name) if (name == QLatin1String("-")) { openSucceeded = _logFile.open(1, QIODevice::WriteOnly); } else { - _logFile.setFileName( name ); + _logFile.setFileName(name); openSucceeded = _logFile.open(QIODevice::WriteOnly); } - if(!openSucceeded) { + if (!openSucceeded) { locker.unlock(); // Just in case postGuiMessage has a qDebug() - postGuiMessage( tr("Error"), - QString(tr("File '%1'
cannot be opened for writing.

" - "The log output can not be saved!
")) - .arg(name)); + postGuiMessage(tr("Error"), + QString(tr("File '%1'
cannot be opened for writing.

" + "The log output can not be saved!
")) + .arg(name)); return; } - _logstream.reset(new QTextStream( &_logFile )); + _logstream.reset(new QTextStream(&_logFile)); } -void Logger::setLogExpire( int expire ) +void Logger::setLogExpire(int expire) { _logExpire = expire; } -void Logger::setLogDir( const QString& dir ) +void Logger::setLogDir(const QString &dir) { _logDirectory = dir; } -void Logger::setLogFlush( bool flush ) +void Logger::setLogFlush(bool flush) { _doFileFlush = flush; } -void Logger::setLogDebug( bool debug ) +void Logger::setLogDebug(bool debug) { QLoggingCategory::setFilterRules(debug ? QStringLiteral("qt.*=true\n*.debug=true") : QString()); _logDebug = debug; @@ -251,23 +261,23 @@ void Logger::enterNextLogFile() // Find out what is the file with the highest number if any QStringList files = dir.entryList(QStringList("owncloud.log.*"), - QDir::Files); + QDir::Files); QRegExp rx("owncloud.log.(\\d+)"); uint maxNumber = 0; QDateTime now = QDateTime::currentDateTime(); - foreach(const QString &s, files) { + foreach (const QString &s, files) { if (rx.exactMatch(s)) { maxNumber = qMax(maxNumber, rx.cap(1).toUInt()); if (_logExpire > 0) { QFileInfo fileInfo = dir.absoluteFilePath(s); - if (fileInfo.lastModified().addSecs(60*60 * _logExpire) < now) { + if (fileInfo.lastModified().addSecs(60 * 60 * _logExpire) < now) { dir.remove(s); } } } } - QString filename = _logDirectory + "/owncloud.log." + QString::number(maxNumber+1); + QString filename = _logDirectory + "/owncloud.log." + QString::number(maxNumber + 1); setLogFile(filename); } } diff --git a/src/libsync/logger.h b/src/libsync/logger.h index 926bb09e4..555abe52f 100644 --- a/src/libsync/logger.h +++ b/src/libsync/logger.h @@ -26,15 +26,16 @@ namespace OCC { -struct Log{ - typedef enum{ - Occ, - CSync - } Source; - - QDateTime timeStamp; - Source source; - QString message; +struct Log +{ + typedef enum { + Occ, + CSync + } Source; + + QDateTime timeStamp; + Source source; + QString message; }; /** @@ -43,56 +44,54 @@ struct Log{ */ class OWNCLOUDSYNC_EXPORT Logger : public QObject { - Q_OBJECT + Q_OBJECT public: + bool isNoop() const; + void log(Log log); + void doLog(const QString &log); - bool isNoop() const; - void log(Log log); - void doLog(const QString &log); - - static void mirallLog( const QString& message ); + static void mirallLog(const QString &message); - const QList& logs() const {return _logs;} + const QList &logs() const { return _logs; } - static Logger* instance(); + static Logger *instance(); - void postGuiLog(const QString& title, const QString& message); - void postOptionalGuiLog(const QString& title, const QString& message); - void postGuiMessage(const QString& title, const QString& message); + void postGuiLog(const QString &title, const QString &message); + void postOptionalGuiLog(const QString &title, const QString &message); + void postGuiMessage(const QString &title, const QString &message); - void setLogWindowActivated(bool activated); - void setLogFile( const QString & name ); - void setLogExpire( int expire ); - void setLogDir( const QString& dir ); - void setLogFlush( bool flush ); + void setLogWindowActivated(bool activated); + void setLogFile(const QString &name); + void setLogExpire(int expire); + void setLogDir(const QString &dir); + void setLogFlush(bool flush); - bool logDebug() const { return _logDebug; } - void setLogDebug( bool debug ); + bool logDebug() const { return _logDebug; } + void setLogDebug(bool debug); signals: - void logWindowLog(const QString&); + void logWindowLog(const QString &); - void guiLog(const QString&, const QString&); - void guiMessage(const QString&, const QString&); - void optionalGuiLog(const QString&, const QString&); + void guiLog(const QString &, const QString &); + void guiMessage(const QString &, const QString &); + void optionalGuiLog(const QString &, const QString &); public slots: - void enterNextLogFile(); + void enterNextLogFile(); private: - Logger(QObject* parent=0); - ~Logger(); - QList _logs; - bool _showTime; - bool _logWindowActivated; - QFile _logFile; - bool _doFileFlush; - int _logExpire; - bool _logDebug; - QScopedPointer _logstream; - QMutex _mutex; - QString _logDirectory; - + Logger(QObject *parent = 0); + ~Logger(); + QList _logs; + bool _showTime; + bool _logWindowActivated; + QFile _logFile; + bool _doFileFlush; + int _logExpire; + bool _logDebug; + QScopedPointer _logstream; + QMutex _mutex; + QString _logDirectory; }; } // namespace OCC diff --git a/src/libsync/networkjobs.cpp b/src/libsync/networkjobs.cpp index ca466bc42..613098dda 100644 --- a/src/libsync/networkjobs.cpp +++ b/src/libsync/networkjobs.cpp @@ -79,7 +79,7 @@ void RequestEtagJob::start() // assumes ownership sendRequest("PROPFIND", makeDavUrl(path()), req, buf); - if( reply()->error() != QNetworkReply::NoError ) { + if (reply()->error() != QNetworkReply::NoError) { qCWarning(lcEtagJob) << "request network error: " << reply()->errorString(); } AbstractNetworkJob::start(); @@ -88,8 +88,8 @@ void RequestEtagJob::start() bool RequestEtagJob::finished() { qCInfo(lcEtagJob) << "Request Etag of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); if (reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 207) { // Parse DAV response @@ -98,8 +98,7 @@ bool RequestEtagJob::finished() QString etag; while (!reader.atEnd()) { QXmlStreamReader::TokenType type = reader.readNext(); - if (type == QXmlStreamReader::StartElement && - reader.namespaceUri() == QLatin1String("DAV:")) { + if (type == QXmlStreamReader::StartElement && reader.namespaceUri() == QLatin1String("DAV:")) { QString name = reader.name().toString(); if (name == QLatin1String("getetag")) { etag += reader.readElementText(); @@ -119,34 +118,36 @@ MkColJob::MkColJob(AccountPtr account, const QString &path, QObject *parent) } MkColJob::MkColJob(AccountPtr account, const QUrl &url, - const QMap &extraHeaders, QObject *parent) - : AbstractNetworkJob(account, QString(), parent), _url(url), _extraHeaders(extraHeaders) + const QMap &extraHeaders, QObject *parent) + : AbstractNetworkJob(account, QString(), parent) + , _url(url) + , _extraHeaders(extraHeaders) { } void MkColJob::start() { - // add 'Content-Length: 0' header (see https://github.com/owncloud/client/issues/3256) - QNetworkRequest req; - req.setRawHeader("Content-Length", "0"); - for(auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) { + // add 'Content-Length: 0' header (see https://github.com/owncloud/client/issues/3256) + QNetworkRequest req; + req.setRawHeader("Content-Length", "0"); + for (auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) { req.setRawHeader(it.key(), it.value()); - } + } - // assumes ownership - if (_url.isValid()) { - sendRequest("MKCOL", _url, req); - } else { - sendRequest("MKCOL", makeDavUrl(path()), req); - } - AbstractNetworkJob::start(); + // assumes ownership + if (_url.isValid()) { + sendRequest("MKCOL", _url, req); + } else { + sendRequest("MKCOL", makeDavUrl(path()), req); + } + AbstractNetworkJob::start(); } bool MkColJob::finished() { qCInfo(lcMkColJob) << "MKCOL of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); emit finished(reply()->error()); return true; @@ -154,7 +155,8 @@ bool MkColJob::finished() /*********************************************************************************************/ // supposed to read when pointing to .. -static QString readContentsAsString(QXmlStreamReader &reader) { +static QString readContentsAsString(QXmlStreamReader &reader) +{ QString result; int level = 0; do { @@ -179,10 +181,9 @@ static QString readContentsAsString(QXmlStreamReader &reader) { LsColXMLParser::LsColXMLParser() { - } -bool LsColXMLParser::parse( const QByteArray& xml, QHash *sizes, const QString& expectedPath) +bool LsColXMLParser::parse(const QByteArray &xml, QHash *sizes, const QString &expectedPath) { // Parse DAV response QXmlStreamReader reader(xml); @@ -258,7 +259,7 @@ bool LsColXMLParser::parse( const QByteArray& xml, QHash *sizes } else if (reader.name() == "propstat") { insidePropstat = false; if (currentPropsHaveHttp200) { - currentHttp200Properties = QMap(currentTmpProperties); + currentHttp200Properties = QMap(currentTmpProperties); } currentTmpProperties.clear(); currentPropsHaveHttp200 = false; @@ -281,7 +282,6 @@ bool LsColXMLParser::parse( const QByteArray& xml, QHash *sizes emit finishedWithoutError(); } return true; - } /*********************************************************************************************/ @@ -292,7 +292,8 @@ LsColJob::LsColJob(AccountPtr account, const QString &path, QObject *parent) } LsColJob::LsColJob(AccountPtr account, const QUrl &url, QObject *parent) - : AbstractNetworkJob(account, QString(), parent), _url(url) + : AbstractNetworkJob(account, QString(), parent) + , _url(url) { } @@ -319,9 +320,9 @@ void LsColJob::start() int colIdx = prop.lastIndexOf(":"); auto ns = prop.left(colIdx); if (ns == "http://owncloud.org/ns") { - propStr += " \n"; + propStr += " \n"; } else { - propStr += " <" + prop.mid(colIdx+1) + " xmlns=\"" + ns + "\" />\n"; + propStr += " <" + prop.mid(colIdx + 1) + " xmlns=\"" + ns + "\" />\n"; } } else { propStr += " \n"; @@ -333,9 +334,8 @@ void LsColJob::start() QByteArray xml("\n" "\n" " \n" - + propStr + - " \n" - "\n"); + + propStr + " \n" + "\n"); QBuffer *buf = new QBuffer(this); buf->setData(xml); buf->open(QIODevice::ReadOnly); @@ -353,24 +353,24 @@ void LsColJob::start() bool LsColJob::finished() { qCInfo(lcLsColJob) << "LSCOL of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); QString contentType = reply()->header(QNetworkRequest::ContentTypeHeader).toString(); int httpCode = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (httpCode == 207 && contentType.contains("application/xml; charset=utf-8")) { LsColXMLParser parser; - connect( &parser, SIGNAL(directoryListingSubfolders(const QStringList&)), - this, SIGNAL(directoryListingSubfolders(const QStringList&)) ); - connect( &parser, SIGNAL(directoryListingIterated(const QString&, const QMap&)), - this, SIGNAL(directoryListingIterated(const QString&, const QMap&)) ); - connect( &parser, SIGNAL(finishedWithError(QNetworkReply *)), - this, SIGNAL(finishedWithError(QNetworkReply *)) ); - connect( &parser, SIGNAL(finishedWithoutError()), - this, SIGNAL(finishedWithoutError()) ); + connect(&parser, SIGNAL(directoryListingSubfolders(const QStringList &)), + this, SIGNAL(directoryListingSubfolders(const QStringList &))); + connect(&parser, SIGNAL(directoryListingIterated(const QString &, const QMap &)), + this, SIGNAL(directoryListingIterated(const QString &, const QMap &))); + connect(&parser, SIGNAL(finishedWithError(QNetworkReply *)), + this, SIGNAL(finishedWithError(QNetworkReply *))); + connect(&parser, SIGNAL(finishedWithoutError()), + this, SIGNAL(finishedWithoutError())); QString expectedPath = reply()->request().url().path(); // something like "/owncloud/remote.php/webdav/folder" - if( !parser.parse( reply()->readAll(), &_sizes, expectedPath ) ) { + if (!parser.parse(reply()->readAll(), &_sizes, expectedPath)) { // XML parse error emit finishedWithError(reply()); } @@ -388,12 +388,12 @@ bool LsColJob::finished() /*********************************************************************************************/ namespace { -const char statusphpC[] = "status.php"; -const char owncloudDirC[] = "owncloud/"; + const char statusphpC[] = "status.php"; + const char owncloudDirC[] = "owncloud/"; } CheckServerJob::CheckServerJob(AccountPtr account, QObject *parent) - : AbstractNetworkJob(account, QLatin1String(statusphpC) , parent) + : AbstractNetworkJob(account, QLatin1String(statusphpC), parent) , _subdirFallback(false) { setIgnoreCredentialFailure(true); @@ -464,8 +464,8 @@ bool CheckServerJob::finished() { #if QT_VERSION > QT_VERSION_CHECK(5, 2, 0) if (reply()->request().url().scheme() == QLatin1String("https") - && reply()->sslConfiguration().sessionTicket().isEmpty() - && reply()->error() == QNetworkReply::NoError) { + && reply()->sslConfiguration().sessionTicket().isEmpty() + && reply()->error() == QNetworkReply::NoError) { qCWarning(lcCheckServerJob) << "No SSL session identifier / session ticket is used, this might impact sync performance negatively."; } #endif @@ -476,15 +476,15 @@ bool CheckServerJob::finished() // at the original location if ((reply()->error() == QNetworkReply::ContentNotFoundError) && (!_subdirFallback)) { _subdirFallback = true; - setPath(QLatin1String(owncloudDirC)+QLatin1String(statusphpC)); + setPath(QLatin1String(owncloudDirC) + QLatin1String(statusphpC)); start(); qCInfo(lcCheckServerJob) << "Retrying with" << reply()->url(); return false; } - QByteArray body = reply()->peek(4*1024); + QByteArray body = reply()->peek(4 * 1024); int httpStatus = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if( body.isEmpty() || httpStatus != 200) { + if (body.isEmpty() || httpStatus != 200) { qCWarning(lcCheckServerJob) << "error: status.php replied " << httpStatus << body; emit instanceNotFound(reply()); } else { @@ -496,7 +496,7 @@ bool CheckServerJob::finished() } qCInfo(lcCheckServerJob) << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply(); - if( status.object().contains("installed") ) { + if (status.object().contains("installed")) { emit instanceFound(reply()->url(), status.object()); } else { qCWarning(lcCheckServerJob) << "No proper answer on " << reply()->url(); @@ -511,7 +511,6 @@ bool CheckServerJob::finished() PropfindJob::PropfindJob(AccountPtr account, const QString &path, QObject *parent) : AbstractNetworkJob(account, path, parent) { - } void PropfindJob::start() @@ -531,7 +530,7 @@ void PropfindJob::start() foreach (const QByteArray &prop, properties) { if (prop.contains(':')) { int colIdx = prop.lastIndexOf(":"); - propStr += " <" + prop.mid(colIdx+1) + " xmlns=\"" + prop.left(colIdx) + "\" />\n"; + propStr += " <" + prop.mid(colIdx + 1) + " xmlns=\"" + prop.left(colIdx) + "\" />\n"; } else { propStr += " \n"; } @@ -539,9 +538,8 @@ void PropfindJob::start() QByteArray xml = "\n" "\n" " \n" - + propStr + - " \n" - "\n"; + + propStr + " \n" + "\n"; QBuffer *buf = new QBuffer(this); buf->setData(xml); @@ -563,8 +561,8 @@ QList PropfindJob::properties() const bool PropfindJob::finished() { qCInfo(lcPropfindJob) << "PROPFIND of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); int http_result_code = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); @@ -587,7 +585,7 @@ bool PropfindJob::finished() } } if (type == QXmlStreamReader::EndElement) { - if(curElement.top() == reader.name()) { + if (curElement.top() == reader.name()) { curElement.pop(); } } @@ -600,7 +598,7 @@ bool PropfindJob::finished() } } else { qCWarning(lcPropfindJob) << "*not* successful, http result code is" << http_result_code - << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); + << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); emit finishedWithError(reply()); } return true; @@ -628,11 +626,9 @@ bool AvatarJob::finished() QImage avImage; if (http_result_code == 200) { - QByteArray pngData = reply()->readAll(); - if( pngData.size() ) { - - if( avImage.loadFromData(pngData) ) { + if (pngData.size()) { + if (avImage.loadFromData(pngData)) { qCDebug(lcAvatarJob) << "Retrieved Avatar pixmap!"; } } @@ -646,7 +642,6 @@ bool AvatarJob::finished() ProppatchJob::ProppatchJob(AccountPtr account, const QString &path, QObject *parent) : AbstractNetworkJob(account, path, parent) { - } void ProppatchJob::start() @@ -665,7 +660,7 @@ void ProppatchJob::start() if (keyName.contains(':')) { int colIdx = keyName.lastIndexOf(":"); keyNs = keyName.left(colIdx); - keyName = keyName.mid(colIdx+1); + keyName = keyName.mid(colIdx + 1); } propStr += " <" + keyName; @@ -679,9 +674,8 @@ void ProppatchJob::start() QByteArray xml = "\n" "\n" " \n" - + propStr + - " \n" - "\n"; + + propStr + " \n" + "\n"; QBuffer *buf = new QBuffer(this); buf->setData(xml); @@ -703,8 +697,8 @@ QMap ProppatchJob::properties() const bool ProppatchJob::finished() { qCInfo(lcProppatchJob) << "PROPPATCH of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); int http_result_code = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); @@ -712,7 +706,7 @@ bool ProppatchJob::finished() emit success(); } else { qCWarning(lcProppatchJob) << "*not* successful, http result code is" << http_result_code - << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); + << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String("")); emit finishedWithError(); } return true; @@ -739,10 +733,12 @@ bool EntityExistsJob::finished() /*********************************************************************************************/ -JsonApiJob::JsonApiJob(const AccountPtr &account, const QString& path, QObject* parent): AbstractNetworkJob(account, path, parent) -{ } +JsonApiJob::JsonApiJob(const AccountPtr &account, const QString &path, QObject *parent) + : AbstractNetworkJob(account, path, parent) +{ +} -void JsonApiJob::addQueryParams(QList< QPair > params) +void JsonApiJob::addQueryParams(QList> params) { _additionalParams = params; } @@ -752,7 +748,7 @@ void JsonApiJob::start() QNetworkRequest req; req.setRawHeader("OCS-APIREQUEST", "true"); QUrl url = Utility::concatUrlPath(account()->url(), path()); - QList > params = _additionalParams; + QList> params = _additionalParams; params << qMakePair(QString::fromLatin1("format"), QString::fromLatin1("json")); url.setQueryItems(params); sendRequest("GET", url, req); @@ -762,8 +758,8 @@ void JsonApiJob::start() bool JsonApiJob::finished() { qCInfo(lcJsonApiJob) << "JsonApiJob of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); int statusCode = 0; @@ -774,9 +770,9 @@ bool JsonApiJob::finished() } QString jsonStr = QString::fromUtf8(reply()->readAll()); - if( jsonStr.contains( "") ) { + if (jsonStr.contains("")) { QRegExp rex("(\\d+)"); - if( jsonStr.contains(rex) ) { + if (jsonStr.contains(rex)) { // this is a error message coming back from ocs. statusCode = rex.cap(1).toInt(); } @@ -784,7 +780,7 @@ bool JsonApiJob::finished() } else { QRegExp rex("\"statuscode\":(\\d+),"); // example: "{"ocs":{"meta":{"status":"ok","statuscode":100,"message":null},"data":{"version":{"major":8,"minor":"... (504) - if( jsonStr.contains(rex) ) { + if (jsonStr.contains(rex)) { statusCode = rex.cap(1).toInt(); } } diff --git a/src/libsync/networkjobs.h b/src/libsync/networkjobs.h index 4ddbf83e2..8929391f2 100644 --- a/src/libsync/networkjobs.h +++ b/src/libsync/networkjobs.h @@ -27,14 +27,15 @@ namespace OCC { * @brief The EntityExistsJob class * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT EntityExistsJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT EntityExistsJob : public AbstractNetworkJob +{ Q_OBJECT public: - explicit EntityExistsJob(AccountPtr account, const QString &path, QObject* parent = 0); + explicit EntityExistsJob(AccountPtr account, const QString &path, QObject *parent = 0); void start() Q_DECL_OVERRIDE; signals: - void exists(QNetworkReply*); + void exists(QNetworkReply *); private slots: virtual bool finished() Q_DECL_OVERRIDE; @@ -44,22 +45,23 @@ private slots: * @brief The LsColJob class * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT LsColXMLParser : public QObject { +class OWNCLOUDSYNC_EXPORT LsColXMLParser : public QObject +{ Q_OBJECT public: explicit LsColXMLParser(); - bool parse(const QByteArray &xml, QHash *sizes, const QString& expectedPath); + bool parse(const QByteArray &xml, QHash *sizes, const QString &expectedPath); signals: void directoryListingSubfolders(const QStringList &items); - void directoryListingIterated(const QString &name, const QMap &properties); + void directoryListingIterated(const QString &name, const QMap &properties); void finishedWithError(QNetworkReply *reply); void finishedWithoutError(); - }; -class OWNCLOUDSYNC_EXPORT LsColJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT LsColJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit LsColJob(AccountPtr account, const QString &path, QObject *parent = 0); @@ -80,7 +82,7 @@ public: signals: void directoryListingSubfolders(const QStringList &items); - void directoryListingIterated(const QString &name, const QMap &properties); + void directoryListingIterated(const QString &name, const QMap &properties); void finishedWithError(QNetworkReply *reply); void finishedWithoutError(); @@ -102,7 +104,8 @@ private: * * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT PropfindJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT PropfindJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit PropfindJob(AccountPtr account, const QString &path, QObject *parent = 0); @@ -140,7 +143,8 @@ private: * * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT AvatarJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT AvatarJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit AvatarJob(AccountPtr account, QObject *parent = 0); @@ -169,7 +173,8 @@ private: * * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT ProppatchJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT ProppatchJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit ProppatchJob(AccountPtr account, const QString &path, QObject *parent = 0); @@ -201,14 +206,16 @@ private: * @brief The MkColJob class * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT MkColJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT MkColJob : public AbstractNetworkJob +{ Q_OBJECT QUrl _url; // Only used if the constructor taking a url is taken. QMap _extraHeaders; + public: explicit MkColJob(AccountPtr account, const QString &path, QObject *parent = 0); explicit MkColJob(AccountPtr account, const QUrl &url, - const QMap &extraHeaders, QObject *parent = 0); + const QMap &extraHeaders, QObject *parent = 0); void start() Q_DECL_OVERRIDE; signals: @@ -222,7 +229,8 @@ private slots: * @brief The CheckServerJob class * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT CheckServerJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT CheckServerJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit CheckServerJob(AccountPtr account, QObject *parent = 0); @@ -233,14 +241,14 @@ public: static bool installed(const QJsonObject &info); signals: - void instanceFound(const QUrl&url, const QJsonObject &info); + void instanceFound(const QUrl &url, const QJsonObject &info); /** Emitted on invalid status.php reply. * * \a reply is never null */ void instanceNotFound(QNetworkReply *reply); - void timeout(const QUrl&url); + void timeout(const QUrl &url); private: bool finished() Q_DECL_OVERRIDE; @@ -257,7 +265,8 @@ private: /** * @brief The RequestEtagJob class */ -class OWNCLOUDSYNC_EXPORT RequestEtagJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT RequestEtagJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit RequestEtagJob(AccountPtr account, const QString &path, QObject *parent = 0); @@ -285,7 +294,8 @@ private slots: * * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT JsonApiJob : public AbstractNetworkJob { +class OWNCLOUDSYNC_EXPORT JsonApiJob : public AbstractNetworkJob +{ Q_OBJECT public: explicit JsonApiJob(const AccountPtr &account, const QString &path, QObject *parent = 0); @@ -300,10 +310,11 @@ public: * * This function needs to be called before start() obviously. */ - void addQueryParams(QList< QPair > params); + void addQueryParams(QList> params); public slots: void start() Q_DECL_OVERRIDE; + protected: bool finished() Q_DECL_OVERRIDE; signals: @@ -316,7 +327,7 @@ signals: void jsonReceived(const QJsonDocument &json, int statusCode); private: - QList< QPair > _additionalParams; + QList> _additionalParams; }; } // namespace OCC diff --git a/src/libsync/owncloudpropagator.cpp b/src/libsync/owncloudpropagator.cpp index 2f18e45c5..62f12f023 100644 --- a/src/libsync/owncloudpropagator.cpp +++ b/src/libsync/owncloudpropagator.cpp @@ -74,7 +74,8 @@ qint64 freeSpaceLimit() } OwncloudPropagator::~OwncloudPropagator() -{} +{ +} int OwncloudPropagator::maximumActiveTransferJob() @@ -83,7 +84,7 @@ int OwncloudPropagator::maximumActiveTransferJob() // disable parallelism when there is a network limit. return 1; } - return qCeil(hardMaximumActiveJob()/2.); + return qCeil(hardMaximumActiveJob() / 2.); } /* The maximum number of active jobs in parallel */ @@ -110,7 +111,7 @@ PropagateItemJob::~PropagateItemJob() static time_t getMinBlacklistTime() { return qMax(qgetenv("OWNCLOUD_BLACKLIST_TIME_MIN").toInt(), - 25); // 25 seconds + 25); // 25 seconds } static time_t getMaxBlacklistTime() @@ -118,7 +119,7 @@ static time_t getMaxBlacklistTime() int v = qgetenv("OWNCLOUD_BLACKLIST_TIME_MAX").toInt(); if (v > 0) return v; - return 24*60*60; // 1 day + return 24 * 60 * 60; // 1 day } /** Creates a blacklist entry, possibly taking into account an old one. @@ -126,7 +127,7 @@ static time_t getMaxBlacklistTime() * The old entry may be invalid, then a fresh entry is created. */ static SyncJournalErrorBlacklistRecord createBlacklistEntry( - const SyncJournalErrorBlacklistRecord& old, const SyncFileItem& item) + const SyncJournalErrorBlacklistRecord &old, const SyncFileItem &item) { SyncJournalErrorBlacklistRecord entry; @@ -145,18 +146,18 @@ static SyncJournalErrorBlacklistRecord createBlacklistEntry( // The factor of 5 feels natural: 25s, 2 min, 10 min, ~1h, ~5h, ~24h entry._ignoreDuration = old._ignoreDuration * 5; - if( item._httpErrorCode == 403 ) { + if (item._httpErrorCode == 403) { qCWarning(lcPropagator) << "Probably firewall error: " << item._httpErrorCode << ", blacklisting up to 1h only"; - entry._ignoreDuration = qMin(entry._ignoreDuration, time_t(60*60)); + entry._ignoreDuration = qMin(entry._ignoreDuration, time_t(60 * 60)); - } else if( item._httpErrorCode == 413 || item._httpErrorCode == 415 ) { + } else if (item._httpErrorCode == 413 || item._httpErrorCode == 415) { qCWarning(lcPropagator) << "Fatal Error condition" << item._httpErrorCode << ", maximum blacklist ignore time!"; entry._ignoreDuration = maxBlacklistTime; } entry._ignoreDuration = qBound(minBlacklistTime, entry._ignoreDuration, maxBlacklistTime); - if( item._status == SyncFileItem::SoftError ) { + if (item._status == SyncFileItem::SoftError) { // Track these errors, but don't actively suppress them. entry._ignoreDuration = 0; } @@ -168,15 +169,15 @@ static SyncJournalErrorBlacklistRecord createBlacklistEntry( * * May adjust the status or item._errorString. */ -static void blacklistUpdate(SyncJournalDb* journal, SyncFileItem& item) +static void blacklistUpdate(SyncJournalDb *journal, SyncFileItem &item) { SyncJournalErrorBlacklistRecord oldEntry = journal->errorBlacklistEntry(item._file); bool mayBlacklist = - item._errorMayBeBlacklisted // explicitly flagged for blacklisting - || ((item._status == SyncFileItem::NormalError - || item._status == SyncFileItem::SoftError) - && item._httpErrorCode != 0 // or non-local error + item._errorMayBeBlacklisted // explicitly flagged for blacklisting + || ((item._status == SyncFileItem::NormalError + || item._status == SyncFileItem::SoftError) + && item._httpErrorCode != 0 // or non-local error ); // No new entry? Possibly remove the old one, then done. @@ -198,17 +199,17 @@ static void blacklistUpdate(SyncJournalDb* journal, SyncFileItem& item) item._errorString.prepend(PropagateItemJob::tr("Continue blacklisting:") + " "); qCInfo(lcPropagator) << "blacklisting " << item._file - << " for " << newEntry._ignoreDuration - << ", retry count " << newEntry._retryCount; + << " for " << newEntry._ignoreDuration + << ", retry count " << newEntry._retryCount; return; } // Some soft errors might become louder on repeat occurrence if (item._status == SyncFileItem::SoftError - && newEntry._retryCount > 1) { + && newEntry._retryCount > 1) { qCWarning(lcPropagator) << "escalating soft error on " << item._file - << " to normal error, " << item._httpErrorCode; + << " to normal error, " << item._httpErrorCode; item._status = SyncFileItem::NormalError; return; } @@ -220,26 +221,25 @@ void PropagateItemJob::done(SyncFileItem::Status statusArg, const QString &error _state = Finished; if (_item->_isRestoration) { - if( _item->_status == SyncFileItem::Success - || _item->_status == SyncFileItem::Conflict) { + if (_item->_status == SyncFileItem::Success + || _item->_status == SyncFileItem::Conflict) { _item->_status = SyncFileItem::Restoration; } else { _item->_errorString += tr("; Restoration Failed: %1").arg(errorString); } } else { - if( _item->_errorString.isEmpty() ) { + if (_item->_errorString.isEmpty()) { _item->_errorString = errorString; } } - if( propagator()->_abortRequested.fetchAndAddRelaxed(0) && - (_item->_status == SyncFileItem::NormalError - || _item->_status == SyncFileItem::FatalError)) { + if (propagator()->_abortRequested.fetchAndAddRelaxed(0) && (_item->_status == SyncFileItem::NormalError + || _item->_status == SyncFileItem::FatalError)) { // an abort request is ongoing. Change the status to Soft-Error _item->_status = SyncFileItem::SoftError; } - switch( _item->_status ) { + switch (_item->_status) { case SyncFileItem::SoftError: case SyncFileItem::FatalError: case SyncFileItem::NormalError: @@ -248,11 +248,11 @@ void PropagateItemJob::done(SyncFileItem::Status statusArg, const QString &error break; case SyncFileItem::Success: case SyncFileItem::Restoration: - if( _item->_hasBlacklistEntry ) { + if (_item->_hasBlacklistEntry) { // wipe blacklist entry. propagator()->_journal->wipeErrorBlacklistEntry(_item->_file); // remove a blacklist entry in case the file was moved. - if( _item->_originalFile != _item->_file ) { + if (_item->_originalFile != _item->_file) { propagator()->_journal->wipeErrorBlacklistEntry(_item->_originalFile); } } @@ -283,15 +283,15 @@ void PropagateItemJob::done(SyncFileItem::Status statusArg, const QString &error * * Return true if the problem is handled. */ -bool PropagateItemJob::checkForProblemsWithShared(int httpStatusCode, const QString& msg) +bool PropagateItemJob::checkForProblemsWithShared(int httpStatusCode, const QString &msg) { PropagateItemJob *newJob = NULL; - if( httpStatusCode == 403 && propagator()->isInSharedDirectory(_item->_file )) { - if( !_item->_isDirectory ) { + if (httpStatusCode == 403 && propagator()->isInSharedDirectory(_item->_file)) { + if (!_item->_isDirectory) { SyncFileItemPtr downloadItem(new SyncFileItem(*_item)); if (downloadItem->_instruction == CSYNC_INSTRUCTION_NEW - || downloadItem->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE) { + || downloadItem->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE) { // don't try to recover pushing new files return false; } else if (downloadItem->_instruction == CSYNC_INSTRUCTION_SYNC) { @@ -319,11 +319,11 @@ bool PropagateItemJob::checkForProblemsWithShared(int httpStatusCode, const QStr propagator()->_journal->avoidRenamesOnNextSync(_item->_file); propagator()->_anotherSyncNeeded = true; } - if( newJob ) { + if (newJob) { newJob->setRestoreJobMsg(msg); _restoreJob.reset(newJob); connect(_restoreJob.data(), SIGNAL(finished(SyncFileItem::Status)), - this, SLOT(slotRestoreJobFinished(SyncFileItem::Status))); + this, SLOT(slotRestoreJobFinished(SyncFileItem::Status))); QMetaObject::invokeMethod(newJob, "start"); } return true; @@ -334,78 +334,81 @@ bool PropagateItemJob::checkForProblemsWithShared(int httpStatusCode, const QStr void PropagateItemJob::slotRestoreJobFinished(SyncFileItem::Status status) { QString msg; - if(_restoreJob) { + if (_restoreJob) { msg = _restoreJob->restoreJobMsg(); _restoreJob->setRestoreJobMsg(); } - if( status == SyncFileItem::Success || status == SyncFileItem::Conflict - || status == SyncFileItem::Restoration) { - done( SyncFileItem::SoftError, msg); + if (status == SyncFileItem::Success || status == SyncFileItem::Conflict + || status == SyncFileItem::Restoration) { + done(SyncFileItem::SoftError, msg); } else { - done( status, tr("A file or folder was removed from a read only share, but restoring failed: %1").arg(msg) ); + done(status, tr("A file or folder was removed from a read only share, but restoring failed: %1").arg(msg)); } } // ================================================================================ -PropagateItemJob* OwncloudPropagator::createJob(const SyncFileItemPtr &item) { +PropagateItemJob *OwncloudPropagator::createJob(const SyncFileItemPtr &item) +{ bool deleteExisting = item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE; - switch(item->_instruction) { - case CSYNC_INSTRUCTION_REMOVE: - if (item->_direction == SyncFileItem::Down) return new PropagateLocalRemove(this, item); - else return new PropagateRemoteDelete(this, item); - case CSYNC_INSTRUCTION_NEW: - case CSYNC_INSTRUCTION_TYPE_CHANGE: - if (item->_isDirectory) { - if (item->_direction == SyncFileItem::Down) { - auto job = new PropagateLocalMkdir(this, item); - job->setDeleteExistingFile(deleteExisting); - return job; - } else { - auto job = new PropagateRemoteMkdir(this, item); - job->setDeleteExisting(deleteExisting); - return job; - } - } //fall through - case CSYNC_INSTRUCTION_SYNC: - case CSYNC_INSTRUCTION_CONFLICT: - if (item->_direction != SyncFileItem::Up) { - auto job = new PropagateDownloadFile(this, item); - job->setDeleteExistingFolder(deleteExisting); + switch (item->_instruction) { + case CSYNC_INSTRUCTION_REMOVE: + if (item->_direction == SyncFileItem::Down) + return new PropagateLocalRemove(this, item); + else + return new PropagateRemoteDelete(this, item); + case CSYNC_INSTRUCTION_NEW: + case CSYNC_INSTRUCTION_TYPE_CHANGE: + if (item->_isDirectory) { + if (item->_direction == SyncFileItem::Down) { + auto job = new PropagateLocalMkdir(this, item); + job->setDeleteExistingFile(deleteExisting); return job; } else { - PropagateUploadFileCommon *job = 0; - if (item->_size > _chunkSize && account()->capabilities().chunkingNg()) { - job = new PropagateUploadFileNG(this, item); - } else { - job = new PropagateUploadFileV1(this, item); - } + auto job = new PropagateRemoteMkdir(this, item); job->setDeleteExisting(deleteExisting); return job; } - case CSYNC_INSTRUCTION_RENAME: - if (item->_direction == SyncFileItem::Up) { - return new PropagateRemoteMove(this, item); + } //fall through + case CSYNC_INSTRUCTION_SYNC: + case CSYNC_INSTRUCTION_CONFLICT: + if (item->_direction != SyncFileItem::Up) { + auto job = new PropagateDownloadFile(this, item); + job->setDeleteExistingFolder(deleteExisting); + return job; + } else { + PropagateUploadFileCommon *job = 0; + if (item->_size > _chunkSize && account()->capabilities().chunkingNg()) { + job = new PropagateUploadFileNG(this, item); } else { - return new PropagateLocalRename(this, item); + job = new PropagateUploadFileV1(this, item); } - case CSYNC_INSTRUCTION_IGNORE: - case CSYNC_INSTRUCTION_ERROR: - return new PropagateIgnoreJob(this, item); - default: - return 0; + job->setDeleteExisting(deleteExisting); + return job; + } + case CSYNC_INSTRUCTION_RENAME: + if (item->_direction == SyncFileItem::Up) { + return new PropagateRemoteMove(this, item); + } else { + return new PropagateLocalRename(this, item); + } + case CSYNC_INSTRUCTION_IGNORE: + case CSYNC_INSTRUCTION_ERROR: + return new PropagateIgnoreJob(this, item); + default: + return 0; } return 0; } quint64 OwncloudPropagator::smallFileSize() { - const quint64 smallFileSize = 100*1024; //default to 1 MB. Not dynamic right now. + const quint64 smallFileSize = 100 * 1024; //default to 1 MB. Not dynamic right now. return smallFileSize; } -void OwncloudPropagator::start(const SyncFileItemVector& items) +void OwncloudPropagator::start(const SyncFileItemVector &items) { Q_ASSERT(std::is_sorted(items.begin(), items.end())); @@ -415,31 +418,30 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) * When we enter a directory, we can create the directory job and push it on the stack. */ _rootJob.reset(new PropagateDirectory(this)); - QStack > directories; + QStack> directories; directories.push(qMakePair(QString(), _rootJob.data())); - QVector directoriesToRemove; + QVector directoriesToRemove; QString removedDirectory; - foreach(const SyncFileItemPtr &item, items) { - + foreach (const SyncFileItemPtr &item, items) { if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) { // this is an item in a directory which is going to be removed. - PropagateDirectory *delDirJob = qobject_cast(directoriesToRemove.first()); + PropagateDirectory *delDirJob = qobject_cast(directoriesToRemove.first()); if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) { // already taken care of. (by the removal of the parent directory) // increase the number of subjobs that would be there. - if( delDirJob ) { + if (delDirJob) { delDirJob->increaseAffectedCount(); } continue; } else if (item->_isDirectory - && (item->_instruction == CSYNC_INSTRUCTION_NEW - || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE)) { + && (item->_instruction == CSYNC_INSTRUCTION_NEW + || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE)) { // create a new directory within a deleted directory? That can happen if the directory // etag was not fetched properly on the previous sync because the sync was aborted // while uploading this directory (which is now removed). We can ignore it. - if( delDirJob ) { + if (delDirJob) { delDirJob->increaseAffectedCount(); } continue; @@ -449,7 +451,7 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) // all is good, the rename will be executed before the directory deletion } else { qCWarning(lcPropagator) << "WARNING: Job within a removed directory? This should not happen!" - << item->_file << item->_instruction; + << item->_file << item->_instruction; } } @@ -461,13 +463,13 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) PropagateDirectory *dir = new PropagateDirectory(this, item); if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE - && item->_direction == SyncFileItem::Up) { + && item->_direction == SyncFileItem::Up) { // Skip all potential uploads to the new folder. // Processing them now leads to problems with permissions: // checkForPermissions() has already run and used the permissions // of the file we're about to delete to decide whether uploading // to the new dir is ok... - foreach(const SyncFileItemPtr &item2, items) { + foreach (const SyncFileItemPtr &item2, items) { if (item2->destination().startsWith(item->destination() + "/")) { item2->_instruction = CSYNC_INSTRUCTION_NONE; _anotherSyncNeeded = true; @@ -490,10 +492,10 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) directories[i].second->_item->_instruction = CSYNC_INSTRUCTION_NONE; } } else { - PropagateDirectory* currentDirJob = directories.top().second; + PropagateDirectory *currentDirJob = directories.top().second; currentDirJob->appendJob(dir); } - directories.push(qMakePair(item->destination() + "/" , dir)); + directories.push(qMakePair(item->destination() + "/", dir)); } else { if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE) { // will delete directories, so defer execution @@ -505,7 +507,7 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) } } - foreach(PropagatorJob* it, directoriesToRemove) { + foreach (PropagatorJob *it, directoriesToRemove) { _rootJob->appendJob(it); } @@ -514,12 +516,12 @@ void OwncloudPropagator::start(const SyncFileItemVector& items) scheduleNextJob(); } -const SyncOptions& OwncloudPropagator::syncOptions() const +const SyncOptions &OwncloudPropagator::syncOptions() const { return _syncOptions; } -void OwncloudPropagator::setSyncOptions(const SyncOptions& syncOptions) +void OwncloudPropagator::setSyncOptions(const SyncOptions &syncOptions) { _syncOptions = syncOptions; _chunkSize = syncOptions._initialChunkSize; @@ -527,14 +529,14 @@ void OwncloudPropagator::setSyncOptions(const SyncOptions& syncOptions) // ownCloud server < 7.0 did not had permissions so we need some other euristics // to detect wrong doing in a Shared directory -bool OwncloudPropagator::isInSharedDirectory(const QString& file) +bool OwncloudPropagator::isInSharedDirectory(const QString &file) { bool re = false; - if( _remoteFolder.startsWith( QLatin1String("Shared") ) ) { + if (_remoteFolder.startsWith(QLatin1String("Shared"))) { // The Shared directory is synced as its own sync connection re = true; } else { - if( file.startsWith("Shared/") || file == "Shared" ) { + if (file.startsWith("Shared/") || file == "Shared") { // The whole ownCloud is synced and Shared is always a top dir re = true; } @@ -551,17 +553,16 @@ int OwncloudPropagator::httpTimeout() ConfigFile cfg; timeout = cfg.timeout(); } - } return timeout; } -bool OwncloudPropagator::localFileNameClash( const QString& relFile ) +bool OwncloudPropagator::localFileNameClash(const QString &relFile) { bool re = false; - const QString file( _localDir + relFile ); + const QString file(_localDir + relFile); - if( !file.isEmpty() && Utility::fsCasePreserving() ) { + if (!file.isEmpty() && Utility::fsCasePreserving()) { #ifdef Q_OS_MAC QFileInfo fileInfo(file); if (!fileInfo.exists()) { @@ -572,22 +573,22 @@ bool OwncloudPropagator::localFileNameClash( const QString& relFile ) // https://bugreports.qt-project.org/browse/QTBUG-39622 const QString cName = fileInfo.canonicalFilePath().normalized(QString::NormalizationForm_C); bool equal = (file == cName); - re = (!equal && ! cName.endsWith(relFile, Qt::CaseSensitive) ); + re = (!equal && !cName.endsWith(relFile, Qt::CaseSensitive)); } #elif defined(Q_OS_WIN) - const QString file( _localDir + relFile ); + const QString file(_localDir + relFile); qCDebug(lcPropagator) << "CaseClashCheck for " << file; WIN32_FIND_DATA FindFileData; HANDLE hFind; - hFind = FindFirstFileW( (wchar_t*)file.utf16(), &FindFileData); + hFind = FindFirstFileW((wchar_t *)file.utf16(), &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { // returns false. } else { - QString realFileName = QString::fromWCharArray( FindFileData.cFileName ); + QString realFileName = QString::fromWCharArray(FindFileData.cFileName); FindClose(hFind); - if( ! file.endsWith(realFileName, Qt::CaseSensitive) ) { + if (!file.endsWith(realFileName, Qt::CaseSensitive)) { qCWarning(lcPropagator) << "Detected case clash between" << file << "and" << realFileName; re = true; } @@ -610,19 +611,19 @@ bool OwncloudPropagator::hasCaseClashAccessibilityProblem(const QString &relfile { #ifdef Q_OS_WIN bool result = false; - const QString file( _localDir + relfile ); + const QString file(_localDir + relfile); WIN32_FIND_DATA FindFileData; HANDLE hFind; - hFind = FindFirstFileW(reinterpret_cast(file.utf16()), &FindFileData); + hFind = FindFirstFileW(reinterpret_cast(file.utf16()), &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { - QString firstFile = QString::fromWCharArray( FindFileData.cFileName ); + QString firstFile = QString::fromWCharArray(FindFileData.cFileName); if (FindNextFile(hFind, &FindFileData)) { - QString secondFile = QString::fromWCharArray( FindFileData.cFileName ); + QString secondFile = QString::fromWCharArray(FindFileData.cFileName); // This extra check shouldn't be necessary, but ensures that there // are two different filenames that are identical when case is ignored. if (firstFile != secondFile - && QString::compare(firstFile, secondFile, Qt::CaseInsensitive) == 0) { + && QString::compare(firstFile, secondFile, Qt::CaseInsensitive) == 0) { result = true; qCWarning(lcPropagator) << "Found two filepaths that only differ in case: " << firstFile << secondFile; } @@ -636,7 +637,7 @@ bool OwncloudPropagator::hasCaseClashAccessibilityProblem(const QString &relfile #endif } -QString OwncloudPropagator::getFilePath(const QString& tmp_file_name) const +QString OwncloudPropagator::getFilePath(const QString &tmp_file_name) const { return _localDir + tmp_file_name; } @@ -669,7 +670,7 @@ void OwncloudPropagator::scheduleNextJobImpl() } } if (_activeJobList.count() < maximumActiveTransferJob() + likelyFinishedQuicklyCount) { - qCDebug(lcPropagator) << "Can pump in another request! activeJobs =" << _activeJobList.count(); + qCDebug(lcPropagator) << "Can pump in another request! activeJobs =" << _activeJobList.count(); if (_rootJob->scheduleSelfOrChild()) { scheduleNextJob(); } @@ -711,12 +712,11 @@ PropagatorJob::PropagatorJob(OwncloudPropagator *propagator) : QObject(propagator) , _state(NotYetStarted) { - } OwncloudPropagator *PropagatorJob::propagator() const { - return qobject_cast(parent()); + return qobject_cast(parent()); } // ================================================================================ @@ -822,13 +822,13 @@ void PropagatorCompositeJob::finalize() return; _state = Finished; - emit finished(_hasError == SyncFileItem::NoStatus ? SyncFileItem::Success : _hasError); + emit finished(_hasError == SyncFileItem::NoStatus ? SyncFileItem::Success : _hasError); } qint64 PropagatorCompositeJob::committedDiskSpace() const { qint64 needed = 0; - foreach (PropagatorJob* job, _runningJobs) { + foreach (PropagatorJob *job, _runningJobs) { needed += job->committedDiskSpace(); } return needed; @@ -881,7 +881,6 @@ bool PropagateDirectory::scheduleSelfOrChild() } return _subJobs.scheduleSelfOrChild(); - } void PropagateDirectory::slotFirstJobFinished(SyncFileItem::Status status) @@ -903,9 +902,9 @@ void PropagateDirectory::slotFirstJobFinished(SyncFileItem::Status status) void PropagateDirectory::slotSubJobsFinished(SyncFileItem::Status status) { if (!_item->isEmpty() && status == SyncFileItem::Success) { - if( !_item->_renameTarget.isEmpty() ) { - if(_item->_instruction == CSYNC_INSTRUCTION_RENAME - && _item->_originalFile != _item->_renameTarget) { + if (!_item->_renameTarget.isEmpty()) { + if (_item->_instruction == CSYNC_INSTRUCTION_RENAME + && _item->_originalFile != _item->_renameTarget) { // Remove the stale entries from the database. propagator()->_journal->deleteFileRecord(_item->_originalFile, true); } @@ -919,13 +918,13 @@ void PropagateDirectory::slotSubJobsFinished(SyncFileItem::Status status) if (_item->_instruction == CSYNC_INSTRUCTION_RENAME || _item->_instruction == CSYNC_INSTRUCTION_NEW || _item->_instruction == CSYNC_INSTRUCTION_UPDATE_METADATA) { - if (PropagateRemoteMkdir* mkdir = qobject_cast(_firstJob.data())) { + if (PropagateRemoteMkdir *mkdir = qobject_cast(_firstJob.data())) { // special case from MKDIR, get the fileId from the job there if (_item->_fileId.isEmpty() && !mkdir->_item->_fileId.isEmpty()) { _item->_fileId = mkdir->_item->_fileId; } } - SyncJournalFileRecord record(*_item, propagator()->_localDir + _item->_file); + SyncJournalFileRecord record(*_item, propagator()->_localDir + _item->_file); bool ok = propagator()->_journal->setFileRecordMetadata(record); if (!ok) { status = _item->_status = SyncFileItem::FatalError; @@ -941,7 +940,8 @@ void PropagateDirectory::slotSubJobsFinished(SyncFileItem::Status status) // ================================================================================ CleanupPollsJob::~CleanupPollsJob() -{} +{ +} void CleanupPollsJob::start() { @@ -985,5 +985,4 @@ void CleanupPollsJob::slotPollFinished() // Continue with the next entry, or finish start(); } - } diff --git a/src/libsync/owncloudpropagator.h b/src/libsync/owncloudpropagator.h index 0f42635f1..0e7dd573c 100644 --- a/src/libsync/owncloudpropagator.h +++ b/src/libsync/owncloudpropagator.h @@ -59,11 +59,12 @@ class OwncloudPropagator; * * @ingroup libsync */ -class PropagatorJob : public QObject { +class PropagatorJob : public QObject +{ Q_OBJECT public: - explicit PropagatorJob(OwncloudPropagator* propagator); + explicit PropagatorJob(OwncloudPropagator *propagator); enum JobState { NotYetStarted, @@ -118,21 +119,24 @@ protected: /* * Abstract class to propagate a single item */ -class PropagateItemJob : public PropagatorJob { +class PropagateItemJob : public PropagatorJob +{ Q_OBJECT protected: void done(SyncFileItem::Status status, const QString &errorString = QString()); - bool checkForProblemsWithShared(int httpStatusCode, const QString& msg); + bool checkForProblemsWithShared(int httpStatusCode, const QString &msg); /* * set a custom restore job message that is used if the restore job succeeded. * It is displayed in the activity view. */ - QString restoreJobMsg() const { + QString restoreJobMsg() const + { return _item->_isRestoration ? _item->_errorString : QString(); } - void setRestoreJobMsg( const QString& msg = QString() ) { + void setRestoreJobMsg(const QString &msg = QString()) + { _item->_isRestoration = true; _item->_errorString = msg; } @@ -144,15 +148,19 @@ private: QScopedPointer _restoreJob; public: - PropagateItemJob(OwncloudPropagator* propagator, const SyncFileItemPtr &item) - : PropagatorJob(propagator), _item(item) {} + PropagateItemJob(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagatorJob(propagator) + , _item(item) + { + } ~PropagateItemJob(); - bool scheduleSelfOrChild() Q_DECL_OVERRIDE { + bool scheduleSelfOrChild() Q_DECL_OVERRIDE + { if (_state != NotYetStarted) { return false; } - const char * instruction_str = csync_instruction_str(_item->_instruction); + const char *instruction_str = csync_instruction_str(_item->_instruction); qCInfo(lcPropagator) << "Starting" << instruction_str << "propagation of" << _item->_file << "by" << this; _state = Running; @@ -160,7 +168,7 @@ public: return true; } - SyncFileItemPtr _item; + SyncFileItemPtr _item; public slots: virtual void start() = 0; @@ -170,34 +178,40 @@ public slots: * @brief Job that runs subjobs. It becomes finished only when all subjobs are finished. * @ingroup libsync */ -class PropagatorCompositeJob : public PropagatorJob { +class PropagatorCompositeJob : public PropagatorJob +{ Q_OBJECT public: QVector _jobsToDo; SyncFileItemVector _tasksToDo; QVector _runningJobs; - SyncFileItem::Status _hasError; // NoStatus, or NormalError / SoftError if there was an error + SyncFileItem::Status _hasError; // NoStatus, or NormalError / SoftError if there was an error explicit PropagatorCompositeJob(OwncloudPropagator *propagator) : PropagatorJob(propagator) , _hasError(SyncFileItem::NoStatus) - { } + { + } - virtual ~PropagatorCompositeJob() { + virtual ~PropagatorCompositeJob() + { qDeleteAll(_jobsToDo); qDeleteAll(_runningJobs); } - void appendJob(PropagatorJob *job) { + void appendJob(PropagatorJob *job) + { _jobsToDo.append(job); } - void appendTask(const SyncFileItemPtr &item) { + void appendTask(const SyncFileItemPtr &item) + { _tasksToDo.append(item); } virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE; virtual JobParallelism parallelism() Q_DECL_OVERRIDE; - virtual void abort() Q_DECL_OVERRIDE { + virtual void abort() Q_DECL_OVERRIDE + { foreach (PropagatorJob *j, _runningJobs) j->abort(); } @@ -205,7 +219,8 @@ public: qint64 committedDiskSpace() const Q_DECL_OVERRIDE; private slots: - bool possiblyRunNextJob(PropagatorJob *next) { + bool possiblyRunNextJob(PropagatorJob *next) + { if (next->_state == NotYetStarted) { connect(next, SIGNAL(finished(SyncFileItem::Status)), this, SLOT(slotSubJobFinished(SyncFileItem::Status))); } @@ -220,39 +235,45 @@ private slots: * @brief Propagate a directory, and all its sub entries. * @ingroup libsync */ -class OWNCLOUDSYNC_EXPORT PropagateDirectory : public PropagatorJob { +class OWNCLOUDSYNC_EXPORT PropagateDirectory : public PropagatorJob +{ Q_OBJECT public: SyncFileItemPtr _item; // e.g: create the directory - QScopedPointer_firstJob; + QScopedPointer _firstJob; PropagatorCompositeJob _subJobs; explicit PropagateDirectory(OwncloudPropagator *propagator, const SyncFileItemPtr &item = SyncFileItemPtr(new SyncFileItem)); - void appendJob(PropagatorJob *job) { + void appendJob(PropagatorJob *job) + { _subJobs.appendJob(job); } - void appendTask(const SyncFileItemPtr &item) { + void appendTask(const SyncFileItemPtr &item) + { _subJobs.appendTask(item); } virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE; virtual JobParallelism parallelism() Q_DECL_OVERRIDE; - virtual void abort() Q_DECL_OVERRIDE { + virtual void abort() Q_DECL_OVERRIDE + { if (_firstJob) _firstJob->abort(); _subJobs.abort(); } - void increaseAffectedCount() { + void increaseAffectedCount() + { _firstJob->_item->_affectedItems++; } - qint64 committedDiskSpace() const Q_DECL_OVERRIDE { + qint64 committedDiskSpace() const Q_DECL_OVERRIDE + { return _subJobs.committedDiskSpace(); } @@ -267,45 +288,51 @@ private slots: * @brief Dummy job that just mark it as completed and ignored * @ingroup libsync */ -class PropagateIgnoreJob : public PropagateItemJob { +class PropagateIgnoreJob : public PropagateItemJob +{ Q_OBJECT public: - PropagateIgnoreJob(OwncloudPropagator* propagator,const SyncFileItemPtr& item) - : PropagateItemJob(propagator, item) {} - void start() Q_DECL_OVERRIDE { + PropagateIgnoreJob(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + { + } + void start() Q_DECL_OVERRIDE + { SyncFileItem::Status status = _item->_status; done(status == SyncFileItem::NoStatus ? SyncFileItem::FileIgnored : status, _item->_errorString); } }; -class OwncloudPropagator : public QObject { +class OwncloudPropagator : public QObject +{ Q_OBJECT public: const QString _localDir; // absolute path to the local directory. ends with '/' const QString _remoteFolder; // remote folder, ends with '/' - SyncJournalDb * const _journal; + SyncJournalDb *const _journal; bool _finishedEmited; // used to ensure that finished is only emitted once public: OwncloudPropagator(AccountPtr account, const QString &localDir, - const QString &remoteFolder, SyncJournalDb *progressDb) - : _localDir((localDir.endsWith(QChar('/'))) ? localDir : localDir+'/' ) - , _remoteFolder((remoteFolder.endsWith(QChar('/'))) ? remoteFolder : remoteFolder+'/' ) - , _journal(progressDb) - , _finishedEmited(false) - , _bandwidthManager(this) - , _anotherSyncNeeded(false) - , _chunkSize(10 * 1000 * 1000) // 10 MB, overridden in setSyncOptions - , _account(account) - { } + const QString &remoteFolder, SyncJournalDb *progressDb) + : _localDir((localDir.endsWith(QChar('/'))) ? localDir : localDir + '/') + , _remoteFolder((remoteFolder.endsWith(QChar('/'))) ? remoteFolder : remoteFolder + '/') + , _journal(progressDb) + , _finishedEmited(false) + , _bandwidthManager(this) + , _anotherSyncNeeded(false) + , _chunkSize(10 * 1000 * 1000) // 10 MB, overridden in setSyncOptions + , _account(account) + { + } ~OwncloudPropagator(); void start(const SyncFileItemVector &_syncedItems); - const SyncOptions& syncOptions() const; - void setSyncOptions(const SyncOptions& syncOptions); + const SyncOptions &syncOptions() const; + void setSyncOptions(const SyncOptions &syncOptions); QAtomicInt _downloadLimit; QAtomicInt _uploadLimit; @@ -319,7 +346,7 @@ public: Jobs add themself to the list when they do an assynchronous operation. Jobs can be several time on the list (example, when several chunks are uploaded in parallel) */ - QList _activeJobList; + QList _activeJobList; /** We detected that another sync is required after this one */ bool _anotherSyncNeeded; @@ -339,12 +366,12 @@ public: /* The maximum number of active jobs in parallel */ int hardMaximumActiveJob(); - bool isInSharedDirectory(const QString& file); + bool isInSharedDirectory(const QString &file); /** Check whether a download would clash with an existing file * in filesystems that are only case-preserving. */ - bool localFileNameClash(const QString& relfile); + bool localFileNameClash(const QString &relfile); /** Check whether a file is properly accessible for upload. * @@ -355,15 +382,16 @@ public: * When that happens, we want to avoid uploading incorrect data * and give up on the file. */ - bool hasCaseClashAccessibilityProblem(const QString& relfile); + bool hasCaseClashAccessibilityProblem(const QString &relfile); - QString getFilePath(const QString& tmp_file_name) const; + QString getFilePath(const QString &tmp_file_name) const; - PropagateItemJob *createJob(const SyncFileItemPtr& item); + PropagateItemJob *createJob(const SyncFileItemPtr &item); void scheduleNextJob(); - void reportProgress(const SyncFileItem&, quint64 bytes); + void reportProgress(const SyncFileItem &, quint64 bytes); - void abort() { + void abort() + { _abortRequested.fetchAndStoreOrdered(true); if (_rootJob) { // We're possibly already in an item's finished stack @@ -378,8 +406,7 @@ public: AccountPtr account() const; - enum DiskSpaceResult - { + enum DiskSpaceResult { DiskSpaceOk, DiskSpaceFailure, DiskSpaceCritical @@ -391,11 +418,11 @@ public: DiskSpaceResult diskSpaceCheck() const; - private slots: /** Emit the finished signal and make sure it is only emitted once */ - void emitFinished(SyncFileItem::Status status) { + void emitFinished(SyncFileItem::Status status) + { if (!_finishedEmited) emit finished(status == SyncFileItem::Success); _finishedEmited = true; @@ -405,7 +432,7 @@ private slots: signals: void itemCompleted(const SyncFileItemPtr &); - void progress(const SyncFileItem&, quint64 bytes); + void progress(const SyncFileItem &, quint64 bytes); void finished(bool success); /** Emitted when propagation has problems with a locked file. */ @@ -419,7 +446,6 @@ signals: void touchedFile(const QString &fileName); private: - AccountPtr _account; QScopedPointer _rootJob; SyncOptions _syncOptions; @@ -441,16 +467,24 @@ private: * @brief Job that wait for all the poll jobs to be completed * @ingroup libsync */ -class CleanupPollsJob : public QObject { +class CleanupPollsJob : public QObject +{ Q_OBJECT - QVector< SyncJournalDb::PollInfo > _pollInfos; + QVector _pollInfos; AccountPtr _account; SyncJournalDb *_journal; QString _localPath; + public: - explicit CleanupPollsJob(const QVector< SyncJournalDb::PollInfo > &pollInfos, AccountPtr account, - SyncJournalDb *journal, const QString &localPath, QObject* parent = 0) - : QObject(parent), _pollInfos(pollInfos), _account(account), _journal(journal), _localPath(localPath) {} + explicit CleanupPollsJob(const QVector &pollInfos, AccountPtr account, + SyncJournalDb *journal, const QString &localPath, QObject *parent = 0) + : QObject(parent) + , _pollInfos(pollInfos) + , _account(account) + , _journal(journal) + , _localPath(localPath) + { + } ~CleanupPollsJob(); @@ -465,7 +499,6 @@ signals: private slots: void slotPollFinished(); }; - } #endif diff --git a/src/libsync/owncloudpropagator_p.h b/src/libsync/owncloudpropagator_p.h index f68dc7b0b..eb4a0e181 100644 --- a/src/libsync/owncloudpropagator_p.h +++ b/src/libsync/owncloudpropagator_p.h @@ -22,7 +22,8 @@ namespace OCC { -inline QByteArray parseEtag(const char *header) { +inline QByteArray parseEtag(const char *header) +{ if (!header) return QByteArray(); QByteArray arr = header; @@ -34,7 +35,7 @@ inline QByteArray parseEtag(const char *header) { // https://github.com/owncloud/client/issues/1195 arr.replace("-gzip", ""); - if(arr.length() >= 2 && arr.startsWith('"') && arr.endsWith('"')) { + if (arr.length() >= 2 && arr.startsWith('"') && arr.endsWith('"')) { arr = arr.mid(1, arr.length() - 2); } return arr; @@ -58,9 +59,10 @@ inline QByteArray getEtagFromReply(QNetworkReply *reply) * Given an error from the network, map to a SyncFileItem::Status error */ inline SyncFileItem::Status classifyError(QNetworkReply::NetworkError nerror, - int httpCode, - bool* anotherSyncNeeded = NULL) { - Q_ASSERT (nerror != QNetworkReply::NoError); // we should only be called when there is an error + int httpCode, + bool *anotherSyncNeeded = NULL) +{ + Q_ASSERT(nerror != QNetworkReply::NoError); // we should only be called when there is an error if (nerror > QNetworkReply::NoError && nerror <= QNetworkReply::UnknownProxyError) { // network error or proxy error -> fatal @@ -82,11 +84,12 @@ inline SyncFileItem::Status classifyError(QNetworkReply::NetworkError nerror, if (httpCode == 423) { // "Locked" // Should be temporary. - if (anotherSyncNeeded) { *anotherSyncNeeded = true; } + if (anotherSyncNeeded) { + *anotherSyncNeeded = true; + } return SyncFileItem::SoftError; } return SyncFileItem::NormalError; } - } diff --git a/src/libsync/owncloudtheme.cpp b/src/libsync/owncloudtheme.cpp index db3a1ad1f..5528fe92d 100644 --- a/src/libsync/owncloudtheme.cpp +++ b/src/libsync/owncloudtheme.cpp @@ -30,8 +30,8 @@ namespace OCC { -ownCloudTheme::ownCloudTheme() : - Theme() +ownCloudTheme::ownCloudTheme() + : Theme() { } @@ -44,33 +44,31 @@ QString ownCloudTheme::about() const { QString devString; devString = trUtf8("

Version %2. For more information visit https://%4

" - "

For known issues and help, please visit: https://central.owncloud.org

" - "

By Klaas Freitag, Daniel Molkentin, Olivier Goffart, Markus Götz, " - " Jan-Christoph Borchardt, and others.

" - "

Copyright ownCloud GmbH

" - "

Licensed under the GNU General Public License (GPL) Version 2.0
" - "ownCloud and the ownCloud Logo are registered trademarks of ownCloud GmbH " - "in the United States, other countries, or both.

" - ) - .arg(Utility::escape(MIRALL_VERSION_STRING), - Utility::escape("https://" MIRALL_STRINGIFY(APPLICATION_DOMAIN)), - Utility::escape(MIRALL_STRINGIFY(APPLICATION_DOMAIN))); + "

For known issues and help, please visit: https://central.owncloud.org

" + "

By Klaas Freitag, Daniel Molkentin, Olivier Goffart, Markus Götz, " + " Jan-Christoph Borchardt, and others.

" + "

Copyright ownCloud GmbH

" + "

Licensed under the GNU General Public License (GPL) Version 2.0
" + "ownCloud and the ownCloud Logo are registered trademarks of ownCloud GmbH " + "in the United States, other countries, or both.

") + .arg(Utility::escape(MIRALL_VERSION_STRING), + Utility::escape("https://" MIRALL_STRINGIFY(APPLICATION_DOMAIN)), + Utility::escape(MIRALL_STRINGIFY(APPLICATION_DOMAIN))); devString += gitSHA1(); return devString; - } #ifndef TOKEN_AUTH_ONLY -QIcon ownCloudTheme::trayFolderIcon( const QString& ) const +QIcon ownCloudTheme::trayFolderIcon(const QString &) const { QPixmap fallback = qApp->style()->standardPixmap(QStyle::SP_FileDialogNewFolder); return QIcon::fromTheme("folder", fallback); } -QIcon ownCloudTheme::applicationIcon( ) const +QIcon ownCloudTheme::applicationIcon() const { - return themeIcon( QLatin1String("owncloud-icon") ); + return themeIcon(QLatin1String("owncloud-icon")); } @@ -121,7 +119,4 @@ QString ownCloudTheme::appNameGUI() const { return QLatin1String("ownCloud"); } - - } - diff --git a/src/libsync/owncloudtheme.h b/src/libsync/owncloudtheme.h index 0ad7f46d5..327c96e5f 100644 --- a/src/libsync/owncloudtheme.h +++ b/src/libsync/owncloudtheme.h @@ -33,8 +33,8 @@ public: QString about() const Q_DECL_OVERRIDE; #ifndef TOKEN_AUTH_ONLY - QIcon trayFolderIcon( const QString& ) const Q_DECL_OVERRIDE; - QIcon applicationIcon() const Q_DECL_OVERRIDE; + QIcon trayFolderIcon(const QString &) const Q_DECL_OVERRIDE; + QIcon applicationIcon() const Q_DECL_OVERRIDE; #endif QString appName() const Q_DECL_OVERRIDE; QString appNameGUI() const Q_DECL_OVERRIDE; @@ -43,15 +43,12 @@ public: #ifndef TOKEN_AUTH_ONLY QVariant customMedia(CustomMediaType type) Q_DECL_OVERRIDE; - QColor wizardHeaderBackgroundColor() const Q_DECL_OVERRIDE; - QColor wizardHeaderTitleColor() const Q_DECL_OVERRIDE; + QColor wizardHeaderBackgroundColor() const Q_DECL_OVERRIDE; + QColor wizardHeaderTitleColor() const Q_DECL_OVERRIDE; QPixmap wizardHeaderLogo() const Q_DECL_OVERRIDE; #endif private: - - }; - } #endif // OWNCLOUD_MIRALL_THEME_H diff --git a/src/libsync/ownsql.cpp b/src/libsync/ownsql.cpp index 620e9d5fd..6db35fda5 100644 --- a/src/libsync/ownsql.cpp +++ b/src/libsync/ownsql.cpp @@ -27,19 +27,22 @@ #define SQLITE_SLEEP_TIME_USEC 100000 #define SQLITE_REPEAT_COUNT 20 -#define SQLITE_DO(A) if(1) { \ - _errId = (A); if(_errId != SQLITE_OK) { _error= QString::fromUtf8(sqlite3_errmsg(_db)); \ - } } +#define SQLITE_DO(A) \ + if (1) { \ + _errId = (A); \ + if (_errId != SQLITE_OK) { \ + _error = QString::fromUtf8(sqlite3_errmsg(_db)); \ + } \ + } namespace OCC { Q_LOGGING_CATEGORY(lcSql, "sync.database.sql", QtInfoMsg) SqlDatabase::SqlDatabase() - :_db(0), - _errId(0) + : _db(0) + , _errId(0) { - } bool SqlDatabase::isOpen() @@ -47,23 +50,23 @@ bool SqlDatabase::isOpen() return _db != 0; } -bool SqlDatabase::openHelper( const QString& filename, int sqliteFlags ) +bool SqlDatabase::openHelper(const QString &filename, int sqliteFlags) { - if( isOpen() ) { + if (isOpen()) { return true; } sqliteFlags |= SQLITE_OPEN_NOMUTEX; - SQLITE_DO( sqlite3_open_v2(filename.toUtf8().constData(), &_db, sqliteFlags, 0) ); + SQLITE_DO(sqlite3_open_v2(filename.toUtf8().constData(), &_db, sqliteFlags, 0)); - if( _errId != SQLITE_OK ) { + if (_errId != SQLITE_OK) { qCWarning(lcSql) << "Error:" << _error << "for" << filename; close(); return false; } - if( !_db ) { + if (!_db) { qCWarning(lcSql) << "Error: no database for" << filename; return false; } @@ -78,14 +81,14 @@ bool SqlDatabase::checkDb() // quick_check can fail with a disk IO error when diskspace is low SqlQuery quick_check(*this); quick_check.prepare("PRAGMA quick_check;", /*allow_failure=*/true); - if( !quick_check.exec() ) { + if (!quick_check.exec()) { qCWarning(lcSql) << "Error running quick_check on database"; return false; } quick_check.next(); QString result = quick_check.stringValue(0); - if( result != "ok" ) { + if (result != "ok") { qCWarning(lcSql) << "quick_check returned failure:" << result; return false; } @@ -93,17 +96,17 @@ bool SqlDatabase::checkDb() return true; } -bool SqlDatabase::openOrCreateReadWrite( const QString& filename ) +bool SqlDatabase::openOrCreateReadWrite(const QString &filename) { - if( isOpen() ) { + if (isOpen()) { return true; } - if( !openHelper(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) ) { + if (!openHelper(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)) { return false; } - if( !checkDb() ) { + if (!checkDb()) { // When disk space is low, checking the db may fail even though it's fine. qint64 freeSpace = Utility::freeDiskSpace(QFileInfo(filename).dir().absolutePath()); if (freeSpace != -1 && freeSpace < 1000000) { @@ -122,17 +125,17 @@ bool SqlDatabase::openOrCreateReadWrite( const QString& filename ) return true; } -bool SqlDatabase::openReadOnly( const QString& filename ) +bool SqlDatabase::openReadOnly(const QString &filename) { - if( isOpen() ) { + if (isOpen()) { return true; } - if( !openHelper(filename, SQLITE_OPEN_READONLY) ) { + if (!openHelper(filename, SQLITE_OPEN_READONLY)) { return false; } - if( !checkDb() ) { + if (!checkDb()) { qCWarning(lcSql) << "Consistency check failed in readonly mode, giving up" << filename; close(); return false; @@ -150,8 +153,8 @@ QString SqlDatabase::error() const void SqlDatabase::close() { - if( _db ) { - SQLITE_DO(sqlite3_close(_db) ); + if (_db) { + SQLITE_DO(sqlite3_close(_db)); // Fatal because reopening an unclosed db might be problematic. ENFORCE(_errId == SQLITE_OK, "Error when closing DB"); _db = 0; @@ -160,7 +163,7 @@ void SqlDatabase::close() bool SqlDatabase::transaction() { - if( ! _db ) { + if (!_db) { return false; } SQLITE_DO(sqlite3_exec(_db, "BEGIN", 0, 0, 0)); @@ -169,63 +172,64 @@ bool SqlDatabase::transaction() bool SqlDatabase::commit() { - if( ! _db ) { + if (!_db) { return false; } SQLITE_DO(sqlite3_exec(_db, "COMMIT", 0, 0, 0)); return _errId == SQLITE_OK; } -sqlite3* SqlDatabase::sqliteDb() +sqlite3 *SqlDatabase::sqliteDb() { return _db; } /* =========================================================================================== */ -SqlQuery::SqlQuery( SqlDatabase& db ) - :_db(db.sqliteDb()), - _stmt(0), _errId(0) +SqlQuery::SqlQuery(SqlDatabase &db) + : _db(db.sqliteDb()) + , _stmt(0) + , _errId(0) { - } SqlQuery::~SqlQuery() { - if( _stmt ) { + if (_stmt) { finish(); } } -SqlQuery::SqlQuery(const QString& sql, SqlDatabase& db) - :_db(db.sqliteDb()), - _stmt(0), _errId(0) +SqlQuery::SqlQuery(const QString &sql, SqlDatabase &db) + : _db(db.sqliteDb()) + , _stmt(0) + , _errId(0) { prepare(sql); } -int SqlQuery::prepare( const QString& sql, bool allow_failure ) +int SqlQuery::prepare(const QString &sql, bool allow_failure) { QString s(sql); _sql = s.trimmed(); - if(_stmt ) { + if (_stmt) { finish(); } - if(!_sql.isEmpty() ) { + if (!_sql.isEmpty()) { int n = 0; int rc; do { rc = sqlite3_prepare_v2(_db, _sql.toUtf8().constData(), -1, &_stmt, 0); - if( (rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED) ) { + if ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)) { n++; OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC); } - } while( (n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED))); + } while ((n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED))); _errId = rc; - if( _errId != SQLITE_OK ) { + if (_errId != SQLITE_OK) { _error = QString::fromUtf8(sqlite3_errmsg(_db)); - qCWarning(lcSql) << "Sqlite prepare statement error:" << _error << "in" <<_sql; + qCWarning(lcSql) << "Sqlite prepare statement error:" << _error << "in" << _sql; ENFORCE(allow_failure, "SQLITE Prepare error"); } } @@ -252,24 +256,24 @@ bool SqlQuery::exec() } // Don't do anything for selects, that is how we use the lib :-| - if( !isSelect() && !isPragma() ) { + if (!isSelect() && !isPragma()) { int rc, n = 0; do { rc = sqlite3_step(_stmt); - if( rc == SQLITE_LOCKED ) { + if (rc == SQLITE_LOCKED) { rc = sqlite3_reset(_stmt); /* This will also return SQLITE_LOCKED */ n++; OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC); - } else if( rc == SQLITE_BUSY ) { + } else if (rc == SQLITE_BUSY) { OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC); n++; } - } while( (n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED))); + } while ((n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED))); _errId = rc; if (_errId != SQLITE_DONE && _errId != SQLITE_ROW) { _error = QString::fromUtf8(sqlite3_errmsg(_db)); - qCWarning(lcSql) << "Sqlite exec statement error:" << _errId << _error << "in" <<_sql; + qCWarning(lcSql) << "Sqlite exec statement error:" << _errId << _error << "in" << _sql; } else { qCDebug(lcSql) << "Last exec affected" << numRowsAffected() << "rows."; } @@ -285,7 +289,7 @@ bool SqlQuery::next() return _errId == SQLITE_ROW; } -void SqlQuery::bindValue(int pos, const QVariant& value) +void SqlQuery::bindValue(int pos, const QVariant &value) { qCDebug(lcSql) << "SQL bind" << pos << value; @@ -311,26 +315,27 @@ void SqlQuery::bindValue(int pos, const QVariant& value) const QDateTime dateTime = value.toDateTime(); const QString str = dateTime.toString(QLatin1String("yyyy-MM-ddThh:mm:ss.zzz")); res = sqlite3_bind_text16(_stmt, pos, str.utf16(), - str.size() * sizeof(ushort), SQLITE_TRANSIENT); + str.size() * sizeof(ushort), SQLITE_TRANSIENT); break; } case QVariant::Time: { const QTime time = value.toTime(); const QString str = time.toString(QLatin1String("hh:mm:ss.zzz")); res = sqlite3_bind_text16(_stmt, pos, str.utf16(), - str.size() * sizeof(ushort), SQLITE_TRANSIENT); + str.size() * sizeof(ushort), SQLITE_TRANSIENT); break; } case QVariant::String: { - if( !value.toString().isNull() ) { + if (!value.toString().isNull()) { // lifetime of string == lifetime of its qvariant - const QString *str = static_cast(value.constData()); + const QString *str = static_cast(value.constData()); res = sqlite3_bind_text16(_stmt, pos, str->utf16(), - (str->size()) * sizeof(QChar), SQLITE_TRANSIENT); + (str->size()) * sizeof(QChar), SQLITE_TRANSIENT); } else { res = sqlite3_bind_null(_stmt, pos); } - break; } + break; + } case QVariant::ByteArray: { auto ba = value.toByteArray(); res = sqlite3_bind_text(_stmt, pos, ba.constData(), ba.size(), SQLITE_TRANSIENT); @@ -340,13 +345,14 @@ void SqlQuery::bindValue(int pos, const QVariant& value) QString str = value.toString(); // SQLITE_TRANSIENT makes sure that sqlite buffers the data res = sqlite3_bind_text16(_stmt, pos, str.utf16(), - (str.size()) * sizeof(QChar), SQLITE_TRANSIENT); - break; } + (str.size()) * sizeof(QChar), SQLITE_TRANSIENT); + break; + } } if (res != SQLITE_OK) { qCWarning(lcSql) << "ERROR binding SQL value:" << value << "error:" << res; } - ASSERT( res == SQLITE_OK ); + ASSERT(res == SQLITE_OK); } bool SqlQuery::nullValue(int index) @@ -356,7 +362,7 @@ bool SqlQuery::nullValue(int index) QString SqlQuery::stringValue(int index) { - return QString::fromUtf16(static_cast(sqlite3_column_text16(_stmt, index))); + return QString::fromUtf16(static_cast(sqlite3_column_text16(_stmt, index))); } int SqlQuery::intValue(int index) @@ -371,8 +377,8 @@ quint64 SqlQuery::int64Value(int index) QByteArray SqlQuery::baValue(int index) { - return QByteArray( static_cast(sqlite3_column_blob(_stmt, index)), - sqlite3_column_bytes(_stmt, index)); + return QByteArray(static_cast(sqlite3_column_blob(_stmt, index)), + sqlite3_column_bytes(_stmt, index)); } QString SqlQuery::error() const diff --git a/src/libsync/ownsql.h b/src/libsync/ownsql.h index 211e77fdd..72c749091 100644 --- a/src/libsync/ownsql.h +++ b/src/libsync/ownsql.h @@ -35,22 +35,21 @@ public: explicit SqlDatabase(); bool isOpen(); - bool openOrCreateReadWrite( const QString& filename ); - bool openReadOnly( const QString& filename ); + bool openOrCreateReadWrite(const QString &filename); + bool openReadOnly(const QString &filename); bool transaction(); bool commit(); void close(); QString error() const; - sqlite3* sqliteDb(); + sqlite3 *sqliteDb(); private: - bool openHelper( const QString& filename, int sqliteFlags ); + bool openHelper(const QString &filename, int sqliteFlags); bool checkDb(); sqlite3 *_db; QString _error; // last error string int _errId; - }; /** @@ -61,12 +60,12 @@ class OWNCLOUDSYNC_EXPORT SqlQuery { Q_DISABLE_COPY(SqlQuery) public: - explicit SqlQuery(SqlDatabase& db); - explicit SqlQuery(const QString& sql, SqlDatabase& db); + explicit SqlQuery(SqlDatabase &db); + explicit SqlQuery(const QString &sql, SqlDatabase &db); ~SqlQuery(); QString error() const; - int errorId() const; + int errorId() const; /// Checks whether the value at the given column index is NULL bool nullValue(int index); @@ -80,9 +79,9 @@ public: bool isSelect(); bool isPragma(); bool exec(); - int prepare( const QString& sql, bool allow_failure = false ); + int prepare(const QString &sql, bool allow_failure = false); bool next(); - void bindValue(int pos, const QVariant& value); + void bindValue(int pos, const QVariant &value); QString lastQuery() const; int numRowsAffected(); void reset_and_clear_bindings(); diff --git a/src/libsync/progressdispatcher.cpp b/src/libsync/progressdispatcher.cpp index 6ed274730..8473bc3ad 100644 --- a/src/libsync/progressdispatcher.cpp +++ b/src/libsync/progressdispatcher.cpp @@ -20,66 +20,65 @@ namespace OCC { -ProgressDispatcher* ProgressDispatcher::_instance = 0; +ProgressDispatcher *ProgressDispatcher::_instance = 0; -QString Progress::asResultString( const SyncFileItem& item) +QString Progress::asResultString(const SyncFileItem &item) { - switch(item._instruction) { + switch (item._instruction) { case CSYNC_INSTRUCTION_SYNC: case CSYNC_INSTRUCTION_NEW: case CSYNC_INSTRUCTION_TYPE_CHANGE: if (item._direction != SyncFileItem::Up) { - return QCoreApplication::translate( "progress", "Downloaded"); + return QCoreApplication::translate("progress", "Downloaded"); } else { - return QCoreApplication::translate( "progress", "Uploaded"); + return QCoreApplication::translate("progress", "Uploaded"); } case CSYNC_INSTRUCTION_CONFLICT: - return QCoreApplication::translate( "progress", "Server version downloaded, copied changed local file into conflict file"); + return QCoreApplication::translate("progress", "Server version downloaded, copied changed local file into conflict file"); case CSYNC_INSTRUCTION_REMOVE: - return QCoreApplication::translate( "progress", "Deleted"); + return QCoreApplication::translate("progress", "Deleted"); case CSYNC_INSTRUCTION_EVAL_RENAME: case CSYNC_INSTRUCTION_RENAME: - return QCoreApplication::translate( "progress", "Moved to %1").arg(item._renameTarget); + return QCoreApplication::translate("progress", "Moved to %1").arg(item._renameTarget); case CSYNC_INSTRUCTION_IGNORE: - return QCoreApplication::translate( "progress", "Ignored"); + return QCoreApplication::translate("progress", "Ignored"); case CSYNC_INSTRUCTION_STAT_ERROR: - return QCoreApplication::translate( "progress", "Filesystem access error"); + return QCoreApplication::translate("progress", "Filesystem access error"); case CSYNC_INSTRUCTION_ERROR: - return QCoreApplication::translate( "progress", "Error"); + return QCoreApplication::translate("progress", "Error"); case CSYNC_INSTRUCTION_UPDATE_METADATA: - return QCoreApplication::translate( "progress", "Updated local metadata"); + return QCoreApplication::translate("progress", "Updated local metadata"); case CSYNC_INSTRUCTION_NONE: case CSYNC_INSTRUCTION_EVAL: - return QCoreApplication::translate( "progress", "Unknown"); - + return QCoreApplication::translate("progress", "Unknown"); } - return QCoreApplication::translate( "progress", "Unknown"); + return QCoreApplication::translate("progress", "Unknown"); } -QString Progress::asActionString( const SyncFileItem &item ) +QString Progress::asActionString(const SyncFileItem &item) { - switch(item._instruction) { + switch (item._instruction) { case CSYNC_INSTRUCTION_CONFLICT: case CSYNC_INSTRUCTION_SYNC: case CSYNC_INSTRUCTION_NEW: case CSYNC_INSTRUCTION_TYPE_CHANGE: if (item._direction != SyncFileItem::Up) - return QCoreApplication::translate( "progress", "downloading"); + return QCoreApplication::translate("progress", "downloading"); else - return QCoreApplication::translate( "progress", "uploading"); + return QCoreApplication::translate("progress", "uploading"); case CSYNC_INSTRUCTION_REMOVE: - return QCoreApplication::translate( "progress", "deleting"); + return QCoreApplication::translate("progress", "deleting"); case CSYNC_INSTRUCTION_EVAL_RENAME: case CSYNC_INSTRUCTION_RENAME: - return QCoreApplication::translate( "progress", "moving"); + return QCoreApplication::translate("progress", "moving"); case CSYNC_INSTRUCTION_IGNORE: - return QCoreApplication::translate( "progress", "ignoring"); + return QCoreApplication::translate("progress", "ignoring"); case CSYNC_INSTRUCTION_STAT_ERROR: - return QCoreApplication::translate( "progress", "error"); + return QCoreApplication::translate("progress", "error"); case CSYNC_INSTRUCTION_ERROR: - return QCoreApplication::translate( "progress", "error"); + return QCoreApplication::translate("progress", "error"); case CSYNC_INSTRUCTION_UPDATE_METADATA: - return QCoreApplication::translate( "progress", "updating local metadata"); + return QCoreApplication::translate("progress", "updating local metadata"); case CSYNC_INSTRUCTION_NONE: case CSYNC_INSTRUCTION_EVAL: break; @@ -87,48 +86,45 @@ QString Progress::asActionString( const SyncFileItem &item ) return QString(); } -bool Progress::isWarningKind( SyncFileItem::Status kind) +bool Progress::isWarningKind(SyncFileItem::Status kind) { - return kind == SyncFileItem::SoftError || kind == SyncFileItem::NormalError - || kind == SyncFileItem::FatalError || kind == SyncFileItem::FileIgnored - || kind == SyncFileItem::Conflict || kind == SyncFileItem::Restoration; - + return kind == SyncFileItem::SoftError || kind == SyncFileItem::NormalError + || kind == SyncFileItem::FatalError || kind == SyncFileItem::FileIgnored + || kind == SyncFileItem::Conflict || kind == SyncFileItem::Restoration; } -bool Progress::isIgnoredKind( SyncFileItem::Status kind) +bool Progress::isIgnoredKind(SyncFileItem::Status kind) { - return kind == SyncFileItem::FileIgnored; - + return kind == SyncFileItem::FileIgnored; } -ProgressDispatcher* ProgressDispatcher::instance() { +ProgressDispatcher *ProgressDispatcher::instance() +{ if (!_instance) { _instance = new ProgressDispatcher(); } return _instance; } -ProgressDispatcher::ProgressDispatcher(QObject *parent) : - QObject(parent) +ProgressDispatcher::ProgressDispatcher(QObject *parent) + : QObject(parent) { - } ProgressDispatcher::~ProgressDispatcher() { - } -void ProgressDispatcher::setProgressInfo(const QString& folder, const ProgressInfo& progress) +void ProgressDispatcher::setProgressInfo(const QString &folder, const ProgressInfo &progress) { - if( folder.isEmpty()) -// The update phase now also has progress -// (progress._currentItems.size() == 0 -// && progress._totalFileCount == 0) ) + if (folder.isEmpty()) + // The update phase now also has progress + // (progress._currentItems.size() == 0 + // && progress._totalFileCount == 0) ) { return; } - emit progressInfo( folder, progress ); + emit progressInfo(folder, progress); } ProgressInfo::ProgressInfo() @@ -170,9 +166,9 @@ static bool shouldCountProgress(const SyncFileItem &item) // Skip any ignored, error or non-propagated files and directories. if (instruction == CSYNC_INSTRUCTION_NONE - || instruction == CSYNC_INSTRUCTION_UPDATE_METADATA - || instruction == CSYNC_INSTRUCTION_IGNORE - || instruction == CSYNC_INSTRUCTION_ERROR) { + || instruction == CSYNC_INSTRUCTION_UPDATE_METADATA + || instruction == CSYNC_INSTRUCTION_IGNORE + || instruction == CSYNC_INSTRUCTION_ERROR) { return false; } @@ -286,25 +282,22 @@ ProgressInfo::Estimates ProgressInfo::totalProgress() const double fpsL = 0.5; double fpsU = 0.8; double nearMaxFps = - qBound(0.0, - (fps - fpsL * _maxFilesPerSecond) / - ((fpsU - fpsL) * _maxFilesPerSecond), - 1.0); + qBound(0.0, + (fps - fpsL * _maxFilesPerSecond) / ((fpsU - fpsL) * _maxFilesPerSecond), + 1.0); // Compute a value that is 0 when transfer is >= U*max and // 1 when transfer is <= L*max double trans = _sizeProgress._progressPerSec; double transU = 0.1; double transL = 0.01; - double slowTransfer = 1.0 - - qBound(0.0, - (trans - transL * _maxBytesPerSecond) / - ((transU - transL) * _maxBytesPerSecond), - 1.0); + double slowTransfer = 1.0 - qBound(0.0, + (trans - transL * _maxBytesPerSecond) / ((transU - transL) * _maxBytesPerSecond), + 1.0); double beOptimistic = nearMaxFps * slowTransfer; size.estimatedEta = (1.0 - beOptimistic) * size.estimatedEta - + beOptimistic * optimisticEta(); + + beOptimistic * optimisticEta(); return size; } @@ -316,7 +309,7 @@ quint64 ProgressInfo::optimisticEta() const // (if we never got to fully excercise transfer or files/second) return _fileProgress.remaining() / _maxFilesPerSecond * 1000 - + _sizeProgress.remaining() / _maxBytesPerSecond * 1000; + + _sizeProgress.remaining() / _maxBytesPerSecond * 1000; } bool ProgressInfo::trustEta() const @@ -342,15 +335,15 @@ void ProgressInfo::updateEstimates() } _maxFilesPerSecond = qMax(_fileProgress._progressPerSec, - _maxFilesPerSecond); + _maxFilesPerSecond); _maxBytesPerSecond = qMax(_sizeProgress._progressPerSec, - _maxBytesPerSecond); + _maxBytesPerSecond); } void ProgressInfo::recomputeCompletedSize() { quint64 r = _totalSizeOfCompletedJobs; - foreach(const ProgressItem &i, _currentItems) { + foreach (const ProgressItem &i, _currentItems) { if (isSizeDependent(i._item)) r += i._progress._completed; } @@ -400,6 +393,4 @@ void ProgressInfo::Progress::setCompleted(quint64 completed) _completed = qMin(completed, _total); _prevCompleted = qMin(_prevCompleted, _completed); } - - } diff --git a/src/libsync/progressdispatcher.h b/src/libsync/progressdispatcher.h index 47d6d1b3c..05aa06b4f 100644 --- a/src/libsync/progressdispatcher.h +++ b/src/libsync/progressdispatcher.h @@ -60,7 +60,7 @@ public: /** * Increase the file and size totals by the amount indicated in item. */ - void adjustTotalsForFile(const SyncFileItem & item); + void adjustTotalsForFile(const SyncFileItem &item); quint64 totalFiles() const; quint64 completedFiles() const; @@ -72,13 +72,12 @@ public: quint64 currentFile() const; /** Return true if the size needs to be taken in account in the total amount of time */ - static inline bool isSizeDependent(const SyncFileItem & item) + static inline bool isSizeDependent(const SyncFileItem &item) { - return ! item._isDirectory && ( - item._instruction == CSYNC_INSTRUCTION_CONFLICT - || item._instruction == CSYNC_INSTRUCTION_SYNC - || item._instruction == CSYNC_INSTRUCTION_NEW - || item._instruction == CSYNC_INSTRUCTION_TYPE_CHANGE); + return !item._isDirectory && (item._instruction == CSYNC_INSTRUCTION_CONFLICT + || item._instruction == CSYNC_INSTRUCTION_SYNC + || item._instruction == CSYNC_INSTRUCTION_NEW + || item._instruction == CSYNC_INSTRUCTION_TYPE_CHANGE); } /** @@ -211,12 +210,11 @@ private: namespace Progress { - OWNCLOUDSYNC_EXPORT QString asActionString( const SyncFileItem& item ); - OWNCLOUDSYNC_EXPORT QString asResultString( const SyncFileItem& item ); - - OWNCLOUDSYNC_EXPORT bool isWarningKind( SyncFileItem::Status ); - OWNCLOUDSYNC_EXPORT bool isIgnoredKind( SyncFileItem::Status ); + OWNCLOUDSYNC_EXPORT QString asActionString(const SyncFileItem &item); + OWNCLOUDSYNC_EXPORT QString asResultString(const SyncFileItem &item); + OWNCLOUDSYNC_EXPORT bool isWarningKind(SyncFileItem::Status); + OWNCLOUDSYNC_EXPORT bool isIgnoredKind(SyncFileItem::Status); } /** @@ -234,7 +232,7 @@ class OWNCLOUDSYNC_EXPORT ProgressDispatcher : public QObject friend class Folder; // only allow Folder class to access the setting slots. public: - static ProgressDispatcher* instance(); + static ProgressDispatcher *instance(); ~ProgressDispatcher(); signals: @@ -245,21 +243,20 @@ signals: @param[out] progress A struct with all progress info. */ - void progressInfo( const QString& folder, const ProgressInfo& progress ); + void progressInfo(const QString &folder, const ProgressInfo &progress); /** * @brief: the item was completed by a job */ - void itemCompleted(const QString &folder, const SyncFileItemPtr & item); + void itemCompleted(const QString &folder, const SyncFileItemPtr &item); protected: - void setProgressInfo(const QString& folder, const ProgressInfo& progress); + void setProgressInfo(const QString &folder, const ProgressInfo &progress); private: - ProgressDispatcher(QObject* parent = 0); + ProgressDispatcher(QObject *parent = 0); QElapsedTimer _timer; - static ProgressDispatcher* _instance; + static ProgressDispatcher *_instance; }; - } #endif // PROGRESSDISPATCHER_H diff --git a/src/libsync/propagatedownload.cpp b/src/libsync/propagatedownload.cpp index 7d05f3eb9..f20651a45 100644 --- a/src/libsync/propagatedownload.cpp +++ b/src/libsync/propagatedownload.cpp @@ -43,7 +43,8 @@ Q_LOGGING_CATEGORY(lcPropagateDownload, "sync.propagator.download", QtInfoMsg) // Always coming in with forward slashes. // In csync_excluded_no_ctx we ignore all files with longer than 254 chars // This function also adds a dot at the beginning of the filename to hide the file on OS X and Linux -QString OWNCLOUDSYNC_EXPORT createDownloadTmpFileName(const QString &previous) { +QString OWNCLOUDSYNC_EXPORT createDownloadTmpFileName(const QString &previous) +{ QString tmpFileName; QString tmpPath; int slashPos = previous.lastIndexOf('/'); @@ -52,10 +53,10 @@ QString OWNCLOUDSYNC_EXPORT createDownloadTmpFileName(const QString &previous) { tmpFileName = previous; tmpPath = QString(); } else { - tmpFileName = previous.mid(slashPos+1); + tmpFileName = previous.mid(slashPos + 1); tmpPath = previous.left(slashPos); } - int overhead = 1 + 1 + 2 + 8; // slash dot dot-tilde ffffffff" + int overhead = 1 + 1 + 2 + 8; // slash dot dot-tilde ffffffff" int spaceForFileName = qMin(254, tmpFileName.length() + overhead) - overhead; if (tmpPath.length() > 0) { return tmpPath + '/' + '.' + tmpFileName.left(spaceForFileName) + ".~" + (QString::number(uint(qrand() % 0xFFFFFFFF), 16)); @@ -65,39 +66,55 @@ QString OWNCLOUDSYNC_EXPORT createDownloadTmpFileName(const QString &previous) { } // DOES NOT take ownership of the device. -GETFileJob::GETFileJob(AccountPtr account, const QString& path, QFile *device, - const QMap &headers, const QByteArray &expectedEtagForResume, - quint64 resumeStart, QObject* parent) -: AbstractNetworkJob(account, path, parent), - _device(device), _headers(headers), _expectedEtagForResume(expectedEtagForResume) -, _resumeStart(resumeStart) , _errorStatus(SyncFileItem::NoStatus) -, _bandwidthLimited(false), _bandwidthChoked(false), _bandwidthQuota(0), _bandwidthManager(0) -, _hasEmittedFinishedSignal(false), _lastModified() +GETFileJob::GETFileJob(AccountPtr account, const QString &path, QFile *device, + const QMap &headers, const QByteArray &expectedEtagForResume, + quint64 resumeStart, QObject *parent) + : AbstractNetworkJob(account, path, parent) + , _device(device) + , _headers(headers) + , _expectedEtagForResume(expectedEtagForResume) + , _resumeStart(resumeStart) + , _errorStatus(SyncFileItem::NoStatus) + , _bandwidthLimited(false) + , _bandwidthChoked(false) + , _bandwidthQuota(0) + , _bandwidthManager(0) + , _hasEmittedFinishedSignal(false) + , _lastModified() { } -GETFileJob::GETFileJob(AccountPtr account, const QUrl& url, QFile *device, - const QMap &headers, const QByteArray &expectedEtagForResume, - quint64 resumeStart, QObject* parent) - -: AbstractNetworkJob(account, url.toEncoded(), parent), - _device(device), _headers(headers), _expectedEtagForResume(expectedEtagForResume) -, _resumeStart(resumeStart), _errorStatus(SyncFileItem::NoStatus), _directDownloadUrl(url) -, _bandwidthLimited(false), _bandwidthChoked(false), _bandwidthQuota(0), _bandwidthManager(0) -, _hasEmittedFinishedSignal(false), _lastModified() +GETFileJob::GETFileJob(AccountPtr account, const QUrl &url, QFile *device, + const QMap &headers, const QByteArray &expectedEtagForResume, + quint64 resumeStart, QObject *parent) + + : AbstractNetworkJob(account, url.toEncoded(), parent) + , _device(device) + , _headers(headers) + , _expectedEtagForResume(expectedEtagForResume) + , _resumeStart(resumeStart) + , _errorStatus(SyncFileItem::NoStatus) + , _directDownloadUrl(url) + , _bandwidthLimited(false) + , _bandwidthChoked(false) + , _bandwidthQuota(0) + , _bandwidthManager(0) + , _hasEmittedFinishedSignal(false) + , _lastModified() { } -void GETFileJob::start() { +void GETFileJob::start() +{ if (_resumeStart > 0) { - _headers["Range"] = "bytes=" + QByteArray::number(_resumeStart) +'-'; + _headers["Range"] = "bytes=" + QByteArray::number(_resumeStart) + '-'; _headers["Accept-Ranges"] = "bytes"; qCDebug(lcGetJob) << "Retry with range " << _headers["Range"]; } QNetworkRequest req; - for(QMap::const_iterator it = _headers.begin(); it != _headers.end(); ++it) { + for (QMap::const_iterator it = _headers.begin(); it != _headers.end(); ++it) { req.setRawHeader(it.key(), it.value()); } @@ -114,13 +131,13 @@ void GETFileJob::start() { _bandwidthManager->registerDownloadJob(this); } - if( reply()->error() != QNetworkReply::NoError ) { + if (reply()->error() != QNetworkReply::NoError) { qCWarning(lcGetJob) << " Network error: " << errorString(); } connect(reply(), SIGNAL(metaDataChanged()), this, SLOT(slotMetaDataChanged())); connect(reply(), SIGNAL(readyRead()), this, SLOT(slotReadyRead())); - connect(reply(), SIGNAL(downloadProgress(qint64,qint64)), this, SIGNAL(downloadProgress(qint64,qint64))); + connect(reply(), SIGNAL(downloadProgress(qint64, qint64)), this, SIGNAL(downloadProgress(qint64, qint64))); connect(this, SIGNAL(networkActivity()), account().data(), SIGNAL(propagatorNetworkActivity())); AbstractNetworkJob::start(); @@ -157,8 +174,8 @@ void GETFileJob::slotMetaDataChanged() reply()->abort(); return; } else if (!_expectedEtagForResume.isEmpty() && _expectedEtagForResume != _etag) { - qCWarning(lcGetJob) << "We received a different E-Tag for resuming!" - << _expectedEtagForResume << "vs" << _etag; + qCWarning(lcGetJob) << "We received a different E-Tag for resuming!" + << _expectedEtagForResume << "vs" << _etag; _errorString = tr("We received a different E-Tag for resuming. Retrying next time."); _errorStatus = SyncFileItem::NormalError; reply()->abort(); @@ -174,7 +191,7 @@ void GETFileJob::slotMetaDataChanged() } } if (start != _resumeStart) { - qCWarning(lcGetJob) << "Wrong content-range: "<< ranges << " while expecting start was" << _resumeStart; + qCWarning(lcGetJob) << "Wrong content-range: " << ranges << " while expecting start was" << _resumeStart; if (ranges.isEmpty()) { // device doesn't support range, just try again from scratch _device->close(); @@ -235,10 +252,10 @@ void GETFileJob::slotReadyRead() { if (!reply()) return; - int bufferSize = qMin(1024*8ll , reply()->bytesAvailable()); + int bufferSize = qMin(1024 * 8ll, reply()->bytesAvailable()); QByteArray buffer(bufferSize, Qt::Uninitialized); - while(reply()->bytesAvailable() > 0) { + while (reply()->bytesAvailable() > 0) { if (_bandwidthChoked) { qCWarning(lcGetJob) << "Download choked"; break; @@ -267,7 +284,7 @@ void GETFileJob::slotReadyRead() if (w != r) { _errorString = _device->errorString(); _errorStatus = SyncFileItem::NormalError; - qCWarning(lcGetJob) << "Error while writing to file" << w << r << _errorString; + qCWarning(lcGetJob) << "Error while writing to file" << w << r << _errorString; reply()->abort(); return; } @@ -281,9 +298,9 @@ void GETFileJob::slotReadyRead() } if (!_hasEmittedFinishedSignal) { qCInfo(lcGetJob) << "GET of" << reply()->request().url().toString() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()) - << reply()->rawHeader("Content-Range") << reply()->rawHeader("Content-Length"); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()) + << reply()->rawHeader("Content-Range") << reply()->rawHeader("Content-Length"); emit finishedSignal(); } @@ -297,7 +314,7 @@ void GETFileJob::onTimedOut() qCWarning(lcGetJob) << "Timeout" << (reply() ? reply()->request().url() : path()); if (!reply()) return; - _errorString = tr("Connection Timeout"); + _errorString = tr("Connection Timeout"); _errorStatus = SyncFileItem::FatalError; reply()->abort(); } @@ -328,9 +345,8 @@ void PropagateDownloadFile::start() } // do a klaas' case clash check. - if( propagator()->localFileNameClash(_item->_file) ) { - done( SyncFileItem::NormalError, tr("File %1 can not be downloaded because of a local file name clash!") - .arg(QDir::toNativeSeparators(_item->_file)) ); + if (propagator()->localFileNameClash(_item->_file)) { + done(SyncFileItem::NormalError, tr("File %1 can not be downloaded because of a local file name clash!").arg(QDir::toNativeSeparators(_item->_file))); return; } @@ -348,7 +364,6 @@ void PropagateDownloadFile::start() tmpFileName = progressInfo._tmpfile; expectedEtagForResume = progressInfo._etag; } - } if (tmpFileName.isEmpty()) { @@ -379,12 +394,10 @@ void PropagateDownloadFile::start() if (diskSpaceResult == OwncloudPropagator::DiskSpaceFailure) { _item->_errorMayBeBlacklisted = true; done(SyncFileItem::NormalError, - tr("The download would reduce free disk space below %1").arg( - Utility::octetsToString(freeSpaceLimit()))); + tr("The download would reduce free disk space below %1").arg(Utility::octetsToString(freeSpaceLimit()))); } else if (diskSpaceResult == OwncloudPropagator::DiskSpaceCritical) { done(SyncFileItem::FatalError, - tr("Free space on disk is less than %1").arg( - Utility::octetsToString(criticalFreeSpaceLimit()))); + tr("Free space on disk is less than %1").arg(Utility::octetsToString(criticalFreeSpaceLimit()))); } // Remove the temporary, if empty. @@ -409,8 +422,8 @@ void PropagateDownloadFile::start() if (_item->_directDownloadUrl.isEmpty()) { // Normal job, download from oC instance _job = new GETFileJob(propagator()->account(), - propagator()->_remoteFolder + _item->_file, - &_tmpFile, headers, expectedEtagForResume, _resumeStart, this); + propagator()->_remoteFolder + _item->_file, + &_tmpFile, headers, expectedEtagForResume, _resumeStart, this); } else { // We were provided a direct URL, use that one qCInfo(lcPropagateDownload) << "directDownloadUrl given for " << _item->_file << _item->_directDownloadUrl; @@ -421,12 +434,12 @@ void PropagateDownloadFile::start() QUrl url = QUrl::fromUserInput(_item->_directDownloadUrl); _job = new GETFileJob(propagator()->account(), - url, - &_tmpFile, headers, expectedEtagForResume, _resumeStart, this); + url, + &_tmpFile, headers, expectedEtagForResume, _resumeStart, this); } _job->setBandwidthManager(&propagator()->_bandwidthManager); connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotGetFinished())); - connect(_job, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(slotDownloadProgress(qint64,qint64))); + connect(_job, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(slotDownloadProgress(qint64, qint64))); propagator()->_activeJobList.append(this); _job->start(); } @@ -478,7 +491,7 @@ void PropagateDownloadFile::slotGetFinished() propagator()->_journal->setDownloadInfo(_item->_file, SyncJournalDb::DownloadInfo()); } - if(!_item->_directDownloadUrl.isEmpty() && err != QNetworkReply::OperationCanceledError) { + if (!_item->_directDownloadUrl.isEmpty() && err != QNetworkReply::OperationCanceledError) { // If this was with a direct download, retry without direct download qCWarning(lcPropagateDownload) << "Direct download of" << _item->_directDownloadUrl << "failed. Retrying through owncloud."; _item->_directDownloadUrl.clear(); @@ -505,7 +518,7 @@ void PropagateDownloadFile::slotGetFinished() SyncFileItem::Status status = job->errorStatus(); if (status == SyncFileItem::NoStatus) { status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); } done(status, job->errorString()); @@ -543,7 +556,7 @@ void PropagateDownloadFile::slotGetFinished() return; } - if(bodySize > 0 && bodySize != _tmpFile.size() - job->resumeStart() ) { + if (bodySize > 0 && bodySize != _tmpFile.size() - job->resumeStart()) { qCDebug(lcPropagateDownload) << bodySize << _tmpFile.size() << job->resumeStart(); propagator()->_anotherSyncNeeded = true; done(SyncFileItem::SoftError, tr("The file could not be downloaded completely.")); @@ -553,7 +566,7 @@ void PropagateDownloadFile::slotGetFinished() if (_tmpFile.size() == 0 && _item->_size > 0) { FileSystem::remove(_tmpFile.fileName()); done(SyncFileItem::NormalError, - tr("The downloaded file is empty despite the server announced it should have been %1.") + tr("The downloaded file is empty despite the server announced it should have been %1.") .arg(Utility::octetsToString(_item->_size))); return; } @@ -562,19 +575,19 @@ void PropagateDownloadFile::slotGetFinished() // will also emit the validated() signal to continue the flow in slot transmissionChecksumValidated() // as this is (still) also correct. ValidateChecksumHeader *validator = new ValidateChecksumHeader(this); - connect(validator, SIGNAL(validated(QByteArray,QByteArray)), - SLOT(transmissionChecksumValidated(QByteArray,QByteArray))); + connect(validator, SIGNAL(validated(QByteArray, QByteArray)), + SLOT(transmissionChecksumValidated(QByteArray, QByteArray))); connect(validator, SIGNAL(validationFailed(QString)), - SLOT(slotChecksumFail(QString))); + SLOT(slotChecksumFail(QString))); auto checksumHeader = job->reply()->rawHeader(checkSumHeaderC); validator->start(_tmpFile.fileName(), checksumHeader); } -void PropagateDownloadFile::slotChecksumFail( const QString& errMsg ) +void PropagateDownloadFile::slotChecksumFail(const QString &errMsg) { FileSystem::remove(_tmpFile.fileName()); propagator()->_anotherSyncNeeded = true; - done(SyncFileItem::SoftError, errMsg ); // tr("The file downloaded with a broken checksum, will be redownloaded.")); + done(SyncFileItem::SoftError, errMsg); // tr("The file downloaded with a broken checksum, will be redownloaded.")); } void PropagateDownloadFile::deleteExistingFolder() @@ -586,7 +599,7 @@ void PropagateDownloadFile::deleteExistingFolder() // Delete the directory if it is empty! QDir dir(existingDir); - if (dir.entryList(QDir::NoDotAndDotDot|QDir::AllEntries).count() == 0) { + if (dir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries).count() == 0) { if (dir.rmdir(existingDir)) { return; } @@ -594,7 +607,7 @@ void PropagateDownloadFile::deleteExistingFolder() } QString conflictDir = FileSystem::makeConflictFileName( - existingDir, Utility::qDateTimeFromTime_t(FileSystem::getModTime(existingDir))); + existingDir, Utility::qDateTimeFromTime_t(FileSystem::getModTime(existingDir))); emit propagator()->touchedFile(existingDir); emit propagator()->touchedFile(conflictDir); @@ -605,75 +618,75 @@ void PropagateDownloadFile::deleteExistingFolder() } namespace { // Anonymous namespace for the recall feature -static QString makeRecallFileName(const QString &fn) -{ - QString recallFileName(fn); - // Add _recall-XXXX before the extension. - int dotLocation = recallFileName.lastIndexOf('.'); - // If no extension, add it at the end (take care of cases like foo/.hidden or foo.bar/file) - if (dotLocation <= recallFileName.lastIndexOf('/') + 1) { - dotLocation = recallFileName.size(); - } + static QString makeRecallFileName(const QString &fn) + { + QString recallFileName(fn); + // Add _recall-XXXX before the extension. + int dotLocation = recallFileName.lastIndexOf('.'); + // If no extension, add it at the end (take care of cases like foo/.hidden or foo.bar/file) + if (dotLocation <= recallFileName.lastIndexOf('/') + 1) { + dotLocation = recallFileName.size(); + } - QString timeString = QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss"); - recallFileName.insert(dotLocation, "_.sys.admin#recall#-" + timeString); + QString timeString = QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss"); + recallFileName.insert(dotLocation, "_.sys.admin#recall#-" + timeString); - return recallFileName; -} + return recallFileName; + } -void handleRecallFile(const QString& filePath, const QString& folderPath, SyncJournalDb& journal) -{ - qCDebug(lcPropagateDownload) << "handleRecallFile: " << filePath; + void handleRecallFile(const QString &filePath, const QString &folderPath, SyncJournalDb &journal) + { + qCDebug(lcPropagateDownload) << "handleRecallFile: " << filePath; - FileSystem::setFileHidden(filePath, true); + FileSystem::setFileHidden(filePath, true); - QFile file(filePath); - if (!file.open(QIODevice::ReadOnly)) { - qCWarning(lcPropagateDownload) << "Could not open recall file" << file.errorString(); - return; - } - QFileInfo existingFile(filePath); - QDir baseDir = existingFile.dir(); + QFile file(filePath); + if (!file.open(QIODevice::ReadOnly)) { + qCWarning(lcPropagateDownload) << "Could not open recall file" << file.errorString(); + return; + } + QFileInfo existingFile(filePath); + QDir baseDir = existingFile.dir(); - while (!file.atEnd()) { - QByteArray line = file.readLine(); - line.chop(1); // remove trailing \n + while (!file.atEnd()) { + QByteArray line = file.readLine(); + line.chop(1); // remove trailing \n - QString recalledFile = QDir::cleanPath(baseDir.filePath(line)); - if (!recalledFile.startsWith(folderPath) || !recalledFile.startsWith(baseDir.path())) { - qCWarning(lcPropagateDownload) << "Ignoring recall of " << recalledFile; - continue; - } + QString recalledFile = QDir::cleanPath(baseDir.filePath(line)); + if (!recalledFile.startsWith(folderPath) || !recalledFile.startsWith(baseDir.path())) { + qCWarning(lcPropagateDownload) << "Ignoring recall of " << recalledFile; + continue; + } - // Path of the recalled file in the local folder - QString localRecalledFile = recalledFile.mid(folderPath.size()); + // Path of the recalled file in the local folder + QString localRecalledFile = recalledFile.mid(folderPath.size()); - SyncJournalFileRecord record = journal.getFileRecord(localRecalledFile); - if (!record.isValid()) { - qCWarning(lcPropagateDownload) << "No db entry for recall of" << localRecalledFile; - continue; - } + SyncJournalFileRecord record = journal.getFileRecord(localRecalledFile); + if (!record.isValid()) { + qCWarning(lcPropagateDownload) << "No db entry for recall of" << localRecalledFile; + continue; + } - qCInfo(lcPropagateDownload) << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum; + qCInfo(lcPropagateDownload) << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum; - QString targetPath = makeRecallFileName(recalledFile); + QString targetPath = makeRecallFileName(recalledFile); - qCDebug(lcPropagateDownload) << "Copy recall file: " << recalledFile << " -> " << targetPath; - // Remove the target first, QFile::copy will not overwrite it. - FileSystem::remove(targetPath); - QFile::copy(recalledFile, targetPath); + qCDebug(lcPropagateDownload) << "Copy recall file: " << recalledFile << " -> " << targetPath; + // Remove the target first, QFile::copy will not overwrite it. + FileSystem::remove(targetPath); + QFile::copy(recalledFile, targetPath); + } } -} -static void preserveGroupOwnership(const QString& fileName, const QFileInfo& fi) -{ + static void preserveGroupOwnership(const QString &fileName, const QFileInfo &fi) + { #ifdef Q_OS_UNIX - chown(fileName.toLocal8Bit().constData(), -1, fi.groupId()); + chown(fileName.toLocal8Bit().constData(), -1, fi.groupId()); #else - Q_UNUSED(fileName); - Q_UNUSED(fi); + Q_UNUSED(fileName); + Q_UNUSED(fi); #endif -} + } } // end namespace void PropagateDownloadFile::transmissionChecksumValidated(const QByteArray &checksumType, const QByteArray &checksum) @@ -692,8 +705,8 @@ void PropagateDownloadFile::transmissionChecksumValidated(const QByteArray &chec auto computeChecksum = new ComputeChecksum(this); computeChecksum->setChecksumType(theContentChecksumType); - connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)), - SLOT(contentChecksumComputed(QByteArray,QByteArray))); + connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)), + SLOT(contentChecksumComputed(QByteArray, QByteArray))); computeChecksum->start(_tmpFile.fileName()); } @@ -712,19 +725,18 @@ void PropagateDownloadFile::downloadFinished() // In case of file name clash, report an error // This can happen if another parallel download saved a clashing file. if (propagator()->localFileNameClash(_item->_file)) { - done( SyncFileItem::NormalError, tr("File %1 cannot be saved because of a local file name clash!") - .arg(QDir::toNativeSeparators(_item->_file)) ); + done(SyncFileItem::NormalError, tr("File %1 cannot be saved because of a local file name clash!").arg(QDir::toNativeSeparators(_item->_file))); return; } // In case of conflict, make a backup of the old file // Ignore conflicts where both files are binary equal bool isConflict = _item->_instruction == CSYNC_INSTRUCTION_CONFLICT - && !FileSystem::fileEquals(fn, _tmpFile.fileName()); + && !FileSystem::fileEquals(fn, _tmpFile.fileName()); if (isConflict) { QString renameError; QString conflictFileName = FileSystem::makeConflictFileName( - fn, Utility::qDateTimeFromTime_t(FileSystem::getModTime(fn))); + fn, Utility::qDateTimeFromTime_t(FileSystem::getModTime(fn))); if (!FileSystem::rename(fn, conflictFileName, &renameError)) { // If the rename fails, don't replace it. @@ -759,7 +771,7 @@ void PropagateDownloadFile::downloadFinished() // the discovery phase and now. const qint64 expectedSize = _item->log._other_size; const time_t expectedMtime = _item->log._other_modtime; - if (! FileSystem::verifyFileUnchanged(fn, expectedSize, expectedMtime)) { + if (!FileSystem::verifyFileUnchanged(fn, expectedSize, expectedMtime)) { propagator()->_anotherSyncNeeded = true; done(SyncFileItem::SoftError, tr("File has changed since discovery")); return; @@ -772,7 +784,7 @@ void PropagateDownloadFile::downloadFinished() const int serverVersionGoodRemotePerm = Account::makeServerVersion(7, 0, 0); if (propagator()->account()->serverVersionInt() >= serverVersionGoodRemotePerm) { FileSystem::setFileReadOnlyWeak(_tmpFile.fileName(), - !_item->_remotePerm.contains('W')); + !_item->_remotePerm.contains('W')); } QString error; @@ -819,21 +831,22 @@ void PropagateDownloadFile::downloadFinished() done(isConflict ? SyncFileItem::Conflict : SyncFileItem::Success); // handle the special recall file - if(!_item->_remotePerm.contains("S") - && (_item->_file == QLatin1String(".sys.admin#recall#") - || _item->_file.endsWith("/.sys.admin#recall#"))) { + if (!_item->_remotePerm.contains("S") + && (_item->_file == QLatin1String(".sys.admin#recall#") + || _item->_file.endsWith("/.sys.admin#recall#"))) { handleRecallFile(fn, propagator()->_localDir, *propagator()->_journal); } qint64 duration = _stopwatch.elapsed(); - if (isLikelyFinishedQuickly() && duration > 5*1000) { + if (isLikelyFinishedQuickly() && duration > 5 * 1000) { qCWarning(lcPropagateDownload) << "WARNING: Unexpectedly slow connection, took" << duration << "msec for" << _item->_size - _resumeStart << "bytes for" << _item->_file; } } void PropagateDownloadFile::slotDownloadProgress(qint64 received, qint64) { - if (!_job) return; + if (!_job) + return; _downloadProgress = received; propagator()->reportProgress(*_item, _resumeStart + received); } @@ -841,9 +854,7 @@ void PropagateDownloadFile::slotDownloadProgress(qint64 received, qint64) void PropagateDownloadFile::abort() { - if (_job && _job->reply()) + if (_job && _job->reply()) _job->reply()->abort(); } - - } diff --git a/src/libsync/propagatedownload.h b/src/libsync/propagatedownload.h index 6e4cad115..69962131b 100644 --- a/src/libsync/propagatedownload.h +++ b/src/libsync/propagatedownload.h @@ -25,9 +25,10 @@ namespace OCC { * @brief The GETFileJob class * @ingroup libsync */ -class GETFileJob : public AbstractNetworkJob { +class GETFileJob : public AbstractNetworkJob +{ Q_OBJECT - QFile* _device; + QFile *_device; QMap _headers; QString _errorString; QByteArray _expectedEtagForResume; @@ -41,24 +42,26 @@ class GETFileJob : public AbstractNetworkJob { QPointer _bandwidthManager; bool _hasEmittedFinishedSignal; time_t _lastModified; -public: +public: // DOES NOT take ownership of the device. - explicit GETFileJob(AccountPtr account, const QString& path, QFile *device, - const QMap &headers, const QByteArray &expectedEtagForResume, - quint64 resumeStart, QObject* parent = 0); + explicit GETFileJob(AccountPtr account, const QString &path, QFile *device, + const QMap &headers, const QByteArray &expectedEtagForResume, + quint64 resumeStart, QObject *parent = 0); // For directDownloadUrl: - explicit GETFileJob(AccountPtr account, const QUrl& url, QFile *device, - const QMap &headers, const QByteArray &expectedEtagForResume, - quint64 resumeStart, QObject* parent = 0); - virtual ~GETFileJob() { + explicit GETFileJob(AccountPtr account, const QUrl &url, QFile *device, + const QMap &headers, const QByteArray &expectedEtagForResume, + quint64 resumeStart, QObject *parent = 0); + virtual ~GETFileJob() + { if (_bandwidthManager) { _bandwidthManager->unregisterDownloadJob(this); } } virtual void start() Q_DECL_OVERRIDE; - virtual bool finished() Q_DECL_OVERRIDE { + virtual bool finished() Q_DECL_OVERRIDE + { if (reply()->bytesAvailable()) { return false; } else { @@ -80,10 +83,10 @@ public: qint64 currentDownloadPosition(); QString errorString() const; - void setErrorString(const QString& s) { _errorString = s; } + void setErrorString(const QString &s) { _errorString = s; } SyncFileItem::Status errorStatus() { return _errorStatus; } - void setErrorStatus(const SyncFileItem::Status & s) { _errorStatus = s; } + void setErrorStatus(const SyncFileItem::Status &s) { _errorStatus = s; } void onTimedOut() Q_DECL_OVERRIDE; @@ -94,7 +97,7 @@ public: signals: void finishedSignal(); - void downloadProgress(qint64,qint64); + void downloadProgress(qint64, qint64); private slots: void slotReadyRead(); void slotMetaDataChanged(); @@ -104,11 +107,17 @@ private slots: * @brief The PropagateDownloadFile class * @ingroup libsync */ -class PropagateDownloadFile : public PropagateItemJob { +class PropagateDownloadFile : public PropagateItemJob +{ Q_OBJECT public: - PropagateDownloadFile(OwncloudPropagator* propagator,const SyncFileItemPtr& item) - : PropagateItemJob(propagator, item), _resumeStart(0), _downloadProgress(0), _deleteExisting(false) {} + PropagateDownloadFile(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + , _resumeStart(0) + , _downloadProgress(0) + , _deleteExisting(false) + { + } void start() Q_DECL_OVERRIDE; qint64 committedDiskSpace() const Q_DECL_OVERRIDE; @@ -129,11 +138,11 @@ public: private slots: void slotGetFinished(); void abort() Q_DECL_OVERRIDE; - void transmissionChecksumValidated(const QByteArray& checksumType, const QByteArray& checksum); - void contentChecksumComputed(const QByteArray& checksumType, const QByteArray& checksum); + void transmissionChecksumValidated(const QByteArray &checksumType, const QByteArray &checksum); + void contentChecksumComputed(const QByteArray &checksumType, const QByteArray &checksum); void downloadFinished(); - void slotDownloadProgress(qint64,qint64); - void slotChecksumFail( const QString& errMsg ); + void slotDownloadProgress(qint64, qint64); + void slotChecksumFail(const QString &errMsg); private: void deleteExistingFolder(); @@ -146,5 +155,4 @@ private: QElapsedTimer _stopwatch; }; - } diff --git a/src/libsync/propagateremotedelete.cpp b/src/libsync/propagateremotedelete.cpp index d0771e8d6..d66cb2d91 100644 --- a/src/libsync/propagateremotedelete.cpp +++ b/src/libsync/propagateremotedelete.cpp @@ -24,13 +24,16 @@ namespace OCC { Q_LOGGING_CATEGORY(lcDeleteJob, "sync.networkjob.delete", QtInfoMsg) Q_LOGGING_CATEGORY(lcPropagateRemoteDelete, "sync.propagator.remotedelete", QtInfoMsg) -DeleteJob::DeleteJob(AccountPtr account, const QString& path, QObject* parent) +DeleteJob::DeleteJob(AccountPtr account, const QString &path, QObject *parent) : AbstractNetworkJob(account, path, parent) -{ } +{ +} -DeleteJob::DeleteJob(AccountPtr account, const QUrl& url, QObject* parent) - : AbstractNetworkJob(account, QString(), parent), _url(url) -{ } +DeleteJob::DeleteJob(AccountPtr account, const QUrl &url, QObject *parent) + : AbstractNetworkJob(account, QString(), parent) + , _url(url) +{ +} void DeleteJob::start() { @@ -41,7 +44,7 @@ void DeleteJob::start() sendRequest("DELETE", makeDavUrl(path()), req); } - if( reply()->error() != QNetworkReply::NoError ) { + if (reply()->error() != QNetworkReply::NoError) { qCWarning(lcDeleteJob) << " Network error: " << reply()->errorString(); } AbstractNetworkJob::start(); @@ -50,8 +53,8 @@ void DeleteJob::start() bool DeleteJob::finished() { qCInfo(lcDeleteJob) << "DELETE of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); emit finishedSignal(); return true; @@ -65,8 +68,8 @@ void PropagateRemoteDelete::start() qCDebug(lcPropagateRemoteDelete) << _item->_file; _job = new DeleteJob(propagator()->account(), - propagator()->_remoteFolder + _item->_file, - this); + propagator()->_remoteFolder + _item->_file, + this); connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotDeleteJobFinished())); propagator()->_activeJobList.append(this); _job->start(); @@ -74,7 +77,7 @@ void PropagateRemoteDelete::start() void PropagateRemoteDelete::abort() { - if (_job && _job->reply()) + if (_job && _job->reply()) _job->reply()->abort(); } @@ -89,14 +92,13 @@ void PropagateRemoteDelete::slotDeleteJobFinished() _item->_httpErrorCode = httpStatus; if (err != QNetworkReply::NoError && err != QNetworkReply::ContentNotFoundError) { - - if( checkForProblemsWithShared(_item->_httpErrorCode, - tr("The file has been removed from a read only share. It was restored.")) ) { + if (checkForProblemsWithShared(_item->_httpErrorCode, + tr("The file has been removed from a read only share. It was restored."))) { return; } SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); done(status, _job->errorString()); return; } @@ -112,9 +114,9 @@ void PropagateRemoteDelete::slotDeleteJobFinished() // If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must // throw an error. done(SyncFileItem::NormalError, - tr("Wrong HTTP code returned by server. Expected 204, but received \"%1 %2\".") - .arg(_item->_httpErrorCode) - .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); + tr("Wrong HTTP code returned by server. Expected 204, but received \"%1 %2\".") + .arg(_item->_httpErrorCode) + .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); return; } @@ -122,7 +124,4 @@ void PropagateRemoteDelete::slotDeleteJobFinished() propagator()->_journal->commit("Remote Remove"); done(SyncFileItem::Success); } - - } - diff --git a/src/libsync/propagateremotedelete.h b/src/libsync/propagateremotedelete.h index 54cd8a0ea..c4367b3ac 100644 --- a/src/libsync/propagateremotedelete.h +++ b/src/libsync/propagateremotedelete.h @@ -22,12 +22,13 @@ namespace OCC { * @brief The DeleteJob class * @ingroup libsync */ -class DeleteJob : public AbstractNetworkJob { +class DeleteJob : public AbstractNetworkJob +{ Q_OBJECT QUrl _url; // Only used if the constructor taking a url is taken. public: - explicit DeleteJob(AccountPtr account, const QString& path, QObject* parent = 0); - explicit DeleteJob(AccountPtr account, const QUrl& url, QObject* parent = 0); + explicit DeleteJob(AccountPtr account, const QString &path, QObject *parent = 0); + explicit DeleteJob(AccountPtr account, const QUrl &url, QObject *parent = 0); void start() Q_DECL_OVERRIDE; bool finished() Q_DECL_OVERRIDE; @@ -40,12 +41,16 @@ signals: * @brief The PropagateRemoteDelete class * @ingroup libsync */ -class PropagateRemoteDelete : public PropagateItemJob { +class PropagateRemoteDelete : public PropagateItemJob +{ Q_OBJECT QPointer _job; + public: - PropagateRemoteDelete (OwncloudPropagator* propagator,const SyncFileItemPtr& item) - : PropagateItemJob(propagator, item) {} + PropagateRemoteDelete(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + { + } void start() Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE; @@ -53,7 +58,5 @@ public: private slots: void slotDeleteJobFinished(); - }; - } diff --git a/src/libsync/propagateremotemkdir.cpp b/src/libsync/propagateremotemkdir.cpp index 7007eda06..f293fa0a9 100644 --- a/src/libsync/propagateremotemkdir.cpp +++ b/src/libsync/propagateremotemkdir.cpp @@ -40,8 +40,8 @@ void PropagateRemoteMkdir::start() } _job = new DeleteJob(propagator()->account(), - propagator()->_remoteFolder + _item->_file, - this); + propagator()->_remoteFolder + _item->_file, + this); connect(_job, SIGNAL(finishedSignal()), SLOT(slotStartMkcolJob())); _job->start(); } @@ -54,15 +54,15 @@ void PropagateRemoteMkdir::slotStartMkcolJob() qCDebug(lcPropagateRemoteMkdir) << _item->_file; _job = new MkColJob(propagator()->account(), - propagator()->_remoteFolder + _item->_file, - this); + propagator()->_remoteFolder + _item->_file, + this); connect(_job, SIGNAL(finished(QNetworkReply::NetworkError)), this, SLOT(slotMkcolJobFinished())); _job->start(); } void PropagateRemoteMkdir::abort() { - if (_job && _job->reply()) + if (_job && _job->reply()) _job->reply()->abort(); } @@ -84,7 +84,7 @@ void PropagateRemoteMkdir::slotMkcolJobFinished() // This happens when the directory already exists. Nothing to do. } else if (err != QNetworkReply::NoError) { SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); done(status, _job->errorString()); return; } else if (_item->_httpErrorCode != 201) { @@ -92,9 +92,9 @@ void PropagateRemoteMkdir::slotMkcolJobFinished() // If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must // throw an error. done(SyncFileItem::NormalError, - tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".") - .arg(_item->_httpErrorCode) - .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); + tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".") + .arg(_item->_httpErrorCode) + .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); return; } @@ -109,7 +109,8 @@ void PropagateRemoteMkdir::slotMkcolJobFinished() // while files are still uploading propagator()->_activeJobList.append(this); auto propfindJob = new PropfindJob(_job->account(), _job->path(), this); - propfindJob->setProperties(QList() << "getetag" << "http://owncloud.org/ns:id"); + propfindJob->setProperties(QList() << "getetag" + << "http://owncloud.org/ns:id"); QObject::connect(propfindJob, SIGNAL(result(QVariantMap)), this, SLOT(propfindResult(QVariantMap))); QObject::connect(propfindJob, SIGNAL(finishedWithError()), this, SLOT(propfindError())); propfindJob->start(); @@ -149,8 +150,4 @@ void PropagateRemoteMkdir::success() done(SyncFileItem::Success); } - - - } - diff --git a/src/libsync/propagateremotemkdir.h b/src/libsync/propagateremotemkdir.h index c5bdc3164..a89fbe99e 100644 --- a/src/libsync/propagateremotemkdir.h +++ b/src/libsync/propagateremotemkdir.h @@ -22,14 +22,18 @@ namespace OCC { * @brief The PropagateRemoteMkdir class * @ingroup libsync */ -class PropagateRemoteMkdir : public PropagateItemJob { +class PropagateRemoteMkdir : public PropagateItemJob +{ Q_OBJECT QPointer _job; bool _deleteExisting; friend class PropagateDirectory; // So it can access the _item; public: - PropagateRemoteMkdir (OwncloudPropagator* propagator,const SyncFileItemPtr& item) - : PropagateItemJob(propagator, item), _deleteExisting(false) {} + PropagateRemoteMkdir(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + , _deleteExisting(false) + { + } void start() Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE; @@ -51,5 +55,4 @@ private slots: void propfindError(); void success(); }; - } diff --git a/src/libsync/propagateremotemove.cpp b/src/libsync/propagateremotemove.cpp index 373f298b2..7f4f96c33 100644 --- a/src/libsync/propagateremotemove.cpp +++ b/src/libsync/propagateremotemove.cpp @@ -28,22 +28,27 @@ namespace OCC { Q_LOGGING_CATEGORY(lcMoveJob, "sync.networkjob.move", QtInfoMsg) Q_LOGGING_CATEGORY(lcPropagateRemoteMove, "sync.propagator.remotemove", QtInfoMsg) -MoveJob::MoveJob(AccountPtr account, const QString& path, - const QString &destination, QObject* parent) - : AbstractNetworkJob(account, path, parent), _destination(destination) -{ } - -MoveJob::MoveJob(AccountPtr account, const QUrl& url, const QString &destination, - QMap extraHeaders, QObject* parent) - : AbstractNetworkJob(account, QString(), parent), _destination(destination), _url(url) +MoveJob::MoveJob(AccountPtr account, const QString &path, + const QString &destination, QObject *parent) + : AbstractNetworkJob(account, path, parent) + , _destination(destination) +{ +} + +MoveJob::MoveJob(AccountPtr account, const QUrl &url, const QString &destination, + QMap extraHeaders, QObject *parent) + : AbstractNetworkJob(account, QString(), parent) + , _destination(destination) + , _url(url) , _extraHeaders(extraHeaders) -{ } +{ +} void MoveJob::start() { QNetworkRequest req; req.setRawHeader("Destination", QUrl::toPercentEncoding(_destination, "/")); - for(auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) { + for (auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) { req.setRawHeader(it.key(), it.value()); } if (_url.isValid()) { @@ -52,7 +57,7 @@ void MoveJob::start() sendRequest("MOVE", makeDavUrl(path()), req); } - if( reply()->error() != QNetworkReply::NoError ) { + if (reply()->error() != QNetworkReply::NoError) { qCWarning(lcPropagateRemoteMove) << " Network error: " << reply()->errorString(); } AbstractNetworkJob::start(); @@ -62,8 +67,8 @@ void MoveJob::start() bool MoveJob::finished() { qCInfo(lcMoveJob) << "MOVE of" << reply()->request().url() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()); emit finishedSignal(); return true; @@ -83,7 +88,7 @@ void PropagateRemoteMove::start() finalize(); return; } - if (_item->_file == QLatin1String("Shared") ) { + if (_item->_file == QLatin1String("Shared")) { // Before owncloud 7, there was no permissions system. At the time all the shared files were // in a directory called "Shared" and were not supposed to be moved, otherwise bad things happened @@ -93,7 +98,7 @@ void PropagateRemoteMove::start() emit propagator()->touchedFile(originalFile); emit propagator()->touchedFile(targetFile); QString renameError; - if( FileSystem::rename(targetFile, originalFile, &renameError) ) { + if (FileSystem::rename(targetFile, originalFile, &renameError)) { done(SyncFileItem::NormalError, tr("This folder must not be renamed. It is renamed back to its original name.")); } else { done(SyncFileItem::NormalError, tr("This folder must not be renamed. Please name it back to Shared.")); @@ -103,19 +108,18 @@ void PropagateRemoteMove::start() } QString destination = QDir::cleanPath(propagator()->account()->url().path() + QLatin1Char('/') - + propagator()->account()->davPath() + propagator()->_remoteFolder + _item->_renameTarget); + + propagator()->account()->davPath() + propagator()->_remoteFolder + _item->_renameTarget); _job = new MoveJob(propagator()->account(), - propagator()->_remoteFolder + _item->_file, - destination, this); + propagator()->_remoteFolder + _item->_file, + destination, this); connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished())); propagator()->_activeJobList.append(this); _job->start(); - } void PropagateRemoteMove::abort() { - if (_job && _job->reply()) + if (_job && _job->reply()) _job->reply()->abort(); } @@ -129,39 +133,37 @@ void PropagateRemoteMove::slotMoveJobFinished() _item->_httpErrorCode = _job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (err != QNetworkReply::NoError) { - - if( checkForProblemsWithShared(_item->_httpErrorCode, + if (checkForProblemsWithShared(_item->_httpErrorCode, tr("The file was renamed but is part of a read only share. The original file was restored."))) { return; } SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); done(status, _job->errorString()); return; } _item->_responseTimeStamp = _job->responseTimestamp(); - if (_item->_httpErrorCode != 201 ) { + if (_item->_httpErrorCode != 201) { // Normally we expect "201 Created" // If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must // throw an error. done(SyncFileItem::NormalError, - tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".") - .arg(_item->_httpErrorCode) - .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); + tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".") + .arg(_item->_httpErrorCode) + .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())); return; } finalize(); - } void PropagateRemoteMove::finalize() { SyncJournalFileRecord oldRecord = - propagator()->_journal->getFileRecord(_item->_originalFile); + propagator()->_journal->getFileRecord(_item->_originalFile); // if reading from db failed still continue hoping that deleteFileRecord // reopens the db successfully. // The db is only queried to transfer the content checksum from the old @@ -224,6 +226,4 @@ bool PropagateRemoteMove::adjustSelectiveSync(SyncJournalDb *journal, const QStr } return true; } - } - diff --git a/src/libsync/propagateremotemove.h b/src/libsync/propagateremotemove.h index 6d9150d79..3180712df 100644 --- a/src/libsync/propagateremotemove.h +++ b/src/libsync/propagateremotemove.h @@ -22,15 +22,17 @@ namespace OCC { * @brief The MoveJob class * @ingroup libsync */ -class MoveJob : public AbstractNetworkJob { +class MoveJob : public AbstractNetworkJob +{ Q_OBJECT const QString _destination; const QUrl _url; // Only used (instead of path) when the constructor taking an URL is used QMap _extraHeaders; + public: - explicit MoveJob(AccountPtr account, const QString& path, const QString &destination, QObject* parent = 0); - explicit MoveJob(AccountPtr account, const QUrl& url, const QString &destination, - QMap _extraHeaders, QObject* parent = 0); + explicit MoveJob(AccountPtr account, const QString &path, const QString &destination, QObject *parent = 0); + explicit MoveJob(AccountPtr account, const QUrl &url, const QString &destination, + QMap _extraHeaders, QObject *parent = 0); void start() Q_DECL_OVERRIDE; bool finished() Q_DECL_OVERRIDE; @@ -43,12 +45,16 @@ signals: * @brief The PropagateRemoteMove class * @ingroup libsync */ -class PropagateRemoteMove : public PropagateItemJob { +class PropagateRemoteMove : public PropagateItemJob +{ Q_OBJECT QPointer _job; + public: - PropagateRemoteMove (OwncloudPropagator* propagator,const SyncFileItemPtr& item) - : PropagateItemJob(propagator, item) {} + PropagateRemoteMove(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + { + } void start() Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE; JobParallelism parallelism() Q_DECL_OVERRIDE { return _item->_isDirectory ? WaitForFinished : FullParallelism; } @@ -62,5 +68,4 @@ private slots: void slotMoveJobFinished(); void finalize(); }; - } diff --git a/src/libsync/propagateupload.cpp b/src/libsync/propagateupload.cpp index 5467d1aa5..93849dff7 100644 --- a/src/libsync/propagateupload.cpp +++ b/src/libsync/propagateupload.cpp @@ -56,14 +56,14 @@ Q_LOGGING_CATEGORY(lcPropagateUpload, "sync.propagator.upload", QtInfoMsg) * manager. If that delay between file-change notification and sync * has passed, we should accept the file for upload here. */ -static bool fileIsStillChanging(const SyncFileItem & item) +static bool fileIsStillChanging(const SyncFileItem &item) { const QDateTime modtime = Utility::qDateTimeFromTime_t(item._modtime); const qint64 msSinceMod = modtime.msecsTo(QDateTime::currentDateTime()); return msSinceMod < SyncEngine::minimumFileAgeForUpload - // if the mtime is too much in the future we *do* upload the file - && msSinceMod > -10000; + // if the mtime is too much in the future we *do* upload the file + && msSinceMod > -10000; } PUTFileJob::~PUTFileJob() @@ -72,9 +72,10 @@ PUTFileJob::~PUTFileJob() setReply(0); } -void PUTFileJob::start() { +void PUTFileJob::start() +{ QNetworkRequest req; - for(QMap::const_iterator it = _headers.begin(); it != _headers.end(); ++it) { + for (QMap::const_iterator it = _headers.begin(); it != _headers.end(); ++it) { req.setRawHeader(it.key(), it.value()); } @@ -84,16 +85,16 @@ void PUTFileJob::start() { sendRequest("PUT", makeDavUrl(path()), req, _device); } - if( reply()->error() != QNetworkReply::NoError ) { + if (reply()->error() != QNetworkReply::NoError) { qCWarning(lcPutJob) << " Network error: " << reply()->errorString(); } - connect(reply(), SIGNAL(uploadProgress(qint64,qint64)), this, SIGNAL(uploadProgress(qint64,qint64))); + connect(reply(), SIGNAL(uploadProgress(qint64, qint64)), this, SIGNAL(uploadProgress(qint64, qint64))); connect(this, SIGNAL(networkActivity()), account().data(), SIGNAL(propagatorNetworkActivity())); - // For Qt versions not including https://codereview.qt-project.org/110150 - // Also do the runtime check if compiled with an old Qt but running with fixed one. - // (workaround disabled on windows and mac because the binaries we ship have patched qt) +// For Qt versions not including https://codereview.qt-project.org/110150 +// Also do the runtime check if compiled with an old Qt but running with fixed one. +// (workaround disabled on windows and mac because the binaries we ship have patched qt) #if QT_VERSION < QT_VERSION_CHECK(5, 4, 2) && !defined Q_OS_WIN && !defined Q_OS_MAC if (QLatin1String(qVersion()) < QLatin1String("5.4.2")) connect(_device, SIGNAL(wasReset()), this, SLOT(slotSoftAbort())); @@ -104,7 +105,8 @@ void PUTFileJob::start() { } #if QT_VERSION < QT_VERSION_CHECK(5, 4, 2) -void PUTFileJob::slotSoftAbort() { +void PUTFileJob::slotSoftAbort() +{ reply()->setProperty(owncloudShouldSoftCancelPropertyName, true); reply()->abort(); } @@ -114,10 +116,10 @@ void PollJob::start() { setTimeout(120 * 1000); QUrl accountUrl = account()->url(); - QUrl finalUrl = QUrl::fromUserInput(accountUrl.scheme() + QLatin1String("://") + accountUrl.authority() + QUrl finalUrl = QUrl::fromUserInput(accountUrl.scheme() + QLatin1String("://") + accountUrl.authority() + (path().startsWith('/') ? QLatin1String("") : QLatin1String("/")) + path()); sendRequest("GET", finalUrl); - connect(reply(), SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(resetTimeout())); + connect(reply(), SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(resetTimeout())); AbstractNetworkJob::start(); } @@ -131,13 +133,12 @@ bool PollJob::finished() if (_item->_status == SyncFileItem::FatalError || _item->_httpErrorCode >= 400) { if (_item->_status != SyncFileItem::FatalError - && _item->_httpErrorCode != 503) { + && _item->_httpErrorCode != 503) { SyncJournalDb::PollInfo info; info._file = _item->_file; // no info._url removes it from the database _journal->setPollInfo(info); _journal->commit("remove poll info"); - } emit finishedSignal(); return true; @@ -191,9 +192,8 @@ void PropagateUploadFileCommon::start() } // Check if the specific file can be accessed - if( propagator()->hasCaseClashAccessibilityProblem(_item->_file) ) { - done( SyncFileItem::NormalError, tr("File %1 cannot be uploaded because another file with the same name, differing only in case, exists") - .arg(QDir::toNativeSeparators(_item->_file)) ); + if (propagator()->hasCaseClashAccessibilityProblem(_item->_file)) { + done(SyncFileItem::NormalError, tr("File %1 cannot be uploaded because another file with the same name, differing only in case, exists").arg(QDir::toNativeSeparators(_item->_file))); return; } @@ -204,11 +204,11 @@ void PropagateUploadFileCommon::start() } auto job = new DeleteJob(propagator()->account(), - propagator()->_remoteFolder + _item->_file, - this); + propagator()->_remoteFolder + _item->_file, + this); _jobs.append(job); connect(job, SIGNAL(finishedSignal()), SLOT(slotComputeContentChecksum())); - connect(job, SIGNAL(destroyed(QObject*)), SLOT(slotJobDestroyed(QObject*))); + connect(job, SIGNAL(destroyed(QObject *)), SLOT(slotJobDestroyed(QObject *))); job->start(); } @@ -232,7 +232,7 @@ void PropagateUploadFileCommon::slotComputeContentChecksum() // Maybe the discovery already computed the checksum? if (_item->_contentChecksumType == checksumType - && !_item->_contentChecksum.isEmpty()) { + && !_item->_contentChecksum.isEmpty()) { slotComputeTransmissionChecksum(checksumType, _item->_contentChecksum); return; } @@ -241,14 +241,14 @@ void PropagateUploadFileCommon::slotComputeContentChecksum() auto computeChecksum = new ComputeChecksum(this); computeChecksum->setChecksumType(checksumType); - connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)), - SLOT(slotComputeTransmissionChecksum(QByteArray,QByteArray))); - connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)), - computeChecksum, SLOT(deleteLater())); + connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)), + SLOT(slotComputeTransmissionChecksum(QByteArray, QByteArray))); + connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)), + computeChecksum, SLOT(deleteLater())); computeChecksum->start(filePath); } -void PropagateUploadFileCommon::slotComputeTransmissionChecksum(const QByteArray& contentChecksumType, const QByteArray& contentChecksum) +void PropagateUploadFileCommon::slotComputeTransmissionChecksum(const QByteArray &contentChecksumType, const QByteArray &contentChecksum) { _item->_contentChecksum = contentChecksum; _item->_contentChecksumType = contentChecksumType; @@ -260,7 +260,7 @@ void PropagateUploadFileCommon::slotComputeTransmissionChecksum(const QByteArray // Reuse the content checksum as the transmission checksum if possible const auto supportedTransmissionChecksums = - propagator()->account()->capabilities().supportedChecksumTypes(); + propagator()->account()->capabilities().supportedChecksumTypes(); if (supportedTransmissionChecksums.contains(contentChecksumType)) { slotStartUpload(contentChecksumType, contentChecksum); return; @@ -274,15 +274,15 @@ void PropagateUploadFileCommon::slotComputeTransmissionChecksum(const QByteArray computeChecksum->setChecksumType(QByteArray()); } - connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)), - SLOT(slotStartUpload(QByteArray,QByteArray))); - connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)), - computeChecksum, SLOT(deleteLater())); + connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)), + SLOT(slotStartUpload(QByteArray, QByteArray))); + connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)), + computeChecksum, SLOT(deleteLater())); const QString filePath = propagator()->getFilePath(_item->_file); computeChecksum->start(filePath); } -void PropagateUploadFileCommon::slotStartUpload(const QByteArray& transmissionChecksumType, const QByteArray& transmissionChecksum) +void PropagateUploadFileCommon::slotStartUpload(const QByteArray &transmissionChecksumType, const QByteArray &transmissionChecksum) { // Remove ourselfs from the list of active job, before any posible call to done() // When we start chunks, we will add it again, once for every chunks. @@ -291,7 +291,7 @@ void PropagateUploadFileCommon::slotStartUpload(const QByteArray& transmissionCh _transmissionChecksum = transmissionChecksum; _transmissionChecksumType = transmissionChecksumType; - if (_item->_contentChecksum.isEmpty() && _item->_contentChecksumType.isEmpty()) { + if (_item->_contentChecksum.isEmpty() && _item->_contentChecksumType.isEmpty()) { // If the _contentChecksum was not set, reuse the transmission checksum as the content checksum. _item->_contentChecksum = transmissionChecksum; _item->_contentChecksumType = transmissionChecksumType; @@ -312,7 +312,7 @@ void PropagateUploadFileCommon::slotStartUpload(const QByteArray& transmissionCh // have been changed again, so better check again here. _item->_modtime = FileSystem::getModTime(fullFilePath); - if( prevModtime != _item->_modtime ) { + if (prevModtime != _item->_modtime) { propagator()->_anotherSyncNeeded = true; done(SyncFileItem::SoftError, tr("Local file changed during syncing. It will be resumed.")); return; @@ -334,23 +334,25 @@ void PropagateUploadFileCommon::slotStartUpload(const QByteArray& transmissionCh } UploadDevice::UploadDevice(BandwidthManager *bwm) - : _read(0), - _bandwidthManager(bwm), - _bandwidthQuota(0), - _readWithProgress(0), - _bandwidthLimited(false), _choked(false) + : _read(0) + , _bandwidthManager(bwm) + , _bandwidthQuota(0) + , _readWithProgress(0) + , _bandwidthLimited(false) + , _choked(false) { _bandwidthManager->registerUploadDevice(this); } -UploadDevice::~UploadDevice() { +UploadDevice::~UploadDevice() +{ if (_bandwidthManager) { _bandwidthManager->unregisterUploadDevice(this); } } -bool UploadDevice::prepareAndOpen(const QString& fileName, qint64 start, qint64 size) +bool UploadDevice::prepareAndOpen(const QString &fileName, qint64 start, qint64 size) { _data.clear(); _read = 0; @@ -374,12 +376,14 @@ bool UploadDevice::prepareAndOpen(const QString& fileName, qint64 start, qint64 } -qint64 UploadDevice::writeData(const char* , qint64 ) { +qint64 UploadDevice::writeData(const char *, qint64) +{ ASSERT(false, "write to read only device"); return 0; } -qint64 UploadDevice::readData(char* data, qint64 maxlen) { +qint64 UploadDevice::readData(char *data, qint64 maxlen) +{ if (_data.size() - _read <= 0) { // at end if (_bandwidthManager) { @@ -396,12 +400,12 @@ qint64 UploadDevice::readData(char* data, qint64 maxlen) { } if (isBandwidthLimited()) { maxlen = qMin(maxlen, _bandwidthQuota); - if (maxlen <= 0) { // no quota + if (maxlen <= 0) { // no quota return 0; } _bandwidthQuota -= maxlen; } - std::memcpy(data, _data.data()+_read, maxlen); + std::memcpy(data, _data.data() + _read, maxlen); _read += maxlen; return maxlen; } @@ -414,11 +418,13 @@ void UploadDevice::slotJobUploadProgress(qint64 sent, qint64 t) _readWithProgress = sent; } -bool UploadDevice::atEnd() const { +bool UploadDevice::atEnd() const +{ return _read >= _data.size(); } -qint64 UploadDevice::size() const{ +qint64 UploadDevice::size() const +{ return _data.size(); } @@ -428,12 +434,14 @@ qint64 UploadDevice::bytesAvailable() const } // random access, we can seek -bool UploadDevice::isSequential() const{ +bool UploadDevice::isSequential() const +{ return false; } -bool UploadDevice::seek ( qint64 pos ) { - if (! QIODevice::seek(pos)) { +bool UploadDevice::seek(qint64 pos) +{ + if (!QIODevice::seek(pos)) { return false; } if (pos < 0 || pos > _data.size()) { @@ -443,29 +451,32 @@ bool UploadDevice::seek ( qint64 pos ) { return true; } -void UploadDevice::giveBandwidthQuota(qint64 bwq) { +void UploadDevice::giveBandwidthQuota(qint64 bwq) +{ if (!atEnd()) { _bandwidthQuota = bwq; QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection); // tell QNAM that we have quota } } -void UploadDevice::setBandwidthLimited(bool b) { +void UploadDevice::setBandwidthLimited(bool b) +{ _bandwidthLimited = b; QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection); } -void UploadDevice::setChoked(bool b) { +void UploadDevice::setChoked(bool b) +{ _choked = b; if (!_choked) { QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection); } } -void PropagateUploadFileCommon::startPollJob(const QString& path) +void PropagateUploadFileCommon::startPollJob(const QString &path) { - PollJob* job = new PollJob(propagator()->account(), path, _item, - propagator()->_journal, propagator()->_localDir, this); + PollJob *job = new PollJob(propagator()->account(), path, _item, + propagator()->_journal, propagator()->_localDir, this); connect(job, SIGNAL(finishedSignal()), SLOT(slotPollFinished())); SyncJournalDb::PollInfo info; info._file = _item->_file; @@ -496,32 +507,31 @@ void PropagateUploadFileCommon::slotPollFinished() void PropagateUploadFileCommon::checkResettingErrors() { if (_item->_httpErrorCode == 412 - || propagator()->account()->capabilities().httpErrorCodesThatResetFailingChunkedUploads() - .contains(_item->_httpErrorCode)) { + || propagator()->account()->capabilities().httpErrorCodesThatResetFailingChunkedUploads().contains(_item->_httpErrorCode)) { auto uploadInfo = propagator()->_journal->getUploadInfo(_item->_file); uploadInfo._errorCount += 1; if (uploadInfo._errorCount > 3) { qCInfo(lcPropagateUpload) << "Reset transfer of" << _item->_file - << "due to repeated error" << _item->_httpErrorCode; + << "due to repeated error" << _item->_httpErrorCode; uploadInfo = SyncJournalDb::UploadInfo(); } else { qCInfo(lcPropagateUpload) << "Error count for maybe-reset error" << _item->_httpErrorCode - << "on file" << _item->_file - << "is" << uploadInfo._errorCount; + << "on file" << _item->_file + << "is" << uploadInfo._errorCount; } propagator()->_journal->setUploadInfo(_item->_file, uploadInfo); propagator()->_journal->commit("Upload info"); } } -void PropagateUploadFileCommon::slotJobDestroyed(QObject* job) +void PropagateUploadFileCommon::slotJobDestroyed(QObject *job) { - _jobs.erase(std::remove(_jobs.begin(), _jobs.end(), job) , _jobs.end()); + _jobs.erase(std::remove(_jobs.begin(), _jobs.end(), job), _jobs.end()); } void PropagateUploadFileCommon::abort() { - foreach(auto *job, _jobs) { + foreach (auto *job, _jobs) { if (job->reply()) { job->reply()->abort(); } @@ -543,7 +553,7 @@ QMap PropagateUploadFileCommon::headers() headers["Content-Type"] = "application/octet-stream"; headers["X-OC-Mtime"] = QByteArray::number(qint64(_item->_modtime)); - if(_item->_file.contains(".sys.admin#recall#")) { + if (_item->_file.contains(".sys.admin#recall#")) { // This is a file recall triggered by the admin. Note: the // recall list file created by the admin and downloaded by the // client (.sys.admin#recall#) also falls into this category @@ -555,10 +565,9 @@ QMap PropagateUploadFileCommon::headers() } if (!_item->_etag.isEmpty() && _item->_etag != "empty_etag" - && _item->_instruction != CSYNC_INSTRUCTION_NEW // On new files never send a If-Match + && _item->_instruction != CSYNC_INSTRUCTION_NEW // On new files never send a If-Match && _item->_instruction != CSYNC_INSTRUCTION_TYPE_CHANGE - && !_deleteExisting - ) { + && !_deleteExisting) { // We add quotes because the owncloud server always adds quotes around the etag, and // csync_owncloud.c's owncloud_file_id always strips the quotes. headers["If-Match"] = '"' + _item->_etag + '"'; @@ -580,6 +589,4 @@ void PropagateUploadFileCommon::finalize() done(SyncFileItem::Success); } - - } diff --git a/src/libsync/propagateupload.h b/src/libsync/propagateupload.h index 913155f8d..e9130d934 100644 --- a/src/libsync/propagateupload.h +++ b/src/libsync/propagateupload.h @@ -32,25 +32,30 @@ class BandwidthManager; * @brief The UploadDevice class * @ingroup libsync */ -class UploadDevice : public QIODevice { +class UploadDevice : public QIODevice +{ Q_OBJECT public: UploadDevice(BandwidthManager *bwm); ~UploadDevice(); /** Reads the data from the file and opens the device */ - bool prepareAndOpen(const QString& fileName, qint64 start, qint64 size); + bool prepareAndOpen(const QString &fileName, qint64 start, qint64 size); - qint64 writeData(const char* , qint64 ) Q_DECL_OVERRIDE; - qint64 readData(char* data, qint64 maxlen) Q_DECL_OVERRIDE; + qint64 writeData(const char *, qint64) Q_DECL_OVERRIDE; + qint64 readData(char *data, qint64 maxlen) Q_DECL_OVERRIDE; bool atEnd() const Q_DECL_OVERRIDE; qint64 size() const Q_DECL_OVERRIDE; qint64 bytesAvailable() const Q_DECL_OVERRIDE; bool isSequential() const Q_DECL_OVERRIDE; - bool seek ( qint64 pos ) Q_DECL_OVERRIDE; + bool seek(qint64 pos) Q_DECL_OVERRIDE; #if QT_VERSION < QT_VERSION_CHECK(5, 4, 2) - bool reset() Q_DECL_OVERRIDE { emit wasReset(); return QIODevice::reset(); } + bool reset() Q_DECL_OVERRIDE + { + emit wasReset(); + return QIODevice::reset(); + } #endif void setBandwidthLimited(bool); @@ -65,7 +70,6 @@ signals: #endif private: - // The file data QByteArray _data; // Position in the data @@ -86,11 +90,12 @@ protected slots: * @brief The PUTFileJob class * @ingroup libsync */ -class PUTFileJob : public AbstractNetworkJob { +class PUTFileJob : public AbstractNetworkJob +{ Q_OBJECT private: - QIODevice* _device; + QIODevice *_device; QMap _headers; QString _errorString; QUrl _url; @@ -98,16 +103,22 @@ private: public: // Takes ownership of the device - explicit PUTFileJob(AccountPtr account, const QString& path, QIODevice *device, - const QMap &headers, int chunk, QObject* parent = 0) - : AbstractNetworkJob(account, path, parent), _device(device), _headers(headers), _chunk(chunk) + explicit PUTFileJob(AccountPtr account, const QString &path, QIODevice *device, + const QMap &headers, int chunk, QObject *parent = 0) + : AbstractNetworkJob(account, path, parent) + , _device(device) + , _headers(headers) + , _chunk(chunk) { _device->setParent(this); } - explicit PUTFileJob(AccountPtr account, const QUrl& url, QIODevice *device, - const QMap &headers, int chunk, QObject* parent = 0) - : AbstractNetworkJob(account, QString(), parent), _device(device), _headers(headers) - , _url(url), _chunk(chunk) + explicit PUTFileJob(AccountPtr account, const QUrl &url, QIODevice *device, + const QMap &headers, int chunk, QObject *parent = 0) + : AbstractNetworkJob(account, QString(), parent) + , _device(device) + , _headers(headers) + , _url(url) + , _chunk(chunk) { _device->setParent(this); } @@ -117,28 +128,31 @@ public: virtual void start() Q_DECL_OVERRIDE; - virtual bool finished() Q_DECL_OVERRIDE { + virtual bool finished() Q_DECL_OVERRIDE + { qCInfo(lcPutJob) << "PUT of" << reply()->request().url().toString() << "FINISHED WITH STATUS" - << reply()->error() - << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()) - << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute) - << reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute); + << reply()->error() + << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString()) + << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute) + << reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute); emit finishedSignal(); return true; } - QString errorString() { + QString errorString() + { return _errorString.isEmpty() ? AbstractNetworkJob::errorString() : _errorString; } - quint64 msSinceStart() const { + quint64 msSinceStart() const + { return _requestTimer.elapsed(); } signals: void finishedSignal(); - void uploadProgress(qint64,qint64); + void uploadProgress(qint64, qint64); private slots: #if QT_VERSION < 0x050402 @@ -153,16 +167,23 @@ private slots: * replies with an etag. https://github.com/owncloud/core/issues/12097 * @ingroup libsync */ -class PollJob : public AbstractNetworkJob { +class PollJob : public AbstractNetworkJob +{ Q_OBJECT SyncJournalDb *_journal; QString _localPath; + public: SyncFileItemPtr _item; // Takes ownership of the device explicit PollJob(AccountPtr account, const QString &path, const SyncFileItemPtr &item, - SyncJournalDb *journal, const QString &localPath, QObject *parent) - : AbstractNetworkJob(account, path, parent), _journal(journal), _localPath(localPath), _item(item) {} + SyncJournalDb *journal, const QString &localPath, QObject *parent) + : AbstractNetworkJob(account, path, parent) + , _journal(journal) + , _localPath(localPath) + , _item(item) + { + } void start() Q_DECL_OVERRIDE; bool finished() Q_DECL_OVERRIDE; @@ -191,15 +212,16 @@ signals: * v * finalize() or abortWithError() or startPollJob() */ -class PropagateUploadFileCommon : public PropagateItemJob { +class PropagateUploadFileCommon : public PropagateItemJob +{ Q_OBJECT protected: - QVector _jobs; /// network jobs that are currently in transit + QVector _jobs; /// network jobs that are currently in transit bool _finished BITFIELD(1); /// Tells that all the jobs have been finished bool _deleteExisting BITFIELD(1); - // measure the performance of checksum calc and upload +// measure the performance of checksum calc and upload #ifdef WITH_TESTING Utility::StopWatch _stopWatch; #endif @@ -208,8 +230,12 @@ protected: QByteArray _transmissionChecksumType; public: - PropagateUploadFileCommon(OwncloudPropagator* propagator,const SyncFileItemPtr& item) - : PropagateItemJob(propagator, item), _finished(false), _deleteExisting(false) {} + PropagateUploadFileCommon(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + , _finished(false) + , _deleteExisting(false) + { + } /** * Whether an existing entity with the same name may be deleted before @@ -226,13 +252,14 @@ public: private slots: void slotComputeContentChecksum(); // Content checksum computed, compute the transmission checksum - void slotComputeTransmissionChecksum(const QByteArray& contentChecksumType, const QByteArray& contentChecksum); + void slotComputeTransmissionChecksum(const QByteArray &contentChecksumType, const QByteArray &contentChecksum); // transmission checksum computed, prepare the upload - void slotStartUpload(const QByteArray& transmissionChecksumType, const QByteArray& transmissionChecksum); + void slotStartUpload(const QByteArray &transmissionChecksumType, const QByteArray &transmissionChecksum); + public: virtual void doStartUpload() = 0; - void startPollJob(const QString& path); + void startPollJob(const QString &path); void finalize(); void abortWithError(SyncFileItem::Status status, const QString &error); @@ -253,7 +280,6 @@ protected: // Bases headers that need to be sent with every chunk QMap headers(); - }; /** @@ -262,7 +288,8 @@ protected: * Propagation job, impementing the old chunking agorithm * */ -class PropagateUploadFileV1 : public PropagateUploadFileCommon { +class PropagateUploadFileV1 : public PropagateUploadFileCommon +{ Q_OBJECT private: @@ -285,15 +312,17 @@ private: public: - PropagateUploadFileV1(OwncloudPropagator* propagator,const SyncFileItemPtr& item) : - PropagateUploadFileCommon(propagator,item) {} + PropagateUploadFileV1(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateUploadFileCommon(propagator, item) + { + } void doStartUpload() Q_DECL_OVERRIDE; private slots: void startNextChunk(); void slotPutFinished(); - void slotUploadProgress(qint64,qint64); + void slotUploadProgress(qint64, qint64); }; /** @@ -302,7 +331,8 @@ private slots: * Propagation job, impementing the new chunking agorithm * */ -class PropagateUploadFileNG : public PropagateUploadFileCommon { +class PropagateUploadFileNG : public PropagateUploadFileCommon +{ Q_OBJECT private: quint64 _sent; /// amount of data (bytes) that was already sent @@ -313,7 +343,11 @@ private: // Map chunk number with its size from the PROPFIND on resume. // (Only used from slotPropfindIterate/slotPropfindFinished because the LsColJob use signals to report data.) - struct ServerChunkInfo { quint64 size; QString originalName; }; + struct ServerChunkInfo + { + quint64 size; + QString originalName; + }; QMap _serverChunks; /** @@ -323,8 +357,11 @@ private: QUrl chunkUrl(int chunk = -1); public: - PropagateUploadFileNG(OwncloudPropagator* propagator,const SyncFileItemPtr& item) : - PropagateUploadFileCommon(propagator,item), _currentChunkSize(0) {} + PropagateUploadFileNG(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateUploadFileCommon(propagator, item) + , _currentChunkSize(0) + { + } void doStartUpload() Q_DECL_OVERRIDE; @@ -334,14 +371,11 @@ private: private slots: void slotPropfindFinished(); void slotPropfindFinishedWithError(); - void slotPropfindIterate(const QString &name, const QMap &properties); + void slotPropfindIterate(const QString &name, const QMap &properties); void slotDeleteJobFinished(); void slotMkColFinished(QNetworkReply::NetworkError); void slotPutFinished(); void slotMoveJobFinished(); - void slotUploadProgress(qint64,qint64); + void slotUploadProgress(qint64, qint64); }; - - } - diff --git a/src/libsync/propagateuploadng.cpp b/src/libsync/propagateuploadng.cpp index 75635667d..d6c213389 100644 --- a/src/libsync/propagateuploadng.cpp +++ b/src/libsync/propagateuploadng.cpp @@ -83,18 +83,19 @@ void PropagateUploadFileNG::doStartUpload() propagator()->_activeJobList.append(this); const SyncJournalDb::UploadInfo progressInfo = propagator()->_journal->getUploadInfo(_item->_file); - if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime ) { + if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime) { _transferId = progressInfo._transferid; auto url = chunkUrl(); auto job = new LsColJob(propagator()->account(), url, this); _jobs.append(job); - job->setProperties(QList() << "resourcetype" << "getcontentlength"); + job->setProperties(QList() << "resourcetype" + << "getcontentlength"); connect(job, SIGNAL(finishedWithoutError()), this, SLOT(slotPropfindFinished())); - connect(job, SIGNAL(finishedWithError(QNetworkReply*)), - this, SLOT(slotPropfindFinishedWithError())); - connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); - connect(job, SIGNAL(directoryListingIterated(QString,QMap)), - this, SLOT(slotPropfindIterate(QString,QMap))); + connect(job, SIGNAL(finishedWithError(QNetworkReply *)), + this, SLOT(slotPropfindFinishedWithError())); + connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *))); + connect(job, SIGNAL(directoryListingIterated(QString, QMap)), + this, SLOT(slotPropfindIterate(QString, QMap))); job->start(); return; } else if (progressInfo._valid) { @@ -108,13 +109,13 @@ void PropagateUploadFileNG::doStartUpload() startNewUpload(); } -void PropagateUploadFileNG::slotPropfindIterate(const QString &name, const QMap &properties) +void PropagateUploadFileNG::slotPropfindIterate(const QString &name, const QMap &properties) { if (name == chunkUrl().path()) { return; // skip the info about the path itself } bool ok = false; - QString chunkName = name.mid(name.lastIndexOf('/')+1); + QString chunkName = name.mid(name.lastIndexOf('/') + 1); auto chunkId = chunkName.toUInt(&ok); if (ok) { ServerChunkInfo chunkinfo = { properties["getcontentlength"].toULongLong(), chunkName }; @@ -140,13 +141,13 @@ void PropagateUploadFileNG::slotPropfindFinished() // Normally this can't happen because the size is xor'ed with the transfer id, and it is // therefore impossible that there is more data on the server than on the file. qCCritical(lcPropagateUpload) << "Inconsistency while resuming " << _item->_file - << ": the size on the server (" << _sent << ") is bigger than the size of the file (" - << _item->_size << ")"; + << ": the size on the server (" << _sent << ") is bigger than the size of the file (" + << _item->_size << ")"; startNewUpload(); return; } - qCInfo(lcPropagateUpload) << "Resuming "<< _item->_file << " from chunk " << _currentChunk << "; sent ="<< _sent; + qCInfo(lcPropagateUpload) << "Resuming " << _item->_file << " from chunk " << _currentChunk << "; sent =" << _sent; if (!_serverChunks.isEmpty()) { qCInfo(lcPropagateUpload) << "To Delete" << _serverChunks.keys(); @@ -216,7 +217,6 @@ void PropagateUploadFileNG::slotDeleteJobFinished() } - void PropagateUploadFileNG::startNewUpload() { ASSERT(propagator()->_activeJobList.count(this) == 1); @@ -229,7 +229,7 @@ void PropagateUploadFileNG::startNewUpload() SyncJournalDb::UploadInfo pi; pi._valid = true; pi._transferid = _transferId; - pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime); + pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime); propagator()->_journal->setUploadInfo(_item->_file, pi); propagator()->_journal->commit("Upload info"); QMap headers; @@ -237,8 +237,8 @@ void PropagateUploadFileNG::startNewUpload() auto job = new MkColJob(propagator()->account(), chunkUrl(), headers, this); connect(job, SIGNAL(finished(QNetworkReply::NetworkError)), - this, SLOT(slotMkColFinished(QNetworkReply::NetworkError))); - connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); + this, SLOT(slotMkColFinished(QNetworkReply::NetworkError))); + connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *))); job->start(); } @@ -252,7 +252,7 @@ void PropagateUploadFileNG::slotMkColFinished(QNetworkReply::NetworkError) if (err != QNetworkReply::NoError || _item->_httpErrorCode != 201) { SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); abortWithError(status, job->errorStringParsingBody()); return; } @@ -281,7 +281,7 @@ void PropagateUploadFileNG::startNextChunk() // "If-Match applies to the source, but we are interested in comparing the etag of the destination auto ifMatch = headers.take("If-Match"); if (!ifMatch.isEmpty()) { - headers["If"] = "<" + destination.toUtf8() + "> ([" + ifMatch + "])"; + headers["If"] = "<" + destination.toUtf8() + "> ([" + ifMatch + "])"; } if (!_transmissionChecksumType.isEmpty()) { headers[checkSumHeaderC] = makeChecksumHeader( @@ -291,10 +291,10 @@ void PropagateUploadFileNG::startNextChunk() headers["OC-Total-Length"] = QByteArray::number(fileSize); auto job = new MoveJob(propagator()->account(), Utility::concatUrlPath(chunkUrl(), "/.file"), - destination, headers, this); + destination, headers, this); _jobs.append(job); connect(job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished())); - connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); + connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *))); propagator()->_activeJobList.append(this); job->start(); return; @@ -303,7 +303,7 @@ void PropagateUploadFileNG::startNextChunk() auto device = new UploadDevice(&propagator()->_bandwidthManager); const QString fileName = propagator()->getFilePath(_item->_file); - if (! device->prepareAndOpen(fileName, _sent, _currentChunkSize)) { + if (!device->prepareAndOpen(fileName, _sent, _currentChunkSize)) { qCWarning(lcPropagateUpload) << "Could not prepare upload device: " << device->errorString(); // If the file is currently locked, we want to retry the sync @@ -312,7 +312,7 @@ void PropagateUploadFileNG::startNextChunk() emit propagator()->seenLockedFile(fileName); } // Soft error because this is likely caused by the user modifying his files while syncing - abortWithError( SyncFileItem::SoftError, device->errorString() ); + abortWithError(SyncFileItem::SoftError, device->errorString()); return; } @@ -323,20 +323,19 @@ void PropagateUploadFileNG::startNextChunk() QUrl url = chunkUrl(_currentChunk); // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing - PUTFileJob* job = new PUTFileJob(propagator()->account(), url, device, headers, _currentChunk, this); + PUTFileJob *job = new PUTFileJob(propagator()->account(), url, device, headers, _currentChunk, this); _jobs.append(job); connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished())); - connect(job, SIGNAL(uploadProgress(qint64,qint64)), - this, SLOT(slotUploadProgress(qint64,qint64))); - connect(job, SIGNAL(uploadProgress(qint64,qint64)), - device, SLOT(slotJobUploadProgress(qint64,qint64))); - connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); + connect(job, SIGNAL(uploadProgress(qint64, qint64)), + this, SLOT(slotUploadProgress(qint64, qint64))); + connect(job, SIGNAL(uploadProgress(qint64, qint64)), + device, SLOT(slotJobUploadProgress(qint64, qint64))); + connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *))); job->start(); propagator()->_activeJobList.append(this); _currentChunk++; // FIXME! parallel chunk? - } void PropagateUploadFileNG::slotPutFinished() @@ -376,7 +375,7 @@ void PropagateUploadFileNG::slotPutFinished() checkResettingErrors(); SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); abortWithError(status, errorString); return; } @@ -392,7 +391,7 @@ void PropagateUploadFileNG::slotPutFinished() double uploadTime = job->msSinceStart(); auto predictedGoodSize = static_cast( - _currentChunkSize / uploadTime * targetDuration); + _currentChunkSize / uploadTime * targetDuration); // The whole targeting is heuristic. The predictedGoodSize will fluctuate // quite a bit because of external factors (like available bandwidth) @@ -403,21 +402,21 @@ void PropagateUploadFileNG::slotPutFinished() quint64 targetSize = (propagator()->_chunkSize + predictedGoodSize) / 2; propagator()->_chunkSize = qBound( - propagator()->syncOptions()._minChunkSize, - targetSize, - propagator()->syncOptions()._maxChunkSize); + propagator()->syncOptions()._minChunkSize, + targetSize, + propagator()->syncOptions()._maxChunkSize); qCInfo(lcPropagateUpload) << "Chunked upload of" << _currentChunkSize << "bytes took" << uploadTime - << "ms, desired is" << targetDuration << "ms, expected good chunk size is" - << predictedGoodSize << "bytes and nudged next chunk size to " - << propagator()->_chunkSize << "bytes"; + << "ms, desired is" << targetDuration << "ms, expected good chunk size is" + << predictedGoodSize << "bytes and nudged next chunk size to " + << propagator()->_chunkSize << "bytes"; } bool finished = _sent == _item->_size; // Check if the file still exists const QString fullFilePath(propagator()->getFilePath(_item->_file)); - if( !FileSystem::fileExists(fullFilePath) ) { + if (!FileSystem::fileExists(fullFilePath)) { if (!finished) { abortWithError(SyncFileItem::SoftError, tr("The local file was removed during sync.")); return; @@ -427,9 +426,9 @@ void PropagateUploadFileNG::slotPutFinished() } // Check whether the file changed since discovery. - if (! FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) { + if (!FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) { propagator()->_anotherSyncNeeded = true; - if( !finished ) { + if (!finished) { abortWithError(SyncFileItem::SoftError, tr("Local file changed during sync.")); return; } @@ -473,7 +472,7 @@ void PropagateUploadFileNG::slotMoveJobFinished() checkResettingErrors(); SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); abortWithError(status, job->errorStringParsingBody()); return; } @@ -483,19 +482,20 @@ void PropagateUploadFileNG::slotMoveJobFinished() } QByteArray fid = job->reply()->rawHeader("OC-FileID"); - if(fid.isEmpty()) { + if (fid.isEmpty()) { qCWarning(lcPropagateUpload) << "Server did not return a OC-FileID" << _item->_file; abortWithError(SyncFileItem::NormalError, tr("Missing File ID from server")); return; } else { // the old file id should only be empty for new files uploaded - if( !_item->_fileId.isEmpty() && _item->_fileId != fid ) { + if (!_item->_fileId.isEmpty() && _item->_fileId != fid) { qCWarning(lcPropagateUpload) << "File ID changed!" << _item->_fileId << fid; } _item->_fileId = fid; } - _item->_etag = getEtagFromReply(job->reply());; + _item->_etag = getEtagFromReply(job->reply()); + ; if (_item->_etag.isEmpty()) { qCWarning(lcPropagateUpload) << "Server did not return an ETAG" << _item->_file; abortWithError(SyncFileItem::NormalError, tr("Missing ETag from server")); @@ -507,9 +507,9 @@ void PropagateUploadFileNG::slotMoveJobFinished() // performance logging quint64 duration = _stopWatch.stop(); qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size - << _stopWatch.durationOfLap(QLatin1String("ContentChecksum")) - << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum")) - << duration; + << _stopWatch.durationOfLap(QLatin1String("ContentChecksum")) + << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum")) + << duration; // The job might stay alive for the whole sync, release this tiny bit of memory. _stopWatch.reset(); #endif @@ -527,5 +527,4 @@ void PropagateUploadFileNG::slotUploadProgress(qint64 sent, qint64 total) } propagator()->reportProgress(*_item, _sent + sent - total); } - } diff --git a/src/libsync/propagateuploadv1.cpp b/src/libsync/propagateuploadv1.cpp index 10f6a4fb2..f8a88020d 100644 --- a/src/libsync/propagateuploadv1.cpp +++ b/src/libsync/propagateuploadv1.cpp @@ -43,7 +43,7 @@ void PropagateUploadFileV1::doStartUpload() const SyncJournalDb::UploadInfo progressInfo = propagator()->_journal->getUploadInfo(_item->_file); - if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime ) { + if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime) { _startChunk = progressInfo._chunk; _transferId = progressInfo._transferid; qCInfo(lcPropagateUpload) << _item->_file << ": Resuming from chunk " << _startChunk; @@ -60,7 +60,7 @@ void PropagateUploadFileV1::startNextChunk() if (propagator()->_abortRequested.fetchAndAddRelaxed(0)) return; - if (! _jobs.isEmpty() && _currentChunk + _startChunk >= _chunkCount - 1) { + if (!_jobs.isEmpty() && _currentChunk + _startChunk >= _chunkCount - 1) { // Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that // https://github.com/owncloud/core/issues/11106 // We return now and when the _jobs are finished we will proceed with the last chunk @@ -71,7 +71,7 @@ void PropagateUploadFileV1::startNextChunk() quint64 fileSize = _item->_size; auto headers = PropagateUploadFileCommon::headers(); headers["OC-Total-Length"] = QByteArray::number(fileSize); - headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize())); + headers["OC-Chunk-Size"] = QByteArray::number(quint64(chunkSize())); QString path = _item->_file; @@ -84,7 +84,7 @@ void PropagateUploadFileV1::startNextChunk() // XOR with chunk size to make sure everything goes well if chunk size changes between runs uint transid = _transferId ^ chunkSize(); qCInfo(lcPropagateUpload) << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid; - path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk); + path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk); headers["OC-Chunked"] = "1"; @@ -92,7 +92,7 @@ void PropagateUploadFileV1::startNextChunk() currentChunkSize = chunkSize(); if (sendingChunk == _chunkCount - 1) { // last chunk currentChunkSize = (fileSize % chunkSize()); - if( currentChunkSize == 0 ) { // if the last chunk pretends to be 0, its actually the full chunk size. + if (currentChunkSize == 0) { // if the last chunk pretends to be 0, its actually the full chunk size. currentChunkSize = chunkSize(); } isFinalChunk = true; @@ -105,11 +105,11 @@ void PropagateUploadFileV1::startNextChunk() if (isFinalChunk && !_transmissionChecksumType.isEmpty()) { headers[checkSumHeaderC] = makeChecksumHeader( - _transmissionChecksumType, _transmissionChecksum); + _transmissionChecksumType, _transmissionChecksum); } const QString fileName = propagator()->getFilePath(_item->_file); - if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) { + if (!device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) { qCWarning(lcPropagateUpload) << "Could not prepare upload device: " << device->errorString(); // If the file is currently locked, we want to retry the sync @@ -118,18 +118,18 @@ void PropagateUploadFileV1::startNextChunk() emit propagator()->seenLockedFile(fileName); } // Soft error because this is likely caused by the user modifying his files while syncing - abortWithError( SyncFileItem::SoftError, device->errorString() ); + abortWithError(SyncFileItem::SoftError, device->errorString()); delete device; return; } // job takes ownership of device via a QScopedPointer. Job deletes itself when finishing - PUTFileJob* job = new PUTFileJob(propagator()->account(), propagator()->_remoteFolder + path, device, headers, _currentChunk, this); + PUTFileJob *job = new PUTFileJob(propagator()->account(), propagator()->_remoteFolder + path, device, headers, _currentChunk, this); _jobs.append(job); connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished())); - connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64))); - connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64))); - connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*))); + connect(job, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(slotUploadProgress(qint64, qint64))); + connect(job, SIGNAL(uploadProgress(qint64, qint64)), device, SLOT(slotJobUploadProgress(qint64, qint64))); + connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *))); job->start(); propagator()->_activeJobList.append(this); _currentChunk++; @@ -161,7 +161,7 @@ void PropagateUploadFileV1::startNextChunk() } if (parallelChunkUpload && (propagator()->_activeJobList.count() < propagator()->maximumActiveTransferJob()) - && _currentChunk < _chunkCount ) { + && _currentChunk < _chunkCount) { startNextChunk(); } if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) { @@ -186,7 +186,7 @@ void PropagateUploadFileV1::slotPutFinished() QNetworkReply::NetworkError err = job->reply()->error(); #if QT_VERSION < QT_VERSION_CHECK(5, 4, 2) - if (err == QNetworkReply::OperationCanceledError && job->reply()->property("owncloud-should-soft-cancel").isValid()) { // Abort the job and try again later. + if (err == QNetworkReply::OperationCanceledError && job->reply()->property("owncloud-should-soft-cancel").isValid()) { // Abort the job and try again later. // This works around a bug in QNAM wich might reuse a non-empty buffer for the next request. qCWarning(lcPropagateUpload) << "Forcing job abort on HTTP connection reset with Qt < 5.4.2."; propagator()->_anotherSyncNeeded = true; @@ -197,9 +197,9 @@ void PropagateUploadFileV1::slotPutFinished() if (err != QNetworkReply::NoError) { _item->_httpErrorCode = job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); - if(checkForProblemsWithShared(_item->_httpErrorCode, - tr("The file was edited locally but is part of a read only share. " - "It is restored and your edit is in the conflict file."))) { + if (checkForProblemsWithShared(_item->_httpErrorCode, + tr("The file was edited locally but is part of a read only share. " + "It is restored and your edit is in the conflict file."))) { return; } QByteArray replyContent; @@ -219,7 +219,7 @@ void PropagateUploadFileV1::slotPutFinished() checkResettingErrors(); SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode, - &propagator()->_anotherSyncNeeded); + &propagator()->_anotherSyncNeeded); abortWithError(status, errorString); return; } @@ -228,7 +228,7 @@ void PropagateUploadFileV1::slotPutFinished() // The server needs some time to process the request and provide us with a poll URL if (_item->_httpErrorCode == 202) { _finished = true; - QString path = QString::fromUtf8(job->reply()->rawHeader("OC-Finish-Poll")); + QString path = QString::fromUtf8(job->reply()->rawHeader("OC-Finish-Poll")); if (path.isEmpty()) { done(SyncFileItem::NormalError, tr("Poll URL missing")); return; @@ -251,7 +251,7 @@ void PropagateUploadFileV1::slotPutFinished() // Check if the file still exists const QString fullFilePath(propagator()->getFilePath(_item->_file)); - if( !FileSystem::fileExists(fullFilePath) ) { + if (!FileSystem::fileExists(fullFilePath)) { if (!finished) { abortWithError(SyncFileItem::SoftError, tr("The local file was removed during sync.")); return; @@ -261,9 +261,9 @@ void PropagateUploadFileV1::slotPutFinished() } // Check whether the file changed since discovery. - if (! FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) { + if (!FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) { propagator()->_anotherSyncNeeded = true; - if( !finished ) { + if (!finished) { abortWithError(SyncFileItem::SoftError, tr("Local file changed during sync.")); // FIXME: the legacy code was retrying for a few seconds. // and also checking that after the last chunk, and removed the file in case of INSTRUCTION_NEW @@ -294,13 +294,13 @@ void PropagateUploadFileV1::slotPutFinished() auto currentChunk = job->_chunk; foreach (auto *job, _jobs) { // Take the minimum finished one - if (auto putJob = qobject_cast(job)) { + if (auto putJob = qobject_cast(job)) { currentChunk = qMin(currentChunk, putJob->_chunk - 1); } } - pi._chunk = (currentChunk + _startChunk + 1) % _chunkCount ; // next chunk to start with + pi._chunk = (currentChunk + _startChunk + 1) % _chunkCount; // next chunk to start with pi._transferid = _transferId; - pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime); + pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime); pi._errorCount = 0; // successful chunk upload resets propagator()->_journal->setUploadInfo(_item->_file, pi); propagator()->_journal->commit("Upload info"); @@ -312,8 +312,8 @@ void PropagateUploadFileV1::slotPutFinished() _finished = true; // the file id should only be empty for new files up- or downloaded QByteArray fid = job->reply()->rawHeader("OC-FileID"); - if( !fid.isEmpty() ) { - if( !_item->_fileId.isEmpty() && _item->_fileId != fid ) { + if (!fid.isEmpty()) { + if (!_item->_fileId.isEmpty() && _item->_fileId != fid) { qCWarning(lcPropagateUpload) << "File ID changed!" << _item->_fileId << fid; } _item->_fileId = fid; @@ -335,9 +335,9 @@ void PropagateUploadFileV1::slotPutFinished() // performance logging quint64 duration = _stopWatch.stop(); qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size - << _stopWatch.durationOfLap(QLatin1String("ContentChecksum")) - << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum")) - << duration; + << _stopWatch.durationOfLap(QLatin1String("ContentChecksum")) + << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum")) + << duration; // The job might stay alive for the whole sync, release this tiny bit of memory. _stopWatch.reset(); #endif @@ -368,7 +368,7 @@ void PropagateUploadFileV1::slotUploadProgress(qint64 sent, qint64 total) sender()->setProperty("byteWritten", sent); if (_jobs.count() > 1) { - amount -= (_jobs.count() -1) * chunkSize(); + amount -= (_jobs.count() - 1) * chunkSize(); foreach (QObject *j, _jobs) { amount += j->property("byteWritten").toULongLong(); } @@ -378,5 +378,4 @@ void PropagateUploadFileV1::slotUploadProgress(qint64 sent, qint64 total) } propagator()->reportProgress(*_item, amount); } - } diff --git a/src/libsync/propagatorjobs.cpp b/src/libsync/propagatorjobs.cpp index 7c8c5a31a..bda94fa11 100644 --- a/src/libsync/propagatorjobs.cpp +++ b/src/libsync/propagatorjobs.cpp @@ -51,7 +51,7 @@ Q_LOGGING_CATEGORY(lcPropagateLocalRename, "sync.propagator.localrename", QtInfo * * \a path is relative to propagator()->_localDir + _item->_file and should start with a slash */ -bool PropagateLocalRemove::removeRecursively(const QString& path) +bool PropagateLocalRemove::removeRecursively(const QString &path) { bool success = true; QString absolute = propagator()->_localDir + _item->_file + path; @@ -61,7 +61,7 @@ bool PropagateLocalRemove::removeRecursively(const QString& path) while (di.hasNext()) { di.next(); - const QFileInfo& fi = di.fileInfo(); + const QFileInfo &fi = di.fileInfo(); bool ok; // The use of isSymLink here is okay: // we never want to go into this branch for .lnk files @@ -72,16 +72,15 @@ bool PropagateLocalRemove::removeRecursively(const QString& path) QString removeError; ok = FileSystem::remove(di.filePath(), &removeError); if (!ok) { - _error += PropagateLocalRemove::tr("Error removing '%1': %2;"). - arg(QDir::toNativeSeparators(di.filePath()), removeError) + " "; + _error += PropagateLocalRemove::tr("Error removing '%1': %2;").arg(QDir::toNativeSeparators(di.filePath()), removeError) + " "; qCWarning(lcPropagateLocalRemove) << "Error removing " << di.filePath() << ':' << removeError; } } if (success && !ok) { // We need to delete the entries from the database now from the deleted vector - foreach(const auto &it, deleted) { + foreach (const auto &it, deleted) { propagator()->_journal->deleteFileRecord(_item->_originalFile + path + QLatin1Char('/') + it.first, - it.second); + it.second); } success = false; deleted.clear(); @@ -92,14 +91,15 @@ bool PropagateLocalRemove::removeRecursively(const QString& path) if (!success && ok) { // This succeeded, so we need to delete it from the database now because the caller won't propagator()->_journal->deleteFileRecord(_item->_originalFile + path + QLatin1Char('/') + di.fileName(), - isDir); + isDir); } } if (success) { success = QDir().rmdir(absolute); if (!success) { _error += PropagateLocalRemove::tr("Could not remove folder '%1'") - .arg(QDir::toNativeSeparators(absolute)) + " "; + .arg(QDir::toNativeSeparators(absolute)) + + " "; qCWarning(lcPropagateLocalRemove) << "Error removing folder" << absolute; } } @@ -111,13 +111,12 @@ void PropagateLocalRemove::start() if (propagator()->_abortRequested.fetchAndAddRelaxed(0)) return; - QString filename = propagator()->_localDir + _item->_file; + QString filename = propagator()->_localDir + _item->_file; qCDebug(lcPropagateLocalRemove) << filename; - if( propagator()->localFileNameClash(_item->_file)) { - done(SyncFileItem::NormalError, tr("Could not remove %1 because of a local file name clash") - .arg(QDir::toNativeSeparators(filename))); + if (propagator()->localFileNameClash(_item->_file)) { + done(SyncFileItem::NormalError, tr("Could not remove %1 because of a local file name clash").arg(QDir::toNativeSeparators(filename))); return; } @@ -129,7 +128,7 @@ void PropagateLocalRemove::start() } else { QString removeError; if (FileSystem::fileExists(filename) - && !FileSystem::remove(filename, &removeError)) { + && !FileSystem::remove(filename, &removeError)) { done(SyncFileItem::NormalError, removeError); return; } @@ -154,22 +153,22 @@ void PropagateLocalMkdir::start() if (_deleteExistingFile && fi.exists() && fi.isFile()) { QString removeError; if (!FileSystem::remove(newDirStr, &removeError)) { - done( SyncFileItem::NormalError, - tr("could not delete file %1, error: %2") - .arg(newDirStr, removeError)); + done(SyncFileItem::NormalError, + tr("could not delete file %1, error: %2") + .arg(newDirStr, removeError)); return; } } - if( Utility::fsCasePreserving() && propagator()->localFileNameClash(_item->_file ) ) { + if (Utility::fsCasePreserving() && propagator()->localFileNameClash(_item->_file)) { qCWarning(lcPropagateLocalMkdir) << "New folder to create locally already exists with different case:" << _item->_file; - done( SyncFileItem::NormalError, tr("Attention, possible case sensitivity clash with %1").arg(newDirStr) ); + done(SyncFileItem::NormalError, tr("Attention, possible case sensitivity clash with %1").arg(newDirStr)); return; } emit propagator()->touchedFile(newDirStr); QDir localDir(propagator()->_localDir); if (!localDir.mkpath(_item->_file)) { - done( SyncFileItem::NormalError, tr("could not create folder %1").arg(newDirStr) ); + done(SyncFileItem::NormalError, tr("could not create folder %1").arg(newDirStr)); return; } @@ -209,16 +208,16 @@ void PropagateLocalRename::start() qCDebug(lcPropagateLocalRename) << "MOVE " << existingFile << " => " << targetFile; if (QString::compare(_item->_file, _item->_renameTarget, Qt::CaseInsensitive) != 0 - && propagator()->localFileNameClash(_item->_renameTarget)) { + && propagator()->localFileNameClash(_item->_renameTarget)) { // Only use localFileNameClash for the destination if we know that the source was not // the one conflicting (renaming A.txt -> a.txt is OK) // Fixme: the file that is the reason for the clash could be named here, // it would have to come out the localFileNameClash function done(SyncFileItem::NormalError, - tr( "File %1 can not be renamed to %2 because of a local file name clash") - .arg(QDir::toNativeSeparators(_item->_file)) - .arg(QDir::toNativeSeparators(_item->_renameTarget)) ); + tr("File %1 can not be renamed to %2 because of a local file name clash") + .arg(QDir::toNativeSeparators(_item->_file)) + .arg(QDir::toNativeSeparators(_item->_renameTarget))); return; } @@ -232,7 +231,7 @@ void PropagateLocalRename::start() } SyncJournalFileRecord oldRecord = - propagator()->_journal->getFileRecord(_item->_originalFile); + propagator()->_journal->getFileRecord(_item->_originalFile); propagator()->_journal->deleteFileRecord(_item->_originalFile); // store the rename file name in the item. @@ -262,5 +261,4 @@ void PropagateLocalRename::start() done(SyncFileItem::Success); } - } diff --git a/src/libsync/propagatorjobs.h b/src/libsync/propagatorjobs.h index 2a30b3cec..2f7c53df7 100644 --- a/src/libsync/propagatorjobs.h +++ b/src/libsync/propagatorjobs.h @@ -36,11 +36,16 @@ static const char checkSumAdlerC[] = "Adler32"; * @brief Declaration of the other propagation jobs * @ingroup libsync */ -class PropagateLocalRemove : public PropagateItemJob { +class PropagateLocalRemove : public PropagateItemJob +{ Q_OBJECT public: - PropagateLocalRemove (OwncloudPropagator* propagator,const SyncFileItemPtr& item) : PropagateItemJob(propagator, item) {} + PropagateLocalRemove(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + { + } void start() Q_DECL_OVERRIDE; + private: bool removeRecursively(const QString &path); QString _error; @@ -50,11 +55,15 @@ private: * @brief The PropagateLocalMkdir class * @ingroup libsync */ -class PropagateLocalMkdir : public PropagateItemJob { +class PropagateLocalMkdir : public PropagateItemJob +{ Q_OBJECT public: - PropagateLocalMkdir (OwncloudPropagator* propagator,const SyncFileItemPtr& item) - : PropagateItemJob(propagator, item), _deleteExistingFile(false) {} + PropagateLocalMkdir(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + , _deleteExistingFile(false) + { + } void start() Q_DECL_OVERRIDE; /** @@ -73,12 +82,15 @@ private: * @brief The PropagateLocalRename class * @ingroup libsync */ -class PropagateLocalRename : public PropagateItemJob { +class PropagateLocalRename : public PropagateItemJob +{ Q_OBJECT public: - PropagateLocalRename (OwncloudPropagator* propagator,const SyncFileItemPtr& item) : PropagateItemJob(propagator, item) {} + PropagateLocalRename(OwncloudPropagator *propagator, const SyncFileItemPtr &item) + : PropagateItemJob(propagator, item) + { + } void start() Q_DECL_OVERRIDE; JobParallelism parallelism() Q_DECL_OVERRIDE { return _item->_isDirectory ? WaitForFinished : FullParallelism; } }; - } diff --git a/src/libsync/syncengine.cpp b/src/libsync/syncengine.cpp index 9673d7a4c..12d6c879c 100644 --- a/src/libsync/syncengine.cpp +++ b/src/libsync/syncengine.cpp @@ -58,23 +58,23 @@ bool SyncEngine::s_anySyncRunning = false; qint64 SyncEngine::minimumFileAgeForUpload = 2000; -SyncEngine::SyncEngine(AccountPtr account, const QString& localPath, - const QString& remotePath, OCC::SyncJournalDb* journal) - : _account(account) - , _needsUpdate(false) - , _syncRunning(false) - , _localPath(localPath) - , _remotePath(remotePath) - , _journal(journal) - , _progressInfo(new ProgressInfo) - , _hasNoneFiles(false) - , _hasRemoveFile(false) - , _hasForwardInTimeFiles(false) - , _backInTimeFiles(0) - , _uploadLimit(0) - , _downloadLimit(0) - , _checksum_hook(journal) - , _anotherSyncNeeded(NoFollowUpSync) +SyncEngine::SyncEngine(AccountPtr account, const QString &localPath, + const QString &remotePath, OCC::SyncJournalDb *journal) + : _account(account) + , _needsUpdate(false) + , _syncRunning(false) + , _localPath(localPath) + , _remotePath(remotePath) + , _journal(journal) + , _progressInfo(new ProgressInfo) + , _hasNoneFiles(false) + , _hasRemoveFile(false) + , _hasForwardInTimeFiles(false) + , _backInTimeFiles(0) + , _uploadLimit(0) + , _downloadLimit(0) + , _checksum_hook(journal) + , _anotherSyncNeeded(NoFollowUpSync) { qRegisterMetaType("SyncFileItem"); qRegisterMetaType("SyncFileItemPtr"); @@ -95,7 +95,7 @@ SyncEngine::SyncEngine(AccountPtr account, const QString& localPath, _syncFileStatusTracker.reset(new SyncFileStatusTracker(this)); _clearTouchedFilesTimer.setSingleShot(true); - _clearTouchedFilesTimer.setInterval(30*1000); + _clearTouchedFilesTimer.setInterval(30 * 1000); connect(&_clearTouchedFilesTimer, SIGNAL(timeout()), SLOT(slotClearTouchedFiles())); _thread.setObjectName("SyncEngine_Thread"); @@ -116,7 +116,7 @@ QString SyncEngine::csyncErrorToString(CSYNC_STATUS err) { QString errStr; - switch( err ) { + switch (err) { case CSYNC_STATUS_OK: errStr = tr("Success."); break; @@ -197,13 +197,12 @@ QString SyncEngine::csyncErrorToString(CSYNC_STATUS err) errStr = tr("Error while reading folder."); break; case CSYNC_STATUS_INVALID_CHARACTERS: - // Handled in callee + // Handled in callee default: - errStr = tr("An internal error number %1 occurred.").arg( (int) err ); + errStr = tr("An internal error number %1 occurred.").arg((int)err); } return errStr; - } /** @@ -212,9 +211,9 @@ QString SyncEngine::csyncErrorToString(CSYNC_STATUS err) * and proper error message, and return true. * If the item is not in the blacklist, or the blacklist is stale, return false. */ -bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item ) +bool SyncEngine::checkErrorBlacklisting(SyncFileItem &item) { - if( !_journal ) { + if (!_journal) { qCCritical(lcEngine) << "Journal is undefined!"; return false; } @@ -222,7 +221,7 @@ bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item ) SyncJournalErrorBlacklistRecord entry = _journal->errorBlacklistEntry(item._file); item._hasBlacklistEntry = false; - if( !entry.isValid() ) { + if (!entry.isValid()) { return false; } @@ -230,37 +229,37 @@ bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item ) // If duration has expired, it's not blacklisted anymore time_t now = Utility::qDateTimeToTime_t(QDateTime::currentDateTime()); - if( now >= entry._lastTryTime + entry._ignoreDuration ) { + if (now >= entry._lastTryTime + entry._ignoreDuration) { qCInfo(lcEngine) << "blacklist entry for " << item._file << " has expired!"; return false; } // If the file has changed locally or on the server, the blacklist // entry no longer applies - if( item._direction == SyncFileItem::Up ) { // check the modtime - if(item._modtime == 0 || entry._lastTryModtime == 0) { + if (item._direction == SyncFileItem::Up) { // check the modtime + if (item._modtime == 0 || entry._lastTryModtime == 0) { return false; - } else if( item._modtime != entry._lastTryModtime ) { + } else if (item._modtime != entry._lastTryModtime) { qCInfo(lcEngine) << item._file << " is blacklisted, but has changed mtime!"; return false; - } else if( item._renameTarget != entry._renameTarget) { + } else if (item._renameTarget != entry._renameTarget) { qCInfo(lcEngine) << item._file << " is blacklisted, but rename target changed from" << entry._renameTarget; return false; } - } else if( item._direction == SyncFileItem::Down ) { + } else if (item._direction == SyncFileItem::Down) { // download, check the etag. - if( item._etag.isEmpty() || entry._lastTryEtag.isEmpty() ) { + if (item._etag.isEmpty() || entry._lastTryEtag.isEmpty()) { qCInfo(lcEngine) << item._file << "one ETag is empty, no blacklisting"; return false; - } else if( item._etag != entry._lastTryEtag ) { + } else if (item._etag != entry._lastTryEtag) { qCInfo(lcEngine) << item._file << " is blacklisted, but has changed etag!"; return false; } } qCInfo(lcEngine) << "Item is on blacklist: " << entry._file - << "retries:" << entry._retryCount - << "for another" << (entry._lastTryTime + entry._ignoreDuration - now) << "s"; + << "retries:" << entry._retryCount + << "for another" << (entry._lastTryTime + entry._ignoreDuration - now) << "s"; item._instruction = CSYNC_INSTRUCTION_ERROR; item._status = SyncFileItem::FileIgnored; item._errorString = tr("The item is not synced because of previous errors: %1").arg(entry._errorString); @@ -272,18 +271,17 @@ void SyncEngine::deleteStaleDownloadInfos(const SyncFileItemVector &syncItems) { // Find all downloadinfo paths that we want to preserve. QSet download_file_paths; - foreach(const SyncFileItemPtr &it, syncItems) { + foreach (const SyncFileItemPtr &it, syncItems) { if (it->_direction == SyncFileItem::Down - && it->_type == SyncFileItem::File) - { + && it->_type == SyncFileItem::File) { download_file_paths.insert(it->_file); } } // Delete from journal and from filesystem. const QVector deleted_infos = - _journal->getAndDeleteStaleDownloadInfos(download_file_paths); - foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) { + _journal->getAndDeleteStaleDownloadInfos(download_file_paths); + foreach (const SyncJournalDb::DownloadInfo &deleted_info, deleted_infos) { const QString tmppath = _propagator->getFilePath(deleted_info._tmpfile); qCInfo(lcEngine) << "Deleting stale temporary file: " << tmppath; FileSystem::remove(tmppath); @@ -294,10 +292,9 @@ void SyncEngine::deleteStaleUploadInfos(const SyncFileItemVector &syncItems) { // Find all blacklisted paths that we want to preserve. QSet upload_file_paths; - foreach(const SyncFileItemPtr &it, syncItems) { + foreach (const SyncFileItemPtr &it, syncItems) { if (it->_direction == SyncFileItem::Up - && it->_type == SyncFileItem::File) - { + && it->_type == SyncFileItem::File) { upload_file_paths.insert(it->_file); } } @@ -308,8 +305,7 @@ void SyncEngine::deleteStaleUploadInfos(const SyncFileItemVector &syncItems) // Delete the stales chunk on the server. if (account()->capabilities().chunkingNg()) { foreach (uint transferId, ids) { - QUrl url = Utility::concatUrlPath(account()->url(), QLatin1String("remote.php/dav/uploads/") - + account()->davUser() + QLatin1Char('/') + QString::number(transferId)); + QUrl url = Utility::concatUrlPath(account()->url(), QLatin1String("remote.php/dav/uploads/") + account()->davUser() + QLatin1Char('/') + QString::number(transferId)); (new DeleteJob(account(), url, this))->start(); } } @@ -319,7 +315,7 @@ void SyncEngine::deleteStaleErrorBlacklistEntries(const SyncFileItemVector &sync { // Find all blacklisted paths that we want to preserve. QSet blacklist_file_paths; - foreach(const SyncFileItemPtr &it, syncItems) { + foreach (const SyncFileItemPtr &it, syncItems) { if (it->_hasBlacklistEntry) blacklist_file_paths.insert(it->_file); } @@ -328,14 +324,14 @@ void SyncEngine::deleteStaleErrorBlacklistEntries(const SyncFileItemVector &sync _journal->deleteStaleErrorBlacklistEntries(blacklist_file_paths); } -int SyncEngine::treewalkLocal( TREE_WALK_FILE* file, void *data ) +int SyncEngine::treewalkLocal(TREE_WALK_FILE *file, void *data) { - return static_cast(data)->treewalkFile( file, false ); + return static_cast(data)->treewalkFile(file, false); } -int SyncEngine::treewalkRemote( TREE_WALK_FILE* file, void *data ) +int SyncEngine::treewalkRemote(TREE_WALK_FILE *file, void *data) { - return static_cast(data)->treewalkFile( file, true ); + return static_cast(data)->treewalkFile(file, true); } /** @@ -348,9 +344,10 @@ int SyncEngine::treewalkRemote( TREE_WALK_FILE* file, void *data ) * * See doc/dev/sync-algorithm.md for an overview. */ -int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) +int SyncEngine::treewalkFile(TREE_WALK_FILE *file, bool remote) { - if( ! file ) return -1; + if (!file) + return -1; QTextCodec::ConverterState utf8State; static QTextCodec *codec = QTextCodec::codecForName("UTF-8"); @@ -385,7 +382,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) item->_originalFile = item->_file; if (item->_instruction == CSYNC_INSTRUCTION_NONE - || (item->_instruction == CSYNC_INSTRUCTION_IGNORE && instruction != CSYNC_INSTRUCTION_NONE)) { + || (item->_instruction == CSYNC_INSTRUCTION_IGNORE && instruction != CSYNC_INSTRUCTION_NONE)) { item->_instruction = instruction; item->_modtime = file->modtime; } else { @@ -402,10 +399,10 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) item->_fileId = file->file_id; } if (file->directDownloadUrl) { - item->_directDownloadUrl = QString::fromUtf8( file->directDownloadUrl ); + item->_directDownloadUrl = QString::fromUtf8(file->directDownloadUrl); } if (file->directDownloadCookies) { - item->_directDownloadCookies = QString::fromUtf8( file->directDownloadCookies ); + item->_directDownloadCookies = QString::fromUtf8(file->directDownloadCookies); } if (file->remotePerm && file->remotePerm[0]) { item->_remotePerm = QByteArray(file->remotePerm); @@ -424,8 +421,8 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) * It needs to go to the sync journal becasue the stat information about remote * files are often read from database rather than being pulled from remote. */ - if( remote ) { - item->_serverHasIgnoredFiles = (file->has_ignored_files > 0); + if (remote) { + item->_serverHasIgnoredFiles = (file->has_ignored_files > 0); } // Sometimes the discovery computes checksums for local files @@ -441,7 +438,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) _seenFiles.insert(renameTarget); } - switch(file->error_status) { + switch (file->error_status) { case CSYNC_STATUS_OK: break; case CSYNC_STATUS_INDIVIDUAL_IS_SYMLINK: @@ -455,7 +452,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) item->_errorString = tr("File names ending with a period are not supported on this file system."); } else { char invalid = '\0'; - foreach(char x, QByteArray("\\:?*\"<>|")) { + foreach (char x, QByteArray("\\:?*\"<>|")) { if (item->_file.contains(x)) { invalid = x; break; @@ -463,7 +460,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) } if (invalid) { item->_errorString = tr("File names containing the character '%1' are not supported on this file system.") - .arg(QLatin1Char(invalid)); + .arg(QLatin1Char(invalid)); } else { item->_errorString = tr("The file name is a reserved name on this file system."); } @@ -526,7 +523,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) item->_inode = file->inode; } - switch( file->type ) { + switch (file->type) { case CSYNC_FTW_TYPE_DIR: item->_type = SyncFileItem::Directory; break; @@ -543,7 +540,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) SyncFileItem::Direction dir = SyncFileItem::None; int re = 0; - switch(file->instruction) { + switch (file->instruction) { case CSYNC_INSTRUCTION_NONE: { // Any files that are instruction NONE? if (!isDirectory && file->other.instruction == CSYNC_INSTRUCTION_NONE) { @@ -623,7 +620,7 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) _hasNoneFiles = true; } else if (!isDirectory) { auto difftime = std::difftime(file->modtime, file->other.modtime); - if (difftime < -3600*2) { + if (difftime < -3600 * 2) { // We are going back on time // We only increment if the difference is more than two hours to avoid clock skew // issues or DST changes. (We simply ignore files that goes in the past less than @@ -649,18 +646,18 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) if (instruction != CSYNC_INSTRUCTION_NONE) { // check for blacklisting of this item. // if the item is on blacklist, the instruction was set to ERROR - checkErrorBlacklisting( *item ); + checkErrorBlacklisting(*item); } _progressInfo->adjustTotalsForFile(*item); _needsUpdate = true; - item->log._other_etag = file->other.etag; - item->log._other_fileId = file->other.file_id; + item->log._other_etag = file->other.etag; + item->log._other_fileId = file->other.file_id; item->log._other_instruction = file->other.instruction; - item->log._other_modtime = file->other.modtime; - item->log._other_size = file->other.size; + item->log._other_modtime = file->other.modtime; + item->log._other_size = file->other.size; _syncItemMap.insert(key, item); @@ -668,12 +665,13 @@ int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote ) return re; } -void SyncEngine::handleSyncError(CSYNC *ctx, const char *state) { - CSYNC_STATUS err = csync_get_status( ctx ); - const char *errMsg = csync_get_status_string( ctx ); +void SyncEngine::handleSyncError(CSYNC *ctx, const char *state) +{ + CSYNC_STATUS err = csync_get_status(ctx); + const char *errMsg = csync_get_status_string(ctx); QString errStr = csyncErrorToString(err); - if( errMsg ) { - if( !errStr.endsWith(" ")) { + if (errMsg) { + if (!errStr.endsWith(" ")) { errStr.append(" "); } errStr += QString::fromUtf8(errMsg); @@ -684,15 +682,16 @@ void SyncEngine::handleSyncError(CSYNC *ctx, const char *state) { } // if there is csyncs url modifier in the error message, replace it. - if( errStr.contains("ownclouds://") ) errStr.replace("ownclouds://", "https://"); - if( errStr.contains("owncloud://") ) errStr.replace("owncloud://", "http://"); + if (errStr.contains("ownclouds://")) + errStr.replace("ownclouds://", "https://"); + if (errStr.contains("owncloud://")) + errStr.replace("owncloud://", "http://"); - qCWarning(lcEngine) << "ERROR during "<< state << ": " << errStr; + qCWarning(lcEngine) << "ERROR during " << state << ": " << errStr; - if( CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_ABORTED) ) { + if (CSYNC_STATUS_IS_EQUAL(err, CSYNC_STATUS_ABORTED)) { qCInfo(lcEngine) << "Update phase was aborted by user!"; - } else if( CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_SERVICE_UNAVAILABLE ) || - CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_CONNECT_ERROR )) { + } else if (CSYNC_STATUS_IS_EQUAL(err, CSYNC_STATUS_SERVICE_UNAVAILABLE) || CSYNC_STATUS_IS_EQUAL(err, CSYNC_STATUS_CONNECT_ERROR)) { emit csyncUnavailable(); } else { emit csyncError(errStr); @@ -703,11 +702,11 @@ void SyncEngine::handleSyncError(CSYNC *ctx, const char *state) { void SyncEngine::startSync() { if (_journal->exists()) { - QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos(); + QVector pollInfos = _journal->getPollInfos(); if (!pollInfos.isEmpty()) { qCInfo(lcEngine) << "Finish Poll jobs before starting a sync"; CleanupPollsJob *job = new CleanupPollsJob(pollInfos, _account, - _journal, _localPath, this); + _journal, _localPath, this); connect(job, SIGNAL(finished()), this, SLOT(startSync())); connect(job, SIGNAL(aborted(QString)), this, SLOT(slotCleanPollsJobAborted(QString))); job->start(); @@ -740,13 +739,14 @@ void SyncEngine::startSync() const qint64 freeBytes = Utility::freeDiskSpace(_localPath); if (freeBytes >= 0) { qCInfo(lcEngine) << "There are" << freeBytes << "bytes available at" << _localPath - << "and at least" << minFree << "are required"; + << "and at least" << minFree << "are required"; if (freeBytes < minFree) { _anotherSyncNeeded = DelayedFollowUp; emit csyncError(tr("Only %1 are available, need at least %2 to start", - "Placeholders are postfixed with file sizes using Utility::octetsToString()").arg( - Utility::octetsToString(freeBytes), - Utility::octetsToString(minFree))); + "Placeholders are postfixed with file sizes using Utility::octetsToString()") + .arg( + Utility::octetsToString(freeBytes), + Utility::octetsToString(minFree))); finalize(false); return; } @@ -767,17 +767,17 @@ void SyncEngine::startSync() } QString verStr("Using Qt "); - verStr.append( qVersion() ); + verStr.append(qVersion()); -#if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - verStr.append( " SSL library " ).append(QSslSocket::sslLibraryVersionString().toUtf8().data()); +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + verStr.append(" SSL library ").append(QSslSocket::sslLibraryVersionString().toUtf8().data()); #endif - verStr.append( " on ").append(Utility::platformName()); + verStr.append(" on ").append(Utility::platformName()); qCInfo(lcEngine) << verStr; fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet - if( fileRecordCount == -1 ) { + if (fileRecordCount == -1) { qCWarning(lcEngine) << "No way to create a sync journal!"; emit csyncError(tr("Unable to open or create the local sync database. Make sure you have write access in the sync folder.")); finalize(false); @@ -821,7 +821,7 @@ void SyncEngine::startSync() _discoveryMainThread->setParent(this); connect(this, SIGNAL(finished(bool)), _discoveryMainThread, SLOT(deleteLater())); qCInfo(lcEngine) << "Server" << account()->serverVersion() - << QString("rootEtagChangesNotOnlySubFolderEtags=%1").arg(account()->rootEtagChangesNotOnlySubFolderEtags()); + << QString("rootEtagChangesNotOnlySubFolderEtags=%1").arg(account()->rootEtagChangesNotOnlySubFolderEtags()); if (account()->rootEtagChangesNotOnlySubFolderEtags()) { connect(_discoveryMainThread, SIGNAL(etag(QString)), this, SLOT(slotRootEtagReceived(QString))); } else { @@ -843,22 +843,23 @@ void SyncEngine::startSync() discoveryJob->_syncOptions = _syncOptions; discoveryJob->moveToThread(&_thread); connect(discoveryJob, SIGNAL(finished(int)), this, SLOT(slotDiscoveryJobFinished(int))); - connect(discoveryJob, SIGNAL(folderDiscovered(bool,QString)), - this, SIGNAL(folderDiscovered(bool,QString))); + connect(discoveryJob, SIGNAL(folderDiscovered(bool, QString)), + this, SIGNAL(folderDiscovered(bool, QString))); - connect(discoveryJob, SIGNAL(newBigFolder(QString,bool)), - this, SIGNAL(newBigFolder(QString,bool))); + connect(discoveryJob, SIGNAL(newBigFolder(QString, bool)), + this, SIGNAL(newBigFolder(QString, bool))); // This is used for the DiscoveryJob to be able to request the main thread/ // to read in directory contents. - _discoveryMainThread->setupHooks( discoveryJob, _remotePath); + _discoveryMainThread->setupHooks(discoveryJob, _remotePath); // Starts the update in a seperate thread QMetaObject::invokeMethod(discoveryJob, "start", Qt::QueuedConnection); } -void SyncEngine::slotRootEtagReceived(const QString &e) { +void SyncEngine::slotRootEtagReceived(const QString &e) +{ if (_remoteRootEtag.isEmpty()) { qCDebug(lcEngine) << "Root etag:" << e; _remoteRootEtag = e; @@ -871,7 +872,7 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) // To clean the progress info emit folderDiscovered(false, QString()); - if (discoveryResult < 0 ) { + if (discoveryResult < 0) { handleSyncError(_csync_ctx, "csync_update"); return; } @@ -888,7 +889,7 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) _journal->commitIfNeededAndStartNewTransaction("Post discovery"); } - if( csync_reconcile(_csync_ctx) < 0 ) { + if (csync_reconcile(_csync_ctx) < 0) { handleSyncError(_csync_ctx, "csync_reconcile"); return; } @@ -906,11 +907,11 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) _temporarilyUnavailablePaths.clear(); _renamedFolders.clear(); - if( csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0 ) { + if (csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0) { qCWarning(lcEngine) << "Error in local treewalk."; walkOk = false; } - if( walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0 ) { + if (walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0) { qCWarning(lcEngine) << "Error in remote treewalk."; } @@ -928,7 +929,7 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) // Adjust the paths for the renames. for (SyncFileItemVector::iterator it = syncItems.begin(); - it != syncItems.end(); ++it) { + it != syncItems.end(); ++it) { (*it)->_file = adjustRenamedPath((*it)->_file); } @@ -937,9 +938,8 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) // Server version older than 8.1 don't support these character in filename. static const QRegExp invalidCharRx("[\\\\:?*\"<>|]"); for (auto it = syncItems.begin(); it != syncItems.end(); ++it) { - if ((*it)->_direction == SyncFileItem::Up && - (*it)->destination().contains(invalidCharRx)) { - (*it)->_errorString = tr("File name contains at least one invalid character"); + if ((*it)->_direction == SyncFileItem::Up && (*it)->destination().contains(invalidCharRx)) { + (*it)->_errorString = tr("File name contains at least one invalid character"); (*it)->_instruction = CSYNC_INSTRUCTION_IGNORE; } } @@ -961,11 +961,11 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) // (for example, upgrading from a previous version, or first sync) // Note that an empty ("") fingerprint is valid and means it was empty on the server before. if (!databaseFingerprint.isNull() - && _discoveryMainThread->_dataFingerprint != databaseFingerprint) { + && _discoveryMainThread->_dataFingerprint != databaseFingerprint) { qCInfo(lcEngine) << "data fingerprint changed, assume restore from backup" << databaseFingerprint << _discoveryMainThread->_dataFingerprint; restoreOldFiles(syncItems); } else if (!_hasForwardInTimeFiles && _backInTimeFiles >= 2 - && _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) { + && _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) { // The server before ownCloud 9.1 did not have the data-fingerprint property. So in that // case we use heuristics to detect restored backup. This is disabled with newer version // because this causes troubles to the user and is not as reliable as the data-fingerprint. @@ -991,14 +991,14 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) _progressInfo->startEstimateUpdates(); // post update phase script: allow to tweak stuff by a custom script in debug mode. - if( !qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT").isEmpty() ) { + if (!qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT").isEmpty()) { #ifndef NDEBUG QString script = qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT"); qCDebug(lcEngine) << "Post Update Script: " << script; QProcess::execute(script.toUtf8()); #else - qCWarning(lcEngine) << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG"; + qCWarning(lcEngine) << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG"; #endif } @@ -1006,12 +1006,12 @@ void SyncEngine::slotDiscoveryJobFinished(int discoveryResult) _journal->commit("post treewalk"); _propagator = QSharedPointer( - new OwncloudPropagator (_account, _localPath, _remotePath, _journal)); + new OwncloudPropagator(_account, _localPath, _remotePath, _journal)); _propagator->setSyncOptions(_syncOptions); connect(_propagator.data(), SIGNAL(itemCompleted(const SyncFileItemPtr &)), - this, SLOT(slotItemCompleted(const SyncFileItemPtr &))); - connect(_propagator.data(), SIGNAL(progress(const SyncFileItem &,quint64)), - this, SLOT(slotProgress(const SyncFileItem &,quint64))); + this, SLOT(slotItemCompleted(const SyncFileItemPtr &))); + connect(_propagator.data(), SIGNAL(progress(const SyncFileItem &, quint64)), + this, SLOT(slotProgress(const SyncFileItem &, quint64))); connect(_propagator.data(), SIGNAL(finished(bool)), this, SLOT(slotFinished(bool)), Qt::QueuedConnection); connect(_propagator.data(), SIGNAL(seenLockedFile(QString)), SIGNAL(seenLockedFile(QString))); connect(_propagator.data(), SIGNAL(touchedFile(QString)), SLOT(slotAddTouchedFile(QString))); @@ -1044,23 +1044,24 @@ void SyncEngine::setNetworkLimits(int upload, int download) _uploadLimit = upload; _downloadLimit = download; - if( !_propagator ) return; + if (!_propagator) + return; _propagator->_uploadLimit = upload; _propagator->_downloadLimit = download; int propDownloadLimit = _propagator->_downloadLimit #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - .load() + .load() #endif - ; + ; int propUploadLimit = _propagator->_uploadLimit #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - .load() + .load() #endif - ; + ; - if( propDownloadLimit != 0 || propUploadLimit != 0 ) { + if (propDownloadLimit != 0 || propUploadLimit != 0) { qCInfo(lcEngine) << "Network Limits (down/up) " << propDownloadLimit << propUploadLimit; } } @@ -1088,7 +1089,7 @@ void SyncEngine::slotFinished(bool success) } // emit the treewalk results. - if( ! _journal->postSyncCleanup( _seenFiles, _temporarilyUnavailablePaths ) ) { + if (!_journal->postSyncCleanup(_seenFiles, _temporarilyUnavailablePaths)) { qCDebug(lcEngine) << "Cleaning of synced "; } @@ -1128,7 +1129,7 @@ void SyncEngine::finalize(bool success) _clearTouchedFilesTimer.start(); } -void SyncEngine::slotProgress(const SyncFileItem& item, quint64 current) +void SyncEngine::slotProgress(const SyncFileItem &item, quint64 current) { _progressInfo->setProgressItem(item, current); emit transmissionProgress(*_progressInfo); @@ -1136,11 +1137,11 @@ void SyncEngine::slotProgress(const SyncFileItem& item, quint64 current) /* Given a path on the remote, give the path as it is when the rename is done */ -QString SyncEngine::adjustRenamedPath(const QString& original) +QString SyncEngine::adjustRenamedPath(const QString &original) { int slashPos = original.size(); - while ((slashPos = original.lastIndexOf('/' , slashPos - 1)) > 0) { - QHash< QString, QString >::const_iterator it = _renamedFolders.constFind(original.left(slashPos)); + while ((slashPos = original.lastIndexOf('/', slashPos - 1)) > 0) { + QHash::const_iterator it = _renamedFolders.constFind(original.left(slashPos)); if (it != _renamedFolders.constEnd()) { return *it + original.mid(slashPos); } @@ -1170,7 +1171,7 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) // if reading the selective sync list from db failed, lets ignore all rather than nothing. if (!selectiveListOk || std::binary_search(selectiveSyncBlackList.constBegin(), selectiveSyncBlackList.constEnd(), - path)) { + path)) { (*it)->_instruction = CSYNC_INSTRUCTION_IGNORE; (*it)->_status = SyncFileItem::FileIgnored; (*it)->_errorString = tr("Ignored because of the \"choose what to sync\" blacklist"); @@ -1186,209 +1187,207 @@ void SyncEngine::checkForPermission(SyncFileItemVector &syncItems) continue; } - switch((*it)->_instruction) { - case CSYNC_INSTRUCTION_TYPE_CHANGE: - case CSYNC_INSTRUCTION_NEW: { - int slashPos = (*it)->_file.lastIndexOf('/'); - QString parentDir = slashPos <= 0 ? "" : (*it)->_file.mid(0, slashPos); - const QByteArray perms = getPermissions(parentDir); - if (perms.isNull()) { - // No permissions set - break; - } else if ((*it)->_isDirectory && !perms.contains("K")) { - qCWarning(lcEngine) << "checkForPermission: ERROR" << (*it)->_file; - (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; - (*it)->_status = SyncFileItem::NormalError; - (*it)->_errorString = tr("Not allowed because you don't have permission to add subfolders to that folder"); + switch ((*it)->_instruction) { + case CSYNC_INSTRUCTION_TYPE_CHANGE: + case CSYNC_INSTRUCTION_NEW: { + int slashPos = (*it)->_file.lastIndexOf('/'); + QString parentDir = slashPos <= 0 ? "" : (*it)->_file.mid(0, slashPos); + const QByteArray perms = getPermissions(parentDir); + if (perms.isNull()) { + // No permissions set + break; + } else if ((*it)->_isDirectory && !perms.contains("K")) { + qCWarning(lcEngine) << "checkForPermission: ERROR" << (*it)->_file; + (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; + (*it)->_status = SyncFileItem::NormalError; + (*it)->_errorString = tr("Not allowed because you don't have permission to add subfolders to that folder"); - for (SyncFileItemVector::iterator it_next = it + 1; it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) { - it = it_next; - if ((*it)->_instruction == CSYNC_INSTRUCTION_RENAME) { - // The file was most likely moved in this directory. - // If the file was read only or could not be moved or removed, it should - // be restored. Do that in the next sync by not considering as a rename - // but delete and upload. It will then be restored if needed. - _journal->avoidRenamesOnNextSync((*it)->_file); - _anotherSyncNeeded = ImmediateFollowUp; - qCWarning(lcEngine) << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder"; - } - (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; - (*it)->_status = SyncFileItem::SoftError; - (*it)->_errorString = tr("Not allowed because you don't have permission to add parent folder"); + for (SyncFileItemVector::iterator it_next = it + 1; it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) { + it = it_next; + if ((*it)->_instruction == CSYNC_INSTRUCTION_RENAME) { + // The file was most likely moved in this directory. + // If the file was read only or could not be moved or removed, it should + // be restored. Do that in the next sync by not considering as a rename + // but delete and upload. It will then be restored if needed. + _journal->avoidRenamesOnNextSync((*it)->_file); + _anotherSyncNeeded = ImmediateFollowUp; + qCWarning(lcEngine) << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder"; } - - } else if (!(*it)->_isDirectory && !perms.contains("C")) { - qCWarning(lcEngine) << "checkForPermission: ERROR" << (*it)->_file; (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; - (*it)->_status = SyncFileItem::NormalError; - (*it)->_errorString = tr("Not allowed because you don't have permission to add files in that folder"); + (*it)->_status = SyncFileItem::SoftError; + (*it)->_errorString = tr("Not allowed because you don't have permission to add parent folder"); } - break; + + } else if (!(*it)->_isDirectory && !perms.contains("C")) { + qCWarning(lcEngine) << "checkForPermission: ERROR" << (*it)->_file; + (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; + (*it)->_status = SyncFileItem::NormalError; + (*it)->_errorString = tr("Not allowed because you don't have permission to add files in that folder"); } - case CSYNC_INSTRUCTION_SYNC: { - const QByteArray perms = getPermissions((*it)->_file); - if (perms.isNull()) { - // No permissions set - break; - } if (!perms.contains("W")) { - qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; - (*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT; - (*it)->_direction = SyncFileItem::Down; - (*it)->_isRestoration = true; - // take the things to write to the db from the "other" node (i.e: info from server) - (*it)->_modtime = (*it)->log._other_modtime; - (*it)->_size = (*it)->log._other_size; - (*it)->_fileId = (*it)->log._other_fileId; - (*it)->_etag = (*it)->log._other_etag; - (*it)->_errorString = tr("Not allowed to upload this file because it is read-only on the server, restoring"); - continue; - } + break; + } + case CSYNC_INSTRUCTION_SYNC: { + const QByteArray perms = getPermissions((*it)->_file); + if (perms.isNull()) { + // No permissions set break; } - case CSYNC_INSTRUCTION_REMOVE: { - const QByteArray perms = getPermissions((*it)->_file); - if (perms.isNull()) { - // No permissions set - break; - } - if (!perms.contains("D")) { - qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; - (*it)->_instruction = CSYNC_INSTRUCTION_NEW; - (*it)->_direction = SyncFileItem::Down; - (*it)->_isRestoration = true; - (*it)->_errorString = tr("Not allowed to remove, restoring"); - - if ((*it)->_isDirectory) { - // restore all sub items - for (SyncFileItemVector::iterator it_next = it + 1; - it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) { - it = it_next; - - if ((*it)->_instruction != CSYNC_INSTRUCTION_REMOVE) { - qCWarning(lcEngine) << "non-removed job within a removed folder" - << (*it)->_file << (*it)->_instruction; - continue; - } - - qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; - - (*it)->_instruction = CSYNC_INSTRUCTION_NEW; - (*it)->_direction = SyncFileItem::Down; - (*it)->_isRestoration = true; - (*it)->_errorString = tr("Not allowed to remove, restoring"); - } - } - } else if(perms.contains("S") && perms.contains("D")) { - // this is a top level shared dir which can be removed to unshare it, - // regardless if it is a read only share or not. - // To avoid that we try to restore files underneath this dir which have - // not delete permission we fast forward the iterator and leave the - // delete jobs intact. It is not physically tried to remove this files - // underneath, propagator sees that. - if( (*it)->_isDirectory ) { - // put a more descriptive message if a top level share dir really is removed. - if( it == syncItems.begin() || !(path.startsWith((*(it-1))->_file)) ) { - (*it)->_errorString = tr("Local files and share folder removed."); - } - - for (SyncFileItemVector::iterator it_next = it + 1; - it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) { - it = it_next; - } - } - } + if (!perms.contains("W")) { + qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; + (*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT; + (*it)->_direction = SyncFileItem::Down; + (*it)->_isRestoration = true; + // take the things to write to the db from the "other" node (i.e: info from server) + (*it)->_modtime = (*it)->log._other_modtime; + (*it)->_size = (*it)->log._other_size; + (*it)->_fileId = (*it)->log._other_fileId; + (*it)->_etag = (*it)->log._other_etag; + (*it)->_errorString = tr("Not allowed to upload this file because it is read-only on the server, restoring"); + continue; + } + break; + } + case CSYNC_INSTRUCTION_REMOVE: { + const QByteArray perms = getPermissions((*it)->_file); + if (perms.isNull()) { + // No permissions set break; } + if (!perms.contains("D")) { + qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; + (*it)->_instruction = CSYNC_INSTRUCTION_NEW; + (*it)->_direction = SyncFileItem::Down; + (*it)->_isRestoration = true; + (*it)->_errorString = tr("Not allowed to remove, restoring"); + + if ((*it)->_isDirectory) { + // restore all sub items + for (SyncFileItemVector::iterator it_next = it + 1; + it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) { + it = it_next; - case CSYNC_INSTRUCTION_RENAME: { - - int slashPos = (*it)->_renameTarget.lastIndexOf('/'); - const QString parentDir = slashPos <= 0 ? "" : (*it)->_renameTarget.mid(0, slashPos); - const QByteArray destPerms = getPermissions(parentDir); - const QByteArray filePerms = getPermissions((*it)->_file); - - //true when it is just a rename in the same directory. (not a move) - bool isRename = (*it)->_file.startsWith(parentDir) && (*it)->_file.lastIndexOf('/') == slashPos; + if ((*it)->_instruction != CSYNC_INSTRUCTION_REMOVE) { + qCWarning(lcEngine) << "non-removed job within a removed folder" + << (*it)->_file << (*it)->_instruction; + continue; + } + qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file; - // Check if we are allowed to move to the destination. - bool destinationOK = true; - if (isRename || destPerms.isNull()) { - // no need to check for the destination dir permission - destinationOK = true; - } else if ((*it)->_isDirectory && !destPerms.contains("K")) { - destinationOK = false; - } else if (!(*it)->_isDirectory && !destPerms.contains("C")) { - destinationOK = false; + (*it)->_instruction = CSYNC_INSTRUCTION_NEW; + (*it)->_direction = SyncFileItem::Down; + (*it)->_isRestoration = true; + (*it)->_errorString = tr("Not allowed to remove, restoring"); + } } + } else if (perms.contains("S") && perms.contains("D")) { + // this is a top level shared dir which can be removed to unshare it, + // regardless if it is a read only share or not. + // To avoid that we try to restore files underneath this dir which have + // not delete permission we fast forward the iterator and leave the + // delete jobs intact. It is not physically tried to remove this files + // underneath, propagator sees that. + if ((*it)->_isDirectory) { + // put a more descriptive message if a top level share dir really is removed. + if (it == syncItems.begin() || !(path.startsWith((*(it - 1))->_file))) { + (*it)->_errorString = tr("Local files and share folder removed."); + } - // check if we are allowed to move from the source - bool sourceOK = true; - if (!filePerms.isNull() - && ((isRename && !filePerms.contains("N")) - || (!isRename && !filePerms.contains("V")))) { + for (SyncFileItemVector::iterator it_next = it + 1; + it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) { + it = it_next; + } + } + } + break; + } - // We are not allowed to move or rename this file - sourceOK = false; + case CSYNC_INSTRUCTION_RENAME: { + int slashPos = (*it)->_renameTarget.lastIndexOf('/'); + const QString parentDir = slashPos <= 0 ? "" : (*it)->_renameTarget.mid(0, slashPos); + const QByteArray destPerms = getPermissions(parentDir); + const QByteArray filePerms = getPermissions((*it)->_file); + + //true when it is just a rename in the same directory. (not a move) + bool isRename = (*it)->_file.startsWith(parentDir) && (*it)->_file.lastIndexOf('/') == slashPos; + + + // Check if we are allowed to move to the destination. + bool destinationOK = true; + if (isRename || destPerms.isNull()) { + // no need to check for the destination dir permission + destinationOK = true; + } else if ((*it)->_isDirectory && !destPerms.contains("K")) { + destinationOK = false; + } else if (!(*it)->_isDirectory && !destPerms.contains("C")) { + destinationOK = false; + } - if (filePerms.contains("D") && destinationOK) { - // but we are allowed to delete it - // TODO! simulate delete & upload - } + // check if we are allowed to move from the source + bool sourceOK = true; + if (!filePerms.isNull() + && ((isRename && !filePerms.contains("N")) + || (!isRename && !filePerms.contains("V")))) { + // We are not allowed to move or rename this file + sourceOK = false; + + if (filePerms.contains("D") && destinationOK) { + // but we are allowed to delete it + // TODO! simulate delete & upload } + } #ifdef OWNCLOUD_RESTORE_RENAME /* We don't like the idea of renaming behind user's back, as the user may be working with the files */ - if (!sourceOK && (!destinationOK || isRename) - // (not for directory because that's more complicated with the contents that needs to be adjusted) - && !(*it)->_isDirectory) { - // Both the source and the destination won't allow move. Move back to the original - std::swap((*it)->_file, (*it)->_renameTarget); - (*it)->_direction = SyncFileItem::Down; - (*it)->_errorString = tr("Move not allowed, item restored"); - (*it)->_isRestoration = true; - qCWarning(lcEngine) << "checkForPermission: MOVING BACK" << (*it)->_file; - // in case something does wrong, we will not do it next time - _journal->avoidRenamesOnNextSync((*it)->_file); - } else + if (!sourceOK && (!destinationOK || isRename) + // (not for directory because that's more complicated with the contents that needs to be adjusted) + && !(*it)->_isDirectory) { + // Both the source and the destination won't allow move. Move back to the original + std::swap((*it)->_file, (*it)->_renameTarget); + (*it)->_direction = SyncFileItem::Down; + (*it)->_errorString = tr("Move not allowed, item restored"); + (*it)->_isRestoration = true; + qCWarning(lcEngine) << "checkForPermission: MOVING BACK" << (*it)->_file; + // in case something does wrong, we will not do it next time + _journal->avoidRenamesOnNextSync((*it)->_file); + } else #endif if (!sourceOK || !destinationOK) { - // One of them is not possible, just throw an error - (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; - (*it)->_status = SyncFileItem::NormalError; - const QString errorString = tr("Move not allowed because %1 is read-only").arg( - sourceOK ? tr("the destination") : tr("the source")); - (*it)->_errorString = errorString; - - qCWarning(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file << errorString; - - // Avoid a rename on next sync: - // TODO: do the resolution now already so we don't need two sync - // At this point we would need to go back to the propagate phase on both remote to take - // the decision. - _journal->avoidRenamesOnNextSync((*it)->_file); - _anotherSyncNeeded = ImmediateFollowUp; - - - if ((*it)->_isDirectory) { - for (SyncFileItemVector::iterator it_next = it + 1; - it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) { - it = it_next; - (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; - (*it)->_status = SyncFileItem::NormalError; - (*it)->_errorString = errorString; - qCWarning(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file; - } + // One of them is not possible, just throw an error + (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; + (*it)->_status = SyncFileItem::NormalError; + const QString errorString = tr("Move not allowed because %1 is read-only").arg(sourceOK ? tr("the destination") : tr("the source")); + (*it)->_errorString = errorString; + + qCWarning(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file << errorString; + + // Avoid a rename on next sync: + // TODO: do the resolution now already so we don't need two sync + // At this point we would need to go back to the propagate phase on both remote to take + // the decision. + _journal->avoidRenamesOnNextSync((*it)->_file); + _anotherSyncNeeded = ImmediateFollowUp; + + + if ((*it)->_isDirectory) { + for (SyncFileItemVector::iterator it_next = it + 1; + it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) { + it = it_next; + (*it)->_instruction = CSYNC_INSTRUCTION_ERROR; + (*it)->_status = SyncFileItem::NormalError; + (*it)->_errorString = errorString; + qCWarning(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file; } } - break; } - default: - break; + break; + } + default: + break; } } } -QByteArray SyncEngine::getPermissions(const QString& file) const +QByteArray SyncEngine::getPermissions(const QString &file) const { static bool isTest = qgetenv("OWNCLOUD_TEST_PERMISSIONS").toInt(); if (isTest) { @@ -1433,7 +1432,7 @@ void SyncEngine::restoreOldFiles(SyncFileItemVector &syncItems) } } -void SyncEngine::slotAddTouchedFile(const QString& fn) +void SyncEngine::slotAddTouchedFile(const QString &fn) { QString file = QDir::cleanPath(fn); @@ -1448,9 +1447,9 @@ void SyncEngine::slotClearTouchedFiles() _touchedFiles.clear(); } -qint64 SyncEngine::timeSinceFileTouched(const QString& fn) const +qint64 SyncEngine::timeSinceFileTouched(const QString &fn) const { - if (! _touchedFiles.contains(fn)) { + if (!_touchedFiles.contains(fn)) { return -1; } @@ -1475,7 +1474,7 @@ void SyncEngine::abort() _discoveryMainThread->abort(); } // For the propagator - if(_propagator) { + if (_propagator) { _propagator->abort(); } } diff --git a/src/libsync/syncengine.h b/src/libsync/syncengine.h index 9cf30c858..8652ef2cb 100644 --- a/src/libsync/syncengine.h +++ b/src/libsync/syncengine.h @@ -48,8 +48,7 @@ class SyncJournalFileRecord; class SyncJournalDb; class OwncloudPropagator; -enum AnotherSyncNeeded -{ +enum AnotherSyncNeeded { NoFollowUpSync, ImmediateFollowUp, // schedule this again immediately (limited amount of times) DelayedFollowUp // regularly schedule this folder again (around 1/minute, unlimited) @@ -64,10 +63,10 @@ class OWNCLOUDSYNC_EXPORT SyncEngine : public QObject Q_OBJECT public: SyncEngine(AccountPtr account, const QString &localPath, - const QString &remotePath, SyncJournalDb *journal); + const QString &remotePath, SyncJournalDb *journal); ~SyncEngine(); - static QString csyncErrorToString( CSYNC_STATUS); + static QString csyncErrorToString(CSYNC_STATUS); Q_INVOKABLE void startSync(); void setNetworkLimits(int upload, int download); @@ -92,7 +91,7 @@ public: * * Thread-safe. */ - qint64 timeSinceFileTouched(const QString& fn) const; + qint64 timeSinceFileTouched(const QString &fn) const; AccountPtr account() const; SyncJournalDb *journal() const { return _journal; } @@ -105,7 +104,7 @@ public: static qint64 minimumFileAgeForUpload; // in ms signals: - void csyncError( const QString& ); + void csyncError(const QString &); void csyncUnavailable(); // During update, before reconcile @@ -113,14 +112,14 @@ signals: void folderDiscovered(bool local, const QString &folderUrl); // before actual syncing (after update+reconcile) for each item - void syncItemDiscovered(const SyncFileItem&); + void syncItemDiscovered(const SyncFileItem &); // after the above signals. with the items that actually need propagating - void aboutToPropagate(SyncFileItemVector&); + void aboutToPropagate(SyncFileItemVector &); // after each item completed by a job (successful or not) - void itemCompleted(const SyncFileItemPtr&); + void itemCompleted(const SyncFileItemPtr &); - void transmissionProgress( const ProgressInfo& progress ); + void transmissionProgress(const ProgressInfo &progress); void finished(bool success); void started(); @@ -149,14 +148,14 @@ signals: private slots: void slotRootEtagReceived(const QString &); - void slotItemCompleted(const SyncFileItemPtr& item); + void slotItemCompleted(const SyncFileItemPtr &item); void slotFinished(bool success); - void slotProgress(const SyncFileItem& item, quint64 curent); + void slotProgress(const SyncFileItem &item, quint64 curent); void slotDiscoveryJobFinished(int updateResult); void slotCleanPollsJobAborted(const QString &error); /** Records that a file was touched by a job. */ - void slotAddTouchedFile(const QString& fn); + void slotAddTouchedFile(const QString &fn); /** Wipes the _touchedFiles hash */ void slotClearTouchedFiles(); @@ -166,10 +165,10 @@ private: QString journalDbFilePath() const; - static int treewalkLocal( TREE_WALK_FILE*, void *); - static int treewalkRemote( TREE_WALK_FILE*, void *); - int treewalkFile( TREE_WALK_FILE*, bool ); - bool checkErrorBlacklisting( SyncFileItem &item ); + static int treewalkLocal(TREE_WALK_FILE *, void *); + static int treewalkRemote(TREE_WALK_FILE *, void *); + int treewalkFile(TREE_WALK_FILE *, bool); + bool checkErrorBlacklisting(SyncFileItem &item); // Cleans up unnecessary downloadinfo entries in the journal as well // as their temporary files. @@ -198,7 +197,7 @@ private: QString _remoteRootEtag; SyncJournalDb *_journal; QPointer _discoveryMainThread; - QSharedPointer _propagator; + QSharedPointer _propagator; // After a sync, only the syncdb entries whose filenames appear in this // set will be kept. See _temporarilyUnavailablePaths. @@ -231,7 +230,7 @@ private: * to recover */ void checkForPermission(SyncFileItemVector &syncItems); - QByteArray getPermissions(const QString& file) const; + QByteArray getPermissions(const QString &file) const; /** * Instead of downloading files from the server, upload the files to the server @@ -269,7 +268,6 @@ private: /** For clearing the _touchedFiles variable after sync finished */ QTimer _clearTouchedFilesTimer; }; - } #endif // CSYNCTHREAD_H diff --git a/src/libsync/syncfileitem.h b/src/libsync/syncfileitem.h index 157d03c05..6273dd5c9 100644 --- a/src/libsync/syncfileitem.h +++ b/src/libsync/syncfileitem.h @@ -24,10 +24,10 @@ #include #if defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && !defined(Q_CC_CLANG) && (__GNUC__ * 100 + __GNUC_MINOR__ < 408) - // openSuse 12.3 didn't like enum bitfields. - #define BITFIELD(size) +// openSuse 12.3 didn't like enum bitfields. +#define BITFIELD(size) #else - #define BITFIELD(size) :size +#define BITFIELD(size) :size #endif @@ -37,18 +37,20 @@ namespace OCC { * @brief The SyncFileItem class * @ingroup libsync */ -class SyncFileItem { +class SyncFileItem +{ public: enum Direction { - None = 0, - Up, - Down }; + None = 0, + Up, + Down + }; enum Type { - UnknownType = 0, - File = CSYNC_FTW_TYPE_FILE, - Directory = CSYNC_FTW_TYPE_DIR, - SoftLink = CSYNC_FTW_TYPE_SLINK + UnknownType = 0, + File = CSYNC_FTW_TYPE_FILE, + Directory = CSYNC_FTW_TYPE_DIR, + SoftLink = CSYNC_FTW_TYPE_SLINK }; enum Status { @@ -64,20 +66,31 @@ public: Restoration ///< The file was restored because what should have been done was not allowed }; - SyncFileItem() : _type(UnknownType), _direction(None), _isDirectory(false), - _serverHasIgnoredFiles(false), _hasBlacklistEntry(false), - _errorMayBeBlacklisted(false), _status(NoStatus), - _isRestoration(false), - _httpErrorCode(0), _affectedItems(1), - _instruction(CSYNC_INSTRUCTION_NONE), _modtime(0), _size(0), _inode(0) + SyncFileItem() + : _type(UnknownType) + , _direction(None) + , _isDirectory(false) + , _serverHasIgnoredFiles(false) + , _hasBlacklistEntry(false) + , _errorMayBeBlacklisted(false) + , _status(NoStatus) + , _isRestoration(false) + , _httpErrorCode(0) + , _affectedItems(1) + , _instruction(CSYNC_INSTRUCTION_NONE) + , _modtime(0) + , _size(0) + , _inode(0) { } - friend bool operator==(const SyncFileItem& item1, const SyncFileItem& item2) { + friend bool operator==(const SyncFileItem &item1, const SyncFileItem &item2) + { return item1._originalFile == item2._originalFile; } - friend bool operator<(const SyncFileItem& item1, const SyncFileItem& item2) { + friend bool operator<(const SyncFileItem &item1, const SyncFileItem &item2) + { // Sort by destination auto d1 = item1.destination(); auto d2 = item2.destination(); @@ -93,7 +106,9 @@ public: // Find the length of the largest prefix int prefixL = 0; auto minSize = std::min(d1.size(), d2.size()); - while (prefixL < minSize && data1[prefixL] == data2[prefixL]) { prefixL++; } + while (prefixL < minSize && data1[prefixL] == data2[prefixL]) { + prefixL++; + } if (prefixL == d2.size()) return false; @@ -108,14 +123,16 @@ public: return data1[prefixL] < data2[prefixL]; } - QString destination() const { + QString destination() const + { if (!_renameTarget.isEmpty()) { return _renameTarget; } return _file; } - bool isEmpty() const { + bool isEmpty() const + { return _file.isEmpty(); } @@ -126,12 +143,13 @@ public: * issues list on the activity page and for checking whether an * item should be announced in the notification message. */ - bool hasErrorStatus() const { + bool hasErrorStatus() const + { return _status == SyncFileItem::SoftError - || _status == SyncFileItem::NormalError - || _status == SyncFileItem::FatalError - || _status == SyncFileItem::Conflict - || !_errorString.isEmpty(); + || _status == SyncFileItem::NormalError + || _status == SyncFileItem::FatalError + || _status == SyncFileItem::Conflict + || !_errorString.isEmpty(); } // Variables useful for everybody @@ -145,54 +163,55 @@ public: /// Whether there's an entry in the blacklist table. /// Note: that entry may have retries left, so this can be true /// without the status being FileIgnored. - bool _hasBlacklistEntry BITFIELD(1); + bool _hasBlacklistEntry BITFIELD(1); /** If true and NormalError, this error may be blacklisted * * Note that non-local errors (httpErrorCode!=0) may also be * blacklisted independently of this flag. */ - bool _errorMayBeBlacklisted BITFIELD(1); + bool _errorMayBeBlacklisted BITFIELD(1); // Variables useful to report to the user - Status _status BITFIELD(4); - bool _isRestoration BITFIELD(1); // The original operation was forbidden, and this is a restoration - quint16 _httpErrorCode; - QString _errorString; // Contains a string only in case of error - QByteArray _responseTimeStamp; - quint32 _affectedItems; // the number of affected items by the operation on this item. - // usually this value is 1, but for removes on dirs, it might be much higher. + Status _status BITFIELD(4); + bool _isRestoration BITFIELD(1); // The original operation was forbidden, and this is a restoration + quint16 _httpErrorCode; + QString _errorString; // Contains a string only in case of error + QByteArray _responseTimeStamp; + quint32 _affectedItems; // the number of affected items by the operation on this item. + // usually this value is 1, but for removes on dirs, it might be much higher. // Variables used by the propagator csync_instructions_e _instruction; - QString _originalFile; // as it is in the csync tree - time_t _modtime; - QByteArray _etag; - quint64 _size; - quint64 _inode; - QByteArray _fileId; - QByteArray _remotePerm; - QByteArray _contentChecksum; - QByteArray _contentChecksumType; - QString _directDownloadUrl; - QString _directDownloadCookies; - - struct { - quint64 _other_size; - time_t _other_modtime; - QByteArray _other_etag; - QByteArray _other_fileId; + QString _originalFile; // as it is in the csync tree + time_t _modtime; + QByteArray _etag; + quint64 _size; + quint64 _inode; + QByteArray _fileId; + QByteArray _remotePerm; + QByteArray _contentChecksum; + QByteArray _contentChecksumType; + QString _directDownloadUrl; + QString _directDownloadCookies; + + struct + { + quint64 _other_size; + time_t _other_modtime; + QByteArray _other_etag; + QByteArray _other_fileId; enum csync_instructions_e _other_instruction BITFIELD(16); } log; }; typedef QSharedPointer SyncFileItemPtr; -inline bool operator<(const SyncFileItemPtr& item1, const SyncFileItemPtr& item2) { +inline bool operator<(const SyncFileItemPtr &item1, const SyncFileItemPtr &item2) +{ return *item1 < *item2; } typedef QVector SyncFileItemVector; - } Q_DECLARE_METATYPE(OCC::SyncFileItem) diff --git a/src/libsync/syncfilestatus.cpp b/src/libsync/syncfilestatus.cpp index 722a60785..12a997786 100644 --- a/src/libsync/syncfilestatus.cpp +++ b/src/libsync/syncfilestatus.cpp @@ -16,14 +16,15 @@ namespace OCC { SyncFileStatus::SyncFileStatus() - :_tag(StatusNone), _sharedWithMe(false) + : _tag(StatusNone) + , _sharedWithMe(false) { } SyncFileStatus::SyncFileStatus(SyncFileStatusTag tag) - :_tag(tag), _sharedWithMe(false) + : _tag(tag) + , _sharedWithMe(false) { - } void SyncFileStatus::set(SyncFileStatusTag tag) @@ -51,8 +52,7 @@ QString SyncFileStatus::toSocketAPIString() const QString statusString; bool canBeShared = true; - switch(_tag) - { + switch (_tag) { case StatusNone: statusString = QLatin1String("NOP"); canBeShared = false; @@ -71,7 +71,7 @@ QString SyncFileStatus::toSocketAPIString() const statusString = QLatin1String("ERROR"); break; } - if(canBeShared && _sharedWithMe) { + if (canBeShared && _sharedWithMe) { statusString += QLatin1String("+SWM"); } diff --git a/src/libsync/syncfilestatus.h b/src/libsync/syncfilestatus.h index cd9a409ae..27006a572 100644 --- a/src/libsync/syncfilestatus.h +++ b/src/libsync/syncfilestatus.h @@ -44,21 +44,23 @@ public: void set(SyncFileStatusTag tag); SyncFileStatusTag tag() const; - void setSharedWithMe( bool isShared ); + void setSharedWithMe(bool isShared); bool sharedWithMe() const; QString toSocketAPIString() const; + private: SyncFileStatusTag _tag; bool _sharedWithMe; - }; -inline bool operator==(const SyncFileStatus &a, const SyncFileStatus &b) { +inline bool operator==(const SyncFileStatus &a, const SyncFileStatus &b) +{ return a.tag() == b.tag() && a.sharedWithMe() == b.sharedWithMe(); } -inline bool operator!=(const SyncFileStatus &a, const SyncFileStatus &b) { +inline bool operator!=(const SyncFileStatus &a, const SyncFileStatus &b) +{ return !(a == b); } } diff --git a/src/libsync/syncfilestatustracker.cpp b/src/libsync/syncfilestatustracker.cpp index a3f5030b8..db1f778c2 100644 --- a/src/libsync/syncfilestatustracker.cpp +++ b/src/libsync/syncfilestatustracker.cpp @@ -35,8 +35,8 @@ static SyncFileStatus::SyncFileStatusTag lookupProblem(const QString &pathToMatc if (problemPath == pathToMatch) { return severity; } else if (severity == SyncFileStatus::StatusError - && problemPath.startsWith(pathToMatch) - && (pathToMatch.isEmpty() || problemPath.at(pathToMatch.size()) == '/')) { + && problemPath.startsWith(pathToMatch) + && (pathToMatch.isEmpty() || problemPath.at(pathToMatch.size()) == '/')) { return SyncFileStatus::StatusWarning; } else if (!problemPath.startsWith(pathToMatch)) { // Starting at lower_bound we get the first path that is not smaller, @@ -59,7 +59,7 @@ static SyncFileStatus::SyncFileStatusTag lookupProblem(const QString &pathToMatc * icon as the problem is most likely going to resolve itself quickly and * automatically. */ -static inline bool showErrorInSocketApi(const SyncFileItem& item) +static inline bool showErrorInSocketApi(const SyncFileItem &item) { const auto status = item._status; return item._instruction == CSYNC_INSTRUCTION_ERROR @@ -68,7 +68,7 @@ static inline bool showErrorInSocketApi(const SyncFileItem& item) || item._hasBlacklistEntry; } -static inline bool showWarningInSocketApi(const SyncFileItem& item) +static inline bool showWarningInSocketApi(const SyncFileItem &item) { const auto status = item._status; return item._instruction == CSYNC_INSTRUCTION_IGNORE @@ -80,16 +80,16 @@ static inline bool showWarningInSocketApi(const SyncFileItem& item) SyncFileStatusTracker::SyncFileStatusTracker(SyncEngine *syncEngine) : _syncEngine(syncEngine) { - connect(syncEngine, SIGNAL(aboutToPropagate(SyncFileItemVector&)), - SLOT(slotAboutToPropagate(SyncFileItemVector&))); - connect(syncEngine, SIGNAL(itemCompleted(const SyncFileItemPtr&)), - SLOT(slotItemCompleted(const SyncFileItemPtr&))); + connect(syncEngine, SIGNAL(aboutToPropagate(SyncFileItemVector &)), + SLOT(slotAboutToPropagate(SyncFileItemVector &))); + connect(syncEngine, SIGNAL(itemCompleted(const SyncFileItemPtr &)), + SLOT(slotItemCompleted(const SyncFileItemPtr &))); connect(syncEngine, SIGNAL(finished(bool)), SLOT(slotSyncFinished())); connect(syncEngine, SIGNAL(started()), SLOT(slotSyncEngineRunningChanged())); connect(syncEngine, SIGNAL(finished(bool)), SLOT(slotSyncEngineRunningChanged())); } -SyncFileStatus SyncFileStatusTracker::fileStatus(const QString& relativePath) +SyncFileStatus SyncFileStatusTracker::fileStatus(const QString &relativePath) { ASSERT(!relativePath.endsWith(QLatin1Char('/'))); @@ -104,13 +104,13 @@ SyncFileStatus SyncFileStatusTracker::fileStatus(const QString& relativePath) // update the exclude list at runtime and doing it statically here removes // our ability to notify changes through the fileStatusChanged signal, // it's an acceptable compromize to treat all exclude types the same. - if( _syncEngine->excludedFiles().isExcluded(_syncEngine->localPath() + relativePath, - _syncEngine->localPath(), - _syncEngine->ignoreHiddenFiles()) ) { + if (_syncEngine->excludedFiles().isExcluded(_syncEngine->localPath() + relativePath, + _syncEngine->localPath(), + _syncEngine->ignoreHiddenFiles())) { return SyncFileStatus(SyncFileStatus::StatusWarning); } - if ( _dirtyPaths.contains(relativePath) ) + if (_dirtyPaths.contains(relativePath)) return SyncFileStatus::StatusSync; // First look it up in the database to know if it's shared @@ -123,7 +123,7 @@ SyncFileStatus SyncFileStatusTracker::fileStatus(const QString& relativePath) return resolveSyncAndErrorStatus(relativePath, NotShared, PathUnknown); } -void SyncFileStatusTracker::slotPathTouched(const QString& fileName) +void SyncFileStatusTracker::slotPathTouched(const QString &fileName) { QString folderPath = _syncEngine->localPath(); @@ -177,7 +177,7 @@ void SyncFileStatusTracker::decSyncCountAndEmitStatusChanged(const QString &rela } } -void SyncFileStatusTracker::slotAboutToPropagate(SyncFileItemVector& items) +void SyncFileStatusTracker::slotAboutToPropagate(SyncFileItemVector &items) { ASSERT(_syncCount.isEmpty()); @@ -283,14 +283,14 @@ SyncFileStatus SyncFileStatusTracker::resolveSyncAndErrorStatus(const QString &r } ASSERT(sharedFlag != UnknownShared, - "The shared status needs to have been fetched from a SyncFileItem or the DB at this point."); + "The shared status needs to have been fetched from a SyncFileItem or the DB at this point."); if (sharedFlag == Shared) status.setSharedWithMe(true); return status; } -void SyncFileStatusTracker::invalidateParentPaths(const QString& path) +void SyncFileStatusTracker::invalidateParentPaths(const QString &path) { QStringList splitPath = path.split('/', QString::SkipEmptyParts); for (int i = 0; i < splitPath.size(); ++i) { @@ -299,15 +299,14 @@ void SyncFileStatusTracker::invalidateParentPaths(const QString& path) } } -QString SyncFileStatusTracker::getSystemDestination(const QString& relativePath) +QString SyncFileStatusTracker::getSystemDestination(const QString &relativePath) { QString systemPath = _syncEngine->localPath() + relativePath; // SyncEngine::localPath() has a trailing slash, make sure to remove it if the // destination is empty. - if( systemPath.endsWith(QLatin1Char('/')) ) { - systemPath.truncate(systemPath.length()-1); + if (systemPath.endsWith(QLatin1Char('/'))) { + systemPath.truncate(systemPath.length() - 1); } return systemPath; } - } diff --git a/src/libsync/syncfilestatustracker.h b/src/libsync/syncfilestatustracker.h index 015f80cc2..12fe0b337 100644 --- a/src/libsync/syncfilestatustracker.h +++ b/src/libsync/syncfilestatustracker.h @@ -35,32 +35,35 @@ class OWNCLOUDSYNC_EXPORT SyncFileStatusTracker : public QObject { Q_OBJECT public: - explicit SyncFileStatusTracker(SyncEngine* syncEngine); - SyncFileStatus fileStatus(const QString& relativePath); + explicit SyncFileStatusTracker(SyncEngine *syncEngine); + SyncFileStatus fileStatus(const QString &relativePath); public slots: - void slotPathTouched(const QString& fileName); + void slotPathTouched(const QString &fileName); signals: - void fileStatusChanged(const QString& systemFileName, SyncFileStatus fileStatus); + void fileStatusChanged(const QString &systemFileName, SyncFileStatus fileStatus); private slots: - void slotAboutToPropagate(SyncFileItemVector& items); - void slotItemCompleted(const SyncFileItemPtr& item); + void slotAboutToPropagate(SyncFileItemVector &items); + void slotItemCompleted(const SyncFileItemPtr &item); void slotSyncFinished(); void slotSyncEngineRunningChanged(); private: - enum SharedFlag { UnknownShared, NotShared, Shared }; - enum PathKnownFlag { PathUnknown = 0, PathKnown }; + enum SharedFlag { UnknownShared, + NotShared, + Shared }; + enum PathKnownFlag { PathUnknown = 0, + PathKnown }; SyncFileStatus resolveSyncAndErrorStatus(const QString &relativePath, SharedFlag sharedState, PathKnownFlag isPathKnown = PathKnown); - void invalidateParentPaths(const QString& path); - QString getSystemDestination(const QString& relativePath); + void invalidateParentPaths(const QString &path); + QString getSystemDestination(const QString &relativePath); void incSyncCountAndEmitStatusChanged(const QString &relativePath, SharedFlag sharedState); void decSyncCountAndEmitStatusChanged(const QString &relativePath, SharedFlag sharedState); - SyncEngine* _syncEngine; + SyncEngine *_syncEngine; std::map _syncProblems; QSet _dirtyPaths; @@ -69,7 +72,6 @@ private: // A directory that starts/ends propagation will in turn increase/decrease its own parent by 1. QHash _syncCount; }; - } #endif diff --git a/src/libsync/syncjournaldb.cpp b/src/libsync/syncjournaldb.cpp index 128ac5043..c6b67fd06 100644 --- a/src/libsync/syncjournaldb.cpp +++ b/src/libsync/syncjournaldb.cpp @@ -35,36 +35,32 @@ namespace OCC { Q_LOGGING_CATEGORY(lcDb, "sync.database", QtInfoMsg) -SyncJournalDb::SyncJournalDb(const QString& dbFilePath, QObject *parent) : - QObject(parent), - _dbFile(dbFilePath), - _transaction(0) +SyncJournalDb::SyncJournalDb(const QString &dbFilePath, QObject *parent) + : QObject(parent) + , _dbFile(dbFilePath) + , _transaction(0) { - } -QString SyncJournalDb::makeDbName(const QUrl& remoteUrl, - const QString& remotePath, - const QString& user) +QString SyncJournalDb::makeDbName(const QUrl &remoteUrl, + const QString &remotePath, + const QString &user) { QString journalPath = QLatin1String("._sync_"); - QString key = QString::fromUtf8("%1@%2:%3").arg( - user, - remoteUrl.toString(), - remotePath); + QString key = QString::fromUtf8("%1@%2:%3").arg(user, remoteUrl.toString(), remotePath); QByteArray ba = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5); - journalPath.append( ba.left(6).toHex() ); + journalPath.append(ba.left(6).toHex()); journalPath.append(".db"); return journalPath; } -bool SyncJournalDb::maybeMigrateDb(const QString& localPath, const QString& absoluteJournalPath) +bool SyncJournalDb::maybeMigrateDb(const QString &localPath, const QString &absoluteJournalPath) { const QString oldDbName = localPath + QLatin1String(".csync_journal.db"); - if( !FileSystem::fileExists(oldDbName) ) { + if (!FileSystem::fileExists(oldDbName)) { return true; } const QString oldDbNameShm = oldDbName + "-shm"; @@ -80,41 +76,41 @@ bool SyncJournalDb::maybeMigrateDb(const QString& localPath, const QString& abso // and therefore already has an (outdated) new-style db file. QString error; - if( FileSystem::fileExists( newDbName ) ) { - if( !FileSystem::remove(newDbName, &error) ) { + if (FileSystem::fileExists(newDbName)) { + if (!FileSystem::remove(newDbName, &error)) { qCWarning(lcDb) << "Database migration: Could not remove db file" << newDbName - << "due to" << error; + << "due to" << error; return false; } } - if( FileSystem::fileExists( newDbNameWal ) ) { - if( !FileSystem::remove(newDbNameWal, &error) ) { + if (FileSystem::fileExists(newDbNameWal)) { + if (!FileSystem::remove(newDbNameWal, &error)) { qCWarning(lcDb) << "Database migration: Could not remove db WAL file" << newDbNameWal - << "due to" << error; + << "due to" << error; return false; } } - if( FileSystem::fileExists( newDbNameShm ) ) { - if( !FileSystem::remove(newDbNameShm, &error) ) { + if (FileSystem::fileExists(newDbNameShm)) { + if (!FileSystem::remove(newDbNameShm, &error)) { qCWarning(lcDb) << "Database migration: Could not remove db SHM file" << newDbNameShm - << "due to" << error; + << "due to" << error; return false; } } - if( !FileSystem::rename(oldDbName, newDbName, &error) ) { + if (!FileSystem::rename(oldDbName, newDbName, &error)) { qCWarning(lcDb) << "Database migration: could not rename " << oldDbName - << "to" << newDbName << ":" << error; + << "to" << newDbName << ":" << error; return false; } - if( !FileSystem::rename(oldDbNameWal, newDbNameWal, &error) ) { + if (!FileSystem::rename(oldDbNameWal, newDbNameWal, &error)) { qCWarning(lcDb) << "Database migration: could not rename " << oldDbNameWal - << "to" << newDbNameWal << ":" << error; + << "to" << newDbNameWal << ":" << error; return false; } - if( !FileSystem::rename(oldDbNameShm, newDbNameShm, &error) ) { + if (!FileSystem::rename(oldDbNameShm, newDbNameShm, &error)) { qCWarning(lcDb) << "Database migration: could not rename " << oldDbNameShm - << "to" << newDbNameShm << ":" << error; + << "to" << newDbNameShm << ":" << error; return false; } @@ -149,8 +145,8 @@ void SyncJournalDb::walCheckpoint() void SyncJournalDb::startTransaction() { - if( _transaction == 0 ) { - if( !_db.transaction() ) { + if (_transaction == 0) { + if (!_db.transaction()) { qCWarning(lcDb) << "ERROR starting transaction: " << _db.error(); return; } @@ -162,8 +158,8 @@ void SyncJournalDb::startTransaction() void SyncJournalDb::commitTransaction() { - if( _transaction == 1 ) { - if( ! _db.commit() ) { + if (_transaction == 1) { + if (!_db.commit()) { qCWarning(lcDb) << "ERROR committing to the database: " << _db.error(); return; } @@ -173,7 +169,7 @@ void SyncJournalDb::commitTransaction() } } -bool SyncJournalDb::sqlFail( const QString& log, const SqlQuery& query ) +bool SyncJournalDb::sqlFail(const QString &log, const SqlQuery &query) { commitTransaction(); qCWarning(lcDb) << "SQL Error" << log << query.error(); @@ -182,7 +178,7 @@ bool SyncJournalDb::sqlFail( const QString& log, const SqlQuery& query ) return false; } -static QString defaultJournalMode(const QString & dbPath) +static QString defaultJournalMode(const QString &dbPath) { #ifdef Q_OS_WIN // See #2693: Some exFAT file systems seem unable to cope with the @@ -201,23 +197,23 @@ static QString defaultJournalMode(const QString & dbPath) bool SyncJournalDb::checkConnect() { - if( _db.isOpen() ) { + if (_db.isOpen()) { return true; } - if( _dbFile.isEmpty()) { + if (_dbFile.isEmpty()) { qCWarning(lcDb) << "Database filename" + _dbFile + " is empty"; return false; } // The database file is created by this call (SQLITE_OPEN_CREATE) - if( !_db.openOrCreateReadWrite(_dbFile) ) { + if (!_db.openOrCreateReadWrite(_dbFile)) { QString error = _db.error(); qCWarning(lcDb) << "Error opening the db: " << error; return false; } - if( !QFile::exists(_dbFile) ) { + if (!QFile::exists(_dbFile)) { qCWarning(lcDb) << "Database file" + _dbFile + " does not exist"; return false; } @@ -269,16 +265,16 @@ bool SyncJournalDb::checkConnect() SqlQuery createQuery(_db); createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata(" - "phash INTEGER(8)," - "pathlen INTEGER," - "path VARCHAR(4096)," - "inode INTEGER," - "uid INTEGER," - "gid INTEGER," - "mode INTEGER," - "modtime INTEGER(8)," - "type INTEGER," - "md5 VARCHAR(32)," /* This is the etag. Called md5 for compatibility */ + "phash INTEGER(8)," + "pathlen INTEGER," + "path VARCHAR(4096)," + "inode INTEGER," + "uid INTEGER," + "gid INTEGER," + "mode INTEGER," + "modtime INTEGER(8)," + "type INTEGER," + "md5 VARCHAR(32)," /* This is the etag. Called md5 for compatibility */ // updateDatabaseStructure() will add // fileid // remotePerm @@ -286,34 +282,34 @@ bool SyncJournalDb::checkConnect() // ignoredChildrenRemote // contentChecksum // contentChecksumTypeId - "PRIMARY KEY(phash)" - ");"); + "PRIMARY KEY(phash)" + ");"); if (!createQuery.exec()) { return sqlFail("Create table metadata", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo(" - "path VARCHAR(4096)," - "tmpfile VARCHAR(4096)," - "etag VARCHAR(32)," - "errorcount INTEGER," - "PRIMARY KEY(path)" - ");"); + "path VARCHAR(4096)," + "tmpfile VARCHAR(4096)," + "etag VARCHAR(32)," + "errorcount INTEGER," + "PRIMARY KEY(path)" + ");"); if (!createQuery.exec()) { return sqlFail("Create table downloadinfo", createQuery); } createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo(" - "path VARCHAR(4096)," - "chunk INTEGER," - "transferid INTEGER," - "errorcount INTEGER," - "size INTEGER(8)," - "modtime INTEGER(8)," - "PRIMARY KEY(path)" - ");"); + "path VARCHAR(4096)," + "chunk INTEGER," + "transferid INTEGER," + "errorcount INTEGER," + "size INTEGER(8)," + "modtime INTEGER(8)," + "PRIMARY KEY(path)" + ");"); if (!createQuery.exec()) { return sqlFail("Create table uploadinfo", createQuery); @@ -334,9 +330,9 @@ bool SyncJournalDb::checkConnect() } createQuery.prepare("CREATE TABLE IF NOT EXISTS poll(" - "path VARCHAR(4096)," - "modtime INTEGER(8)," - "pollpath VARCHAR(4096));"); + "path VARCHAR(4096)," + "modtime INTEGER(8)," + "pollpath VARCHAR(4096));"); if (!createQuery.exec()) { return sqlFail("Create table poll", createQuery); } @@ -353,9 +349,9 @@ bool SyncJournalDb::checkConnect() // create the checksumtype table. createQuery.prepare("CREATE TABLE IF NOT EXISTS checksumtype(" - "id INTEGER PRIMARY KEY," - "name TEXT UNIQUE" - ");"); + "id INTEGER PRIMARY KEY," + "name TEXT UNIQUE" + ");"); if (!createQuery.exec()) { return sqlFail("Create table version", createQuery); } @@ -369,11 +365,11 @@ bool SyncJournalDb::checkConnect() } createQuery.prepare("CREATE TABLE IF NOT EXISTS version(" - "major INTEGER(8)," - "minor INTEGER(8)," - "patch INTEGER(8)," - "custom VARCHAR(256)" - ");"); + "major INTEGER(8)," + "minor INTEGER(8)," + "patch INTEGER(8)," + "custom VARCHAR(256)" + ");"); if (!createQuery.exec()) { return sqlFail("Create table version", createQuery); } @@ -400,7 +396,7 @@ bool SyncJournalDb::checkConnect() int minor = versionQuery.intValue(1); int patch = versionQuery.intValue(2); - if( major == 1 && minor == 8 && (patch == 0 || patch == 1) ) { + if (major == 1 && minor == 8 && (patch == 0 || patch == 1)) { qCInfo(lcDb) << "possibleUpgradeFromMirall_1_8_0_or_1 detected!"; forceRemoteDiscovery = true; } @@ -408,13 +404,13 @@ bool SyncJournalDb::checkConnect() // There was a bug in versions <2.3.0 that could lead to stale // local files and a remote discovery will fix them. // See #5190 #5242. - if( major == 2 && minor < 3) { + if (major == 2 && minor < 3) { qCInfo(lcDb) << "upgrade form client < 2.3.0 detected! forcing remote discovery"; forceRemoteDiscovery = true; } // Not comparing the BUILD id here, correct? - if( !(major == MIRALL_VERSION_MAJOR && minor == MIRALL_VERSION_MINOR && patch == MIRALL_VERSION_PATCH) ) { + if (!(major == MIRALL_VERSION_MAJOR && minor == MIRALL_VERSION_MINOR && patch == MIRALL_VERSION_PATCH)) { createQuery.prepare("UPDATE version SET major=?1, minor=?2, patch =?3, custom=?4 " "WHERE major=?5 AND minor=?6 AND patch=?7;"); createQuery.bindValue(1, MIRALL_VERSION_MAJOR); @@ -427,14 +423,13 @@ bool SyncJournalDb::checkConnect() if (!createQuery.exec()) { return sqlFail("Update version", createQuery); } - } } commitInternal("checkConnect"); bool rc = updateDatabaseStructure(); - if( !rc ) { + if (!rc) { qCWarning(lcDb) << "Failed to update the database structure!"; } @@ -456,18 +451,18 @@ bool SyncJournalDb::checkConnect() " ignoredChildrenRemote, contentChecksum, contentchecksumtype.name" " FROM metadata" " LEFT JOIN checksumtype as contentchecksumtype ON metadata.contentChecksumTypeId == contentchecksumtype.id" - " WHERE phash=?1" )) { + " WHERE phash=?1")) { return sqlFail("prepare _getFileRecordQuery", *_getFileRecordQuery); } - _setFileRecordQuery.reset(new SqlQuery(_db) ); + _setFileRecordQuery.reset(new SqlQuery(_db)); if (_setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata " - "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote, contentChecksum, contentChecksumTypeId) " - "VALUES (?1 , ?2, ?3 , ?4 , ?5 , ?6 , ?7, ?8 , ?9 , ?10, ?11, ?12, ?13, ?14, ?15, ?16);" )) { + "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote, contentChecksum, contentChecksumTypeId) " + "VALUES (?1 , ?2, ?3 , ?4 , ?5 , ?6 , ?7, ?8 , ?9 , ?10, ?11, ?12, ?13, ?14, ?15, ?16);")) { return sqlFail("prepare _setFileRecordQuery", *_setFileRecordQuery); } - _setFileRecordChecksumQuery.reset(new SqlQuery(_db) ); + _setFileRecordChecksumQuery.reset(new SqlQuery(_db)); if (_setFileRecordChecksumQuery->prepare( "UPDATE metadata" " SET contentChecksum = ?2, contentChecksumTypeId = ?3" @@ -482,40 +477,40 @@ bool SyncJournalDb::checkConnect() " WHERE phash == ?1;")) { return sqlFail("prepare _setFileRecordLocalMetadataQuery", *_setFileRecordLocalMetadataQuery); } - - _getDownloadInfoQuery.reset(new SqlQuery(_db) ); - if (_getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM " - "downloadinfo WHERE path=?1" )) { + + _getDownloadInfoQuery.reset(new SqlQuery(_db)); + if (_getDownloadInfoQuery->prepare("SELECT tmpfile, etag, errorcount FROM " + "downloadinfo WHERE path=?1")) { return sqlFail("prepare _getDownloadInfoQuery", *_getDownloadInfoQuery); } - _setDownloadInfoQuery.reset(new SqlQuery(_db) ); - if (_setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo " - "(path, tmpfile, etag, errorcount) " - "VALUES ( ?1 , ?2, ?3, ?4 )" )) { + _setDownloadInfoQuery.reset(new SqlQuery(_db)); + if (_setDownloadInfoQuery->prepare("INSERT OR REPLACE INTO downloadinfo " + "(path, tmpfile, etag, errorcount) " + "VALUES ( ?1 , ?2, ?3, ?4 )")) { return sqlFail("prepare _setDownloadInfoQuery", *_setDownloadInfoQuery); } - _deleteDownloadInfoQuery.reset(new SqlQuery(_db) ); - if (_deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?1" )) { + _deleteDownloadInfoQuery.reset(new SqlQuery(_db)); + if (_deleteDownloadInfoQuery->prepare("DELETE FROM downloadinfo WHERE path=?1")) { return sqlFail("prepare _deleteDownloadInfoQuery", *_deleteDownloadInfoQuery); } _getUploadInfoQuery.reset(new SqlQuery(_db)); - if (_getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM " - "uploadinfo WHERE path=?1" )) { + if (_getUploadInfoQuery->prepare("SELECT chunk, transferid, errorcount, size, modtime FROM " + "uploadinfo WHERE path=?1")) { return sqlFail("prepare _getUploadInfoQuery", *_getUploadInfoQuery); } _setUploadInfoQuery.reset(new SqlQuery(_db)); - if (_setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo " - "(path, chunk, transferid, errorcount, size, modtime) " - "VALUES ( ?1 , ?2, ?3 , ?4 , ?5, ?6 )")) { + if (_setUploadInfoQuery->prepare("INSERT OR REPLACE INTO uploadinfo " + "(path, chunk, transferid, errorcount, size, modtime) " + "VALUES ( ?1 , ?2, ?3 , ?4 , ?5, ?6 )")) { return sqlFail("prepare _setUploadInfoQuery", *_setUploadInfoQuery); } _deleteUploadInfoQuery.reset(new SqlQuery(_db)); - if (_deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?1" )) { + if (_deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?1")) { return sqlFail("prepare _deleteUploadInfoQuery", *_deleteUploadInfoQuery); } @@ -530,9 +525,9 @@ bool SyncJournalDb::checkConnect() return sqlFail("prepare _deleteFileRecordRecursively", *_deleteFileRecordRecursively); } - QString sql( "SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget " - "FROM blacklist WHERE path=?1"); - if( Utility::fsCasePreserving() ) { + QString sql("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget " + "FROM blacklist WHERE path=?1"); + if (Utility::fsCasePreserving()) { // if the file system is case preserving we have to check the blacklist // case insensitively sql += QLatin1String(" COLLATE NOCASE"); @@ -544,8 +539,8 @@ bool SyncJournalDb::checkConnect() _setErrorBlacklistQuery.reset(new SqlQuery(_db)); if (_setErrorBlacklistQuery->prepare("INSERT OR REPLACE INTO blacklist " - "(path, lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget) " - "VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")) { + "(path, lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget) " + "VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")) { return sqlFail("prepare _setErrorBlacklistQuery", *_setErrorBlacklistQuery); } @@ -644,91 +639,87 @@ bool SyncJournalDb::updateMetadataTableStructure() bool re = true; // check if the file_id column is there and create it if not - if( !checkConnect() ) { + if (!checkConnect()) { return false; } - if( columns.indexOf(QLatin1String("fileid")) == -1 ) { + if (columns.indexOf(QLatin1String("fileid")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN fileid VARCHAR(128);"); - if( !query.exec() ) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: Add column fileid", query); re = false; } query.prepare("CREATE INDEX metadata_file_id ON metadata(fileid);"); - if( ! query.exec() ) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: create index fileid", query); re = false; } commitInternal("update database structure: add fileid col"); } - if( columns.indexOf(QLatin1String("remotePerm")) == -1 ) { - + if (columns.indexOf(QLatin1String("remotePerm")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN remotePerm VARCHAR(128);"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: add column remotePerm", query); re = false; } commitInternal("update database structure (remotePerm)"); } - if( columns.indexOf(QLatin1String("filesize")) == -1 ) - { + if (columns.indexOf(QLatin1String("filesize")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN filesize BIGINT;"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateDatabaseStructure: add column filesize", query); re = false; } commitInternal("update database structure: add filesize col"); } - if( 1 ) { + if (1) { SqlQuery query(_db); query.prepare("CREATE INDEX IF NOT EXISTS metadata_inode ON metadata(inode);"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: create index inode", query); re = false; } commitInternal("update database structure: add inode index"); - } - if( 1 ) { + if (1) { SqlQuery query(_db); query.prepare("CREATE INDEX IF NOT EXISTS metadata_path ON metadata(path);"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: create index path", query); re = false; } commitInternal("update database structure: add path index"); - } - if( columns.indexOf(QLatin1String("ignoredChildrenRemote")) == -1 ) { + if (columns.indexOf(QLatin1String("ignoredChildrenRemote")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN ignoredChildrenRemote INT;"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: add ignoredChildrenRemote column", query); re = false; } commitInternal("update database structure: add ignoredChildrenRemote col"); } - if( columns.indexOf(QLatin1String("contentChecksum")) == -1 ) { + if (columns.indexOf(QLatin1String("contentChecksum")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN contentChecksum TEXT;"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: add contentChecksum column", query); re = false; } commitInternal("update database structure: add contentChecksum col"); } - if( columns.indexOf(QLatin1String("contentChecksumTypeId")) == -1 ) { + if (columns.indexOf(QLatin1String("contentChecksumTypeId")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE metadata ADD COLUMN contentChecksumTypeId INTEGER;"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateMetadataTableStructure: add contentChecksumTypeId column", query); re = false; } @@ -745,28 +736,28 @@ bool SyncJournalDb::updateErrorBlacklistTableStructure() bool re = true; // check if the file_id column is there and create it if not - if( !checkConnect() ) { + if (!checkConnect()) { return false; } - if( columns.indexOf(QLatin1String("lastTryTime")) == -1 ) { + if (columns.indexOf(QLatin1String("lastTryTime")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE blacklist ADD COLUMN lastTryTime INTEGER(8);"); - if( !query.exec() ) { + if (!query.exec()) { sqlFail("updateBlacklistTableStructure: Add lastTryTime fileid", query); re = false; } query.prepare("ALTER TABLE blacklist ADD COLUMN ignoreDuration INTEGER(8);"); - if( !query.exec() ) { + if (!query.exec()) { sqlFail("updateBlacklistTableStructure: Add ignoreDuration fileid", query); re = false; } commitInternal("update database structure: add lastTryTime, ignoreDuration cols"); } - if( columns.indexOf(QLatin1String("renameTarget")) == -1 ) { + if (columns.indexOf(QLatin1String("renameTarget")) == -1) { SqlQuery query(_db); query.prepare("ALTER TABLE blacklist ADD COLUMN renameTarget VARCHAR(4096);"); - if( !query.exec() ) { + if (!query.exec()) { sqlFail("updateBlacklistTableStructure: Add renameTarget", query); re = false; } @@ -775,7 +766,7 @@ bool SyncJournalDb::updateErrorBlacklistTableStructure() SqlQuery query(_db); query.prepare("CREATE INDEX IF NOT EXISTS blacklist_index ON blacklist(path collate nocase);"); - if( !query.exec()) { + if (!query.exec()) { sqlFail("updateErrorBlacklistTableStructure: create index blacklit", query); re = false; } @@ -783,22 +774,21 @@ bool SyncJournalDb::updateErrorBlacklistTableStructure() return re; } -QStringList SyncJournalDb::tableColumns( const QString& table ) +QStringList SyncJournalDb::tableColumns(const QString &table) { QStringList columns; - if( !table.isEmpty() ) { - - if( checkConnect() ) { + if (!table.isEmpty()) { + if (checkConnect()) { QString q = QString("PRAGMA table_info('%1');").arg(table); SqlQuery query(_db); query.prepare(q); - if(!query.exec()) { + if (!query.exec()) { return columns; } - while( query.next() ) { - columns.append( query.stringValue(1) ); + while (query.next()) { + columns.append(query.stringValue(1)); } } } @@ -807,22 +797,22 @@ QStringList SyncJournalDb::tableColumns( const QString& table ) return columns; } -qint64 SyncJournalDb::getPHash(const QString& file) +qint64 SyncJournalDb::getPHash(const QString &file) { QByteArray utf8File = file.toUtf8(); int64_t h; - if( file.isEmpty() ) { + if (file.isEmpty()) { return -1; } int len = utf8File.length(); - h = c_jhash64((uint8_t *) utf8File.data(), len, 0); + h = c_jhash64((uint8_t *)utf8File.data(), len, 0); return h; } -bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record ) +bool SyncJournalDb::setFileRecord(const SyncJournalFileRecord &_record) { SyncJournalFileRecord record = _record; QMutexLocker locker(&_mutex); @@ -830,7 +820,7 @@ bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record ) if (!_avoidReadFromDbOnNextSyncFilter.isEmpty()) { // If we are a directory that should not be read from db next time, don't write the etag QString prefix = record._path + "/"; - foreach(const QString &it, _avoidReadFromDbOnNextSyncFilter) { + foreach (const QString &it, _avoidReadFromDbOnNextSyncFilter) { if (it.startsWith(prefix)) { qCInfo(lcDb) << "Filtered writing the etag of" << prefix << "because it is a prefix of" << it; record._etag = "_invalid_"; @@ -839,42 +829,45 @@ bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record ) } } - qCInfo(lcDb) << "Updating file record for path:" << record._path << "inode:" << record._inode - << "modtime:" << record._modtime << "type:" << record._type - << "etag:" << record._etag << "fileId:" << record._fileId << "remotePerm:" << record._remotePerm - << "fileSize:" << record._fileSize << "checksum:" << record._contentChecksum << record._contentChecksumType; + qCInfo(lcDb) << "Updating file record for path:" << record._path << "inode:" << record._inode + << "modtime:" << record._modtime << "type:" << record._type + << "etag:" << record._etag << "fileId:" << record._fileId << "remotePerm:" << record._remotePerm + << "fileSize:" << record._fileSize << "checksum:" << record._contentChecksum << record._contentChecksumType; qlonglong phash = getPHash(record._path); - if( checkConnect() ) { + if (checkConnect()) { QByteArray arr = record._path.toUtf8(); int plen = arr.length(); - QString etag( record._etag ); - if( etag.isEmpty() ) etag = ""; - QString fileId( record._fileId); - if( fileId.isEmpty() ) fileId = ""; - QString remotePerm (record._remotePerm); - if (remotePerm.isEmpty()) remotePerm = QString(); // have NULL in DB (vs empty) + QString etag(record._etag); + if (etag.isEmpty()) + etag = ""; + QString fileId(record._fileId); + if (fileId.isEmpty()) + fileId = ""; + QString remotePerm(record._remotePerm); + if (remotePerm.isEmpty()) + remotePerm = QString(); // have NULL in DB (vs empty) int contentChecksumTypeId = mapChecksumType(record._contentChecksumType); _setFileRecordQuery->reset_and_clear_bindings(); _setFileRecordQuery->bindValue(1, QString::number(phash)); _setFileRecordQuery->bindValue(2, plen); - _setFileRecordQuery->bindValue(3, record._path ); - _setFileRecordQuery->bindValue(4, record._inode ); - _setFileRecordQuery->bindValue(5, 0 ); // uid Not used - _setFileRecordQuery->bindValue(6, 0 ); // gid Not used - _setFileRecordQuery->bindValue(7, 0 ); // mode Not used + _setFileRecordQuery->bindValue(3, record._path); + _setFileRecordQuery->bindValue(4, record._inode); + _setFileRecordQuery->bindValue(5, 0); // uid Not used + _setFileRecordQuery->bindValue(6, 0); // gid Not used + _setFileRecordQuery->bindValue(7, 0); // mode Not used _setFileRecordQuery->bindValue(8, QString::number(Utility::qDateTimeToTime_t(record._modtime))); - _setFileRecordQuery->bindValue(9, QString::number(record._type) ); - _setFileRecordQuery->bindValue(10, etag ); - _setFileRecordQuery->bindValue(11, fileId ); - _setFileRecordQuery->bindValue(12, remotePerm ); - _setFileRecordQuery->bindValue(13, record._fileSize ); - _setFileRecordQuery->bindValue(14, record._serverHasIgnoredFiles ? 1:0); - _setFileRecordQuery->bindValue(15, record._contentChecksum ); - _setFileRecordQuery->bindValue(16, contentChecksumTypeId ); - - if( !_setFileRecordQuery->exec() ) { + _setFileRecordQuery->bindValue(9, QString::number(record._type)); + _setFileRecordQuery->bindValue(10, etag); + _setFileRecordQuery->bindValue(11, fileId); + _setFileRecordQuery->bindValue(12, remotePerm); + _setFileRecordQuery->bindValue(13, record._fileSize); + _setFileRecordQuery->bindValue(14, record._serverHasIgnoredFiles ? 1 : 0); + _setFileRecordQuery->bindValue(15, record._contentChecksum); + _setFileRecordQuery->bindValue(16, contentChecksumTypeId); + + if (!_setFileRecordQuery->exec()) { return false; } @@ -886,27 +879,27 @@ bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record ) } } -bool SyncJournalDb::deleteFileRecord(const QString& filename, bool recursively) +bool SyncJournalDb::deleteFileRecord(const QString &filename, bool recursively) { QMutexLocker locker(&_mutex); - if( checkConnect() ) { + if (checkConnect()) { // if (!recursively) { // always delete the actual file. qlonglong phash = getPHash(filename); _deleteFileRecordPhash->reset_and_clear_bindings(); - _deleteFileRecordPhash->bindValue( 1, QString::number(phash) ); + _deleteFileRecordPhash->bindValue(1, QString::number(phash)); - if( !_deleteFileRecordPhash->exec() ) { + if (!_deleteFileRecordPhash->exec()) { return false; } _deleteFileRecordPhash->reset_and_clear_bindings(); - if( recursively) { + if (recursively) { _deleteFileRecordRecursively->reset_and_clear_bindings(); _deleteFileRecordRecursively->bindValue(1, filename); - if( !_deleteFileRecordRecursively->exec() ) { + if (!_deleteFileRecordRecursively->exec()) { return false; } @@ -920,14 +913,14 @@ bool SyncJournalDb::deleteFileRecord(const QString& filename, bool recursively) } -SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString& filename) +SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString &filename) { QMutexLocker locker(&_mutex); - qlonglong phash = getPHash( filename ); + qlonglong phash = getPHash(filename); SyncJournalFileRecord rec; - if( !filename.isEmpty() && checkConnect() ) { + if (!filename.isEmpty() && checkConnect()) { _getFileRecordQuery->reset_and_clear_bindings(); _getFileRecordQuery->bindValue(1, QString::number(phash)); @@ -937,27 +930,27 @@ SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString& filename) return rec; } - if( _getFileRecordQuery->next() ) { - rec._path = _getFileRecordQuery->stringValue(0); - rec._inode = _getFileRecordQuery->intValue(1); + if (_getFileRecordQuery->next()) { + rec._path = _getFileRecordQuery->stringValue(0); + rec._inode = _getFileRecordQuery->intValue(1); //rec._uid = _getFileRecordQuery->value(2).toInt(&ok); Not Used //rec._gid = _getFileRecordQuery->value(3).toInt(&ok); Not Used //rec._mode = _getFileRecordQuery->intValue(4); rec._modtime = Utility::qDateTimeFromTime_t(_getFileRecordQuery->int64Value(5)); - rec._type = _getFileRecordQuery->intValue(6); - rec._etag = _getFileRecordQuery->baValue(7); - rec._fileId = _getFileRecordQuery->baValue(8); + rec._type = _getFileRecordQuery->intValue(6); + rec._etag = _getFileRecordQuery->baValue(7); + rec._fileId = _getFileRecordQuery->baValue(8); rec._remotePerm = _getFileRecordQuery->baValue(9); - rec._fileSize = _getFileRecordQuery->int64Value(10); + rec._fileSize = _getFileRecordQuery->int64Value(10); rec._serverHasIgnoredFiles = (_getFileRecordQuery->intValue(11) > 0); rec._contentChecksum = _getFileRecordQuery->baValue(12); - if( !_getFileRecordQuery->nullValue(13) ) { + if (!_getFileRecordQuery->nullValue(13)) { rec._contentChecksumType = _getFileRecordQuery->baValue(13); } _getFileRecordQuery->reset_and_clear_bindings(); } else { int errId = _getFileRecordQuery->errorId(); - if( errId != SQLITE_DONE ) { // only do this if the problem is different from SQLITE_DONE + if (errId != SQLITE_DONE) { // only do this if the problem is different from SQLITE_DONE QString err = _getFileRecordQuery->error(); qCWarning(lcDb) << "No journal entry found for " << filename << "Error: " << err; locker.unlock(); @@ -972,12 +965,12 @@ SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString& filename) return rec; } -bool SyncJournalDb::postSyncCleanup(const QSet& filepathsToKeep, - const QSet& prefixesToKeep) +bool SyncJournalDb::postSyncCleanup(const QSet &filepathsToKeep, + const QSet &prefixesToKeep) { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return false; } @@ -990,28 +983,28 @@ bool SyncJournalDb::postSyncCleanup(const QSet& filepathsToKeep, QStringList superfluousItems; - while(query.next()) { + while (query.next()) { const QString file = query.stringValue(1); bool keep = filepathsToKeep.contains(file); - if( !keep ) { - foreach( const QString & prefix, prefixesToKeep ) { - if( file.startsWith(prefix) ) { + if (!keep) { + foreach (const QString &prefix, prefixesToKeep) { + if (file.startsWith(prefix)) { keep = true; break; } } } - if( !keep ) { + if (!keep) { superfluousItems.append(query.stringValue(0)); } } - if( superfluousItems.count() ) { - QString sql = "DELETE FROM metadata WHERE phash in ("+ superfluousItems.join(",")+")"; + if (superfluousItems.count()) { + QString sql = "DELETE FROM metadata WHERE phash in (" + superfluousItems.join(",") + ")"; qCInfo(lcDb) << "Sync Journal cleanup for" << superfluousItems; SqlQuery delQuery(_db); delQuery.prepare(sql); - if( !delQuery.exec() ) { + if (!delQuery.exec()) { return false; } } @@ -1026,7 +1019,7 @@ int SyncJournalDb::getFileRecordCount() { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return -1; } @@ -1045,29 +1038,29 @@ int SyncJournalDb::getFileRecordCount() return 0; } -bool SyncJournalDb::updateFileRecordChecksum(const QString& filename, - const QByteArray& contentChecksum, - const QByteArray& contentChecksumType) +bool SyncJournalDb::updateFileRecordChecksum(const QString &filename, + const QByteArray &contentChecksum, + const QByteArray &contentChecksumType) { QMutexLocker locker(&_mutex); qCInfo(lcDb) << "Updating file checksum" << filename << contentChecksum << contentChecksumType; qlonglong phash = getPHash(filename); - if( !checkConnect() ) { + if (!checkConnect()) { qCWarning(lcDb) << "Failed to connect database."; return false; } int checksumTypeId = mapChecksumType(contentChecksumType); - auto & query = _setFileRecordChecksumQuery; + auto &query = _setFileRecordChecksumQuery; query->reset_and_clear_bindings(); query->bindValue(1, QString::number(phash)); query->bindValue(2, contentChecksum); query->bindValue(3, checksumTypeId); - if( !query->exec() ) { + if (!query->exec()) { return false; } @@ -1075,8 +1068,8 @@ bool SyncJournalDb::updateFileRecordChecksum(const QString& filename, return true; } -bool SyncJournalDb::updateLocalMetadata(const QString& filename, - qint64 modtime, quint64 size, quint64 inode) +bool SyncJournalDb::updateLocalMetadata(const QString &filename, + qint64 modtime, quint64 size, quint64 inode) { QMutexLocker locker(&_mutex); @@ -1084,12 +1077,12 @@ bool SyncJournalDb::updateLocalMetadata(const QString& filename, qCInfo(lcDb) << "Updating local metadata for:" << filename << modtime << size << inode; qlonglong phash = getPHash(filename); - if( !checkConnect() ) { + if (!checkConnect()) { qCWarning(lcDb) << "Failed to connect database."; return false; } - auto & query = _setFileRecordLocalMetadataQuery; + auto &query = _setFileRecordLocalMetadataQuery; query->reset_and_clear_bindings(); query->bindValue(1, QString::number(phash)); @@ -1097,7 +1090,7 @@ bool SyncJournalDb::updateLocalMetadata(const QString& filename, query->bindValue(3, modtime); query->bindValue(4, size); - if( !query->exec() ) { + if (!query->exec()) { return false; } @@ -1105,7 +1098,7 @@ bool SyncJournalDb::updateLocalMetadata(const QString& filename, return true; } -bool SyncJournalDb::setFileRecordMetadata(const SyncJournalFileRecord& record) +bool SyncJournalDb::setFileRecordMetadata(const SyncJournalFileRecord &record) { SyncJournalFileRecord existing = getFileRecord(record._path); @@ -1126,23 +1119,23 @@ bool SyncJournalDb::setFileRecordMetadata(const SyncJournalFileRecord& record) return setFileRecord(existing); } -static void toDownloadInfo(SqlQuery &query, SyncJournalDb::DownloadInfo * res) +static void toDownloadInfo(SqlQuery &query, SyncJournalDb::DownloadInfo *res) { bool ok = true; - res->_tmpfile = query.stringValue(0); - res->_etag = query.baValue(1); + res->_tmpfile = query.stringValue(0); + res->_etag = query.baValue(1); res->_errorCount = query.intValue(2); - res->_valid = ok; + res->_valid = ok; } -static bool deleteBatch(SqlQuery & query, const QStringList & entries, const QString & name) +static bool deleteBatch(SqlQuery &query, const QStringList &entries, const QString &name) { if (entries.isEmpty()) return true; qCDebug(lcDb) << "Removing stale " << qPrintable(name) << " entries: " << entries.join(", "); // FIXME: Was ported from execBatch, check if correct! - foreach( const QString& entry, entries ) { + foreach (const QString &entry, entries) { query.reset_and_clear_bindings(); query.bindValue(1, entry); if (!query.exec()) { @@ -1154,13 +1147,13 @@ static bool deleteBatch(SqlQuery & query, const QStringList & entries, const QSt return true; } -SyncJournalDb::DownloadInfo SyncJournalDb::getDownloadInfo(const QString& file) +SyncJournalDb::DownloadInfo SyncJournalDb::getDownloadInfo(const QString &file) { QMutexLocker locker(&_mutex); DownloadInfo res; - if( checkConnect() ) { + if (checkConnect()) { _getDownloadInfoQuery->reset_and_clear_bindings(); _getDownloadInfoQuery->bindValue(1, file); @@ -1168,7 +1161,7 @@ SyncJournalDb::DownloadInfo SyncJournalDb::getDownloadInfo(const QString& file) return res; } - if( _getDownloadInfoQuery->next() ) { + if (_getDownloadInfoQuery->next()) { toDownloadInfo(*_getDownloadInfoQuery, &res); } else { res._valid = false; @@ -1178,11 +1171,11 @@ SyncJournalDb::DownloadInfo SyncJournalDb::getDownloadInfo(const QString& file) return res; } -void SyncJournalDb::setDownloadInfo(const QString& file, const SyncJournalDb::DownloadInfo& i) +void SyncJournalDb::setDownloadInfo(const QString &file, const SyncJournalDb::DownloadInfo &i) { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return; } @@ -1190,10 +1183,10 @@ void SyncJournalDb::setDownloadInfo(const QString& file, const SyncJournalDb::Do _setDownloadInfoQuery->reset_and_clear_bindings(); _setDownloadInfoQuery->bindValue(1, file); _setDownloadInfoQuery->bindValue(2, i._tmpfile); - _setDownloadInfoQuery->bindValue(3, i._etag ); - _setDownloadInfoQuery->bindValue(4, i._errorCount ); + _setDownloadInfoQuery->bindValue(3, i._etag); + _setDownloadInfoQuery->bindValue(4, i._errorCount); - if( !_setDownloadInfoQuery->exec() ) { + if (!_setDownloadInfoQuery->exec()) { return; } @@ -1201,9 +1194,9 @@ void SyncJournalDb::setDownloadInfo(const QString& file, const SyncJournalDb::Do } else { _deleteDownloadInfoQuery->reset_and_clear_bindings(); - _deleteDownloadInfoQuery->bindValue( 1, file ); + _deleteDownloadInfoQuery->bindValue(1, file); - if( !_deleteDownloadInfoQuery->exec() ) { + if (!_deleteDownloadInfoQuery->exec()) { return; } @@ -1211,7 +1204,7 @@ void SyncJournalDb::setDownloadInfo(const QString& file, const SyncJournalDb::Do } } -QVector SyncJournalDb::getAndDeleteStaleDownloadInfos(const QSet& keep) +QVector SyncJournalDb::getAndDeleteStaleDownloadInfos(const QSet &keep) { QVector empty_result; QMutexLocker locker(&_mutex); @@ -1252,27 +1245,26 @@ int SyncJournalDb::downloadInfoCount() int re = 0; QMutexLocker locker(&_mutex); - if( checkConnect() ) { + if (checkConnect()) { SqlQuery query("SELECT count(*) FROM downloadinfo", _db); - if( ! query.exec() ) { + if (!query.exec()) { sqlFail("Count number of downloadinfo entries failed", query); } - if( query.next() ) { + if (query.next()) { re = query.intValue(0); } } return re; } -SyncJournalDb::UploadInfo SyncJournalDb::getUploadInfo(const QString& file) +SyncJournalDb::UploadInfo SyncJournalDb::getUploadInfo(const QString &file) { QMutexLocker locker(&_mutex); UploadInfo res; - if( checkConnect() ) { - + if (checkConnect()) { _getUploadInfoQuery->reset_and_clear_bindings(); _getUploadInfoQuery->bindValue(1, file); @@ -1280,25 +1272,25 @@ SyncJournalDb::UploadInfo SyncJournalDb::getUploadInfo(const QString& file) return res; } - if( _getUploadInfoQuery->next() ) { + if (_getUploadInfoQuery->next()) { bool ok = true; - res._chunk = _getUploadInfoQuery->intValue(0); + res._chunk = _getUploadInfoQuery->intValue(0); res._transferid = _getUploadInfoQuery->intValue(1); res._errorCount = _getUploadInfoQuery->intValue(2); - res._size = _getUploadInfoQuery->int64Value(3); - res._modtime = Utility::qDateTimeFromTime_t(_getUploadInfoQuery->int64Value(4)); - res._valid = ok; + res._size = _getUploadInfoQuery->int64Value(3); + res._modtime = Utility::qDateTimeFromTime_t(_getUploadInfoQuery->int64Value(4)); + res._valid = ok; } _getUploadInfoQuery->reset_and_clear_bindings(); } return res; } -void SyncJournalDb::setUploadInfo(const QString& file, const SyncJournalDb::UploadInfo& i) +void SyncJournalDb::setUploadInfo(const QString &file, const SyncJournalDb::UploadInfo &i) { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return; } @@ -1306,12 +1298,12 @@ void SyncJournalDb::setUploadInfo(const QString& file, const SyncJournalDb::Uplo _setUploadInfoQuery->reset_and_clear_bindings(); _setUploadInfoQuery->bindValue(1, file); _setUploadInfoQuery->bindValue(2, i._chunk); - _setUploadInfoQuery->bindValue(3, i._transferid ); - _setUploadInfoQuery->bindValue(4, i._errorCount ); - _setUploadInfoQuery->bindValue(5, i._size ); - _setUploadInfoQuery->bindValue(6, Utility::qDateTimeToTime_t(i._modtime) ); + _setUploadInfoQuery->bindValue(3, i._transferid); + _setUploadInfoQuery->bindValue(4, i._errorCount); + _setUploadInfoQuery->bindValue(5, i._size); + _setUploadInfoQuery->bindValue(6, Utility::qDateTimeToTime_t(i._modtime)); - if( !_setUploadInfoQuery->exec() ) { + if (!_setUploadInfoQuery->exec()) { return; } @@ -1320,7 +1312,7 @@ void SyncJournalDb::setUploadInfo(const QString& file, const SyncJournalDb::Uplo _deleteUploadInfoQuery->reset_and_clear_bindings(); _deleteUploadInfoQuery->bindValue(1, file); - if( !_deleteUploadInfoQuery->exec() ) { + if (!_deleteUploadInfoQuery->exec()) { return; } @@ -1358,28 +1350,29 @@ QVector SyncJournalDb::deleteStaleUploadInfos(const QSet &keep) return ids; } -SyncJournalErrorBlacklistRecord SyncJournalDb::errorBlacklistEntry( const QString& file ) +SyncJournalErrorBlacklistRecord SyncJournalDb::errorBlacklistEntry(const QString &file) { QMutexLocker locker(&_mutex); SyncJournalErrorBlacklistRecord entry; - if( file.isEmpty() ) return entry; + if (file.isEmpty()) + return entry; // SELECT lastTryEtag, lastTryModtime, retrycount, errorstring - if( checkConnect() ) { + if (checkConnect()) { _getErrorBlacklistQuery->reset_and_clear_bindings(); - _getErrorBlacklistQuery->bindValue( 1, file ); - if( _getErrorBlacklistQuery->exec() ){ - if( _getErrorBlacklistQuery->next() ) { - entry._lastTryEtag = _getErrorBlacklistQuery->baValue(0); + _getErrorBlacklistQuery->bindValue(1, file); + if (_getErrorBlacklistQuery->exec()) { + if (_getErrorBlacklistQuery->next()) { + entry._lastTryEtag = _getErrorBlacklistQuery->baValue(0); entry._lastTryModtime = _getErrorBlacklistQuery->int64Value(1); - entry._retryCount = _getErrorBlacklistQuery->intValue(2); - entry._errorString = _getErrorBlacklistQuery->stringValue(3); - entry._lastTryTime = _getErrorBlacklistQuery->int64Value(4); + entry._retryCount = _getErrorBlacklistQuery->intValue(2); + entry._errorString = _getErrorBlacklistQuery->stringValue(3); + entry._lastTryTime = _getErrorBlacklistQuery->int64Value(4); entry._ignoreDuration = _getErrorBlacklistQuery->int64Value(5); - entry._renameTarget = _getErrorBlacklistQuery->stringValue(6); - entry._file = file; + entry._renameTarget = _getErrorBlacklistQuery->stringValue(6); + entry._file = file; } _getErrorBlacklistQuery->reset_and_clear_bindings(); } @@ -1422,13 +1415,13 @@ int SyncJournalDb::errorBlackListEntryCount() int re = 0; QMutexLocker locker(&_mutex); - if( checkConnect() ) { + if (checkConnect()) { SqlQuery query("SELECT count(*) FROM blacklist", _db); - if( ! query.exec() ) { + if (!query.exec()) { sqlFail("Count number of blacklist entries failed", query); } - if( query.next() ) { + if (query.next()) { re = query.intValue(0); } } @@ -1438,12 +1431,12 @@ int SyncJournalDb::errorBlackListEntryCount() int SyncJournalDb::wipeErrorBlacklist() { QMutexLocker locker(&_mutex); - if( checkConnect() ) { + if (checkConnect()) { SqlQuery query(_db); query.prepare("DELETE FROM blacklist"); - if( ! query.exec() ) { + if (!query.exec()) { sqlFail("Deletion of whole blacklist failed", query); return -1; } @@ -1452,33 +1445,33 @@ int SyncJournalDb::wipeErrorBlacklist() return -1; } -void SyncJournalDb::wipeErrorBlacklistEntry( const QString& file ) +void SyncJournalDb::wipeErrorBlacklistEntry(const QString &file) { - if( file.isEmpty() ) { + if (file.isEmpty()) { return; } QMutexLocker locker(&_mutex); - if( checkConnect() ) { + if (checkConnect()) { SqlQuery query(_db); query.prepare("DELETE FROM blacklist WHERE path=?1"); query.bindValue(1, file); - if( ! query.exec() ) { + if (!query.exec()) { sqlFail("Deletion of blacklist item failed.", query); } } } -void SyncJournalDb::updateErrorBlacklistEntry( const SyncJournalErrorBlacklistRecord& item ) +void SyncJournalDb::updateErrorBlacklistEntry(const SyncJournalErrorBlacklistRecord &item) { QMutexLocker locker(&_mutex); qCInfo(lcDb) << "Setting blacklist entry for " << item._file << item._retryCount - << item._errorString << item._lastTryTime << item._ignoreDuration - << item._lastTryModtime << item._lastTryEtag << item._renameTarget ; + << item._errorString << item._lastTryTime << item._ignoreDuration + << item._lastTryModtime << item._lastTryEtag << item._renameTarget; - if( !checkConnect() ) { + if (!checkConnect()) { return; } @@ -1492,25 +1485,24 @@ void SyncJournalDb::updateErrorBlacklistEntry( const SyncJournalErrorBlacklistRe _setErrorBlacklistQuery->bindValue(8, item._renameTarget); _setErrorBlacklistQuery->exec(); _setErrorBlacklistQuery->reset_and_clear_bindings(); - } -QVector< SyncJournalDb::PollInfo > SyncJournalDb::getPollInfos() +QVector SyncJournalDb::getPollInfos() { QMutexLocker locker(&_mutex); - QVector< SyncJournalDb::PollInfo > res; + QVector res; - if( !checkConnect() ) + if (!checkConnect()) return res; - SqlQuery query("SELECT path, modtime, pollpath FROM poll",_db); + SqlQuery query("SELECT path, modtime, pollpath FROM poll", _db); if (!query.exec()) { return res; } - while( query.next() ) { + while (query.next()) { PollInfo info; info._file = query.stringValue(0); info._modtime = query.int64Value(1); @@ -1522,10 +1514,10 @@ QVector< SyncJournalDb::PollInfo > SyncJournalDb::getPollInfos() return res; } -void SyncJournalDb::setPollInfo(const SyncJournalDb::PollInfo& info) +void SyncJournalDb::setPollInfo(const SyncJournalDb::PollInfo &info) { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return; } @@ -1543,13 +1535,13 @@ void SyncJournalDb::setPollInfo(const SyncJournalDb::PollInfo& info) } } -QStringList SyncJournalDb::getSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, bool *ok ) +QStringList SyncJournalDb::getSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, bool *ok) { QStringList result; ASSERT(ok); QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { *ok = false; return result; } @@ -1560,7 +1552,7 @@ QStringList SyncJournalDb::getSelectiveSyncList(SyncJournalDb::SelectiveSyncList *ok = false; return result; } - while( _getSelectiveSyncListQuery->next() ) { + while (_getSelectiveSyncListQuery->next()) { auto entry = _getSelectiveSyncListQuery->stringValue(0); if (!entry.endsWith(QLatin1Char('/'))) { entry.append(QLatin1Char('/')); @@ -1572,22 +1564,22 @@ QStringList SyncJournalDb::getSelectiveSyncList(SyncJournalDb::SelectiveSyncList return result; } -void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, const QStringList& list) +void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, const QStringList &list) { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return; } //first, delete all entries of this type SqlQuery delQuery("DELETE FROM selectivesync WHERE type == ?1", _db); delQuery.bindValue(1, int(type)); - if( !delQuery.exec() ) { + if (!delQuery.exec()) { qCWarning(lcDb) << "SQL error when deleting selective sync list" << list << delQuery.error(); } - SqlQuery insQuery("INSERT INTO selectivesync VALUES (?1, ?2)" , _db); - foreach(const auto &path, list) { + SqlQuery insQuery("INSERT INTO selectivesync VALUES (?1, ?2)", _db); + foreach (const auto &path, list) { insQuery.reset_and_clear_bindings(); insQuery.bindValue(1, path); insQuery.bindValue(2, int(type)); @@ -1597,11 +1589,11 @@ void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType ty } } -void SyncJournalDb::avoidRenamesOnNextSync(const QString& path) +void SyncJournalDb::avoidRenamesOnNextSync(const QString &path) { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return; } @@ -1617,7 +1609,7 @@ void SyncJournalDb::avoidRenamesOnNextSync(const QString& path) avoidReadFromDbOnNextSync(path); } -void SyncJournalDb::avoidReadFromDbOnNextSync(const QString& fileName) +void SyncJournalDb::avoidReadFromDbOnNextSync(const QString &fileName) { // Make sure that on the next sync, fileName is not read from the DB but uses the PROPFIND to // get the info from the server @@ -1625,7 +1617,7 @@ void SyncJournalDb::avoidReadFromDbOnNextSync(const QString& fileName) QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return; } @@ -1644,7 +1636,7 @@ void SyncJournalDb::forceRemoteDiscoveryNextSync() { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return; } @@ -1663,26 +1655,26 @@ void SyncJournalDb::forceRemoteDiscoveryNextSyncLocked() QByteArray SyncJournalDb::getChecksumType(int checksumTypeId) { QMutexLocker locker(&_mutex); - if( !checkConnect() ) { + if (!checkConnect()) { return QByteArray(); } // Retrieve the id - auto & query = *_getChecksumTypeQuery; + auto &query = *_getChecksumTypeQuery; query.reset_and_clear_bindings(); query.bindValue(1, checksumTypeId); - if( !query.exec() ) { + if (!query.exec()) { return 0; } - if( !query.next() ) { + if (!query.next()) { qCWarning(lcDb) << "No checksum type mapping found for" << checksumTypeId; return 0; } return query.baValue(0); } -int SyncJournalDb::mapChecksumType(const QByteArray& checksumType) +int SyncJournalDb::mapChecksumType(const QByteArray &checksumType) { if (checksumType.isEmpty()) { return 0; @@ -1691,18 +1683,18 @@ int SyncJournalDb::mapChecksumType(const QByteArray& checksumType) // Ensure the checksum type is in the db _insertChecksumTypeQuery->reset_and_clear_bindings(); _insertChecksumTypeQuery->bindValue(1, checksumType); - if( !_insertChecksumTypeQuery->exec() ) { + if (!_insertChecksumTypeQuery->exec()) { return 0; } // Retrieve the id _getChecksumTypeIdQuery->reset_and_clear_bindings(); _getChecksumTypeIdQuery->bindValue(1, checksumType); - if( !_getChecksumTypeIdQuery->exec() ) { + if (!_getChecksumTypeIdQuery->exec()) { return 0; } - if( !_getChecksumTypeIdQuery->next() ) { + if (!_getChecksumTypeIdQuery->next()) { qCWarning(lcDb) << "No checksum type mapping found for" << checksumType; return 0; } @@ -1749,7 +1741,7 @@ void SyncJournalDb::clearFileTable() query.exec(); } -void SyncJournalDb::commit(const QString& context, bool startTrans) +void SyncJournalDb::commit(const QString &context, bool startTrans) { QMutexLocker lock(&_mutex); commitInternal(context, startTrans); @@ -1758,7 +1750,7 @@ void SyncJournalDb::commit(const QString& context, bool startTrans) void SyncJournalDb::commitIfNeededAndStartNewTransaction(const QString &context) { QMutexLocker lock(&_mutex); - if( _transaction == 1 ) { + if (_transaction == 1) { commitInternal(context, true); } else { startTransaction(); @@ -1766,12 +1758,12 @@ void SyncJournalDb::commitIfNeededAndStartNewTransaction(const QString &context) } -void SyncJournalDb::commitInternal(const QString& context, bool startTrans ) +void SyncJournalDb::commitInternal(const QString &context, bool startTrans) { qCDebug(lcDb) << "Transaction commit " << context << (startTrans ? "and starting new transaction" : ""); commitTransaction(); - if( startTrans ) { + if (startTrans) { startTransaction(); } } @@ -1787,25 +1779,24 @@ bool SyncJournalDb::isConnected() return checkConnect(); } -bool operator==(const SyncJournalDb::DownloadInfo & lhs, - const SyncJournalDb::DownloadInfo & rhs) +bool operator==(const SyncJournalDb::DownloadInfo &lhs, + const SyncJournalDb::DownloadInfo &rhs) { - return lhs._errorCount == rhs._errorCount - && lhs._etag == rhs._etag - && lhs._tmpfile == rhs._tmpfile - && lhs._valid == rhs._valid; - + return lhs._errorCount == rhs._errorCount + && lhs._etag == rhs._etag + && lhs._tmpfile == rhs._tmpfile + && lhs._valid == rhs._valid; } -bool operator==(const SyncJournalDb::UploadInfo & lhs, - const SyncJournalDb::UploadInfo & rhs) +bool operator==(const SyncJournalDb::UploadInfo &lhs, + const SyncJournalDb::UploadInfo &rhs) { - return lhs._errorCount == rhs._errorCount - && lhs._chunk == rhs._chunk - && lhs._modtime == rhs._modtime - && lhs._valid == rhs._valid - && lhs._size == rhs._size - && lhs._transferid == rhs._transferid; + return lhs._errorCount == rhs._errorCount + && lhs._chunk == rhs._chunk + && lhs._modtime == rhs._modtime + && lhs._valid == rhs._valid + && lhs._size == rhs._size + && lhs._transferid == rhs._transferid; } } // namespace OCC diff --git a/src/libsync/syncjournaldb.h b/src/libsync/syncjournaldb.h index cd4572644..21f68a549 100644 --- a/src/libsync/syncjournaldb.h +++ b/src/libsync/syncjournaldb.h @@ -37,53 +37,66 @@ class OWNCLOUDSYNC_EXPORT SyncJournalDb : public QObject { Q_OBJECT public: - explicit SyncJournalDb(const QString& dbFilePath, QObject *parent = 0); + explicit SyncJournalDb(const QString &dbFilePath, QObject *parent = 0); virtual ~SyncJournalDb(); /// Create a journal path for a specific configuration - static QString makeDbName(const QUrl& remoteUrl, - const QString& remotePath, - const QString& user); + static QString makeDbName(const QUrl &remoteUrl, + const QString &remotePath, + const QString &user); /// Migrate a csync_journal to the new path, if necessary. Returns false on error - static bool maybeMigrateDb(const QString& localPath, const QString& absoluteJournalPath); + static bool maybeMigrateDb(const QString &localPath, const QString &absoluteJournalPath); // to verify that the record could be queried successfully check // with SyncJournalFileRecord::isValid() - SyncJournalFileRecord getFileRecord(const QString& filename); - bool setFileRecord( const SyncJournalFileRecord& record ); + SyncJournalFileRecord getFileRecord(const QString &filename); + bool setFileRecord(const SyncJournalFileRecord &record); /// Like setFileRecord, but preserves checksums - bool setFileRecordMetadata( const SyncJournalFileRecord& record ); + bool setFileRecordMetadata(const SyncJournalFileRecord &record); - bool deleteFileRecord( const QString& filename, bool recursively = false ); + bool deleteFileRecord(const QString &filename, bool recursively = false); int getFileRecordCount(); - bool updateFileRecordChecksum(const QString& filename, - const QByteArray& contentChecksum, - const QByteArray& contentChecksumType); - bool updateLocalMetadata(const QString& filename, - qint64 modtime, quint64 size, quint64 inode); + bool updateFileRecordChecksum(const QString &filename, + const QByteArray &contentChecksum, + const QByteArray &contentChecksumType); + bool updateLocalMetadata(const QString &filename, + qint64 modtime, quint64 size, quint64 inode); bool exists(); void walCheckpoint(); QString databaseFilePath() const; - static qint64 getPHash(const QString& ); + static qint64 getPHash(const QString &); - void updateErrorBlacklistEntry( const SyncJournalErrorBlacklistRecord& item ); - void wipeErrorBlacklistEntry(const QString& file); + void updateErrorBlacklistEntry(const SyncJournalErrorBlacklistRecord &item); + void wipeErrorBlacklistEntry(const QString &file); int wipeErrorBlacklist(); int errorBlackListEntryCount(); - struct DownloadInfo { - DownloadInfo() : _errorCount(0), _valid(false) {} + struct DownloadInfo + { + DownloadInfo() + : _errorCount(0) + , _valid(false) + { + } QString _tmpfile; QByteArray _etag; int _errorCount; bool _valid; }; - struct UploadInfo { - UploadInfo() : _chunk(0), _transferid(0), _size(0), _errorCount(0), _valid(false) {} + struct UploadInfo + { + UploadInfo() + : _chunk(0) + , _transferid(0) + , _size(0) + , _errorCount(0) + , _valid(false) + { + } int _chunk; int _transferid; quint64 _size; //currently unused @@ -92,7 +105,8 @@ public: bool _valid; }; - struct PollInfo { + struct PollInfo + { QString _file; QString _url; time_t _modtime; @@ -100,16 +114,16 @@ public: DownloadInfo getDownloadInfo(const QString &file); void setDownloadInfo(const QString &file, const DownloadInfo &i); - QVector getAndDeleteStaleDownloadInfos(const QSet& keep); + QVector getAndDeleteStaleDownloadInfos(const QSet &keep); int downloadInfoCount(); UploadInfo getUploadInfo(const QString &file); void setUploadInfo(const QString &file, const UploadInfo &i); // Return the list of transfer ids that were removed. - QVector deleteStaleUploadInfos(const QSet& keep); + QVector deleteStaleUploadInfos(const QSet &keep); - SyncJournalErrorBlacklistRecord errorBlacklistEntry( const QString& ); - bool deleteStaleErrorBlacklistEntries(const QSet& keep); + SyncJournalErrorBlacklistRecord errorBlacklistEntry(const QString &); + bool deleteStaleErrorBlacklistEntries(const QSet &keep); void avoidRenamesOnNextSync(const QString &path); void setPollInfo(const PollInfo &); @@ -137,7 +151,7 @@ public: * Make sure that on the next sync, fileName is not read from the DB but uses the PROPFIND to * get the info from the server */ - void avoidReadFromDbOnNextSync(const QString& fileName); + void avoidReadFromDbOnNextSync(const QString &fileName); /** * Ensures full remote discovery happens on the next sync. @@ -146,8 +160,8 @@ public: */ void forceRemoteDiscoveryNextSync(); - bool postSyncCleanup(const QSet& filepathsToKeep, - const QSet& prefixesToKeep); + bool postSyncCleanup(const QSet &filepathsToKeep, + const QSet &prefixesToKeep); /* Because sqlite transactions are really slow, we encapsulate everything in big transactions * Commit will actually commit the transaction and create a new one. @@ -184,11 +198,11 @@ private: bool updateDatabaseStructure(); bool updateMetadataTableStructure(); bool updateErrorBlacklistTableStructure(); - bool sqlFail(const QString& log, const SqlQuery &query ); + bool sqlFail(const QString &log, const SqlQuery &query); void commitInternal(const QString &context, bool startTrans = true); void startTransaction(); void commitTransaction(); - QStringList tableColumns( const QString& table ); + QStringList tableColumns(const QString &table); bool checkConnect(); // Same as forceRemoteDiscoveryNextSync but without acquiring the lock @@ -197,7 +211,7 @@ private: // Returns the integer id of the checksum type // // Returns 0 on failure and for empty checksum types. - int mapChecksumType(const QByteArray& checksumType); + int mapChecksumType(const QByteArray &checksumType); SqlDatabase _db; QString _dbFile; @@ -235,11 +249,11 @@ private: }; bool OWNCLOUDSYNC_EXPORT -operator==(const SyncJournalDb::DownloadInfo & lhs, - const SyncJournalDb::DownloadInfo & rhs); +operator==(const SyncJournalDb::DownloadInfo &lhs, + const SyncJournalDb::DownloadInfo &rhs); bool OWNCLOUDSYNC_EXPORT -operator==(const SyncJournalDb::UploadInfo & lhs, - const SyncJournalDb::UploadInfo & rhs); +operator==(const SyncJournalDb::UploadInfo &lhs, + const SyncJournalDb::UploadInfo &rhs); -} // namespace OCC +} // namespace OCC #endif // SYNCJOURNALDB_H diff --git a/src/libsync/syncjournalfilerecord.cpp b/src/libsync/syncjournalfilerecord.cpp index 3025a1002..693778914 100644 --- a/src/libsync/syncjournalfilerecord.cpp +++ b/src/libsync/syncjournalfilerecord.cpp @@ -31,16 +31,24 @@ namespace OCC { Q_LOGGING_CATEGORY(lcFileRecord, "sync.database.filerecord", QtInfoMsg) SyncJournalFileRecord::SyncJournalFileRecord() - :_inode(0), _type(0), _fileSize(0), _serverHasIgnoredFiles(false) + : _inode(0) + , _type(0) + , _fileSize(0) + , _serverHasIgnoredFiles(false) { } SyncJournalFileRecord::SyncJournalFileRecord(const SyncFileItem &item, const QString &localFileName) - : _path(item._file), _modtime(Utility::qDateTimeFromTime_t(item._modtime)), - _type(item._type), _etag(item._etag), _fileId(item._fileId), _fileSize(item._size), - _remotePerm(item._remotePerm), _serverHasIgnoredFiles(item._serverHasIgnoredFiles), - _contentChecksum(item._contentChecksum), - _contentChecksumType(item._contentChecksumType) + : _path(item._file) + , _modtime(Utility::qDateTimeFromTime_t(item._modtime)) + , _type(item._type) + , _etag(item._etag) + , _fileId(item._fileId) + , _fileSize(item._size) + , _remotePerm(item._remotePerm) + , _serverHasIgnoredFiles(item._serverHasIgnoredFiles) + , _contentChecksum(item._contentChecksum) + , _contentChecksumType(item._contentChecksumType) { // use the "old" inode coming with the item for the case where the // filesystem stat fails. That can happen if the the file was removed @@ -53,15 +61,15 @@ SyncJournalFileRecord::SyncJournalFileRecord(const SyncFileItem &item, const QSt based on code from csync_vio_local.c (csync_vio_local_stat) Get the Windows file id as an inode replacement. */ - HANDLE h = CreateFileW( (wchar_t*) FileSystem::longWinPath(localFileName).utf16(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL+FILE_FLAG_BACKUP_SEMANTICS, NULL ); + HANDLE h = CreateFileW((wchar_t *)FileSystem::longWinPath(localFileName).utf16(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL + FILE_FLAG_BACKUP_SEMANTICS, NULL); - if( h == INVALID_HANDLE_VALUE ) { + if (h == INVALID_HANDLE_VALUE) { qCWarning(lcFileRecord) << "Failed to query the 'inode' because CreateFileW failed for file " << localFileName; } else { BY_HANDLE_FILE_INFORMATION fileInfo; - if( GetFileInformationByHandle( h, &fileInfo ) ) { + if (GetFileInformationByHandle(h, &fileInfo)) { ULARGE_INTEGER FileIndex; FileIndex.HighPart = fileInfo.nFileIndexHigh; FileIndex.LowPart = fileInfo.nFileIndexLow; @@ -72,20 +80,18 @@ SyncJournalFileRecord::SyncJournalFileRecord(const SyncFileItem &item, const QSt _inode = FileIndex.QuadPart; } else { qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName; - } CloseHandle(h); } #else struct stat sb; - if( stat(QFile::encodeName(localFileName).constData(), &sb) < 0) { + if (stat(QFile::encodeName(localFileName).constData(), &sb) < 0) { qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName; } else { _inode = sb.st_ino; } #endif qCDebug(lcFileRecord) << localFileName << "Retrieved inode " << _inode << "(previous item inode: " << item._inode << ")"; - } SyncFileItem SyncJournalFileRecord::toSyncFileItem() @@ -107,25 +113,24 @@ SyncFileItem SyncJournalFileRecord::toSyncFileItem() bool SyncJournalErrorBlacklistRecord::isValid() const { - return ! _file.isEmpty() + return !_file.isEmpty() && (!_lastTryEtag.isEmpty() || _lastTryModtime != 0) && _lastTryTime > 0; } -bool operator==(const SyncJournalFileRecord & lhs, - const SyncJournalFileRecord & rhs) +bool operator==(const SyncJournalFileRecord &lhs, + const SyncJournalFileRecord &rhs) { - return lhs._path == rhs._path - && lhs._inode == rhs._inode - && lhs._modtime.toTime_t() == rhs._modtime.toTime_t() - && lhs._type == rhs._type - && lhs._etag == rhs._etag - && lhs._fileId == rhs._fileId - && lhs._fileSize == rhs._fileSize - && lhs._remotePerm == rhs._remotePerm - && lhs._serverHasIgnoredFiles == rhs._serverHasIgnoredFiles - && lhs._contentChecksum == rhs._contentChecksum - && lhs._contentChecksumType == rhs._contentChecksumType; + return lhs._path == rhs._path + && lhs._inode == rhs._inode + && lhs._modtime.toTime_t() == rhs._modtime.toTime_t() + && lhs._type == rhs._type + && lhs._etag == rhs._etag + && lhs._fileId == rhs._fileId + && lhs._fileSize == rhs._fileSize + && lhs._remotePerm == rhs._remotePerm + && lhs._serverHasIgnoredFiles == rhs._serverHasIgnoredFiles + && lhs._contentChecksum == rhs._contentChecksum + && lhs._contentChecksumType == rhs._contentChecksumType; } - } diff --git a/src/libsync/syncjournalfilerecord.h b/src/libsync/syncjournalfilerecord.h index 1debbacb7..f96e85b3b 100644 --- a/src/libsync/syncjournalfilerecord.h +++ b/src/libsync/syncjournalfilerecord.h @@ -34,7 +34,7 @@ public: SyncJournalFileRecord(); /// Creates a record from an existing item while updating the inode - SyncJournalFileRecord(const SyncFileItem&, const QString &localFileName); + SyncJournalFileRecord(const SyncFileItem &, const QString &localFileName); /** Creates a basic SyncFileItem from the record * @@ -43,26 +43,27 @@ public: */ SyncFileItem toSyncFileItem(); - bool isValid() { + bool isValid() + { return !_path.isEmpty(); } - QString _path; - quint64 _inode; - QDateTime _modtime; - int _type; + QString _path; + quint64 _inode; + QDateTime _modtime; + int _type; QByteArray _etag; QByteArray _fileId; - qint64 _fileSize; + qint64 _fileSize; QByteArray _remotePerm; - bool _serverHasIgnoredFiles; + bool _serverHasIgnoredFiles; QByteArray _contentChecksum; QByteArray _contentChecksumType; }; bool OWNCLOUDSYNC_EXPORT -operator==(const SyncJournalFileRecord & lhs, - const SyncJournalFileRecord & rhs); +operator==(const SyncJournalFileRecord &lhs, + const SyncJournalFileRecord &rhs); class SyncJournalErrorBlacklistRecord { @@ -72,29 +73,29 @@ public: , _lastTryModtime(0) , _lastTryTime(0) , _ignoreDuration(0) - {} + { + } /// The number of times the operation was unsuccessful so far. - int _retryCount; + int _retryCount; /// The last error string. - QString _errorString; + QString _errorString; - time_t _lastTryModtime; + time_t _lastTryModtime; QByteArray _lastTryEtag; /// The last time the operation was attempted (in s since epoch). - time_t _lastTryTime; + time_t _lastTryTime; /// The number of seconds the file shall be ignored. - time_t _ignoreDuration; + time_t _ignoreDuration; - QString _file; - QString _renameTarget; + QString _file; + QString _renameTarget; bool isValid() const; }; - } #endif // SYNCJOURNALFILERECORD_H diff --git a/src/libsync/syncresult.cpp b/src/libsync/syncresult.cpp index 625ebae2c..de5c81c54 100644 --- a/src/libsync/syncresult.cpp +++ b/src/libsync/syncresult.cpp @@ -15,11 +15,10 @@ #include "syncresult.h" #include "progressdispatcher.h" -namespace OCC -{ +namespace OCC { SyncResult::SyncResult() - : _status( Undefined ) + : _status(Undefined) , _foundFilesNotSynced(false) , _folderStructureWasChanged(false) , _numNewItems(0) @@ -47,7 +46,7 @@ QString SyncResult::statusString() const QString re; Status stat = status(); - switch( stat ){ + switch (stat) { case Undefined: re = QLatin1String("Undefined"); break; @@ -82,7 +81,7 @@ QString SyncResult::statusString() const return re; } -void SyncResult::setStatus( Status stat ) +void SyncResult::setStatus(Status stat) { _status = stat; _syncTime = QDateTime::currentDateTime(); @@ -98,14 +97,15 @@ QStringList SyncResult::errorStrings() const return _errors; } -void SyncResult::appendErrorString( const QString& err ) +void SyncResult::appendErrorString(const QString &err) { - _errors.append( err ); + _errors.append(err); } QString SyncResult::errorString() const { - if( _errors.isEmpty() ) return QString::null; + if (_errors.isEmpty()) + return QString::null; return _errors.first(); } @@ -114,7 +114,7 @@ void SyncResult::clearErrors() _errors.clear(); } -void SyncResult::setFolder(const QString& folder) +void SyncResult::setFolder(const QString &folder) { _folder = folder; } @@ -132,21 +132,21 @@ void SyncResult::processCompletedItem(const SyncFileItemPtr &item) } if (item->_isDirectory && (item->_instruction == CSYNC_INSTRUCTION_NEW - || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE - || item->_instruction == CSYNC_INSTRUCTION_REMOVE - || item->_instruction == CSYNC_INSTRUCTION_RENAME)) { + || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE + || item->_instruction == CSYNC_INSTRUCTION_REMOVE + || item->_instruction == CSYNC_INSTRUCTION_RENAME)) { _folderStructureWasChanged = true; } // Process the item to the gui - if( item->_status == SyncFileItem::FatalError || item->_status == SyncFileItem::NormalError ) { + if (item->_status == SyncFileItem::FatalError || item->_status == SyncFileItem::NormalError) { //: this displays an error string (%2) for a file %1 - appendErrorString( QObject::tr("%1: %2").arg(item->_file, item->_errorString) ); + appendErrorString(QObject::tr("%1: %2").arg(item->_file, item->_errorString)); _numErrorItems++; if (!_firstItemError) { _firstItemError = item; } - } else if( item->_status == SyncFileItem::Conflict ) { + } else if (item->_status == SyncFileItem::Conflict) { _numConflictItems++; if (!_firstConflictItem) { _firstConflictItem = item; @@ -180,13 +180,12 @@ void SyncResult::processCompletedItem(const SyncFileItemPtr &item) // nothing. break; } - } else if( item->_direction == SyncFileItem::None ) { - if( item->_instruction == CSYNC_INSTRUCTION_IGNORE ) { + } else if (item->_direction == SyncFileItem::None) { + if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) { _foundFilesNotSynced = true; } } } - } } // ns mirall diff --git a/src/libsync/syncresult.h b/src/libsync/syncresult.h index 0c630f737..7c5e501aa 100644 --- a/src/libsync/syncresult.h +++ b/src/libsync/syncresult.h @@ -22,8 +22,7 @@ #include "owncloudlib.h" #include "syncfileitem.h" -namespace OCC -{ +namespace OCC { /** * @brief The SyncResult class @@ -32,33 +31,32 @@ namespace OCC class OWNCLOUDSYNC_EXPORT SyncResult { public: - enum Status - { - Undefined, - NotYetStarted, - SyncPrepare, - SyncRunning, - SyncAbortRequested, - Success, - Problem, - Error, - SetupError, - Paused + enum Status { + Undefined, + NotYetStarted, + SyncPrepare, + SyncRunning, + SyncAbortRequested, + Success, + Problem, + Error, + SetupError, + Paused }; SyncResult(); void reset(); - void appendErrorString( const QString& ); + void appendErrorString(const QString &); QString errorString() const; QStringList errorStrings() const; - void clearErrors(); + void clearErrors(); - void setStatus( Status ); + void setStatus(Status); Status status() const; QString statusString() const; QDateTime syncTime() const; - void setFolder(const QString& folder); + void setFolder(const QString &folder); QString folder() const; bool foundFilesNotSynced() const { return _foundFilesNotSynced; } @@ -71,24 +69,24 @@ public: int numConflictItems() const { return _numConflictItems; } int numErrorItems() const { return _numErrorItems; } - const SyncFileItemPtr& firstItemNew() const { return _firstItemNew; } - const SyncFileItemPtr& firstItemDeleted() const { return _firstItemDeleted; } - const SyncFileItemPtr& firstItemUpdated() const { return _firstItemUpdated; } - const SyncFileItemPtr& firstItemRenamed() const { return _firstItemRenamed; } - const SyncFileItemPtr& firstConflictItem() const { return _firstConflictItem; } - const SyncFileItemPtr& firstItemError() const { return _firstItemError; } + const SyncFileItemPtr &firstItemNew() const { return _firstItemNew; } + const SyncFileItemPtr &firstItemDeleted() const { return _firstItemDeleted; } + const SyncFileItemPtr &firstItemUpdated() const { return _firstItemUpdated; } + const SyncFileItemPtr &firstItemRenamed() const { return _firstItemRenamed; } + const SyncFileItemPtr &firstConflictItem() const { return _firstConflictItem; } + const SyncFileItemPtr &firstItemError() const { return _firstItemError; } void processCompletedItem(const SyncFileItemPtr &item); private: - Status _status; + Status _status; SyncFileItemVector _syncItems; - QDateTime _syncTime; - QString _folder; + QDateTime _syncTime; + QString _folder; /** * when the sync tool support this... */ - QStringList _errors; + QStringList _errors; bool _foundFilesNotSynced; bool _folderStructureWasChanged; @@ -107,7 +105,6 @@ private: SyncFileItemPtr _firstConflictItem; SyncFileItemPtr _firstItemError; }; - } #endif diff --git a/src/libsync/theme.cpp b/src/libsync/theme.cpp index 2f7b288a7..9dd1c88a9 100644 --- a/src/libsync/theme.cpp +++ b/src/libsync/theme.cpp @@ -28,18 +28,19 @@ #include "owncloudtheme.h" #ifdef THEME_INCLUDE -# define Mirall OCC // namespace hack to make old themes work -# define QUOTEME(M) #M -# define INCLUDE_FILE(M) QUOTEME(M) -# include INCLUDE_FILE(THEME_INCLUDE) -# undef Mirall +#define Mirall OCC // namespace hack to make old themes work +#define QUOTEME(M) #M +#define INCLUDE_FILE(M) QUOTEME(M) +#include INCLUDE_FILE(THEME_INCLUDE) +#undef Mirall #endif namespace OCC { -Theme* Theme::_instance = 0; +Theme *Theme::_instance = 0; -Theme* Theme::instance() { +Theme *Theme::instance() +{ if (!_instance) { _instance = new THEME_CLASS; // some themes may not call the base ctor @@ -48,13 +49,15 @@ Theme* Theme::instance() { return _instance; } -Theme::~Theme() {} +Theme::~Theme() +{ +} -QString Theme::statusHeaderText( SyncResult::Status status ) const +QString Theme::statusHeaderText(SyncResult::Status status) const { QString resultStr; - switch( status ) { + switch (status) { case SyncResult::Undefined: resultStr = QCoreApplication::translate("theme", "Status undefined"); break; @@ -74,13 +77,13 @@ QString Theme::statusHeaderText( SyncResult::Status status ) const resultStr = QCoreApplication::translate("theme", "Sync Error"); break; case SyncResult::SetupError: - resultStr = QCoreApplication::translate("theme", "Setup Error" ); + resultStr = QCoreApplication::translate("theme", "Setup Error"); break; case SyncResult::SyncPrepare: - resultStr = QCoreApplication::translate("theme", "Preparing to sync" ); + resultStr = QCoreApplication::translate("theme", "Preparing to sync"); break; case SyncResult::SyncAbortRequested: - resultStr = QCoreApplication::translate("theme", "Aborting..." ); + resultStr = QCoreApplication::translate("theme", "Aborting..."); break; case SyncResult::Paused: resultStr = QCoreApplication::translate("theme", "Sync is paused"); @@ -106,7 +109,7 @@ QString Theme::version() const #ifndef TOKEN_AUTH_ONLY -QIcon Theme::trayFolderIcon( const QString& backend ) const +QIcon Theme::trayFolderIcon(const QString &backend) const { Q_UNUSED(backend) return applicationIcon(); @@ -116,7 +119,7 @@ QIcon Theme::trayFolderIcon( const QString& backend ) const * helper to load a icon from either the icon theme the desktop provides or from * the apps Qt resources. */ -QIcon Theme::themeIcon( const QString& name, bool sysTray, bool sysTrayMenuVisible ) const +QIcon Theme::themeIcon(const QString &name, bool sysTray, bool sysTrayMenuVisible) const { QString flavor; if (sysTray) { @@ -126,15 +129,15 @@ QIcon Theme::themeIcon( const QString& name, bool sysTray, bool sysTrayMenuVisib } QString key = name + "," + flavor; - QIcon & cached = _iconCache[key]; + QIcon &cached = _iconCache[key]; if (cached.isNull()) { - if(QIcon::hasThemeIcon(name)) { + if (QIcon::hasThemeIcon(name)) { // use from theme return cached = QIcon::fromTheme(name); } QList sizes; - sizes <<16 << 22 << 32 << 48 << 64 << 128 << 256; + sizes << 16 << 22 << 32 << 48 << 64 << 128 << 256; foreach (int size, sizes) { QString pixmapName = QString::fromLatin1(":/client/theme/%1/%2-%3.png").arg(flavor).arg(name).arg(size); if (QFile::exists(pixmapName)) { @@ -159,54 +162,52 @@ QIcon Theme::themeIcon( const QString& name, bool sysTray, bool sysTrayMenuVisib } } - #ifdef Q_OS_MAC - #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) +#ifdef Q_OS_MAC +#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) // This defines the icon as a template and enables automatic macOS color handling // See https://bugreports.qt.io/browse/QTBUG-42109 cached.setIsMask(_mono && sysTray && !sysTrayMenuVisible); - #endif - #endif +#endif +#endif return cached; } QString Theme::hidpiFileName(const QString &fileName, QPaintDevice *dev) { - #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0) - qreal devicePixelRatio = dev ? dev->devicePixelRatio() : - qApp->primaryScreen()->devicePixelRatio(); +#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0) + qreal devicePixelRatio = dev ? dev->devicePixelRatio() : qApp->primaryScreen()->devicePixelRatio(); if (devicePixelRatio <= 1.0) { return fileName; } // try to find a 2x version - const int dotIndex = fileName.lastIndexOf(QLatin1Char('.')); if (dotIndex != -1) { QString at2xfileName = fileName; at2xfileName.insert(dotIndex, QStringLiteral("@2x")); - if (QFile::exists(at2xfileName)) { + if (QFile::exists(at2xfileName)) { return at2xfileName; } } - #endif +#endif return fileName; } #endif -Theme::Theme() : - QObject(0) - ,_mono(false) +Theme::Theme() + : QObject(0) + , _mono(false) { - } // If this option returns true, the client only supports one folder to sync. // The Add-Button is removed accordingly. -bool Theme::singleSyncFolder() const { +bool Theme::singleSyncFolder() const +{ return false; } @@ -236,18 +237,18 @@ QString Theme::defaultClientFolder() const return appName(); } -QString Theme::systrayIconFlavor(bool mono, bool sysTrayMenuVisible ) const +QString Theme::systrayIconFlavor(bool mono, bool sysTrayMenuVisible) const { Q_UNUSED(sysTrayMenuVisible) QString flavor; if (mono) { flavor = Utility::hasDarkSystray() ? QLatin1String("white") : QLatin1String("black"); - #ifdef Q_OS_MAC +#ifdef Q_OS_MAC if (sysTrayMenuVisible) { flavor = QLatin1String("white"); } - #endif +#endif } else { flavor = QLatin1String("colored"); } @@ -297,19 +298,20 @@ QString Theme::gitSHA1() const QString devString; #ifdef GIT_SHA1 const QString githubPrefix(QLatin1String( - "https://github.com/owncloud/client/commit/")); + "https://github.com/owncloud/client/commit/")); const QString gitSha1(QLatin1String(GIT_SHA1)); devString = QCoreApplication::translate("ownCloudTheme::about()", - "

Built from Git revision %2" - " on %3, %4 using Qt %5, %6

") - .arg(githubPrefix+gitSha1).arg(gitSha1.left(6)) - .arg(__DATE__).arg(__TIME__) - .arg(QString::fromAscii(qVersion())) + "

Built from Git revision %2" + " on %3, %4 using Qt %5, %6

") + .arg(githubPrefix + gitSha1) + .arg(gitSha1.left(6)) + .arg(__DATE__) + .arg(__TIME__) + .arg(QString::fromAscii(qVersion())) #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - .arg(QSslSocket::sslLibraryVersionString()); + .arg(QSslSocket::sslLibraryVersionString()); #else - .arg(QCoreApplication::translate("ownCloudTheme::about()", "built with %1").arg( - QString::fromAscii(OPENSSL_VERSION_TEXT))); + .arg(QCoreApplication::translate("ownCloudTheme::about()", "built with %1").arg(QString::fromAscii(OPENSSL_VERSION_TEXT))); #endif #endif return devString; @@ -319,27 +321,28 @@ QString Theme::about() const { QString re; re = tr("

Version %1. For more information please visit %3.

") - .arg(MIRALL_VERSION_STRING).arg("http://" MIRALL_STRINGIFY(APPLICATION_DOMAIN)) - .arg(MIRALL_STRINGIFY(APPLICATION_DOMAIN)); + .arg(MIRALL_VERSION_STRING) + .arg("http://" MIRALL_STRINGIFY(APPLICATION_DOMAIN)) + .arg(MIRALL_STRINGIFY(APPLICATION_DOMAIN)); re += tr("

Copyright ownCloud GmbH

"); re += tr("

Distributed by %1 and licensed under the GNU General Public License (GPL) Version 2.0.
" "%2 and the %2 logo are registered trademarks of %1 in the " "United States, other countries, or both.

") - .arg(APPLICATION_VENDOR).arg(APPLICATION_NAME); + .arg(APPLICATION_VENDOR) + .arg(APPLICATION_NAME); re += gitSHA1(); return re; } #ifndef TOKEN_AUTH_ONLY -QVariant Theme::customMedia( CustomMediaType type ) +QVariant Theme::customMedia(CustomMediaType type) { QVariant re; QString key; - switch ( type ) - { + switch (type) { case oCSetupTop: key = QLatin1String("oCSetupTop"); break; @@ -355,24 +358,24 @@ QVariant Theme::customMedia( CustomMediaType type ) } QString imgPath = QString::fromLatin1(":/client/theme/colored/%1.png").arg(key); - if ( QFile::exists( imgPath ) ) { - QPixmap pix( imgPath ); - if( pix.isNull() ) { + if (QFile::exists(imgPath)) { + QPixmap pix(imgPath); + if (pix.isNull()) { // pixmap loading hasn't succeeded. We take the text instead. - re.setValue( key ); + re.setValue(key); } else { - re.setValue( pix ); + re.setValue(pix); } } return re; } -QIcon Theme::syncStateIcon( SyncResult::Status status, bool sysTray, bool sysTrayMenuVisible ) const +QIcon Theme::syncStateIcon(SyncResult::Status status, bool sysTray, bool sysTrayMenuVisible) const { // FIXME: Mind the size! QString statusIcon; - switch( status ) { + switch (status) { case SyncResult::Undefined: // this can happen if no sync connections are configured. statusIcon = QLatin1String("state-information"); @@ -394,22 +397,22 @@ QIcon Theme::syncStateIcon( SyncResult::Status status, bool sysTray, bool sysTra break; case SyncResult::Error: case SyncResult::SetupError: - // FIXME: Use state-problem once we have an icon. + // FIXME: Use state-problem once we have an icon. default: statusIcon = QLatin1String("state-error"); } - return themeIcon( statusIcon, sysTray, sysTrayMenuVisible ); + return themeIcon(statusIcon, sysTray, sysTrayMenuVisible); } -QIcon Theme::folderDisabledIcon( ) const +QIcon Theme::folderDisabledIcon() const { - return themeIcon( QLatin1String("state-pause") ); + return themeIcon(QLatin1String("state-pause")); } -QIcon Theme::folderOfflineIcon(bool sysTray, bool sysTrayMenuVisible ) const +QIcon Theme::folderOfflineIcon(bool sysTray, bool sysTrayMenuVisible) const { - return themeIcon( QLatin1String("state-offline"), sysTray, sysTrayMenuVisible ); + return themeIcon(QLatin1String("state-offline"), sysTray, sysTrayMenuVisible); } QColor Theme::wizardHeaderTitleColor() const diff --git a/src/libsync/theme.h b/src/libsync/theme.h index a3fd81c70..cc51251df 100644 --- a/src/libsync/theme.h +++ b/src/libsync/theme.h @@ -38,14 +38,14 @@ class OWNCLOUDSYNC_EXPORT Theme : public QObject Q_OBJECT public: enum CustomMediaType { - oCSetupTop, // ownCloud connect page + oCSetupTop, // ownCloud connect page oCSetupSide, oCSetupBottom, oCSetupResultTop // ownCloud connect result page }; /* returns a singleton instance. */ - static Theme* instance(); + static Theme *instance(); ~Theme(); @@ -92,19 +92,19 @@ public: /** * the icon that is shown in the tray context menu left of the folder name */ - virtual QIcon trayFolderIcon( const QString& ) const; + virtual QIcon trayFolderIcon(const QString &) const; /** * get an sync state icon */ - virtual QIcon syncStateIcon( SyncResult::Status, bool sysTray = false, bool sysTrayMenuVisible = false) const; + virtual QIcon syncStateIcon(SyncResult::Status, bool sysTray = false, bool sysTrayMenuVisible = false) const; - virtual QIcon folderDisabledIcon() const; - virtual QIcon folderOfflineIcon(bool sysTray = false, bool sysTrayMenuVisible = false) const; - virtual QIcon applicationIcon() const = 0; + virtual QIcon folderDisabledIcon() const; + virtual QIcon folderOfflineIcon(bool sysTray = false, bool sysTrayMenuVisible = false) const; + virtual QIcon applicationIcon() const = 0; #endif - virtual QString statusHeaderText( SyncResult::Status ) const; + virtual QString statusHeaderText(SyncResult::Status) const; virtual QString version() const; /** @@ -160,7 +160,7 @@ public: * The default implementation will try to look up * :/client/theme/.png */ - virtual QVariant customMedia( CustomMediaType type ); + virtual QVariant customMedia(CustomMediaType type); /** @return color for the setup wizard */ virtual QColor wizardHeaderTitleColor() const; @@ -266,7 +266,9 @@ public: * @value UserIDEmail Wizard asks for an email as ID * @value UserIDCustom Specify string in \ref customUserID */ - enum UserIDType { UserIDUserName = 0, UserIDEmail, UserIDCustom }; + enum UserIDType { UserIDUserName = 0, + UserIDEmail, + UserIDCustom }; /** @brief What to display as the userID (e.g. in the wizards) * @@ -321,7 +323,7 @@ public: protected: #ifndef TOKEN_AUTH_ONLY - QIcon themeIcon(const QString& name, bool sysTray = false, bool sysTrayMenuVisible = false) const; + QIcon themeIcon(const QString &name, bool sysTray = false, bool sysTrayMenuVisible = false) const; #endif Theme(); @@ -329,15 +331,14 @@ signals: void systrayUseMonoIconsChanged(bool); private: - Theme(Theme const&); - Theme& operator=(Theme const&); + Theme(Theme const &); + Theme &operator=(Theme const &); - static Theme* _instance; + static Theme *_instance; bool _mono; #ifndef TOKEN_AUTH_ONLY mutable QHash _iconCache; #endif }; - } #endif // _THEME_H diff --git a/src/libsync/utility.cpp b/src/libsync/utility.cpp index 1f1139d9e..b3813f14b 100644 --- a/src/libsync/utility.cpp +++ b/src/libsync/utility.cpp @@ -65,42 +65,42 @@ namespace OCC { Q_LOGGING_CATEGORY(lcUtility, "sync.utility", QtInfoMsg) -bool Utility::writeRandomFile( const QString& fname, int size ) +bool Utility::writeRandomFile(const QString &fname, int size) { - int maxSize = 10*10*1024; + int maxSize = 10 * 10 * 1024; qsrand(QDateTime::currentMSecsSinceEpoch()); - if( size == -1 ) size = qrand() % maxSize; + if (size == -1) + size = qrand() % maxSize; QString randString; - for( int i = 0; i < size; i++ ) { + for (int i = 0; i < size; i++) { int r = qrand() % 128; randString.append(QChar(r)); } QFile file(fname); - if( file.open(QIODevice::WriteOnly | QIODevice::Text) ) { + if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out << randString; - // optional, as QFile destructor will already do it: + // optional, as QFile destructor will already do it: file.close(); return true; } return false; - } -QString Utility::formatFingerprint( const QByteArray& fmhash, bool colonSeparated ) +QString Utility::formatFingerprint(const QByteArray &fmhash, bool colonSeparated) { QByteArray hash; - int steps = fmhash.length()/2; + int steps = fmhash.length() / 2; for (int i = 0; i < steps; i++) { - hash.append(fmhash[i*2]); - hash.append(fmhash[i*2+1]); + hash.append(fmhash[i * 2]); + hash.append(fmhash[i * 2 + 1]); hash.append(' '); } - QString fp = QString::fromLatin1( hash.trimmed() ); + QString fp = QString::fromLatin1(hash.trimmed()); if (colonSeparated) { fp.replace(QChar(' '), QChar(':')); } @@ -113,7 +113,7 @@ void Utility::setupFavLink(const QString &folder) setupFavLink_private(folder); } -QString Utility::octetsToString( qint64 octets ) +QString Utility::octetsToString(qint64 octets) { #define THE_FACTOR 1024 static const qint64 kb = THE_FACTOR; @@ -142,7 +142,7 @@ QString Utility::octetsToString( qint64 octets ) } else if (octets >= kb) { s = QCoreApplication::translate("Utility", "%L1 KB"); value /= kb; - } else { + } else { s = QCoreApplication::translate("Utility", "%L1 B"); } @@ -189,7 +189,7 @@ QByteArray Utility::userAgentString() // this constant "ownCloud" is defined in the default OEM theming // that is used for the standard client. If it is changed there, // it needs to be adjusted here. - if( appName != QLatin1String("ownCloud") ) { + if (appName != QLatin1String("ownCloud")) { re += QString(" (%1)").arg(appName); } return re.toLatin1(); @@ -200,7 +200,7 @@ bool Utility::hasLaunchOnStartup(const QString &appName) return hasLaunchOnStartup_private(appName); } -void Utility::setLaunchOnStartup(const QString &appName, const QString& guiName, bool enable) +void Utility::setLaunchOnStartup(const QString &appName, const QString &guiName, bool enable) { setLaunchOnStartup_private(appName, guiName, enable); } @@ -210,24 +210,24 @@ qint64 Utility::freeDiskSpace(const QString &path) #if defined(Q_OS_MAC) || defined(Q_OS_FREEBSD) || defined(Q_OS_FREEBSD_KERNEL) || defined(Q_OS_NETBSD) || defined(Q_OS_OPENBSD) struct statvfs stat; if (statvfs(path.toLocal8Bit().data(), &stat) == 0) { - return (qint64) stat.f_bavail * stat.f_frsize; + return (qint64)stat.f_bavail * stat.f_frsize; } #elif defined(Q_OS_UNIX) struct statvfs64 stat; if (statvfs64(path.toLocal8Bit().data(), &stat) == 0) { - return (qint64) stat.f_bavail * stat.f_frsize; + return (qint64)stat.f_bavail * stat.f_frsize; } #elif defined(Q_OS_WIN) ULARGE_INTEGER freeBytes; freeBytes.QuadPart = 0L; - if (GetDiskFreeSpaceEx( reinterpret_cast(path.utf16()), &freeBytes, NULL, NULL )) { + if (GetDiskFreeSpaceEx(reinterpret_cast(path.utf16()), &freeBytes, NULL, NULL)) { return freeBytes.QuadPart; } #endif return -1; } -QString Utility::compactFormatDouble(double value, int prec, const QString& unit) +QString Utility::compactFormatDouble(double value, int prec, const QString &unit) { QLocale locale = QLocale::system(); QChar decPoint = locale.decimalPoint(); @@ -239,8 +239,8 @@ QString Utility::compactFormatDouble(double value, int prec, const QString& unit } str.chop(1); } - if( !unit.isEmpty() ) - str += (QLatin1Char(' ')+unit); + if (!unit.isEmpty()) + str += (QLatin1Char(' ') + unit); return str; } @@ -256,7 +256,8 @@ QString Utility::escape(const QString &in) #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // In Qt 4, QThread::sleep functions are protected. // This is a hack to make them visible in this namespace. -struct QThread : ::QThread { +struct QThread : ::QThread +{ using ::QThread::sleep; using ::QThread::usleep; }; @@ -283,7 +284,7 @@ bool Utility::fsCasePreserving() return isWindows() || isMac(); } -bool Utility::fileNamesEqual( const QString& fn1, const QString& fn2) +bool Utility::fileNamesEqual(const QString &fn1, const QString &fn2) { const QDir fd1(fn1); const QDir fd2(fn2); @@ -291,9 +292,8 @@ bool Utility::fileNamesEqual( const QString& fn1, const QString& fn2) // Attention: If the path does not exist, canonicalPath returns "" // ONLY use this function with existing pathes. const QString a = fd1.canonicalPath(); - const QString b = fd2.canonicalPath(); - bool re = !a.isEmpty() && QString::compare( a, b, - fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive) == 0; + const QString b = fd2.canonicalPath(); + bool re = !a.isEmpty() && QString::compare(a, b, fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive) == 0; return re; } @@ -302,7 +302,7 @@ QDateTime Utility::qDateTimeFromTime_t(qint64 t) return QDateTime::fromMSecsSinceEpoch(t * 1000); } -qint64 Utility::qDateTimeToTime_t(const QDateTime& t) +qint64 Utility::qDateTimeToTime_t(const QDateTime &t) { return t.toMSecsSinceEpoch() / 1000; } @@ -316,8 +316,8 @@ namespace { QString description(quint64 value) const { return QCoreApplication::translate( - "Utility", name, 0, QCoreApplication::UnicodeUTF8, - value); + "Utility", name, 0, QCoreApplication::UnicodeUTF8, + value); } }; // QTBUG-3945 and issue #4855: QT_TRANSLATE_NOOP does not work with plural form because lupdate @@ -326,12 +326,12 @@ namespace { #undef QT_TRANSLATE_NOOP #define QT_TRANSLATE_NOOP(ctx, str, ...) str Q_DECL_CONSTEXPR Period periods[] = { - { QT_TRANSLATE_NOOP("Utility", "%n year(s)" , 0, _) , 365*24*3600*1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n month(s)", 0, _) , 30*24*3600*1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n day(s)", 0, _) , 24*3600*1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n hour(s)", 0, _) , 3600*1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n minute(s)", 0, _) , 60*1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n second(s)", 0, _ ), 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n year(s)", 0, _), 365 * 24 * 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n month(s)", 0, _), 30 * 24 * 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n day(s)", 0, _), 24 * 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n hour(s)", 0, _), 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n minute(s)", 0, _), 60 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n second(s)", 0, _), 1000LL }, { 0, 0 } }; } // anonymous namespace @@ -339,40 +339,39 @@ namespace { QString Utility::durationToDescriptiveString2(quint64 msecs) { int p = 0; - while (periods[p+1].name && msecs < periods[p].msec) { + while (periods[p + 1].name && msecs < periods[p].msec) { p++; } auto firstPart = periods[p].description(int(msecs / periods[p].msec)); - if (!periods[p+1].name) { + if (!periods[p + 1].name) { return firstPart; } - quint64 secondPartNum = qRound( double(msecs % periods[p].msec) / periods[p+1].msec); + quint64 secondPartNum = qRound(double(msecs % periods[p].msec) / periods[p + 1].msec); if (secondPartNum == 0) { return firstPart; } - return QCoreApplication::translate("Utility", "%1 %2").arg(firstPart, - periods[p+1].description(secondPartNum)); + return QCoreApplication::translate("Utility", "%1 %2").arg(firstPart, periods[p + 1].description(secondPartNum)); } QString Utility::durationToDescriptiveString1(quint64 msecs) { int p = 0; - while (periods[p+1].name && msecs < periods[p].msec) { + while (periods[p + 1].name && msecs < periods[p].msec) { p++; } - quint64 amount = qRound( double(msecs) / periods[p].msec ); + quint64 amount = qRound(double(msecs) / periods[p].msec); return periods[p].description(amount); } -QString Utility::fileNameForGuiUse(const QString& fName) +QString Utility::fileNameForGuiUse(const QString &fName) { - if( isMac() ) { + if (isMac()) { QString n(fName); return n.replace(QChar(':'), QChar('/')); } @@ -435,13 +434,13 @@ QString Utility::platformName() QString re("Windows"); #if QT_VERSION < QT_VERSION_CHECK(5, 4, 0) - if( isMac() ) { + if (isMac()) { re = QLatin1String("MacOSX"); - } else if( isLinux() ) { + } else if (isLinux()) { re = QLatin1String("Linux"); - } else if( isBSD() ) { + } else if (isBSD()) { re = QLatin1String("BSD"); - } else if( isUnix() ) { + } else if (isUnix()) { re = QLatin1String("Unix"); } #else @@ -452,7 +451,7 @@ QString Utility::platformName() void Utility::crash() { - volatile int* a = (int*)(NULL); + volatile int *a = (int *)(NULL); *a = 1; } @@ -463,12 +462,12 @@ void Utility::crash() // // This version only delivers output on linux, as Mac and Win get their // restarting from the installer. -QByteArray Utility::versionOfInstalledBinary( const QString& command ) +QByteArray Utility::versionOfInstalledBinary(const QString &command) { QByteArray re; - if( isLinux() ) { + if (isLinux()) { QString binary(command); - if( binary.isEmpty() ) { + if (binary.isEmpty()) { binary = qApp->arguments()[0]; } QStringList params; @@ -478,42 +477,42 @@ QByteArray Utility::versionOfInstalledBinary( const QString& command ) process.waitForFinished(); // sets current thread to sleep and waits for pingProcess end re = process.readAllStandardOutput(); int newline = re.indexOf(QChar('\n')); - if( newline > 0 ) { - re.truncate( newline ); + if (newline > 0) { + re.truncate(newline); } } return re; } -QString Utility::timeAgoInWords(const QDateTime& dt, const QDateTime& from) +QString Utility::timeAgoInWords(const QDateTime &dt, const QDateTime &from) { QDateTime now = QDateTime::currentDateTimeUtc(); - if( from.isValid() ) { + if (from.isValid()) { now = from; } - if( dt.daysTo(now)>0 ) { + if (dt.daysTo(now) > 0) { int dtn = dt.daysTo(now); return QObject::tr("%n day(s) ago", "", dtn); } else { qint64 secs = dt.secsTo(now); - if( secs < 0 ) { + if (secs < 0) { return QObject::tr("in the future"); } - if( floor(secs / 3600.0) > 0 ) { - int hours = floor(secs/3600.0); - return( QObject::tr("%n hour(s) ago", "", hours) ); + if (floor(secs / 3600.0) > 0) { + int hours = floor(secs / 3600.0); + return (QObject::tr("%n hour(s) ago", "", hours)); } else { - int minutes = qRound(secs/60.0); - if( minutes == 0 ) { - if(secs < 5) { + int minutes = qRound(secs / 60.0); + if (minutes == 0) { + if (secs < 5) { return QObject::tr("now"); } else { return QObject::tr("Less than a minute ago"); } } - return( QObject::tr("%n minute(s) ago", "", minutes) ); + return (QObject::tr("%n minute(s) ago", "", minutes)); } } return QObject::tr("Some time ago"); @@ -544,9 +543,9 @@ void Utility::StopWatch::reset() _lapTimes.clear(); } -quint64 Utility::StopWatch::addLapTime( const QString& lapName ) +quint64 Utility::StopWatch::addLapTime(const QString &lapName) { - if( !_timer.isValid() ) { + if (!_timer.isValid()) { start(); } quint64 re = _timer.elapsed(); @@ -559,10 +558,10 @@ QDateTime Utility::StopWatch::startTime() const return _startTime; } -QDateTime Utility::StopWatch::timeOfLap( const QString& lapName ) const +QDateTime Utility::StopWatch::timeOfLap(const QString &lapName) const { quint64 t = durationOfLap(lapName); - if( t ) { + if (t) { QDateTime re(_startTime); return re.addMSecs(t); } @@ -570,12 +569,12 @@ QDateTime Utility::StopWatch::timeOfLap( const QString& lapName ) const return QDateTime(); } -quint64 Utility::StopWatch::durationOfLap( const QString& lapName ) const +quint64 Utility::StopWatch::durationOfLap(const QString &lapName) const { return _lapTimes.value(lapName, 0); } -void Utility::sortFilenames(QStringList& fileNames) +void Utility::sortFilenames(QStringList &fileNames) { #if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) QCollator collator; @@ -590,10 +589,10 @@ void Utility::sortFilenames(QStringList& fileNames) } QUrl Utility::concatUrlPath(const QUrl &url, const QString &concatPath, - const QList< QPair > &queryItems) + const QList> &queryItems) { QString path = url.path(); - if (! concatPath.isEmpty()) { + if (!concatPath.isEmpty()) { // avoid '//' if (path.endsWith('/') && concatPath.startsWith('/')) { path.chop(1); @@ -606,7 +605,7 @@ QUrl Utility::concatUrlPath(const QUrl &url, const QString &concatPath, QUrl tmpUrl = url; tmpUrl.setPath(path); - if( queryItems.size() > 0 ) { + if (queryItems.size() > 0) { tmpUrl.setQueryItems(queryItems); } return tmpUrl; @@ -614,7 +613,7 @@ QUrl Utility::concatUrlPath(const QUrl &url, const QString &concatPath, Q_GLOBAL_STATIC(QString, g_configFileName) -std::unique_ptr Utility::settingsWithGroup(const QString& group, QObject *parent) +std::unique_ptr Utility::settingsWithGroup(const QString &group, QObject *parent) { if (g_configFileName()->isEmpty()) { // cache file name diff --git a/src/libsync/utility.h b/src/libsync/utility.h index c17c7a56c..7c26f2ab2 100644 --- a/src/libsync/utility.h +++ b/src/libsync/utility.h @@ -35,17 +35,16 @@ Q_DECLARE_LOGGING_CATEGORY(lcUtility) /** \addtogroup libsync * @{ */ -namespace Utility -{ +namespace Utility { OWNCLOUDSYNC_EXPORT void sleep(int sec); OWNCLOUDSYNC_EXPORT void usleep(int usec); - OWNCLOUDSYNC_EXPORT QString formatFingerprint( const QByteArray&, bool colonSeparated = true ); - OWNCLOUDSYNC_EXPORT void setupFavLink( const QString &folder ); - OWNCLOUDSYNC_EXPORT bool writeRandomFile( const QString& fname, int size = -1); - OWNCLOUDSYNC_EXPORT QString octetsToString( qint64 octets ); + OWNCLOUDSYNC_EXPORT QString formatFingerprint(const QByteArray &, bool colonSeparated = true); + OWNCLOUDSYNC_EXPORT void setupFavLink(const QString &folder); + OWNCLOUDSYNC_EXPORT bool writeRandomFile(const QString &fname, int size = -1); + OWNCLOUDSYNC_EXPORT QString octetsToString(qint64 octets); OWNCLOUDSYNC_EXPORT QByteArray userAgentString(); OWNCLOUDSYNC_EXPORT bool hasLaunchOnStartup(const QString &appName); - OWNCLOUDSYNC_EXPORT void setLaunchOnStartup(const QString &appName, const QString& guiName, bool launch); + OWNCLOUDSYNC_EXPORT void setLaunchOnStartup(const QString &appName, const QString &guiName, bool launch); /** * Return the amount of free space available. @@ -62,10 +61,10 @@ namespace Utility * @param unit an optional unit that is appended if present. * @return the formatted string. */ - OWNCLOUDSYNC_EXPORT QString compactFormatDouble(double value, int prec, const QString& unit = QString::null); + OWNCLOUDSYNC_EXPORT QString compactFormatDouble(double value, int prec, const QString &unit = QString::null); // porting methods - OWNCLOUDSYNC_EXPORT QString escape(const QString&); + OWNCLOUDSYNC_EXPORT QString escape(const QString &); // conversion function QDateTime <-> time_t (because the ones builtin work on only unsigned 32bit) OWNCLOUDSYNC_EXPORT QDateTime qDateTimeFromTime_t(qint64 t); @@ -117,16 +116,16 @@ namespace Utility // Check if two pathes that MUST exist are equal. This function // uses QDir::canonicalPath() to judge and cares for the systems // case sensitivity. - OWNCLOUDSYNC_EXPORT bool fileNamesEqual( const QString& fn1, const QString& fn2); + OWNCLOUDSYNC_EXPORT bool fileNamesEqual(const QString &fn1, const QString &fn2); // Call the given command with the switch --version and rerun the first line // of the output. // If command is empty, the function calls the running application which, on // Linux, might have changed while this one is running. // For Mac and Windows, it returns QString() - OWNCLOUDSYNC_EXPORT QByteArray versionOfInstalledBinary(const QString& command = QString() ); + OWNCLOUDSYNC_EXPORT QByteArray versionOfInstalledBinary(const QString &command = QString()); - OWNCLOUDSYNC_EXPORT QString fileNameForGuiUse(const QString& fName); + OWNCLOUDSYNC_EXPORT QString fileNameForGuiUse(const QString &fName); /** * @brief timeAgoInWords - human readable time span @@ -136,40 +135,41 @@ namespace Utility * * If the second parameter is ommitted, the current time is used. */ - OWNCLOUDSYNC_EXPORT QString timeAgoInWords(const QDateTime& dt, const QDateTime& from = QDateTime() ); + OWNCLOUDSYNC_EXPORT QString timeAgoInWords(const QDateTime &dt, const QDateTime &from = QDateTime()); - class OWNCLOUDSYNC_EXPORT StopWatch { + class OWNCLOUDSYNC_EXPORT StopWatch + { private: QMap _lapTimes; QDateTime _startTime; QElapsedTimer _timer; + public: void start(); quint64 stop(); - quint64 addLapTime( const QString& lapName ); + quint64 addLapTime(const QString &lapName); void reset(); // out helpers, return the measured times. QDateTime startTime() const; - QDateTime timeOfLap( const QString& lapName ) const; - quint64 durationOfLap( const QString& lapName ) const; + QDateTime timeOfLap(const QString &lapName) const; + quint64 durationOfLap(const QString &lapName) const; }; /** * @brief Sort a QStringList in a way that's appropriate for filenames */ - OWNCLOUDSYNC_EXPORT void sortFilenames(QStringList& fileNames); + OWNCLOUDSYNC_EXPORT void sortFilenames(QStringList &fileNames); /** Appends concatPath and queryItems to the url */ OWNCLOUDSYNC_EXPORT QUrl concatUrlPath( - const QUrl &url, const QString &concatPath, - const QList< QPair > &queryItems = (QList>())); + const QUrl &url, const QString &concatPath, + const QList> &queryItems = (QList>())); /** Returns a new settings pre-set in a specific group. The Settings will be created with the given parent. If no parent is specified, the caller must destroy the settings */ - OWNCLOUDSYNC_EXPORT std::unique_ptr settingsWithGroup(const QString& group, QObject* parent = 0); + OWNCLOUDSYNC_EXPORT std::unique_ptr settingsWithGroup(const QString &group, QObject *parent = 0); } /** @} */ // \addtogroup - } #endif // UTILITY_H diff --git a/src/libsync/utility_mac.cpp b/src/libsync/utility_mac.cpp index 19f3042ef..5a71aa2af 100644 --- a/src/libsync/utility_mac.cpp +++ b/src/libsync/utility_mac.cpp @@ -21,14 +21,14 @@ static void setupFavLink_private(const QString &folder) { // Finder: Place under "Places"/"Favorites" on the left sidebar CFStringRef folderCFStr = CFStringCreateWithCString(0, folder.toUtf8().data(), kCFStringEncodingUTF8); - CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true); + CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); LSSharedFileListRef placesItems = LSSharedFileListCreate(0, kLSSharedFileListFavoriteItems, 0); if (placesItems) { //Insert an item to the list. LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(placesItems, - kLSSharedFileListItemLast, 0, 0, - urlRef, 0, 0); + kLSSharedFileListItemLast, 0, 0, + urlRef, 0, 0); if (item) CFRelease(item); } @@ -41,9 +41,9 @@ bool hasLaunchOnStartup_private(const QString &) { // this is quite some duplicate code with setLaunchOnStartup, at some point we should fix this FIXME. bool returnValue = false; - QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath(); + QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath(); CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); - CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true); + CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); if (loginItems) { // We need to iterate over the items and check which one is "ours". @@ -56,7 +56,7 @@ bool hasLaunchOnStartup_private(const QString &) if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { CFStringRef itemUrlString = CFURLGetString(itemUrlRef); - if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) { + if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { returnValue = true; } CFRelease(itemUrlRef); @@ -70,24 +70,24 @@ bool hasLaunchOnStartup_private(const QString &) return returnValue; } -void setLaunchOnStartup_private(const QString &appName, const QString& guiName, bool enable) +void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) { Q_UNUSED(appName) Q_UNUSED(guiName) - QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath(); + QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath(); CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); - CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true); + CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); if (loginItems && enable) { //Insert an item to the list. LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems, - kLSSharedFileListItemLast, 0, 0, - urlRef, 0, 0); + kLSSharedFileListItemLast, 0, 0, + urlRef, 0, 0); if (item) CFRelease(item); CFRelease(loginItems); - } else if (loginItems && !enable){ + } else if (loginItems && !enable) { // We need to iterate over the items and check which one is "ours". UInt32 seedValue; CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue); @@ -98,8 +98,8 @@ void setLaunchOnStartup_private(const QString &appName, const QString& guiName, if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { CFStringRef itemUrlString = CFURLGetString(itemUrlRef); - if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) { - LSSharedFileListItemRemove(loginItems,item); // remove it! + if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { + LSSharedFileListItemRemove(loginItems, item); // remove it! } CFRelease(itemUrlRef); } @@ -119,7 +119,7 @@ static bool hasDarkSystray_private() CFStringRef interfaceStyle = NULL; CFStringRef darkInterfaceStyle = CFSTR("Dark"); interfaceStyle = (CFStringRef)CFPreferencesCopyAppValue(interfaceStyleKey, - kCFPreferencesCurrentApplication); + kCFPreferencesCurrentApplication); if (interfaceStyle != NULL) { returnValue = (kCFCompareEqualTo == CFStringCompare(interfaceStyle, darkInterfaceStyle, 0)); CFRelease(interfaceStyle); diff --git a/src/libsync/utility_unix.cpp b/src/libsync/utility_unix.cpp index b1d3d96d6..e21c1cc75 100644 --- a/src/libsync/utility_unix.cpp +++ b/src/libsync/utility_unix.cpp @@ -14,14 +14,15 @@ */ #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - #include +#include #endif namespace OCC { -static void setupFavLink_private(const QString &folder) { +static void setupFavLink_private(const QString &folder) +{ // Nautilus: add to ~/.gtk-bookmarks - QFile gtkBookmarks(QDir::homePath()+QLatin1String("/.gtk-bookmarks")); + QFile gtkBookmarks(QDir::homePath() + QLatin1String("/.gtk-bookmarks")); QByteArray folderUrl = "file://" + folder.toUtf8(); if (gtkBookmarks.open(QFile::ReadWrite)) { QByteArray places = gtkBookmarks.readAll(); @@ -43,7 +44,7 @@ QString getUserAutostartDir_private() QString config = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); if (config.isEmpty()) { - config = QDir::homePath()+QLatin1String("/.config"); + config = QDir::homePath() + QLatin1String("/.config"); } #endif config += QLatin1String("/autostart/"); @@ -52,14 +53,14 @@ QString getUserAutostartDir_private() bool hasLaunchOnStartup_private(const QString &appName) { - QString desktopFileLocation = getUserAutostartDir_private()+appName+QLatin1String(".desktop"); + QString desktopFileLocation = getUserAutostartDir_private() + appName + QLatin1String(".desktop"); return QFile::exists(desktopFileLocation); } -void setLaunchOnStartup_private(const QString &appName, const QString& guiName, bool enable) +void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) { QString userAutoStartPath = getUserAutostartDir_private(); - QString desktopFileLocation = userAutoStartPath+appName+QLatin1String(".desktop"); + QString desktopFileLocation = userAutoStartPath + appName + QLatin1String(".desktop"); if (enable) { if (!QDir().exists(userAutoStartPath) && !QDir().mkpath(userAutoStartPath)) { qCWarning(lcUtility) << "Could not create autostart folder"; @@ -81,8 +82,7 @@ void setLaunchOnStartup_private(const QString &appName, const QString& guiName, << QLatin1String("Categories=") << QLatin1String("Network") << endl << QLatin1String("Type=") << QLatin1String("Application") << endl << QLatin1String("StartupNotify=") << "false" << endl - << QLatin1String("X-GNOME-Autostart-enabled=") << "true" << endl - ; + << QLatin1String("X-GNOME-Autostart-enabled=") << "true" << endl; } else { if (!QFile::remove(desktopFileLocation)) { qCWarning(lcUtility) << "Could not remove autostart desktop file"; diff --git a/src/libsync/utility_win.cpp b/src/libsync/utility_win.cpp index b862e2e59..f46cde4d5 100644 --- a/src/libsync/utility_win.cpp +++ b/src/libsync/utility_win.cpp @@ -25,26 +25,25 @@ static const char runPathC[] = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"; namespace OCC { - + static void setupFavLink_private(const QString &folder) { // Windows Explorer: Place under "Favorites" (Links) - - QString linkName; + + QString linkName; QDir folderDir(QDir::fromNativeSeparators(folder)); - + /* Use new WINAPI functions */ PWSTR path; - - if(SHGetKnownFolderPath(FOLDERID_Links, 0, NULL, &path) == S_OK) { - QString links = QDir::fromNativeSeparators(QString::fromWCharArray(path)); + + if (SHGetKnownFolderPath(FOLDERID_Links, 0, NULL, &path) == S_OK) { + QString links = QDir::fromNativeSeparators(QString::fromWCharArray(path)); linkName = QDir(links).filePath(folderDir.dirName() + QLatin1String(".lnk")); - CoTaskMemFree(path); + CoTaskMemFree(path); } qCDebug(lcUtility) << " creating link from " << linkName << " to " << folder; if (!QFile::link(folder, linkName)) qCWarning(lcUtility) << "linking" << folder << "to" << linkName << "failed!"; - } @@ -55,13 +54,13 @@ bool hasLaunchOnStartup_private(const QString &appName) return settings.contains(appName); } -void setLaunchOnStartup_private(const QString &appName, const QString& guiName, bool enable) +void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) { Q_UNUSED(guiName); QString runPath = QLatin1String(runPathC); QSettings settings(runPath, QSettings::NativeFormat); if (enable) { - settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/','\\')); + settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/', '\\')); } else { settings.remove(appName); } -- 2.30.2