Apply clang-format
authorChristian Kamm <mail@ckamm.de>
Wed, 17 May 2017 08:55:42 +0000 (10:55 +0200)
committerckamm <mail@ckamm.de>
Wed, 17 May 2017 10:26:27 +0000 (12:26 +0200)
235 files changed:
src/cmd/cmd.cpp
src/cmd/cmd.h
src/cmd/netrcparser.cpp
src/cmd/simplesslerrorhandler.cpp
src/cmd/simplesslerrorhandler.h
src/crashreporter/main.cpp
src/gui/accountmanager.cpp
src/gui/accountmanager.h
src/gui/accountsettings.cpp
src/gui/accountsettings.h
src/gui/accountstate.cpp
src/gui/accountstate.h
src/gui/activitydata.cpp
src/gui/activitydata.h
src/gui/activityitemdelegate.cpp
src/gui/activityitemdelegate.h
src/gui/activitylistmodel.cpp
src/gui/activitylistmodel.h
src/gui/activitywidget.cpp
src/gui/activitywidget.h
src/gui/addcertificatedialog.cpp
src/gui/addcertificatedialog.h
src/gui/application.cpp
src/gui/application.h
src/gui/authenticationdialog.cpp
src/gui/authenticationdialog.h
src/gui/cocoainitializer.h
src/gui/creds/credentialsfactory.cpp
src/gui/creds/credentialsfactory.h
src/gui/creds/httpcredentialsgui.cpp
src/gui/creds/httpcredentialsgui.h
src/gui/creds/shibboleth/shibbolethuserjob.cpp
src/gui/creds/shibboleth/shibbolethuserjob.h
src/gui/creds/shibboleth/shibbolethwebview.cpp
src/gui/creds/shibboleth/shibbolethwebview.h
src/gui/creds/shibbolethcredentials.cpp
src/gui/creds/shibbolethcredentials.h
src/gui/folder.cpp
src/gui/folder.h
src/gui/folderman.cpp
src/gui/folderman.h
src/gui/folderstatusdelegate.cpp
src/gui/folderstatusdelegate.h
src/gui/folderstatusmodel.cpp
src/gui/folderstatusmodel.h
src/gui/folderwatcher.cpp
src/gui/folderwatcher.h
src/gui/folderwatcher_linux.cpp
src/gui/folderwatcher_linux.h
src/gui/folderwatcher_mac.cpp
src/gui/folderwatcher_mac.h
src/gui/folderwatcher_win.cpp
src/gui/folderwatcher_win.h
src/gui/folderwizard.cpp
src/gui/folderwizard.h
src/gui/generalsettings.cpp
src/gui/generalsettings.h
src/gui/ignorelisteditor.cpp
src/gui/ignorelisteditor.h
src/gui/lockwatcher.cpp
src/gui/lockwatcher.h
src/gui/logbrowser.cpp
src/gui/logbrowser.h
src/gui/main.cpp
src/gui/networksettings.cpp
src/gui/networksettings.h
src/gui/notificationconfirmjob.cpp
src/gui/notificationconfirmjob.h
src/gui/notificationwidget.cpp
src/gui/notificationwidget.h
src/gui/ocsjob.cpp
src/gui/ocsjob.h
src/gui/ocsshareejob.cpp
src/gui/ocsshareejob.h
src/gui/ocssharejob.cpp
src/gui/ocssharejob.h
src/gui/openfilemanager.cpp
src/gui/owncloudgui.cpp
src/gui/owncloudgui.h
src/gui/owncloudsetupwizard.cpp
src/gui/owncloudsetupwizard.h
src/gui/protocolwidget.cpp
src/gui/protocolwidget.h
src/gui/proxyauthdialog.cpp
src/gui/proxyauthdialog.h
src/gui/proxyauthhandler.cpp
src/gui/proxyauthhandler.h
src/gui/quotainfo.cpp
src/gui/quotainfo.h
src/gui/selectivesyncdialog.cpp
src/gui/selectivesyncdialog.h
src/gui/servernotificationhandler.cpp
src/gui/servernotificationhandler.h
src/gui/settingsdialog.cpp
src/gui/settingsdialog.h
src/gui/settingsdialogmac.cpp
src/gui/settingsdialogmac.h
src/gui/sharedialog.cpp
src/gui/sharedialog.h
src/gui/sharee.cpp
src/gui/sharee.h
src/gui/sharelinkwidget.cpp
src/gui/sharelinkwidget.h
src/gui/sharemanager.cpp
src/gui/sharemanager.h
src/gui/sharepermissions.h
src/gui/shareusergroupwidget.cpp
src/gui/shareusergroupwidget.h
src/gui/socketapi.cpp
src/gui/socketapi.h
src/gui/sslbutton.cpp
src/gui/sslbutton.h
src/gui/sslerrordialog.cpp
src/gui/sslerrordialog.h
src/gui/synclogdialog.cpp
src/gui/synclogdialog.h
src/gui/syncrunfilelog.cpp
src/gui/syncrunfilelog.h
src/gui/systray.cpp
src/gui/systray.h
src/gui/thumbnailjob.cpp
src/gui/thumbnailjob.h
src/gui/tooltipupdater.cpp
src/gui/tooltipupdater.h
src/gui/updater/ocupdater.cpp
src/gui/updater/ocupdater.h
src/gui/updater/sparkleupdater.h
src/gui/updater/updateinfo.cpp
src/gui/updater/updateinfo.h
src/gui/updater/updater.cpp
src/gui/updater/updater.h
src/gui/wizard/abstractcredswizardpage.cpp
src/gui/wizard/abstractcredswizardpage.h
src/gui/wizard/owncloudadvancedsetuppage.cpp
src/gui/wizard/owncloudadvancedsetuppage.h
src/gui/wizard/owncloudconnectionmethoddialog.cpp
src/gui/wizard/owncloudconnectionmethoddialog.h
src/gui/wizard/owncloudhttpcredspage.cpp
src/gui/wizard/owncloudhttpcredspage.h
src/gui/wizard/owncloudsetuppage.cpp
src/gui/wizard/owncloudsetuppage.h
src/gui/wizard/owncloudshibbolethcredspage.cpp
src/gui/wizard/owncloudshibbolethcredspage.h
src/gui/wizard/owncloudwizard.cpp
src/gui/wizard/owncloudwizard.h
src/gui/wizard/owncloudwizardcommon.cpp
src/gui/wizard/owncloudwizardcommon.h
src/gui/wizard/owncloudwizardresultpage.cpp
src/gui/wizard/owncloudwizardresultpage.h
src/gui/wizard/postfixlineedit.cpp
src/gui/wizard/postfixlineedit.h
src/libsync/abstractnetworkjob.cpp
src/libsync/abstractnetworkjob.h
src/libsync/accessmanager.cpp
src/libsync/accessmanager.h
src/libsync/account.cpp
src/libsync/account.h
src/libsync/asserts.h
src/libsync/bandwidthmanager.cpp
src/libsync/bandwidthmanager.h
src/libsync/capabilities.cpp
src/libsync/capabilities.h
src/libsync/checksums.cpp
src/libsync/checksums.h
src/libsync/clientproxy.cpp
src/libsync/clientproxy.h
src/libsync/configfile.cpp
src/libsync/configfile.h
src/libsync/connectionvalidator.cpp
src/libsync/connectionvalidator.h
src/libsync/cookiejar.cpp
src/libsync/cookiejar.h
src/libsync/creds/abstractcredentials.cpp
src/libsync/creds/abstractcredentials.h
src/libsync/creds/credentialscommon.cpp
src/libsync/creds/credentialscommon.h
src/libsync/creds/dummycredentials.cpp
src/libsync/creds/dummycredentials.h
src/libsync/creds/httpcredentials.cpp
src/libsync/creds/httpcredentials.h
src/libsync/creds/tokencredentials.cpp
src/libsync/creds/tokencredentials.h
src/libsync/discoveryphase.cpp
src/libsync/discoveryphase.h
src/libsync/excludedfiles.cpp
src/libsync/excludedfiles.h
src/libsync/filesystem.cpp
src/libsync/filesystem.h
src/libsync/logger.cpp
src/libsync/logger.h
src/libsync/networkjobs.cpp
src/libsync/networkjobs.h
src/libsync/owncloudpropagator.cpp
src/libsync/owncloudpropagator.h
src/libsync/owncloudpropagator_p.h
src/libsync/owncloudtheme.cpp
src/libsync/owncloudtheme.h
src/libsync/ownsql.cpp
src/libsync/ownsql.h
src/libsync/progressdispatcher.cpp
src/libsync/progressdispatcher.h
src/libsync/propagatedownload.cpp
src/libsync/propagatedownload.h
src/libsync/propagateremotedelete.cpp
src/libsync/propagateremotedelete.h
src/libsync/propagateremotemkdir.cpp
src/libsync/propagateremotemkdir.h
src/libsync/propagateremotemove.cpp
src/libsync/propagateremotemove.h
src/libsync/propagateupload.cpp
src/libsync/propagateupload.h
src/libsync/propagateuploadng.cpp
src/libsync/propagateuploadv1.cpp
src/libsync/propagatorjobs.cpp
src/libsync/propagatorjobs.h
src/libsync/syncengine.cpp
src/libsync/syncengine.h
src/libsync/syncfileitem.h
src/libsync/syncfilestatus.cpp
src/libsync/syncfilestatus.h
src/libsync/syncfilestatustracker.cpp
src/libsync/syncfilestatustracker.h
src/libsync/syncjournaldb.cpp
src/libsync/syncjournaldb.h
src/libsync/syncjournalfilerecord.cpp
src/libsync/syncjournalfilerecord.h
src/libsync/syncresult.cpp
src/libsync/syncresult.h
src/libsync/theme.cpp
src/libsync/theme.h
src/libsync/utility.cpp
src/libsync/utility.h
src/libsync/utility_mac.cpp
src/libsync/utility_unix.cpp
src/libsync/utility_win.cpp

index 32fa03b49ebee4b5041b993cc2b3a3bbfb7eb4e1..0535875cd411a6c320671ea15183b0c895e70ca7 100644 (file)
 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();
 
-        ifoption == "--httpproxy" && !it.peekNext().startsWith("-")) {
+        if (option == "--httpproxy" && !it.peekNext().startsWith("-")) {
             options->proxy = it.next();
-        } else ifoption == "-s" || option == "--silent") {
+        } else if (option == "-s" || option == "--silent") {
             options->silent = true;
-        } else ifoption == "--trust") {
+        } else if (option == "--trust") {
             options->trustSSL = true;
-        } else ifoption == "-n") {
+        } else if (option == "-n") {
             options->useNetrc = true;
-        } else ifoption == "-h") {
+        } else if (option == "-h") {
             options->ignoreHiddenFiles = false;
-        } else ifoption == "--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 );
-        ifurl.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;
 }
-
index 06ae2fa6c4d7310b37a844793f08bbed2802ea3f..34b4a15ad727ba9537f38011c921358c14e7c3ce 100644 (file)
  * @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()
+    {
     }
 };
 
index 9e831305c9fd4a569e1409928b7289f1aef2847a..a89eb762289f13adc3d6ccd9c1ee35a485b8a7c0 100644 (file)
 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);
 
index a9d7605326a9381ce9e36a5c14cac76e75f22bc9..18a03293acbfa3e688519a1745cccc9381cd5576 100644 (file)
@@ -20,18 +20,17 @@ namespace OCC {
 
 bool SimpleSslErrorHandler::handleErrors(QList<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *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;
 }
-
 }
index 05ee5ed42914616f79affeba6ec166786c73bfb2..33376b820d64ab389a5168a989a845f38120d84f 100644 (file)
@@ -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<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *certs, OCC::AccountPtr) Q_DECL_OVERRIDE;
 };
-
 }
 
 #endif // SIMPLESSLERRORHANDLER_H
index 048b9ff0b737292393d736f5db973449a98d2a30..631c211b5041869f83e2a84f93d5f47054fc7a8f 100644 (file)
 #include <QApplication>
 #include <QDebug>
 
-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("<html><head/><body><p><span style=\" font-weight:600;\">Sorry!</span> " 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.</p></body></html>");
 
-    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();
 
index 1c1ab175483ebda2dc8a15851cdf2ae15bf9aa10..a54a1b6c81a5eb6afe9d962e69bd10b78a6abace 100644 (file)
@@ -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 autoaccountId, 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<QSettings> 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(Accounta)
+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(AccountStatea)
+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<CookieJar*>(acc->_am->cookieJar());
+        CookieJar *jar = qobject_cast<CookieJar *>(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(QSettingssettings)
+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 QStringname)
+AccountStatePtr AccountManager::account(const QString &name)
 {
-    foreach (const autoacc, _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 AccountPtrnewAccount)
+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(AccountStateaccount)
+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 QStringid) const
+bool AccountManager::isAccountIdAvailable(const QString &id) const
 {
-    foreach (const autoacc, _accounts) {
+    foreach (const auto &acc, _accounts) {
         if (acc->account()->id() == id) {
             return false;
         }
@@ -347,15 +353,14 @@ QString AccountManager::generateFreeAccountId() const
     }
 }
 
-void AccountManager::addAccountState(AccountStateaccountState)
+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);
 }
-
 }
index 2dcb9c88d7d97b8193038cde278266a7be4d22e6..a2c13bec29aa17b5b6bd45f7ddb0434b8a3430f2 100644 (file)
@@ -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 QStringname);
+    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(QSettingssettings);
+    void saveAccountHelper(Account *account, QSettings &settings, bool saveCredentials = true);
+    AccountPtr loadAccountHelper(QSettings &settings);
 
     bool restoreFromLegacySettings();
 
-    bool isAccountIdAvailable(const QStringid) const;
+    bool isAccountIdAvailable(const QString &id) const;
     QString generateFreeAccountId() const;
 
     // Adds an account to the tracked list, emitting accountAdded()
-    void addAccountState(AccountStateaccountState);
+    void addAccountState(AccountState *accountState);
 
 public slots:
     /// Saves account data, not including the credentials
-    void saveAccount(Accounta);
+    void saveAccount(Account *a);
 
     /// Saves account state data, not including the account
-    void saveAccountState(AccountStatea);
+    void saveAccountState(AccountState *a);
 
 
 Q_SIGNALS:
@@ -105,5 +106,4 @@ private:
     AccountManager() {}
     QList<AccountStatePtr> _accounts;
 };
-
 }
index b12d245f7948d7b7c7ceaf2b716c19ba8dcea26b..9eb3a53d258d96828086e49375df86796381aa25 100644 (file)
@@ -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<SettingsDialogMac*>(topLevelWidget());
+    SettingsDialogMac *sd = qobject_cast<SettingsDialogMac *>(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 QModelIndexindx)
+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<FolderWizard*>(sender());
+    FolderWizard *folderWizard = qobject_cast<FolderWizard *>(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("<p>Could not create local folder <i>%1</i>.")
-                                        .arg(QDir::toNativeSeparators(definition.localPath)));
+                    tr("<p>Could not create local folder <i>%1</i>.")
+                        .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("<p>Do you really want to stop syncing the folder <i>%1</i>?</p>"
-                                  "<p><b>Note:</b> This will <b>not</b> delete any files.</p>").arg(shortGuiLocalPath),
-                               QMessageBox::NoButton,
-                               this);
-        QPushButton* yesButton =
-                messageBox.addButton(tr("Remove Folder Sync Connection"), QMessageBox::YesRole);
+            tr("Confirm Folder Sync Connection Removal"),
+            tr("<p>Do you really want to stop syncing the folder <i>%1</i>?</p>"
+               "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
+                .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.<br/>Do you want to terminate it?"),
-                                   QMessageBox::Yes | QMessageBox::No, parent, flags);
+                    tr("The syncing operation is running.<br/>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 (Foldercurrent = 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("<a href=\"%1\">%2</a>")
                              .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 <i>%2</i>").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 QStringlink)
+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="));
-    ifli.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);
-            ifmyFolder.endsWith('/')) {
+            if (myFolder.endsWith('/')) {
                 myFolder.chop(1);
             }
             QModelIndex theIndx = _model->indexForPath(folder, myFolder);
-            if(theIndx.isValid()) {
+            if (theIndx.isValid()) {
                 msg += QString::fromLatin1("<a href=\"%1?folder=%2\">%1</a>")
                            .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("<p>Do you really want to remove the connection to the account <i>%1</i>?</p>"
-                                  "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
-                                 .arg(_accountState->account()->displayName()),
-                               QMessageBox::NoButton,
-                               this);
-        QPushButtonyesButton =
-                messageBox.addButton(tr("Remove connection"), QMessageBox::YesRole);
+            tr("Confirm Account Removal"),
+            tr("<p>Do you really want to remove the connection to the account <i>%1</i>?</p>"
+               "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
+                .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(QEvente)
+bool AccountSettings::event(QEvent *e)
 {
     if (e->type() == QEvent::Hide || e->type() == QEvent::Show) {
         _quotaInfo.setActive(isVisible());
index 5ad47239733ef426f4ebb126c77bca7a73e37926..9c4a1fc5696ee61083a7a4e67214a1fe14b2864d 100644 (file)
@@ -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);
 
-    AccountStateaccountsState() { 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 QStringmessage,
-                             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;
index b141974673722d9f3dadacbbcfaed0c2f0d9393e..90dfa5e62f728285795321d2ebc23474cce4c54a 100644 (file)
@@ -33,14 +33,14 @@ AccountState::AccountState(AccountPtr account)
     , _connectionStatus(ConnectionValidator::Undefined)
     , _waitingForNewCredentials(false)
 {
-    qRegisterMetaType<AccountState*>("AccountState*");
+    qRegisterMetaType<AccountState *>("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 QStringListerrors)
+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(AbstractCredentialscredentials)
+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(AbstractCredentialscredentials)
+void AccountState::slotCredentialsAsked(AbstractCredentials *credentials)
 {
     _waitingForNewCredentials = false;
 
@@ -346,5 +344,4 @@ QString AccountState::shortDisplayNameForSettings(int width) const
 }
 
 
-
 } // namespace OCC
index ef81bb39ff7c5512fe900aed1a1c3de81bee1e8c..450766bf8244fd29d54ab372bf2331db04e677b1 100644 (file)
@@ -36,7 +36,8 @@ typedef QExplicitlySharedDataPointer<AccountState> 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(QSettingssettings);
+    void writeToSettings(QSettings &settings);
 
     AccountPtr account() const;
 
@@ -134,10 +135,10 @@ signals:
     void isConnectedChanged();
 
 protected Q_SLOTS:
-    void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringListerrors);
+    void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList &errors);
     void slotInvalidCredentials();
-    void slotCredentialsFetched(AbstractCredentialscreds);
-    void slotCredentialsAsked(AbstractCredentialscreds);
+    void slotCredentialsFetched(AbstractCredentials *creds);
+    void slotCredentialsAsked(AbstractCredentials *creds);
 
 private:
     AccountPtr _account;
@@ -148,10 +149,9 @@ private:
     QElapsedTimer _timeSinceLastETagCheck;
     QPointer<ConnectionValidator> _connectionValidator;
 };
-
 }
 
-Q_DECLARE_METATYPE(OCC::AccountState*)
+Q_DECLARE_METATYPE(OCC::AccountState *)
 Q_DECLARE_METATYPE(OCC::AccountStatePtr)
 
 #endif //ACCOUNTINFO_H
index cd67c94943bdc68294922c40579b8e182e648aec..b0236658e789c5a66af7aff5fec254e2f129ddd7 100644 (file)
 #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);
 }
-
-
 }
index 7817f56721f784d50660d00cf6fe107e44bac595..40cd35e05429f3d6746ae290f34a744dcb1d57bf 100644 (file)
@@ -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 <ActivityLink> _links;
+    QVector<ActivityLink> _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<Activity> ActivityList;
-
-
 }
 
 #endif // ACTIVITYDATA_H
index 171b5895e482eb0ae1a049c9ddf02b218ec5afb7..8de739eb794d420d8fc815e73c3ba7cdc9c3267f 100644 (file)
@@ -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<QIcon>(index.data(ActionIconRole));
-    QIcon userIcon        = qvariant_cast<QIcon>(index.data(UserIconRole));
-    QString actionText    = qvariant_cast<QString>(index.data(ActionTextRole));
-    QString pathText      = qvariant_cast<QString>(index.data(PathRole));
+    QIcon actionIcon = qvariant_cast<QIcon>(index.data(ActionIconRole));
+    QIcon userIcon = qvariant_cast<QIcon>(index.data(UserIconRole));
+    QString actionText = qvariant_cast<QString>(index.data(ActionTextRole));
+    QString pathText = qvariant_cast<QString>(index.data(PathRole));
 
-    QString remoteLink    = qvariant_cast<QString>(index.data(LinkRole));
-    QString timeText      = qvariant_cast<QString>(index.data(PointInTimeRole));
-    QString accountRole   = qvariant_cast<QString>(index.data(AccountRole));
-    bool    accountOnline = qvariant_cast<bool>   (index.data(AccountConnectedRole));
+    QString remoteLink = qvariant_cast<QString>(index.data(LinkRole));
+    QString timeText = qvariant_cast<QString>(index.data(PointInTimeRole));
+    QString accountRole = qvariant_cast<QString>(index.data(AccountRole));
+    bool accountOnline = qvariant_cast<bool>(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);
 }
index 82919ee24498d6200e0f86d91743f798d86beb23..193e15da94be9c5ca25585ce21e66efec83d77c0 100644 (file)
@@ -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
-
index fb1201ef380b9d9e45193a99b11d075e0e9937fc..05af4a8e3456c491f51802fd226b9bc467a7da8b 100644 (file)
@@ -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(AccountStates)
+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<QPointer<AccountState>>(s));
 
-    QList< QPair<QString,QString> > params;
-    params.append(qMakePair(QString::fromLatin1("page"),     QString::fromLatin1("0")));
+    QList<QPair<QString, QString>> 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 QJsonDocumentjson, 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<AccountStatePtr> 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);
     }
 }
-
 }
index ed3a9e270e92add6217c5c26e3b049b4af6ed2ff..ad5574d2770515a7b5081bbae7e6a37a11131fe4 100644 (file)
@@ -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 QModelIndexparent = 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(AccountStateast);
-    void slotRemoveAccount( AccountState *ast );
+    void slotRefreshActivity(AccountState *ast);
+    void slotRemoveAccount(AccountState *ast);
 
 private slots:
-    void slotActivitiesReceived(const QJsonDocumentjson, int statusCode);
+    void slotActivitiesReceived(const QJsonDocument &json, int statusCode);
 
 signals:
-    void activityJobStatusCode(AccountStateast, int statusCode);
+    void activityJobStatusCode(AccountState *ast, int statusCode);
 
 private:
-    void startFetchJob(AccountStates);
+    void startFetchJob(AccountState *s);
     void combineActivityLists();
 
-    QMap<AccountState*, ActivityList> _activityLists;
+    QMap<AccountState *, ActivityList> _activityLists;
     ActivityList _finalList;
-    QSet<AccountState*> _currentlyFetching;
+    QSet<AccountState *> _currentlyFetching;
 };
-
-
 }
 #endif // ACTIVITYLISTMODEL_H
index 176679316213cd7be72fcb5630b6fcfe1a5338b0..6a55001c00a9b122960e4490424514601387a176 100644 (file)
 
 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<QString> i(_accountsWithoutActivities);
-    while (i.hasNext() ) {
-        t.append( tr("<br/>Account %1 does not have activities enabled.").arg(i.next()));
+    while (i.hasNext()) {
+        t.append(tr("<br/>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 ActivityListlist)
+void ActivityWidget::slotBuildNotificationDisplay(const ActivityList &list)
 {
     QHash<QString, int> 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() ) {
-                ifaccNotified.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<Activity::Identifier> 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<NotificationWidget*>(sender());
+    NotificationWidget *theSender = qobject_cast<NotificationWidget *>(sender());
 
-    const QStringList validVerbs = QStringList() << "GET" << "PUT" << "POST" << "DELETE";
+    const QStringList validVerbs = QStringList() << "GET"
+                                                 << "PUT"
+                                                 << "POST"
+                                                 << "DELETE";
 
-    ifvalidVerbs.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<NotificationConfirmJob*>(sender());
-    if( !job ) {
+    NotificationConfirmJob *job = qobject_cast<NotificationConfirmJob *>(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<NotificationConfirmJob*>(sender());
-    if( !job ) {
+    NotificationConfirmJob *job = qobject_cast<NotificationConfirmJob *>(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 ActivityblacklistActivity)
+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(QEvente)
+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()
 {
-
 }
-
-
 }
index a60f51d4fd37f9cada5ae90a6cb237259567fc20..bae9b6ff951294c20fec91f6024f002904239ae3 100644 (file)
@@ -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(AccountStateptr);
+    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 ActivityblacklistActivity);
+    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 ActivityListlist);
-    void slotSendNotificationRequest(const QString &accountName, const QStringlink, 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<QString> _accountsWithoutActivities;
-    QMap<Activity::Identifier, NotificationWidget*> _widgetForNotifId;
+    QMap<Activity::Identifier, NotificationWidget *> _widgetForNotifId;
     QElapsedTimer _guiLogTimer;
     QSet<int> _guiLoggedNotifications;
     ActivityList _blacklistedNotifications;
 
-    QHash<NotificationWidget*, QDateTime> _widgetsToRemove;
+    QHash<NotificationWidget *, QDateTime> _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(QEvente) 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<AccountState*, QElapsedTimer>  _timeSinceLastCheck;
+    QTimer _notificationCheckTimer;
+    QHash<AccountState *, QElapsedTimer> _timeSinceLastCheck;
 };
-
 }
 #endif // ActivityWIDGET_H
index 34e0fc2424fb93365084cfb456da07714f4c4ba8..fabaeec5b6d141332e8aef58aa5fab83948387b9 100644 (file)
@@ -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();
 }
-
 }
index 1840f5007aa869a99f58d9d061ff1b68f0e68439..c9e6826c2482e67299652fa32495de8952ceb1bb 100644 (file)
@@ -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
index 04e8176344b5044f734b9dbe2b6a6f85f2dd349b..4991aac56c3a1e62855acce977462e21d05c65d7 100644 (file)
@@ -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 <dirname>  : Use the given configuration folder.\n"
-        ;
+        "  --confdir <dirname>  : 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;
-    ExcludedFilesexcludes = 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
-
index 0228ecafc2d48c0fb6fccd1cf25db90a10e36e77..099053def054fa2f0bdb9f40367a3f471604e9dc 100644 (file)
@@ -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;
 
index 1d05e7264372f5db1d838120c1674eb6693f1cf0..bae0bcd134a31f1529c5ad50c0a38480b62ca3cc 100644 (file)
@@ -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);
index 4dc23987d682732446f6612adc82e75a1b3e8d98..3983e20a3e1fa2ac03e628f10bb0c837e4fdf429 100644 (file)
@@ -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;
-
 };
 
 
index bdeb540918b16381e722b2e09ef27be01c646f43..7919a169843cce7c5da3a5a1c157e405b9577947 100644 (file)
 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
index 9a60209c7f533eb415efc9c7041105e053beec96..f9574f096cca9347936626c216244330e9a203f7 100644 (file)
 #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
 
index 5dcb5197b583d0f965b6ee1df15a3e82cd777d71..d346a2f71e08f27a56e1d77ae6ab0f3867a410a0 100644 (file)
@@ -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
 
index d157f4c57cbfec1af269533dec1ec847d0e9b429..50d2a2367c7e696785e5f37f17f424f10723a06a 100644 (file)
@@ -21,8 +21,7 @@
 
 using namespace QKeychain;
 
-namespace OCC
-{
+namespace OCC {
 
 void HttpCredentialsGui::askFromUser()
 {
@@ -36,9 +35,9 @@ void HttpCredentialsGui::askFromUserAsync()
                      "<br>"
                      "User: %2<br>"
                      "Account: %3<br>")
-                  .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("<br>")
-                + tr("Reading from keychain failed with error: '%1'")
-                .arg(Utility::escape(_fetchErrorString)) + QLatin1String("<br>");
+            + tr("Reading from keychain failed with error: '%1'")
+                  .arg(Utility::escape(_fetchErrorString))
+            + QLatin1String("<br>");
     }
 
     QInputDialog dialog;
@@ -69,7 +69,7 @@ void HttpCredentialsGui::askFromUserAsync()
     emit asked();
 }
 
-QString HttpCredentialsGui::requestAppPasswordText(const Accountaccount)
+QString HttpCredentialsGui::requestAppPasswordText(const Account *account)
 {
     int version = account->serverVersionInt();
     QString path;
index 4e80ae77a7bf51af6b5b6694fa8e5fed708f8d48..235fd523ea3d13c08d0586fe49922b8ada72a37c 100644 (file)
 #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
-
index 02d4d22f4fc76c8c2b5172164b79cb474599c5fb..743643692974f876463a861b41f75c654132599a 100644 (file)
@@ -23,7 +23,7 @@ namespace OCC {
 
 Q_DECLARE_LOGGING_CATEGORY(lcShibboleth)
 
-ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObjectparent)
+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);
 }
-
 }
index feb59014a1820d9b296085d82ce5bf1f386bdea0..22706b1c16dba1a2bc99c9630b8dca9bbbdebe2d 100644 (file)
 
 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, QObjectparent = 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
-
index fb5709bb7c3de2accdfd8ff83e08a5b8d1ce726b..64a1f7c3548a7256e26949acc6d3e052d8f21f85 100644 (file)
 #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, QWidgetparent)
+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);
 
-    QWebPagepage = 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<QSslError>)),
-            _account.data(), SLOT(slotHandleSslErrors(QNetworkReply*,QList<QSslError>)));
+    QObject::connect(page->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
+        _account.data(), SLOT(slotHandleSslErrors(QNetworkReply *, QList<QSslError>)));
 
     // The Account keeps ownership of the cookie jar, it must outlive this webview.
     account->lendCookieJarTo(page->networkAccessManager());
     connect(page->networkAccessManager()->cookieJar(),
-            SIGNAL(newCookiesForUrl (QList<QNetworkCookie>, QUrl)),
-            this, SLOT(onNewCookiesForUrl (QList<QNetworkCookie>, QUrl)));
+        SIGNAL(newCookiesForUrl(QList<QNetworkCookie>, QUrl)),
+        this, SLOT(onNewCookiesForUrl(QList<QNetworkCookie>, 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<QNetworkCookie>& cookieList, const QUrl& url)
+void ShibbolethWebView::onNewCookiesForUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
 {
     if (url.host() == _account->url().host()) {
         QNetworkCookie shibCookie = ShibbolethCredentials::findShibCookie(_account.data(), cookieList);
index 9005c17b0ebfcd83fc44b5df11fcb11a9ccce892..b2b45c1ab2e0cbc7973b938c5d05998c8ccb8c57 100644 (file)
@@ -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<QNetworkCookie>& cookieList, const QUrl& url);
-  void slotLoadStarted();
-  void slotLoadFinished(bool success);
+    void onNewCookiesForUrl(const QList<QNetworkCookie> &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
index a8cae2eb6d91f267ae4d3902b504e024fff265eb..a827106df699d25e298f2d36d140dd43e610ef2f 100644 (file)
 
 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(Accountaccount)
+void ShibbolethCredentials::setAccount(Account *account)
 {
     AbstractCredentials::setAccount(account);
 
@@ -91,15 +90,15 @@ QString ShibbolethCredentials::user() const
     return _user;
 }
 
-QNetworkAccessManagerShibbolethCredentials::getQNAM() const
+QNetworkAccessManager *ShibbolethCredentials::getQNAM() const
 {
-    QNetworkAccessManagerqnam(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(QNetworkReplyr)
+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<CookieJar*>(_account->networkAccessManager()->cookieJar());
+    CookieJar *jar = static_cast<CookieJar *>(_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 QNetworkCookieshibCookie)
+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?)
-    EntityExistsJobjob = 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<ReadPasswordJob*>(job);
+        ReadPasswordJob *readJob = static_cast<ReadPasswordJob *>(job);
         delete readJob->settings();
         QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(readJob->textData().toUtf8());
         if (cookies.count() > 0) {
@@ -267,7 +266,7 @@ void ShibbolethCredentials::showLoginWindow()
         return;
     }
 
-    CookieJar *jar = static_cast<CookieJar*>(_account->networkAccessManager()->cookieJar());
+    CookieJar *jar = static_cast<CookieJar *>(_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<QNetworkCookie> ShibbolethCredentials::accountCookies(Accountaccount)
+QList<QNetworkCookie> ShibbolethCredentials::accountCookies(Account *account)
 {
     return account->networkAccessManager()->cookieJar()->cookiesForUrl(account->davUrl());
 }
 
-QNetworkCookie ShibbolethCredentials::findShibCookie(Accountaccount, QList<QNetworkCookie> cookies)
+QNetworkCookie ShibbolethCredentials::findShibCookie(Account *account, QList<QNetworkCookie> 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;
         }
index 1114b4d6c5210227899c189141c56b8d87825ba6..46b6bc08dfd2b4fc91a57fcca47a42ddc978300e 100644 (file)
 #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(Accountaccount) Q_DECL_OVERRIDE;
+    void setAccount(Account *account) Q_DECL_OVERRIDE;
     QString authType() const Q_DECL_OVERRIDE;
     QString user() const Q_DECL_OVERRIDE;
-    QNetworkAccessManagergetQNAM() 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 QStringuser);
+    void slotReadJobDone(QKeychain::Job *);
+    void slotReplyFinished(QNetworkReply *);
+    void slotUserFetched(const QString &user);
     void slotFetchUser();
     void slotFetchUserHelper();
 
 Q_SIGNALS:
-    void newCookie(const QNetworkCookiecookie);
+    void newCookie(const QNetworkCookie &cookie);
 
 private:
     void storeShibCookie(const QNetworkCookie &cookie);
index f9ef2caeb9e3da29e0a201ba85442805d395f0f1..b17a87d0de630c47264efe5ae14b5a0140eed0ab 100644 (file)
@@ -47,20 +47,20 @@ namespace OCC {
 
 Q_LOGGING_CATEGORY(lcFolder, "gui.folder", QtInfoMsg)
 
-Folder::Folder(const FolderDefinitiondefinition,
-               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 QStringetag)
+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 QStringetag)
+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<QString> keep_nothing;
     const QVector<SyncJournalDb::DownloadInfo> 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 QStringpath)
+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 (Folderother, 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 QStringfullPath) const
+bool Folder::isFileExcludedAbsolute(const QString &fullPath) const
 {
     return _engine->excludedFiles().isExcluded(fullPath, path(), _definition.ignoreHiddenFiles);
 }
 
-bool Folder::isFileExcludedRelative(const QStringrelativePath) 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 QStringerr)
+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);
-    QPushButtonkeepBtn = 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);
-    QPushButtonkeepBtn = 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 QStringpath)
+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
-
index 591f2de9e10a4d69e85b7dc43f63d18bf9c318a4..ce1b3a7d991e5924a89df7ce9edea6df03be12d0 100644 (file)
@@ -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 QStringpath);
+    static QString prepareLocalPath(const QString &path);
 
     /// Ensure starting / and no ending /.
-    static QString prepareTargetPath(const QStringpath);
+    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<QString, Folder*> Map;
-    typedef QMapIterator<QString, Folder*> MapIterator;
+    typedef QMap<QString, Folder *> Map;
+    typedef QMapIterator<QString, Folder *> MapIterator;
 
     /**
      * The account the folder is configured on.
      */
-    AccountStateaccountState() 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 ProgressInfoprogress);
+    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 QStringpath);
+    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 ProgressInfopi);
-    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 QStringfilename, 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<SyncEngine> _engine;
-    bool         _csyncUnavail;
-    bool         _proxyDirty;
+    bool _csyncUnavail;
+    bool _proxyDirty;
     QPointer<RequestEtagJob> _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<SyncRunFileLog> _fileLog;
 
@@ -362,7 +363,6 @@ private:
      */
     bool _saveBackwardsCompatible;
 };
-
 }
 
 #endif
index 367e9072f958ddf63ada10b9693cb661575c5bbd..b1d5d3a92e8354b0ebc92a23c5cc15e6e0312ef4 100644 (file)
@@ -42,14 +42,14 @@ namespace OCC {
 
 Q_LOGGING_CATEGORY(lcFolderMan, "gui.folder.manager", QtInfoMsg)
 
-FolderManFolderMan::_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();
-        Folderf = 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 autoaccount, 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 autofolderAlias, 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());
             }
 
-            Folderf = 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.
-    AccountStateaccountState = 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<Folder*>(sender());
+    Folder *f = qobject_cast<Folder *>(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 QStringpath)
+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(Folderf)
+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<AccountState*>(sender());
-    if (! accountState) {
+    AccountState *accountState = qobject_cast<AccountState *>(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<Folder*> it(_scheduledFolders);
+        QMutableListIterator<Folder *> it(_scheduledFolders);
         while (it.hasNext()) {
-            Folderf = 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 (FolderlastFolder = _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.
-    Folderfolder = 0;
-    while( !_scheduledFolders.isEmpty() ) {
-        Folderg = _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(AccountStateaccountState)
+void FolderMan::slotRemoveFoldersForAccount(AccountState *accountState)
 {
     QVarLengthArray<Folder *, 16> foldersToRemove;
     Folder::MapIterator i(_folderMap);
     while (i.hasNext()) {
         i.next();
-        Folderfolder = 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<Folder*>(sender())) {
+    if (Folder *f = qobject_cast<Folder *>(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 (autof, _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 QStringpath)
+void FolderMan::slotWatchedFileUnlocked(const QString &path)
 {
-    if (Folderf = folderForPath(path)) {
+    if (Folder *f = folderForPath(path)) {
         f->scheduleThisFolderSoon();
     }
 }
 
 void FolderMan::slotScheduleFolderByTime()
 {
-    foreach (autof, _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 (Folderother, 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;
 }
 
-FolderFolderMan::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<Folder*> &folders)
+SyncResult FolderMan::accountStatus(const QList<Folder *> &folders)
 {
     SyncResult overallResult;
 
@@ -1132,45 +1133,45 @@ SyncResult FolderMan::accountStatus(const QList<Folder*> &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<Folder*> &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<Folder*> &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<Folder*> &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 QStringpath, 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<Folder*>(i.value());
-        QString folderDir = QDir( f->path() ).canonicalPath();
-        if( folderDir.isEmpty() ) {
+    for (auto i = _folderMap.constBegin(); i != _folderMap.constEnd(); ++i) {
+        Folder *f = static_cast<Folder *>(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 (Folderfolder, _folderMap) {
+    foreach (Folder *folder, _folderMap) {
         folder->setIgnoreHiddenFiles(ignore);
         folder->saveToSettings();
     }
 }
 
-QQueue<Folder*> FolderMan::scheduleQueue() const
+QQueue<Folder *> 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();
index 2545c88387ae1e857814265f97979d4eb1879604..a504cc99b6dc99bbc48ad6beb3540d6cbe54d3c0 100644 (file)
@@ -63,7 +63,7 @@ class FolderMan : public QObject
     Q_OBJECT
 public:
     ~FolderMan();
-    static FolderManinstance();
+    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 QStringjournalDbFile);
+    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<Folder*> &folders );
+    static SyncResult accountStatus(const QList<Folder *> &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 QUrlserverUrl = 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<Folder*> scheduleQueue() const;
+    QQueue<Folder *> scheduleQueue() const;
 
     /**
      * Access to the currently syncing folder.
      */
-    FoldercurrentSyncFolder() 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 QStringpath);
+    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(AccountStateaccountState);
+    void slotRemoveFoldersForAccount(AccountState *accountState);
 
     // Wraps the Folder::syncStateChange() signal into the
     // FolderMan::folderSyncStateChange(Folder*) signal.
     void slotForwardFolderSyncStateChange();
 
-    void slotServerVersionChanged(Accountaccount);
+    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 QStringpath);
+    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.
       */
-    FolderaddFolderInternal(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(QSettingssettings, AccountStatePtr account, bool backwardsCompatible);
+    void setupFoldersHelper(QSettings &settings, AccountStatePtr account, bool backwardsCompatible);
 
-    QSet<Folder*>  _disabledFolders;
-    Folder::Map    _folderMap;
-    QString        _folderConfigPath;
-    Folder        *_currentSyncFolder;
+    QSet<Folder *> _disabledFolders;
+    Folder::Map _folderMap;
+    QString _folderConfigPath;
+    Folder *_currentSyncFolder;
     QPointer<Folder> _lastSyncFolder;
-    bool           _syncEnabled;
+    bool _syncEnabled;
 
     /// Watching for file changes in folders
-    QMap<QString, FolderWatcher*> _folderWatchers;
+    QMap<QString, FolderWatcher *> _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<Folder*> _scheduledFolders;
+    QQueue<Folder *> _scheduledFolders;
 
     /// Picks the next scheduled folder and starts the sync
-    QTimer          _startScheduledSyncTimer;
+    QTimer _startScheduledSyncTimer;
 
     QScopedPointer<SocketApi> _socketApi;
 
-    bool            _appRestartRequired;
+    bool _appRestartRequired;
 
     static FolderMan *_instance;
     explicit FolderMan(QObject *parent = 0);
index 628fc893ef547a7af2de0fed0a7ae0c3694fd29c..ddb5038675575f0bd80f028ed05439e21784698f 100644 (file)
@@ -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<const FolderStatusModel *>(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<QStyleOption&>(opt) = option;
+        static_cast<QStyleOption &>(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<QStringList>(index.data(FolderErrorMsg)).isEmpty() ) {
-        int margin = fm.height()/4;
+    if (!qvariant_cast<QStringList>(index.data(FolderErrorMsg)).isEmpty()) {
+        int margin = fm.height() / 4;
         QStringList errMsgs = qvariant_cast<QStringList>(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<QStyleOption&>(opt) = option;
+        static_cast<QStyleOption &>(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<QIcon>(index.data(FolderStatusIconRole));
-    QString aliasText     = qvariant_cast<QString>(index.data(HeaderRole));
-    QString pathText      = qvariant_cast<QString>(index.data(FolderPathRole));
-    QString remotePath    = qvariant_cast<QString>(index.data(FolderSecondPathRole));
-    QStringList errorTexts= qvariant_cast<QStringList>(index.data(FolderErrorMsg));
+    QIcon statusIcon = qvariant_cast<QIcon>(index.data(FolderStatusIconRole));
+    QString aliasText = qvariant_cast<QString>(index.data(HeaderRole));
+    QString pathText = qvariant_cast<QString>(index.data(FolderPathRole));
+    QString remotePath = qvariant_cast<QString>(index.data(FolderSecondPathRole));
+    QStringList errorTexts = qvariant_cast<QStringList>(index.data(FolderErrorMsg));
 
-    int overallPercent    = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
+    int overallPercent = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
     QString overallString = qvariant_cast<QString>(index.data(SyncProgressOverallString));
-    QString itemString    = qvariant_cast<QString>(index.data(SyncProgressItemString));
-    int warningCount      = qvariant_cast<int>(index.data(WarningCount));
-    bool syncOngoing      = qvariant_cast<bool>(index.data(SyncRunning));
-    bool syncEnabled      = qvariant_cast<bool>(index.data(FolderAccountConnected));
+    QString itemString = qvariant_cast<QString>(index.data(SyncProgressItemString));
+    int warningCount = qvariant_cast<int>(index.data(WarningCount));
+    bool syncOngoing = qvariant_cast<bool>(index.data(SyncRunning));
+    bool syncEnabled = qvariant_cast<bool>(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.
-    ifwarningCount > 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);
 }
 
index 6d533258d1cfcb65abe522391d12d2455f39f682..b42ae134d01e632cc29b9595159203b07be20806 100644 (file)
@@ -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
-
index bb8edb746b3d9872a922e76f690fd4615347a77e..037285b530645b1f901330eda2de58074eb8ba29 100644 (file)
@@ -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 AccountStateaccountState)
+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<SubFolderInfo *>(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<SubFolderInfo *>(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.
-                    ifstatus == 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<Qt::CheckState>(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 QModelIndexparent) 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 QModelIndexindex) const
+FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex &index) const
 {
-    if (auto sub = static_cast<SubFolderInfo*>(index.internalPointer())) {
+    if (auto sub = static_cast<SubFolderInfo *>(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<SubFolderInfo*>(index.internalPointer())) {
+    if (auto parentInfo = static_cast<SubFolderInfo *>(index.internalPointer())) {
         if (parentInfo->hasLabel()) {
             return 0;
         }
@@ -399,9 +411,9 @@ FolderStatusModel::SubFolderInfo* FolderStatusModel::infoForIndex(const QModelIn
     }
 }
 
-QModelIndex FolderStatusModel::indexForPath(Folder *f, const QStringpath) 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) {
-            autoinfo = _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 QModelIndexparent) 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<SubFolderInfo *>(&_folders[parent.row()]));
-        case SubFolder: {
-            auto pinfo = static_cast<SubFolderInfo*>(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<SubFolderInfo *>(&_folders[parent.row()]));
+    case SubFolder: {
+        auto pinfo = static_cast<SubFolderInfo *>(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 QModelIndexchild) 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<SubFolderInfo*>(child.internalPointer())->_pathIdx;
+    auto pathIdx = static_cast<SubFolderInfo *>(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<SubFolderInfo *>(info));
 }
 
-bool FolderStatusModel::hasChildren(const QModelIndexparent) 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 QModelIndexparent) 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 QModelIndexparent)
+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<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size" << "http://owncloud.org/ns:permissions");
+    job->setProperties(QList<QByteArray>() << "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<QString,QString>&)),
-            this, SLOT(slotGatherPermissions(const QString&, const QMap<QString,QString>&)));
+        SLOT(slotUpdateDirectories(QStringList)));
+    connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
+        this, SLOT(slotLscolFinishedWithError(QNetworkReply *)));
+    connect(job, SIGNAL(directoryListingIterated(const QString &, const QMap<QString, QString> &)),
+        this, SLOT(slotGatherPermissions(const QString &, const QMap<QString, QString> &)));
 
     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<QString,QString> &map)
+void FolderStatusModel::slotGatherPermissions(const QString &href, const QMap<QString, QString> &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, 00);
         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<SubFolderInfo> newSubs;
     newSubs.reserve(sortedSubfolders.size());
-    foreach (const QStringpath, 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(QNetworkReplyr)
+void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply *r)
 {
     auto job = qobject_cast<LsColJob *>(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<QWidget*>(QObject::parent());
+    auto par = qobject_cast<QWidget *>(QObject::parent());
     if (!par->isVisible()) {
         return; // for https://github.com/owncloud/client/issues/2648#issuecomment-71377909
     }
 
-    Folder *f = qobject_cast<Folder*>(sender());
-    if( !f ) { return; }
+    Folder *f = qobject_cast<Folder *>(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;
+    }
 
-    autopi = _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) {
-        FolderManfolderMan = 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 (Folderf, 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 autoundecidedFolder, 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<QPersistentModelIndex, QElapsedTimer> it(_fetchingItems);
     while (it.hasNext()) {
         it.next();
-        if (it.value().elapsed() > 800)
-        {
+        if (it.value().elapsed() > 800) {
             auto idx = it.key();
-            autoinfo = 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(FolderStatusModelmodel, QModelIndex index)
+void FolderStatusModel::SubFolderInfo::resetSubs(FolderStatusModel *model, QModelIndex index)
 {
     _fetched = false;
     _fetching = false;
     if (hasLabel()) {
-        model->beginRemoveRows(index, 0 ,0);
+        model->beginRemoveRows(index, 00);
         _fetchingLabel = false;
         _hasError = false;
         model->endRemoveRows();
index d7ad69cb245cdb5aeb43dffc4231eca9a7f674d4..02bb09618d62c2ea6c88fabf81c2dabe6412269a 100644 (file)
@@ -37,25 +37,35 @@ class FolderStatusModel : public QAbstractItemModel
 {
     Q_OBJECT
 public:
-    FolderStatusModel(QObject * parent = 0);
+    FolderStatusModel(QObject *parent = 0);
     ~FolderStatusModel();
-    void setAccountState(const AccountStateaccountState);
+    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<SubFolderInfo> _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<QString,QString> &properties);
+    void slotGatherPermissions(const QString &name, const QMap<QString, QString> &properties);
     void slotLscolFinishedWithError(QNetworkReply *r);
-    void slotFolderSyncStateChange(Folderf);
+    void slotFolderSyncStateChange(Folder *f);
     void slotFolderScheduleQueueChanged();
     void slotNewBigFolder();
 
@@ -131,10 +151,10 @@ private slots:
     void slotShowFetchProgress();
 
 private:
-    QStringList createBlackList(OCC::FolderStatusModel::SubFolderInforoot,
-                                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<int> &roles = QVector<int>())
-    { emit QAbstractItemModel::dataChanged(topLeft,bottomRight); }
+    {
+        emit QAbstractItemModel::dataChanged(topLeft, bottomRight);
+    }
 #endif
 
 signals:
index 8a9308aa6aa24f00403b7720fc49cb8af5f572bb..0f5fee413ee5c31eacb2ba433d249e4f987be77d 100644 (file)
@@ -39,9 +39,9 @@ namespace OCC {
 
 Q_LOGGING_CATEGORY(lcFolderWatcher, "gui.folderwatcher", QtInfoMsg)
 
-FolderWatcher::FolderWatcher(const QString &root, Folderfolder)
-    : 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<QString> 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
-
index 3f1d1a9813339a82b553a178aabd9caa3b1ac851..334abf1b7552003c055de7c3c494fcb9bd186df5 100644 (file)
@@ -58,7 +58,7 @@ public:
     /**
      * @param root Path of the root of the folder
      */
-    FolderWatcher(const QString &root, Folderfolder = 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 QStringerror);
+    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<QString, int> _pendingPathes;
@@ -92,11 +92,10 @@ private:
     QScopedPointer<FolderWatcherPrivate> _d;
     QTime _timer;
     QSet<QString> _lastPaths;
-    Folder_folder;
+    Folder *_folder;
 
     friend class FolderWatcherPrivate;
 };
-
 }
 
 #endif
index 5a4d2b5901c767528b0f0ef871e2aaf63b46d789..b505b8dd0b084bafd3edc8a8b1a11c3ff8c586d2 100644 (file)
 
 namespace OCC {
 
-FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QStringpath)
-    : 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 QStringpath)
+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_eventevent;
+    struct inotify_event *event;
     int i;
     int error;
     QVarLengthArray<char, 2048> 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<unsigned int>(len)) {
+    while (i + sizeof(struct inotify_event) < static_cast<unsigned int>(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 QStringpath)
+void FolderWatcherPrivate::addPath(const QString &path)
 {
     slotAddFolderRecursive(path);
 }
 
-void FolderWatcherPrivate::removePath(const QStringpath)
+void FolderWatcherPrivate::removePath(const QString &path)
 {
     int wid = -1;
     // Remove the inotify watch.
     QHash<int, QString>::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);
     }
index 9c7ef2a983dc5b8e18f4aacd71656da00c417dbe..24d3377777c23ef803dab245946cfd986f42e551 100644 (file)
@@ -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 QStringpath);
+    bool findFoldersBelow(const QDir &dir, QStringList &fullList);
+    void inotifyRegisterPath(const QString &path);
 
 private:
     FolderWatcher *_parent;
 
     QString _folder;
-    QHash <int, QString> _watches;
+    QHash<int, QString> _watches;
     QScopedPointer<QSocketNotifier> _socket;
     int _fd;
 };
-
 }
 
 #endif
index d18ad8dbab65f1cf3b64545ef7ed0ab9283bb43f..a28277fea9eb98f7fe58164bfe32c63e44d6178e 100644 (file)
 #include <QStringList>
 
 
-
 namespace OCC {
 
-FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QStringpath)
-    : _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<FolderWatcherPrivate*>(clientCallBackInfo)->doNotifyParent(paths);
+    reinterpret_cast<FolderWatcherPrivate *>(clientCallBackInfo)->doNotifyParent(paths);
 }
 
 void FolderWatcherPrivate::startWatching()
 {
     qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::startWatching()" << _folder;
     CFStringRef folderCF = CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(_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
index 52c0a0a693d43c8c71287c136f508e0a6d840143..a25d89f6df3785ace5cd0e9fda6ed4600f74f741 100644 (file)
@@ -21,8 +21,7 @@
 #include <CoreServices/CoreServices.h>
 
 
-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
index 4bf3a7a8098ec157282b7eae9ccda68129bde692..19c623f5663e15b9d98792764573d8c91b63df74 100644 (file)
 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<char, 4096*10> fileNotifyBuffer;
+    QVarLengthArray<char, 4096 * 10> 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<LPCWSTR>(file.utf16()), fileNameBuffer, fileNameBufferSize);
                 if (longNameSize > 0) {
                     longfile = QString::fromUtf16(reinterpret_cast<const ushort *>(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 QStringpath)
+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();
 }
 
index dd5af77fed226434ed283c96cd1966de13381fe0..687ec891d7bcb2c27e5dd7a52029b409c6038c52 100644 (file)
@@ -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 QStringpath);
+    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
index 199977efaf5f68fbbf82382b882e7064e121dcc0..940cf8b3ac7d78b8c8cac36964aa4f7aaaffcd53 100644 (file)
@@ -37,8 +37,7 @@
 
 #include <stdlib.h>
 
-namespace OCC
-{
+namespace OCC {
 
 QString FormatWarningsWizardPage::formatWarnings(const QStringList &warnings) const
 {
@@ -47,7 +46,7 @@ QString FormatWarningsWizardPage::formatWarnings(const QStringList &warnings) co
         ret = tr("<b>Warning:</b> %1").arg(warnings.first());
     } else if (warnings.count() > 1) {
         ret = tr("<b>Warning:</b>") + " <ul>";
-        Q_FOREACH(QString warning, warnings) {
+        Q_FOREACH (QString warning, warnings) {
             ret += QString::fromLatin1("<li>%1</li>").arg(warning);
         }
         ret += "</ul>";
@@ -56,9 +55,9 @@ QString FormatWarningsWizardPage::formatWarnings(const QStringList &warnings) co
     return ret;
 }
 
-FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtraccount)
-    : 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 AccountPtraccount)
+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<MkColJob *>(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 QStringpath, 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 QStringtext)
+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 QStringListsubpaths)
+void FolderWizardRemotePath::slotTypedPathFound(const QStringList &subpaths)
 {
     slotUpdateDirectories(subpaths);
     selectByPath(_ui.folderEntry->text());
 }
 
-void FolderWizardRemotePath::slotTypedPathError(QNetworkReplyreply)
+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<QByteArray>() << "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<Folder*>(i.value());
+    for (i = map.constBegin(); i != map.constEnd(); i++) {
+        Folder *f = static_cast<Folder *>(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 <i>%1</i>, which is a parent folder of <i>%2</i>.").arg(
-                Utility::escape(curDir), Utility::escape(dir)));
+            warnStrings.append(tr("You are already syncing <i>%1</i>, which is a parent folder of <i>%2</i>.").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 AccountPtraccount)
+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
-
index f598b14752c7287f3897f1a27d9dccb090e42fbc..e24cb5ac9ee93c9cc95417f75f8cde097e6f602f 100644 (file)
@@ -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 AccountPtraccount);
+    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 AccountPtraccount);
+    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 QStringtext);
+    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 AccountPtraccount);
+    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;
index 9f285f9bf2aa0b778b55680147e6221a80b8fda4..853fd730b8c6063dc062e54f09ac8e93d968065b 100644 (file)
 
 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<bool> 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<OCUpdater*>(Updater::instance());
+    OCUpdater *updater = qobject_cast<OCUpdater *>(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);
index 8652a7dbbd4e3fe5650c74224dcbed762cda5f4d..360e651674d36d038c0bb2a38fee7b88022ca130 100644 (file)
@@ -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<IgnoreListEditor> _ignoreEditor;
     QPointer<SyncLogDialog> _syncLogDialog;
index d21cd0d875efbb5fe469f7ed90ee32bc39132087..83fd39ffd9a7ca2cfcbb7b2a7905c35cc97e07a8 100644 (file)
@@ -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 (Folderfolder, 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;
index b6fcf0df6d1cdf9ad32847e49c948384e9abfafd..0018e2361f2bae61b7cbccb905c58d95480a6629 100644 (file)
@@ -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 QStringfile, bool readOnly);
-    int addPattern(const QStringpattern, 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;
 };
index 832edc9001a4761d4d410ee5916df2bcb5cad61e..da83744a9a90d5dd36318400761c269245f32b7b 100644 (file)
@@ -24,15 +24,15 @@ Q_LOGGING_CATEGORY(lcLockWatcher, "gui.lockwatcher", QtInfoMsg)
 
 static const int check_frequency = 20 * 1000; // ms
 
-LockWatcher::LockWatcher(QObjectparent)
+LockWatcher::LockWatcher(QObject *parent)
     : QObject(parent)
 {
     connect(&_timer, SIGNAL(timeout()),
-            SLOT(checkFiles()));
+        SLOT(checkFiles()));
     _timer.start(check_frequency);
 }
 
-void LockWatcher::addFile(const QStringpath)
+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<QString> unlocked;
 
-    foreach (const QStringpath, _watchedPaths) {
+    foreach (const QString &path, _watchedPaths) {
         if (!FileSystem::isFileLocked(path)) {
             qCInfo(lcLockWatcher) << "Lock of" << path << "was released";
             emit fileUnlocked(path);
index 9815940718c95618114da5782b77506be2af4ebb..ba2d8f8a75ce3f528bfd27705aec6a36c1d14f13 100644 (file)
@@ -42,19 +42,19 @@ class LockWatcher : public QObject
 {
     Q_OBJECT
 public:
-    explicit LockWatcher(QObjectparent = 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 QStringpath);
+    void addFile(const QString &path);
 
 signals:
     /** Emitted when one of the watched files is no longer
      *  being locked. */
-    void fileUnlocked(const QStringpath);
+    void fileUnlocked(const QString &path);
 
 private slots:
     void checkFiles();
@@ -63,5 +63,4 @@ private:
     QSet<QString> _watchedPaths;
     QTimer _timer;
 };
-
 }
index b4971bf4507365480a36a47f3edc9349e7d54a60..41b526a3c89fb33ef63eea4e5bdd6009f2ee4a22 100644 (file)
@@ -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<QTextEdit::ExtraSelection> 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()
index 940e7a9277d4c999b754a6df8b868390c574f201..a1c5c6da0c27b0a43348a80858f2b4583a4c3289 100644 (file)
@@ -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
index f846f6ae3b034d36174350735c2fa2b50503e75b..8f77b50bc23aa599c3dd77526b948b3509d3075d 100644 (file)
@@ -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 "
-                                          "<a href=\"http://docs.xfce.org/xfce/xfce4-panel/systray\">these instructions</a>. "
-                                          "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 "
+                                    "<a href=\"http://docs.xfce.org/xfce/xfce4-panel/systray\">these instructions</a>. "
+                                    "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();
 }
-
index 88f38259aea09c3804c4a6589fbccca8c0baf1f0..ff99524e187a8f36b61606124930d0aa2f895b69 100644 (file)
@@ -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;
index a64eaff29ea889b55a9f32b3ccb673bb438207d4..34419a26161ec220e2908a24f33246540aae6b01 100644 (file)
@@ -21,7 +21,7 @@
 namespace OCC {
 
 namespace Ui {
-class NetworkSettings;
+    class NetworkSettings;
 }
 
 /**
index 537f763c735d0a8f81528e82e27f98a9acf232e5..871ce64493d7872b7e993769a9ceee0b93544564 100644 (file)
@@ -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 QUrllink, 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( "<?xml version=\"1.0\"?>") ) {
-         QRegExp rex("<statuscode>(\\d+)</statuscode>");
-         if( replyStr.contains(rex) ) {
-             // this is a error message coming back from ocs.
-             replyCode = rex.cap(1).toInt();
-         }
+    if (replyStr.contains("<?xml version=\"1.0\"?>")) {
+        QRegExp rex("<statuscode>(\\d+)</statuscode>");
+        if (replyStr.contains(rex)) {
+            // this is a error message coming back from ocs.
+            replyCode = rex.cap(1).toInt();
+        }
     }
     emit jobFinished(replyStr, replyCode);
 
     return true;
-
 }
-
 }
index a65e458d124bb11b58829c1ddffb7ff69613b9d5..4602dcf678f8f3bbb511d0b24be321c027777ce2 100644 (file)
@@ -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 QUrllink, 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
index 6d6cfa95280f5a456ed2aac58bd4e435bc4d529a..7d1132c6ae1cf35853e494a2bf61d37263f4d037 100644 (file)
@@ -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 Activityactivity)
+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();
-
 }
-
 }
index 06265494d873405e81bafc9f625c6a2f38b8c5a7..ce0e95f2b586d04d5ffce7e325929c3f750bee47 100644 (file)
@@ -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<QPushButton*> _buttons;
+    QList<QPushButton *> _buttons;
     QString _accountName;
     QProgressIndicator *_progressIndi;
     QString _actionLabel;
 };
-
 }
 
 #endif // NOTIFICATIONWIDGET_H
index 3ce97416964a5d5d002c32618b339632c83992ec..cc1e0d9faaafbff89391f9b770dca05836a2bf7b 100644 (file)
@@ -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<QPair<QByteArray, QByteArray>>
 percentEncodeQueryItems(
-        const QList<QPair<QString, QString>> & items)
+    const QList<QPair<QString, QString>> &items)
 {
     QList<QPair<QByteArray, QByteArray>> result;
-    foreach (const autoitem, 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;
 }
-
 }
index 9a02201e540fd71126ed6dd75957c3f28a01ff05..4560b3a364e3e28cdbc6dc916dd8bacd8fbd40d9 100644 (file)
@@ -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 QByteArrayverb);
+    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 QStringname, 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<QPair<QString, QString> >& postParams);
+    void setPostParams(const QList<QPair<QString, QString>> &postParams);
 
     /**
      * List of expected statuscodes for this request
@@ -127,10 +127,9 @@ private slots:
 
 private:
     QByteArray _verb;
-    QList<QPair<QString, QString> > _params;
+    QList<QPair<QString, QString>> _params;
     QVector<int> _passStatusCodes;
 };
-
 }
 
 #endif // OCSJOB_H
index 652859dd9d06cbc71dd4fd7b7d1742d025dfb128..b359201c009ab1026a1f9bcc7281bd8b56956c20 100644 (file)
 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);
 }
-
 }
index c38016768925455b049a86344275f739ee36e6f1..f511f5fb8355c43fa3fd7787882580d3b5da179f 100644 (file)
@@ -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
index b73cc72a14395153efd2428c17513dc08491db56..9b93ee99f77b5da6a12794f3b9b4b2e35652ef0b 100644 (file)
@@ -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);
 }
-
 }
index 6e2d834071ac4299117a80d5919042decfd74309..09c69410d8f2796d75c2a9e416bb712bc0c8210b 100644 (file)
@@ -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 QStringpath = "");
+    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 QDatedate);
+    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 QStringpassword);
+    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
index 84e066e12c319bab86efe726c4ab7e32669f0807..d06402eca4e6951f7c0a41343f61fda3e376455e 100644 (file)
@@ -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)
         }
     }
 }
-
 }
index a82836f8b4342c0284c08e62cb41aba12d5af9b4..25418c62abb77b4340aa15e92a070c0c679afd99 100644 (file)
 #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> &shareDialog, _shareDialogs) {
+            Q_FOREACH (const QPointer<ShareDialog> &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(Accountaccount)
+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 (Folderf, 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 (Folderfolder, 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<QObject*>(_tray->contextMenu()->platformMenu());
+        QObject *platformMenu = reinterpret_cast<QObject *>(_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) {
-            QMenuaccountMenu = 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");
         }
-        QActionaction = _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");
         }
-        QActionaction = _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 SyncFileItemitem)
+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 ProgressInfoprogress)
+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<AccountState*> accounts;
+    QList<AccountState *> accounts;
     if (auto account = qvariant_cast<AccountStatePtr>(sender()->property(propertyAccountC))) {
         accounts.append(account.data());
     } else {
@@ -917,7 +918,7 @@ void ownCloudGui::setPauseOnAllFoldersHelper(bool pause)
             accounts.append(a.data());
         }
     }
-    foreach (Folderf, 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)
 {
-    ifraiseWidget && 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<QString, QPointer<ShareDialog> > it(_shareDialogs);
+    QMutableMapIterator<QString, QPointer<ShareDialog>> it(_shareDialogs);
     while (it.hasNext()) {
         it.next();
-        if (! it.value() || it.value() == sender()) {
+        if (!it.value() || it.value() == sender()) {
             it.remove();
         }
     }
index f72a5a437c0646bfcdfb4c5bf19e63bfb68cf46e..c0238a76176f4e27736e38400eab9969d42fea8e 100644 (file)
@@ -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 ProgressInfoprogress);
+    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 QStringpath);
+    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, QMenumenu, bool separateMenu);
+    void addAccountContextMenu(AccountStatePtr accountState, QMenu *menu, bool separateMenu);
 
     QPointer<Systray> _tray;
 #if defined(Q_OS_MAC)
@@ -108,8 +108,8 @@ private:
 #else
     QPointer<SettingsDialog> _settingsDialog;
 #endif
-    QPointer<LogBrowser>_logBrowser;
-       // tray's menu
+    QPointer<LogBrowser> _logBrowser;
+    // tray's menu
     QScopedPointer<QMenu> _contextMenu;
 
     // Manually tracking whether the context menu is visible, but only works
@@ -117,10 +117,10 @@ private:
     bool _contextMenuVisibleOsx;
 
     QMenu *_recentActionsMenu;
-    QVector<QMenu*> _accountMenus;
+    QVector<QMenu *> _accountMenus;
     bool _qdbusmenuWorkaround;
     QTimer _workaroundBatchTrayUpdate;
-    QMap<QString, QPointer<ShareDialog> > _shareDialogs;
+    QMap<QString, QPointer<ShareDialog>> _shareDialogs;
 
     QAction *_actionLogin;
     QAction *_actionLogout;
@@ -134,7 +134,7 @@ private:
     QAction *_actionQuit;
     QAction *_actionCrash;
 
-    QList<QAction*> _recentItemsActions;
+    QList<QAction *> _recentItemsActions;
 
     QSignalMapper *_folderOpenActionMapper;
     QSignalMapper *_recentItemsMapper;
index 7a52899791c357c1dde889500e7e87e51ecb2056..9a7359f3ef97af6780080d2e68b0e2e022ee13e8 100644 (file)
 
 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<OwncloudSetupWizard> 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 QUrlurl, const QJsonObject &info)
+void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl &url, const QJsonObject &info)
 {
     auto serverVersion = CheckServerJob::version(info);
 
     _ocWizard->appendToConfigurationLog(tr("<font color=\"green\">Successfully connected to %1: %2 version %3 (%4)</font><br/><br/>")
-                                        .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:<br/>%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<PropfindJob*>(sender());
+    PropfindJob *job = qobject_cast<PropfindJob *>(sender());
     if (!job) {
         qCWarning(lcWizard) << "Can't check for authed redirects. This slot should be invoked from PropfindJob!";
         return;
     }
-    QNetworkReplyreply = 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(QNetworkReplyreply)
+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!"
-                                    "<br/>Please go back and check your credentials.</p>"), false);
-        _ocWizard->appendToConfigurationLog( tr("<p><font color=\"red\">Remote folder creation failed probably because the provided credentials are wrong.</font>"
-                                                "<br/>Please go back and check your credentials.</p>"));
+    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!"
+                                   "<br/>Please go back and check your credentials.</p>"),
+            false);
+        _ocWizard->appendToConfigurationLog(tr("<p><font color=\"red\">Remote folder creation failed probably because the provided credentials are wrong.</font>"
+                                               "<br/>Please go back and check your credentials.</p>"));
         _remoteFolder.clear();
         success = false;
     } else {
-        _ocWizard->appendToConfigurationLog( tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_remoteFolder)).arg(error));
-        _ocWizard->displayError( tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_remoteFolder)).arg(error), false );
+        _ocWizard->appendToConfigurationLog(tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_remoteFolder)).arg(error));
+        _ocWizard->displayError(tr("Remote folder %1 creation failed with error <tt>%2</tt>.").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("<p><font color=\"green\"><b>")
-                                             + tr("Successfully connected to %1!")
-                                             .arg(Theme::instance()->appNameGUI())
-                                             + QLatin1String("</b></font></p>"));
+        _ocWizard->appendToConfigurationLog(QLatin1String(" "));
+        _ocWizard->appendToConfigurationLog(QLatin1String("<p><font color=\"green\"><b>")
+            + tr("Successfully connected to %1!")
+                  .arg(Theme::instance()->appNameGUI())
+            + QLatin1String("</b></font></p>"));
         _ocWizard->successfulStep();
     } else {
         // ### this is not quite true, pass in the real problem as optional parameter
         _ocWizard->appendToConfigurationLog(QLatin1String("<p><font color=\"red\">")
-                                            + tr("Connection to %1 could not be established. Please check again.")
-                                            .arg(Theme::instance()->appNameGUI())
-                                            + QLatin1String("</font></p>"));
+            + tr("Connection to %1 could not be established. Please check again.")
+                  .arg(Theme::instance()->appNameGUI())
+            + QLatin1String("</font></p>"));
     }
 }
 
-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("<font color=\"green\"><b>Local sync folder %1 successfully created!</b></font>").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()
index d26fb9cdced247c474589867e113726497d61b7f..39f401db6b25c44b45f9c07642ae9d027a7db557 100644 (file)
@@ -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(QNetworkReplyreply);
+    bool checkDowngradeAdvised(QNetworkReply *reply);
 
-    OwncloudWizard_ocWizard;
+    OwncloudWizard *_ocWizard;
     QString _initLocalFolder;
     QString _remoteFolder;
 };
-
 }
 
 #endif // OWNCLOUDSETUPWIZARD_H
index 8828d2fd652f9727aecccf2b01ff93849805f548..9d7058dd8b84d1c68b05e3a3e23dc49bddec005e 100644 (file)
 
 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 QStringfolder)
+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(QTextStreamts)
+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(QTextStreamts)
+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;
     }
 }
-
 }
index de11bdcd07a9d46ec6202a7ace2dd61ab9533e86..927a23c4b10dbe897cc93034304f13e3198228bc 100644 (file)
@@ -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(QTextStreamts);
-    void storeSyncIssues(QTextStreamts);
+    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
index 044d8c9f2774d9d2154ccb01001655f4d5874f82..c5680bb7e7a1098826dc46781c062fb20e3cea7b 100644 (file)
@@ -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);
 }
index 5b6f27d037b44a69912b71a51e99c16b1d1a3b57..5a6e7bd4cee887f8451dfbc9d63a689238ed5eaf 100644 (file)
@@ -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 QStringaddress);
+    void setProxyAddress(const QString &address);
 
     QString username() const;
     QString password() const;
index 479b3f224082bb495fdbb54caab6a0aa848d0f07..5b7d7382da9d85d6d9c098c6443caebaafa91ce3 100644 (file)
@@ -27,7 +27,7 @@ using namespace OCC;
 
 Q_LOGGING_CATEGORY(lcProxy, "gui.credentials.proxy", QtInfoMsg)
 
-ProxyAuthHandlerProxyAuthHandler::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.
-    QNetworkAccessManagersending_qnam = 0;
+    QNetworkAccessManager *sending_qnam = 0;
     QWeakPointer<QNetworkAccessManager> qnam_alive;
-    if (Account* account = qobject_cast<Account*>(sender())) {
+    if (Account *account = qobject_cast<Account *>(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(QObjectobj)
+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);
 
-    WritePasswordJobjob = 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();
 
index b1fc3d0f82ba7807492d38c2fbd52ee374ef0c87..3d5afedd3f13809bddc8d37a8f6b99bf182ab075 100644 (file)
@@ -47,18 +47,18 @@ class ProxyAuthHandler : public QObject
     Q_OBJECT
 
 public:
-    static ProxyAuthHandlerinstance();
+    static ProxyAuthHandler *instance();
 
     virtual ~ProxyAuthHandler();
 
 public slots:
     /// Intended for QNetworkAccessManager::proxyAuthenticationRequired()
-    void handleProxyAuthenticationRequired(const QNetworkProxyproxy,
-                                           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<QObject*> _gaveCredentialsTo;
+    QSet<QObject *> _gaveCredentialsTo;
 };
 
 } // namespace OCC
index f2ccb2c55f61a0f7d82f64ffa2cd34b63484acc0..1eb1066cc9d9bc0fad95e2a08d7b3c0093d3cd1f 100644 (file)
@@ -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<QByteArray>() << "quota-available-bytes" << "quota-used-bytes");
+    _job->setProperties(QList<QByteArray>() << "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();
 }
-
 }
index 90725e0819b2f763b4a22818674a449dd11fb5ef..4fef65a95ea407613d1a95d99ae359845ac4f4b4 100644 (file)
@@ -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
index c103317233da5903b176490c3f650317644d14f5..1663ca4817458114a0c1a8445d14d4c9c2e062a3 100644 (file)
 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<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size");
+    job->setProperties(QList<QByteArray>() << "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(QTreeWidgetItemparent, 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<SelectiveSyncTreeViewItem*>(findFirstChild(parent, pathTrail.first()));
+        SelectiveSyncTreeViewItem *item = static_cast<SelectiveSyncTreeViewItem *>(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<bool> isInserting(_inserting);
     _inserting = true;
 
-    SelectiveSyncTreeViewItem *root = static_cast<SelectiveSyncTreeViewItem*>(_folderTree->topLevelItem(0));
+    SelectiveSyncTreeViewItem *root = static_cast<SelectiveSyncTreeViewItem *>(_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<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size");
+    job->setProperties(QList<QByteArray>() << "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(QTreeWidgetItemroot) 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(QTreeWidgetItemroot)
+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();
 }
-
 }
-
index e49dfee973045ce847f40152df4eff817eab49f6..15e4d7d331c9eb6218e8c4d5d245e865f59e1633 100644 (file)
@@ -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, QWidgetparent = 0);
+    explicit SelectiveSyncWidget(AccountPtr account, QWidget *parent = 0);
 
     /// Returns a list of blacklisted paths, each including the trailing /
-    QStringList createBlackList(QTreeWidgetItemroot = 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(QTreeWidgetItemparent, 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, QWidgetparent = 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, QWidgetparent = 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;
 };
-
 }
index 62ba5e973e39ffe01ce807dd93694e4355669852..afbd66ddff2fb4bb6395aed9264dd32f3f4ebe8a 100644 (file)
 #include <QJsonDocument>
 #include <QJsonObject>
 
-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<AccountState*>(ptr));
+        this, SLOT(slotNotificationsReceived(QJsonDocument, int)));
+    _notificationJob->setProperty("AccountStatePtr", QVariant::fromValue<AccountState *>(ptr));
 
     _notificationJob->start();
 }
 
-void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocumentjson, 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<AccountState*>(sender()->property("AccountStatePtr"));
+    AccountState *ai = qvariant_cast<AccountState *>(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();
-        foreachauto 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();
 }
-
 }
index 8c8fef976de736dc05a362087b6615a7e13eb33c..875c3189ef9bb9055281825c883db0a270b2dd4a 100644 (file)
@@ -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 QJsonDocumentjson, int statusCode);
+    void slotNotificationsReceived(const QJsonDocument &json, int statusCode);
 
 private:
     QPointer<JsonApiJob> _notificationJob;
-
-
 };
-
 }
 
 #endif // SERVERNOTIFICATIONHANDLER_H
index 6c9fc1b546cdef1d711a7b7c01144a8defe362ca..bb44a080aa8880a376cf84e0edb3a4c5faf2fee2 100644 (file)
 #include <QPainterPath>
 
 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<QAction*> actions = _toolBar->actions();
+    QList<QAction *> 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<Account*>(sender());
-    ifaccount && _actionForAccount.contains(account)) {
+    Account *account = static_cast<Account *>(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<QToolButton*>(_toolBar->widgetForAction(a));
+        QToolButton *btn = qobject_cast<QToolButton *>(_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<QToolBar*>(parent);
+    QWidget *createWidget(QWidget *parent) Q_DECL_OVERRIDE
+    {
+        auto toolbar = qobject_cast<QToolBar *>(parent);
         if (!toolbar) {
             // this means we are in the extention menu, no special action here
             return 0;
         }
 
-        QToolButtonbtn = new QToolButton(parent);
+        QToolButton *btn = new QToolButton(parent);
         btn->setDefaultAction(this);
         btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
         btn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
-//         btn->setMinimumWidth(qMax<int>(parent->sizeHint().height() * buttonSizeRatio,
-//                                        btn->sizeHint().width()));
+        //         btn->setMinimumWidth(qMax<int>(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);
index 39f2595a1ae62a4d5125b246cf7a0516d511ecdf..9d445995994a76b3512a3daa5c2940aad5422cdf 100644 (file)
@@ -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<QAction*, QWidget*> _actionGroupWidgets;
+    QHash<QAction *, QWidget *> _actionGroupWidgets;
 
     // Maps the action in the dialog to their according account. Needed in
     // case the account avatar changes
-    QHash<Account*, QAction*> _actionForAccount;
+    QHash<Account *, QAction *> _actionForAccount;
 
-    QToolBar_toolBar;
+    QToolBar *_toolBar;
 
     ActivitySettings *_activitySettings;
 
-    QAction * _activityAction;
+    QAction *_activityAction;
     ownCloudGui *_gui;
 };
-
 }
 
 #endif // SETTINGSDIALOG_H
index 65ae6ac389ef620f39d2c9de3f10eafd8f649c8e..486bc7018435f6ee48e4dd21e8513205ca35dc2e 100644 (file)
@@ -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<AccountSettings*>(QString());
-    foreach(auto p, list) {
+    auto list = findChildren<AccountSettings *>(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<Account*>(sender());
-    auto list = findChildren<AccountSettings*>(QString());
-    foreach(auto p, list) {
+    Account *account = static_cast<Account *>(sender());
+    auto list = findChildren<AccountSettings *>(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()
         }
     }
 }
-
 }
index a000461534e38a68f13e306841aae322bd5868c9..f931f90095c69d1f10666e36b12ea6a3d9529f1d 100644 (file)
@@ -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
index 3ad8eed321f39e4b5bd5ae183cfc9f6032dd8d53..60d6167d41397612201d03c5338a43744d09d0e8 100644 (file)
@@ -35,19 +35,19 @@ namespace OCC {
 static const int thumbnailSize = 40;
 
 ShareDialog::ShareDialog(QPointer<AccountState> 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> 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> 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> accountState,
     job->setProperties(QList<QByteArray>() << "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);
     }
 }
-
 }
-
index f7a3380d1c92268c56bd1d72d3a8aa0841107397..dac7b9841dd5eceffbb24b923516477fa967d9dc 100644 (file)
@@ -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> 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
index 1553a3069c49d709558666c38a71688b16206124..2d1ca4d498ff375e660a2d3dd7bffe3598e5b8ac 100644 (file)
@@ -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<QSharedPointer<Sharee>> 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<Sharee> ShareeModel::parseSharee(const QJsonObject &data)
 
 // Helper function for setNewSharees   (could be a lambda when we can use them)
 static QSharedPointer<Sharee> shareeFromModelIndex(const QModelIndex &idx)
-{ return idx.data(Qt::UserRole).value<QSharedPointer<Sharee>>(); }
+{
+    return idx.data(Qt::UserRole).value<QSharedPointer<Sharee>>();
+}
 
-struct FindShareeHelper {
+struct FindShareeHelper
+{
     const QSharedPointer<Sharee> &sharee;
-    bool operator()(const QSharedPointer<Sharee> &s2) const {
+    bool operator()(const QSharedPointer<Sharee> &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<QSharedPointer<Sharee>>newSharees)
+void ShareeModel::setNewSharees(const QVector<QSharedPointer<Sharee>> &newSharees)
 {
     layoutAboutToBeChanged();
     const auto persistent = persistentIndexList();
@@ -172,13 +178,13 @@ void ShareeModel::setNewSharees(const QVector<QSharedPointer<Sharee>>& 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> &sharee, oldPersistantSharee) {
+    foreach (const QSharedPointer<Sharee> &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<Sharee> ShareeModel::getSharee(int at) {
+QSharedPointer<Sharee> ShareeModel::getSharee(int at)
+{
     if (at < 0 || at > _sharees.size()) {
         return QSharedPointer<Sharee>(NULL);
     }
 
     return _sharees.at(at);
 }
-
 }
index 0391eae531fab1a9cae10c45cedfc89c32f7f5e0..ec053d2a96a42fed96079bf4227ac633e59e89ee 100644 (file)
@@ -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<QSharedPointer<Sharee>> _sharees;
     QVector<QSharedPointer<Sharee>> _shareeBlacklist;
 };
-
 }
 
 Q_DECLARE_METATYPE(QSharedPointer<OCC::Sharee>)
 
-#endif  //SHAREE_H
+#endif //SHAREE_H
index dcdff486a926e742bb9a9045558263e924f880b8..3988a9a833e3c30827456fba8b7e7ddc0e4fd402 100644 (file)
@@ -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<QSharedPointer<Share>>)), SLOT(slotSharesFetched(QList<QSharedPointer<Share>>)));
     connect(_manager, SIGNAL(linkShareCreated(QSharedPointer<LinkShare>)), SLOT(slotCreateShareFetched(const QSharedPointer<LinkShare>)));
     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<QSharedPointer<Share>> &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<QSharedPointer<Share>> &shar
         auto linkShare = qSharedPointerDynamicCast<LinkShare>(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<QSharedPointer<Share>> &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 QStringnewText)
+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(QTableWidgetItemitem)
+void ShareLinkWidget::slotNameEdited(QTableWidgetItem *item)
 {
     if (!_namesSupported) {
         return;
@@ -429,7 +428,7 @@ void ShareLinkWidget::slotCreateShareFetched(const QSharedPointer<LinkShare> sha
     getShares();
 }
 
-void ShareLinkWidget::slotCreateShareRequiresPassword(const QStringmessage)
+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 QStringerrMsg)
+void ShareLinkWidget::displayError(const QString &errMsg)
 {
-    _ui->errorLabel->setText( errMsg );
+    _ui->errorLabel->setText(errMsg);
     _ui->errorLabel->show();
 }
-
 }
index c919b86d51eef3291112505f81a822b338dc9507..78dcc596b7147e1add3a6ccee2b1040982aff89e 100644 (file)
@@ -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 QStringnewText);
-    void slotNameEdited(QTableWidgetItemitem);
+    void slotPasswordChanged(const QString &newText);
+    void slotNameEdited(QTableWidgetItem *item);
 
-    void slotShareLinkButtonTriggered(QActionaction);
+    void slotShareLinkButtonTriggered(QAction *action);
 
     void slotDeleteShareFetched();
     void slotCreateShareFetched(const QSharedPointer<LinkShare> share);
-    void slotCreateShareRequiresPassword(const QStringmessage);
+    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 QStringerrMsg);
+    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
index 3993430fd5405bf742489fa8239300ffb9b9c9c0..cc8233289ef916fa8b93a838132fc126b078e85e 100644 (file)
@@ -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<Sharee> 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<Sharee> 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 QStringname)
+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 QJsonDocumentreply, 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 QStringpath,
-                               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<QSharedPointer<Share>> 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<LinkShare> 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<LinkShare>(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<Share> ShareManager::parseShare(const QJsonObject &data)
 {
     QSharedPointer<Sharee> 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<Share>(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);
 }
-
 }
index 72e3d73de260354a37971aea916d8cc7b2fa3376..62ff6ee4c60be0450160992b465de91b2935b6f0 100644 (file)
@@ -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<Sharee> shareWith = QSharedPointer<Sharee>(NULL));
+        const QString &id,
+        const QString &path,
+        const ShareType shareType,
+        const Permissions permissions = SharePermissionDefault,
+        const QSharedPointer<Sharee> shareWith = QSharedPointer<Sharee>(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 QStringname);
+    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 QStringpassword);
+    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 QDateexpireDate);
+    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 QJsonDocumentreply, 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 QStringpath,
-                         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 QStringpath,
-                     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 QStringpath);
+    void fetchShares(const QString &path);
 
 signals:
     void shareCreated(const QSharedPointer<Share> &share);
@@ -305,10 +305,9 @@ private:
     QSharedPointer<LinkShare> parseLinkShare(const QJsonObject &data);
     QSharedPointer<Share> parseShare(const QJsonObject &data);
 
-    QMap<QObject*, QVariant> _jobContinuation;
+    QMap<QObject *, QVariant> _jobContinuation;
     AccountPtr _account;
 };
-
 }
 
 #endif // SHAREMANAGER_H
index 8a8f906e9eb973c7248950dbf45a8c91327bea56..5d1245912fd0f1ff378afcb9e7920baa46473872 100644 (file)
@@ -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)
index 66008b4d155dc03387d21c0c8f3689ae07db5714..1351f888f38d651b9cae2b727c24483ed06b42b1 100644 (file)
 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<QSharedPointer<Share>>)), SLOT(slotSharesFetched(QList<QSharedPointer<Share>>)));
     connect(_manager, SIGNAL(shareCreated(QSharedPointer<Share>)), 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 QStringtext)
+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<Sharee> currentUser(new Sharee(_account->credentials()->user(), "", Sharee::Type::User));
     blacklist << currentUser;
 
-    foreach (auto sw, _ui->scrollArea->findChildren<ShareUserLine*>()) {
+    foreach (auto sw, _ui->scrollArea->findChildren<ShareUserLine *>()) {
         blacklist << sw->share()->getShareWith();
     }
     _ui->errorLabel->hide();
@@ -180,7 +180,7 @@ void ShareUserGroupWidget::slotSharesFetched(const QList<QSharedPointer<Share>>
     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<QSharedPointer<Share>>
 void ShareUserGroupWidget::slotAdjustScrollWidgetSize()
 {
     QScrollArea *scrollArea = _ui->scrollArea;
-    if (scrollArea->findChildren<ShareUserLine*>().count() <= 3) {
+    if (scrollArea->findChildren<ShareUserLine *>().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<QVBoxLayout*>(viewPort->layout());
+    auto layout = qobject_cast<QVBoxLayout *>(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 QStringmessage)
+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<QProgressIndicator*>()) {
+    foreach (auto pi, _ui->scrollArea->findChildren<QProgressIndicator *>()) {
         delete pi;
     }
 
@@ -302,18 +302,18 @@ void ShareUserGroupWidget::displayError(int code, const QString& message)
 }
 
 ShareUserLine::ShareUserLine(QSharedPointer<Share> 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> 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> 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> 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);
     }
 }
-
 }
index 6da721435c2a446087c06af54ef8dee81ac75521..36639196da821ef59cdf5b9fff16c08ec4de58e9 100644 (file)
@@ -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 codeconst QString &message);
 
 private:
     Ui::ShareUserGroupWidget *_ui;
@@ -104,9 +104,9 @@ class ShareUserLine : public QWidget
 
 public:
     explicit ShareUserLine(QSharedPointer<Share> Share,
-                           SharePermissions maxSharingPermissions,
-                           bool isFile,
-                           QWidget *parent = 0);
+        SharePermissions maxSharingPermissions,
+        bool isFile,
+        QWidget *parent = 0);
     ~ShareUserLine();
 
     QSharedPointer<Share> 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
index a4973aeb84a0e6a74e6804cf3ee195113872d7fa..82705c59ae5ee2e19642f794528fba9258ce5496 100644 (file)
 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:
-    QIODevicesocket;
+    QIODevice *socket;
 
-    SocketListener(QIODevice* socket = 0) : socket(socket) { }
+    SocketListener(QIODevice *socket = 0)
+        : socket(socket)
+    {
+    }
 
-    void sendMessage(const QStringmessage, 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 QStringmessage, 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(QObjectparent)
+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()
 {
-    QIODevicesocket = _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(QObjectobj)
+void SocketApi::slotSocketDestroyed(QObject *obj)
 {
-    QIODevice* socket = static_cast<QIODevice*>(obj);
+    QIODevice *socket = static_cast<QIODevice *>(obj);
     _listeners.erase(std::remove_if(_listeners.begin(), _listeners.end(), ListenerHasSocketPred(socket)), _listeners.end());
 }
 
 void SocketApi::slotReadSocket()
 {
-    QIODevice* socket = qobject_cast<QIODevice*>(sender());
+    QIODevice *socket = qobject_cast<QIODevice *>(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 QStringmsg, bool doWait)
+void SocketApi::broadcastMessage(const QString &msg, bool doWait)
 {
     foreach (auto &listener, _listeners) {
         listener.sendMessage(msg, doWait);
     }
 }
 
-void SocketApi::broadcastStatusPushMessage(const QStringsystemPath, 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, SocketListenerlistener)
+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 &, SocketListenerlistener)
+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 QStringpath)
+QString SocketApi::buildRegisterPathMessage(const QString &path)
 {
     QFileInfo fi(path);
     QString message = QLatin1String("REGISTER_PATH:");
index 2c14cff273b5a024ea37f0ab773ad4309bde42fa..e0b4c3ada3dc9d81096c5393dcf160e5d17ba97f 100644 (file)
@@ -43,16 +43,16 @@ class SocketListener;
  */
 class SocketApi : public QObject
 {
-Q_OBJECT
+    Q_OBJECT
 
 public:
-    explicit SocketApi(QObjectparent = 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(QObjectobj);
+    void slotSocketDestroyed(QObject *obj);
     void slotReadSocket();
-    void broadcastStatusPushMessage(const QStringsystemPath, SyncFileStatus fileStatus);
+    void broadcastStatusPushMessage(const QString &systemPath, SyncFileStatus fileStatus);
 
 private:
-    void broadcastMessage(const QStringmsg, 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 QStringpath);
+    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<QString> _registeredAliases;
     QList<SocketListener> _listeners;
     SocketApiServer _localServer;
 };
-
 }
 #endif // SOCKETAPI_H
index 8a6a4d50365cef5d97d369f05e8528a2fb653715..89401c31e8c78d1118e2c857695371afd669c999 100644 (file)
@@ -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<QSslCertificate>& userApproved, int pos)
+QMenu *SslButton::buildCertMenu(QMenu *parent, const QSslCertificate &cert,
+    const QList<QSslCertificate> &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("<br/>")
-            + Utility::escape(Utility::formatFingerprint(sha265hash.mid(sha265hash.length()/2), false));
+        Utility::escape(Utility::formatFingerprint(sha265hash.left(sha265hash.length() / 2), false))
+        + QLatin1String("<br/>")
+        + 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("<table>");
     stream << addCertDetailsField(tr("Common Name (CN):"), Utility::escape(cn));
-    stream << addCertDetailsField(tr("Subject Alternative Names:"), Utility::escape(sna)
-                                  .replace(" ", "<br/>"));
+    stream << addCertDetailsField(tr("Subject Alternative Names:"), Utility::escape(sna).replace(" ", "<br/>"));
     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<QSslCertificate> 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;
             }
index dec5e74f1e20d4708e2c2b152f10bd24fefad27b..ffdafe52b6b785627fbfc4107e3f77da68ab26fc 100644 (file)
@@ -43,10 +43,10 @@ public slots:
     void slotUpdateMenu();
 
 private:
-    QMenu* buildCertMenu(QMenu *parent, const QSslCertificate& cert,
-                         const QList<QSslCertificate>& userApproved, int pos);
+    QMenu *buildCertMenu(QMenu *parent, const QSslCertificate &cert,
+        const QList<QSslCertificate> &userApproved, int pos);
     QPointer<AccountState> _accountState;
-    QMenu_menu;
+    QMenu *_menu;
 };
 
 } // namespace OCC
index 53e90961e692ba7eb6ff475630a352350cf20fed..4f6be75d6e490ec4e7a25c65f375d35b2887e317 100644 (file)
@@ -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<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *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<QSslError> 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<QSslError> &errors )
+bool SslErrorDialog::checkFailingCertsKnown(const QList<QSslError> &errors)
 {
     // check if unknown certs caused errors.
     _unknownCerts.clear();
@@ -113,8 +114,7 @@ bool SslErrorDialog::checkFailingCertsKnown( const QList<QSslError> &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<QSslError> &errors )
     }
 
     QString msg = QL("<html><head>");
-            msg += QL("<link rel='stylesheet' type='text/css' href='format.css'>");
-            msg += QL("</head><body>");
+    msg += QL("<link rel='stylesheet' type='text/css' href='format.css'>");
+    msg += QL("</head><body>");
 
     auto host = _account->url().host();
     msg += QL("<h3>") + tr("Cannot connect securely to <i>%1</i>:").arg(host) + QL("</h3>");
     // loop over the unknown certs and line up their errors.
     msg += QL("<div id=\"ca_errors\">");
-    foreach( const QSslCertificate& cert, _unknownCerts ) {
+    foreach (const QSslCertificate &cert, _unknownCerts) {
         msg += QL("<div id=\"ca_error\">");
         // add the errors for this cert
-        foreach( QSslError err, errors ) {
-            if( err.certificate() == cert ) {
+        foreach (QSslError err, errors) {
+            if (err.certificate() == cert) {
                 msg += QL("<p>") + err.errorString() + QL("</p>");
             }
         }
         msg += QL("</div>");
-        msg += certDiv( cert );
-        if( _unknownCerts.count() > 1 ) {
+        msg += certDiv(cert);
+        if (_unknownCerts.count() > 1) {
             msg += QL("<hr/>");
         }
     }
@@ -155,30 +155,33 @@ bool SslErrorDialog::checkFailingCertsKnown( const QList<QSslError> &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("<div id=\"cert\">");
-    msg += QL("<h3>") + tr("with Certificate %1").arg( Utility::escape(cert.subjectInfo( QSslCertificate::CommonName ))) + QL("</h3>");
+    msg += QL("<h3>") + tr("with Certificate %1").arg(Utility::escape(cert.subjectInfo(QSslCertificate::CommonName))) + QL("</h3>");
 
     msg += QL("<div id=\"ccert\">");
     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("&lt;not specified&gt;");
-    if (org.isEmpty()) org = tr("&lt;not specified&gt;");
-    if (country.isEmpty()) country = tr("&lt;not specified&gt;");
+    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("&lt;not specified&gt;");
+    if (org.isEmpty())
+        org = tr("&lt;not specified&gt;");
+    if (country.isEmpty())
+        country = tr("&lt;not specified&gt;");
     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("<p>");
 
     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): <tt>%1</tt>").arg(md5sum) + QL("<br/>");
     msg += tr("Fingerprint (SHA1): <tt>%1</tt>").arg(sha1sum) + QL("<br/>");
     msg += QL("<br/>");
-    msg += tr("Effective Date: %1").arg( cert.effectiveDate().toString()) + QL("<br/>");
-    msg += tr("Expiration Date: %1").arg( cert.expiryDate().toString()) + QL("</p>");
+    msg += tr("Effective Date: %1").arg(cert.effectiveDate().toString()) + QL("<br/>");
+    msg += tr("Expiration Date: %1").arg(cert.expiryDate().toString()) + QL("</p>");
 
-    msg += QL("</div>" );
+    msg += QL("</div>");
 
-    msg += QL("<h3>") + tr("Issuer: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::CommonName))) + QL("</h3>");
+    msg += QL("<h3>") + tr("Issuer: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::CommonName))) + QL("</h3>");
     msg += QL("<div id=\"issuer\">");
     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("<p>") + li.join(QL("<br/>")) + QL("</p>");
-    msg += QL("</div>" );
-    msg += QL("</div>" );
+    msg += QL("</div>");
+    msg += QL("</div>");
 
     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;
index e4de70ac81a1a521f2216a2dcb6048dbb85c000d..d0bb40310c8488175e722d97025df1bb60c7e4c4 100644 (file)
 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<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *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<QSslError> &errors );
+    bool checkFailingCertsKnown(const QList<QSslError> &errors);
     bool trustConnection();
     QList<QSslCertificate> unknownCerts() const { return _unknownCerts; }
 
@@ -58,12 +58,12 @@ private:
     QString styleSheet() const;
     bool _allTrusted;
 
-    QString certDiv( QSslCertificate ) const;
+    QString certDiv(QSslCertificate) const;
 
     QList<QSslCertificate> _unknownCerts;
-    QString                _customConfigHandle;
-    Ui::SslErrorDialog     *_ui;
-    AccountPtr               _account;
+    QString _customConfigHandle;
+    Ui::SslErrorDialog *_ui;
+    AccountPtr _account;
 };
 } // end namespace
 
index 885b61d423a0045dd559f96d8fc234abf420439e..d57f288518796e5a0950768a919f8029d8027e40 100644 (file)
 
 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);
 
-    ifprotoWidget) {
+    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()
 {
-
 }
-
 }
index 1ca0a3e54afa797ffc9997e42b8ce31aab36f53f..c530c35abf60bb13c2b31680e73488394e16bc35 100644 (file)
@@ -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
index c0f5c142fb4cf5ce23b513d2d6662d5a751f5011..d0a5259f14f2ab1793849e6f6e639f77595f3b60 100644 (file)
@@ -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 QStringname)
+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();
 }
-
 }
index 4f54a45c025b63265c3197b2b24c6e21f16e01d7..e31917e967ec7afb103831c0c99c15fb1d57e656 100644 (file)
@@ -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<QFile> _file;
     QTextStream _out;
index e1e72cb06db4e069c587b2732b5f0fcaa953c083..af6e933ccbf6ba470add6b8ba296bc1557374034 100644 (file)
 
 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<QVariant> args = QList<QVariant>() << "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
index 14e9607ab71f72b19cb23ec11d0a461ee734c91f..523d4b689cad338b8be0fbe8824188bc75131b76 100644 (file)
@@ -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);
 };
 
index 2f58fcded5405c30081fc7cbb3ca6d39ab7c2879..81d63128984a253d5e38315c2047320d26549655 100644 (file)
@@ -18,8 +18,8 @@
 
 namespace OCC {
 
-ThumbnailJob::ThumbnailJob(const QString &path, AccountPtr account, QObjectparent)
-: 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;
 }
-
 }
index 13b7543801cb7611032701939b1fcf538bed6f9b..37c9ba9228cf5e2f12635623fd2a701f18079d35 100644 (file)
@@ -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
index 0f9b0510adcd4439cf1e22087e9e749108576851..30f12a39c713f89509b7c3ec11df1b97bf7e9a49 100644 (file)
 
 using namespace OCC;
 
-ToolTipUpdater::ToolTipUpdater(QTreeViewtreeView)
+ToolTipUpdater::ToolTipUpdater(QTreeView *treeView)
     : QObject(treeView)
     , _treeView(treeView)
 {
-    connect(_treeView->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)),
-            SLOT(dataChanged(QModelIndex,QModelIndex,QVector<int>)));
+    connect(_treeView->model(), SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)),
+        SLOT(dataChanged(QModelIndex, QModelIndex, QVector<int>)));
     _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<QHelpEvent *>(ev);
         _toolTipPos = helpEvent->globalPos();
     }
     return false;
 }
 
-void ToolTipUpdater::dataChanged(const QModelIndextopLeft,
-                                 const QModelIndex& bottomRight,
-                                 const QVector<int>& roles)
+void ToolTipUpdater::dataChanged(const QModelIndex &topLeft,
+    const QModelIndex &bottomRight,
+    const QVector<int> &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());
 }
-
index e1eefb453c9b555b6c015c157871b8f7174362b5..05144b04a1a6559ba78b887e846150c6bc123501 100644 (file)
@@ -37,16 +37,16 @@ class ToolTipUpdater : public QObject
 {
     Q_OBJECT
 public:
-    ToolTipUpdater(QTreeViewtreeView);
+    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<int>& roles);
+    void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles);
 
 private:
-    QTreeView_treeView;
+    QTreeView *_treeView;
     QPoint _toolTipPos;
 };
 
index 7bb94ad697696c87fcb37c719c06daf7df5c8d65..bac0da50388d9d1a2a126355afb0500970bc38ae 100644 (file)
@@ -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<OCUpdater*>(Updater::instance())) {
-        connect(updater,  SIGNAL(newUpdateAvailable(QString,QString)),
-                this,     SIGNAL(updaterAnnouncement(QString,QString)) );
+    if (OCUpdater *updater = qobject_cast<OCUpdater *>(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<QNetworkReply*>(sender());
+    QNetworkReply *reply = qobject_cast<QNetworkReply *>(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<QNetworkReply*>(sender());
-    if(_file->isOpen()) {
+    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
+    if (_file->isOpen()) {
         _file->write(reply->readAll());
     }
 }
 
 void NSISUpdater::slotDownloadFinished()
 {
-    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
+    QNetworkReply *reply = qobject_cast<QNetworkReply *>(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("<p>A new version of the %1 Client is available.</p>"
                      "<p><b>%2</b> is available for download. The installed version is %3.</p>")
                       .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 {
index 170a03305c2bfaca0628e7a30d5d6fdb98b64c3f..b157b93ceee5ff1ed1df655a4b005a9f32f630a0 100644 (file)
@@ -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;
-    QNetworkAccessManagerqnam() 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<QTemporaryFile> _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
index 22c93d80f5124afd051e318835e54376663c9e53..e9a2c8882341de56388753f274cb9174f78fbc29 100644 (file)
 
 namespace OCC {
 
-class SparkleUpdater : public Updater {
+class SparkleUpdater : public Updater
+{
 public:
-    SparkleUpdater(const QStringappCastUrl);
+    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;
index 225cdb69f8b23a9eef0e25c9f97ea4af6ecfbe36..711daa942779ab609b970d2ec439bcd51206af07 100644 (file)
 
 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
index 4ed09857944b2961161d406130df5c56bf481cf2..af5e76b5ab58a24411372cebd63e740ff828a9ba 100644 (file)
@@ -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;
index de9e339c71772f591541d986e7d0d347dc182fc9..2529b261ae08b62cb7862e1c11662def1d34b3e4 100644 (file)
@@ -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 QStringversion)
+qint64 Updater::Helper::stringVersionToInt(const QString &version)
 {
     if (version.isEmpty())
         return 0;
index 07c6528bf41a341d3b1625804123c6bfdfc5ada4..77f3226385bacca161f4b7a08930f81486a0a4ca 100644 (file)
@@ -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();
index ce5a4fdf4c1c4968a221170977ff43e4f745d7a7..696e98e0918e963d9ff941f30369e2603c0bffef 100644 (file)
@@ -26,7 +26,7 @@ void AbstractCredentialsWizardPage::cleanupPage()
 {
     // Reset the credentials when the 'Back' button is used.
 
-    AccountPtr account = static_cast<OwncloudWizard*>(wizard())->account();
+    AccountPtr account = static_cast<OwncloudWizard *>(wizard())->account();
     AbstractCredentials *creds = account->credentials();
     if (creds) {
         if (!creds->inherits("DummyCredentials")) {
@@ -34,5 +34,4 @@ void AbstractCredentialsWizardPage::cleanupPage()
         }
     }
 }
-
 }
index 82d61ac42a0d495e40650c44ee64719c42f4296e..87e50620bd3fca0f5303ad816766510783c4dff5 100644 (file)
@@ -17,8 +17,7 @@
 
 #include <QWizardPage>
 
-namespace OCC
-{
+namespace OCC {
 
 class AbstractCredentials;
 
@@ -30,7 +29,7 @@ class AbstractCredentialsWizardPage : public QWizardPage
 {
 public:
     void cleanupPage() Q_DECL_OVERRIDE;
-    virtual AbstractCredentialsgetCredentials() const = 0;
+    virtual AbstractCredentials *getCredentials() const = 0;
 };
 
 } // namespace OCC
index 3c9dd69793ac111f68c70130c722cd5a9f5f8c87..9bc1b60c309ed2ff69e4c0b7a0943793996f6f73 100644 (file)
 #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("<p><small><strong>Warning:</strong> The local folder is not empty. "
                     "Pick a resolution!</small></p>");
         }
@@ -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)
 {
-    iferr.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
-
index 5d1c82ed219e01cdebacabefadb1823e49694f8a..a51c51b1bcdee91beacfe9ae69c372a10304abfa 100644 (file)
@@ -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 QVariantMapresult);
+    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
index 1312da5620e424ce061ecba8add5afd41eb95ef9..f0d670480e86010d9d2e9d2d7390958c86f6ea97 100644 (file)
@@ -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("<html><head/><body><p>Failed to connect to the secure server address <em>%1</em>. How do you wish to proceed?</p></body></html>")
 #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;
 }
-
 }
index b08076f59a3862869116fc037e467172b4579f98..c3e3412c13012e57d80f519cbe35aab292ef0381 100644 (file)
@@ -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
index 4c8bbd5a10ec36f76652f0c2637be52a53499b84..265d3bf3c559a1696822423d20a4e41d613c67bf 100644 (file)
 #include "wizard/owncloudwizardcommon.h"
 #include "wizard/owncloudwizard.h"
 
-namespace OCC
-{
+namespace OCC {
 
-OwncloudHttpCredsPage::OwncloudHttpCredsPage(QWidgetparent)
-  : 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<OwncloudWizard *>(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<OwncloudWizard *>(wizard());
     AbstractCredentials *cred = ocWizard->account()->credentials();
-    HttpCredentials *httpCreds = qobject_cast<HttpCredentials*>(cred);
+    HttpCredentials *httpCreds = qobject_cast<HttpCredentials *>(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<OwncloudWizard *>(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 QStringerr)
+void OwncloudHttpCredsPage::setErrorString(const QString &err)
 {
-    iferr.isEmpty()) {
+    if (err.isEmpty()) {
         _ui.errorLabel->setVisible(false);
     } else {
         _ui.errorLabel->setVisible(true);
@@ -190,7 +189,7 @@ void OwncloudHttpCredsPage::setErrorString(const QString& err)
     stopSpinner();
 }
 
-AbstractCredentialsOwncloudHttpCredsPage::getCredentials() const
+AbstractCredentials *OwncloudHttpCredsPage::getCredentials() const
 {
     return new HttpCredentialsGui(_ui.leUsername->text(), _ui.lePassword->text(), _ocWizard->_clientSslCertificate, _ocWizard->_clientSslKey);
 }
index f339b23ec186ea3fac86d3f147985429a812d34b..3fce61e1a5108a7401db61a03fa91bcc20845b50 100644 (file)
@@ -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
index 8e67d6f8c071a8d88c802b1e2298b592242eea0c..39710e892379e54f50ee73eed08d2fc4f3a04224 100644 (file)
 #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<OwncloudWizard *>(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 QStringurl)
+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
-            ifurl.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<QPushButton*>(nextButton);
+    QPushButton *pushButton = qobject_cast<QPushButton *>(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)
 {
-    iferr.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 QSslCertificatecert, 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<QSslCertificate> 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
index e0b1ba8525470b65091d6cb5317fe7afde6bef63..accd3998988c3c5fb7e22a09630743a1362980ab 100644 (file)
@@ -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
index 9b031c064a61e1dd736d98444fb0e4169c8a1723..9d88555a615dd3e664f7cb04fc8c5540bab3effd 100644 (file)
 #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<OwncloudWizard*>(wizard());
+    OwncloudWizard *ocWizard = qobject_cast<OwncloudWizard *>(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();
 }
 
-AbstractCredentialsOwncloudShibbolethCredsPage::getCredentials() const
+AbstractCredentials *OwncloudShibbolethCredsPage::getCredentials() const
 {
     return new ShibbolethCredentials(_cookie);
 }
index 75584674d244011c845e3346fdf2546aa2d7f48c..daa9817a9e91cdce44ca86d4eb6f8e3e4a7bd1fb 100644 (file)
@@ -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<ShibbolethWebView> _browser;
-  bool _afterInitialSetup;
-  QNetworkCookie _cookie;
+    QPointer<ShibbolethWebView> _browser;
+    bool _afterInitialSetup;
+    QNetworkCookie _cookie;
 };
 
 } // namespace OCC
index c611a4e66498862f0d3b3abf7f317aa1c068c4e6..84068ddd58ede20a5c883a7ef43994e96af97c8a 100644 (file)
 
 #include <stdlib.h>
 
-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);
 }
 
-AbstractCredentialsOwncloudWizard::getCredentials() const
+AbstractCredentials *OwncloudWizard::getCredentials() const
 {
-  if (_credentialsPage) {
-    return _credentialsPage->getCredentials();
-  }
+    if (_credentialsPage) {
+        return _credentialsPage->getCredentials();
+    }
 
-  return 0;
+    return 0;
 }
 
 } // end namespace
index 93391a2b5365fb44afc57e1db403a6aeb5de34a8..4b9097f74e91e72aa957740d52e50cc38023aa90 100644 (file)
@@ -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);
-    AbstractCredentialsgetCredentials() 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;
 };
index 0c4bcc07b2555daac858fe86ab4cab1546626cb1..229987ece12aa6c63bd24ea9b76805acf2d06862 100644 (file)
 #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<QPixmap>();
-    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<QPixmap>();
+        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("<font color=\"%1\" size=\"5\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
-}
+    QString titleTemplate()
+    {
+        return QString::fromLatin1("<font color=\"%1\" size=\"5\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
+    }
 
-QString subTitleTemplate()
-{
-  return QString::fromLatin1("<font color=\"%1\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
-}
+    QString subTitleTemplate()
+    {
+        return QString::fromLatin1("<font color=\"%1\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
+    }
 
-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
 
index 1eeeef006f60bb810ee16816a63693edb583e70a..bf6248c2c65052a5bd6499a8d93c67d696c23162 100644 (file)
 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
 
index 891417387d75cf577b37ee4483f1a9d274c5e85c..4610b409dca7a0397cb4be9d0d9b55e2512114de 100644 (file)
 #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()));
 
-    Themetheme = 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()
 {
-    Themetheme = Theme::instance();
+    Theme *theme = Theme::instance();
     QUrl url = QUrl(field("OCUrl").toString() + theme->wizardUrlPostfix());
     QDesktopServices::openUrl(url);
 }
index 0e318b68089c48a17caec585a0935660b6d9741c..8d309f625712a9c5f6bd56b550fb1fa3fdce37c8 100644 (file)
@@ -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
index 5e4171c324a02328396d6648e65ee6dd8406ca39..1cc44a248b1eaf4457d8f9fdc0d7aa89fb8e2104 100644 (file)
@@ -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);
 }
 
index 2d0d29775b9c0062585fc582945194d996e769fa..09855f373c89b427d7e5beb24a67aed4750494e6 100644 (file)
@@ -34,7 +34,7 @@ public:
     PostfixLineEdit(QWidget *parent);
 
     /** @brief sets an optional postfix shown greyed out */
-    void setPostfix(const QStringpostfix);
+    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;
 };
index 5f6d7aa823045940a90622eecdfb622f6b40ff1f..25fe28ce38a13ac853b0dd902d595303907f789a 100644 (file)
@@ -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<QSslError>)), 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()));
 }
 
-QNetworkReplyAbstractNetworkJob::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 QStringrelativePath) const
+QUrl AbstractNetworkJob::makeAccountUrl(const QString &relativePath) const
 {
     return Utility::concatUrlPath(_account->url(), relativePath);
 }
 
-QUrl AbstractNetworkJob::makeDavUrl(const QStringrelativePath) 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(QByteArraybody)
+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<QTimer*>();
-    if(!_timer.isNull()) {
+    _timer = reply->property("timer").value<QTimer *>();
+    if (!_timer.isNull()) {
         _timer->stop();
     }
 }
 
 NetworkJobTimeoutPauser::~NetworkJobTimeoutPauser()
 {
-    if(!_timer.isNull()) {
+    if (!_timer.isNull()) {
         _timer->start();
     }
 }
 
-QString extractErrorMessage(const QByteArrayerrorResponse)
+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 QNetworkReplyreply)
+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 QNetworkReplyreply)
+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
             );
 }
index 73e77fec15279ecef463c98a63dc4a3aab4ded8b..36a5113ff633814f6df8ca2c06a4f09c73e273d1 100644 (file)
@@ -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, QObjectparent = 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);
-    QNetworkReplyreply() 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(QByteArraybody = 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 QStringrelativePath) const;
+    QUrl makeAccountUrl(const QString &relativePath) const;
 
     /// Like makeAccountUrl() but uses the account's dav base path
-    QUrl makeDavUrl(const QStringrelativePath) 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:
-    QNetworkReplyaddTimer(QNetworkReply *reply);
+    QNetworkReply *addTimer(QNetworkReply *reply);
     bool _ignoreCredentialFailure;
     QPointer<QNetworkReply> _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<QTimer> _timer;
 };
@@ -184,16 +188,16 @@ private:
  *
  * Returns a null string if no message was found.
  */
-QString OWNCLOUDSYNC_EXPORT extractErrorMessage(const QByteArrayerrorResponse);
+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 QNetworkReplyreply);
+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 QNetworkReplyreply);
+QString OWNCLOUDSYNC_EXPORT networkReplyErrorString(const QNetworkReply &reply);
 
 } // namespace OCC
-
-
index 62e4038089b0ec067452d83bbb6e3753406092d6..1d8e91d4cb5060ae5296f6acd013c2f31a549925 100644 (file)
 #include "accessmanager.h"
 #include "utility.h"
 
-namespace OCC
-{
+namespace OCC {
 
 Q_LOGGING_CATEGORY(lcAccessManager, "sync.accessmanager", QtInfoMsg)
 
-AccessManager::AccessManager(QObjectparent)
-    : 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<QNetworkCookie> 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);
 }
index bbe28ab96ef6425d58ec73e4157607d1941a2f12..d38a13487fb8c32799bc4de61c1b30ab66b6b10a 100644 (file)
@@ -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(QObjectparent = 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
index 7e183ecb631c6e009b96b78f1a1c95bf2a209bfa..39d15f9719b2660414fc7ace3031e8aa820ab1ac 100644 (file)
@@ -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>("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<QSslError>)),
-            SLOT(slotHandleSslErrors(QNetworkReply*,QList<QSslError>)));
-    connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
-            SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
+    connect(_am.data(), SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
+        SLOT(slotHandleSslErrors(QNetworkReply *, QList<QSslError>)));
+    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<CookieJar*>(_am->cookieJar());
+    auto jar = qobject_cast<CookieJar *>(_am->cookieJar());
     ASSERT(jar);
     jar->setAllCookies(QList<QNetworkCookie>());
     emit wantsAccountSaved(this);
@@ -195,17 +195,17 @@ void Account::resetNetworkAccessManager()
     }
 
     qCDebug(lcAccount) << "Resetting QNAM";
-    QNetworkCookieJarjar = _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<QNetworkAccessManager>(_credentials->getQNAM(), &QObject::deleteLater);
 
     _am->setCookieJar(jar); // takes ownership of the old cookie jar
-    connect(_am.data(), SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
-            SLOT(slotHandleSslErrors(QNetworkReply*,QList<QSslError>)));
-    connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
-            SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
+    connect(_am.data(), SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
+        SLOT(slotHandleSslErrors(QNetworkReply *, QList<QSslError>)));
+    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<QSslError> errors)
+void Account::slotHandleSslErrors(QNetworkReply *reply, QList<QSslError> 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<QSslError> 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<QSslCertificate> 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<QSslError> errors
     QPointer<QObject> 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<QSslError> 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 QStringversion)
+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
index 829439bf9a91ad30c5bf0cd8ec70cdd5189045a7..4e554e59083c2906e7a318035d49688e3e50b7dd 100644 (file)
@@ -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<QSslError>, const QSslConfiguration &conf, QList<QSslCertificate>*, AccountPtr) = 0;
+    virtual bool handleErrors(QList<QSslError>, const QSslConfiguration &conf, QList<QSslCertificate> *, 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 QImageimg);
+    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 */
-    AbstractCredentialscredentials() const;
+    AbstractCredentials *credentials() const;
     void setCredentials(AbstractCredentials *cred);
 
 
     // For creating various network requests
-    QNetworkReplysendRequest(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 QStringkey) const;
-    void setCredentialSetting(const QStringkey, 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();
-    QNetworkAccessManagernetworkAccessManager();
+    QNetworkAccessManager *networkAccessManager();
     QSharedPointer<QNetworkAccessManager> sharedNetworkAccessManager();
 
     /// Called by network jobs on credential errors, emits invalidCredentials()
@@ -202,21 +204,21 @@ signals:
     /// Triggered by handleInvalidCredentials()
     void invalidCredentials();
 
-    void credentialsFetched(AbstractCredentialscredentials);
-    void credentialsAsked(AbstractCredentialscredentials);
+    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(Accountacc);
+    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<QSslError>);
+    void slotHandleSslErrors(QNetworkReply *, QList<QSslError>);
     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)
index 5e02cf7308de21c0a238fb3e8e021720cdab305c..e96e57bb98492611a5e2c860b720bef79b9041e0 100644 (file)
 
 // 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.
index 6e65d0b44a5df7ee577164ed98d5f149ce7f557c..2cd8d70a61ed8d0cdfbd808edd3fe00a62cf028f 100644 (file)
@@ -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<UploadDevice*>(o);
+    UploadDevice *p = qobject_cast<UploadDevice *>(o);
     if (p) {
         unregisterUploadDevice(p);
     }
 }
 
-void BandwidthManager::unregisterUploadDevice(UploadDevicep)
+void BandwidthManager::unregisterUploadDevice(UploadDevice *p)
 {
     _absoluteUploadDeviceList.removeAll(p);
     _relativeUploadDeviceList.removeAll(p);
@@ -126,10 +127,10 @@ void BandwidthManager::unregisterUploadDevice(UploadDevice* p)
     }
 }
 
-void BandwidthManager::registerDownloadJob(GETFileJobj)
+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(GETFileJobj)
+void BandwidthManager::unregisterDownloadJob(GETFileJob *j)
 {
     _downloadJobList.removeAll(j);
     if (_relativeLimitCurrentMeasuredJob == j) {
@@ -152,9 +153,9 @@ void BandwidthManager::unregisterDownloadJob(GETFileJob* j)
     }
 }
 
-void BandwidthManager::unregisterDownloadJob(QObjecto)
+void BandwidthManager::unregisterDownloadJob(QObject *o)
 {
-    GETFileJob *p = qobject_cast<GETFileJob*>(o);
+    GETFileJob *p = qobject_cast<GETFileJob *>(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;
         }
     }
 }
-
-
 }
index a57ca073fa40568eaadd8333526f605f814bc185..77a32728790b8e3d107212da3dcfda1d472c30fa 100644 (file)
@@ -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<UploadDevice*> _absoluteUploadDeviceList;
-    QLinkedList<UploadDevice*> _relativeUploadDeviceList;
+    QLinkedList<UploadDevice *> _absoluteUploadDeviceList;
+    QLinkedList<UploadDevice *> _relativeUploadDeviceList;
 
     QTimer _relativeUploadMeasuringTimer;
 
@@ -87,7 +88,7 @@ private:
     qint64 _relativeUploadLimitProgressAtMeasuringRestart;
     qint64 _currentUploadLimit;
 
-    QLinkedList<GETFileJob*> _downloadJobList;
+    QLinkedList<GETFileJob *> _downloadJobList;
     QTimer _relativeDownloadMeasuringTimer;
 
     // for relative bw limiting, we need to wait this amount before measuring again
@@ -101,7 +102,6 @@ private:
 
     qint64 _currentDownloadLimit;
 };
-
 }
 
 #endif
index 95459051f9e523f1ac5544f3b60d432acef6e289..651b1981d512f2569392e7c740ba0bf78ceb729b 100644 (file)
@@ -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<QByteArray> Capabilities::supportedChecksumTypes() const
 {
     QList<QByteArray> 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<int> Capabilities::httpErrorCodesThatResetFailingChunkedUploads() const
 {
     QList<int> 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;
 }
-
 }
index 56ef6f622bc0488d7cf5c14f297017f2770440ca..4044d85841307750fe3d368451edf7134e477e9e 100644 (file)
@@ -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
index 4498b4b7bb235789f99521f8e7405bd775d74cae..00818442fb5a5c0336d39ed34c6125205be43251 100644 (file)
@@ -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(QObjectparent)
+ComputeChecksum::ComputeChecksum(QObject *parent)
     : QObject(parent)
 {
 }
 
-void ComputeChecksum::setChecksumType(const QByteArraytype)
+void ComputeChecksum::setChecksumType(const QByteArray &type)
 {
     _checksumType = type;
 }
@@ -135,29 +135,29 @@ QByteArray ComputeChecksum::checksumType() const
     return _checksumType;
 }
 
-void ComputeChecksum::start(const QStringfilePath)
+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 ifchecksumType == 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 QByteArraychecksumType,
-                                                    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<CSyncChecksumHook*>(this_obj);
+    CSyncChecksumHook *checksumHook = static_cast<CSyncChecksumHook *>(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 QStringpath, 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;
 }
-
-
 }
index eb2bd275f41a5ce223a02c27b4153b6cf72a1c00..5d88b0bcb6868b4b1598e0e7c9eafc7059eed462 100644 (file)
@@ -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(QObjectparent = 0);
+    explicit ComputeChecksum(QObject *parent = 0);
 
     /**
      * Sets the checksum type to be used. The default is empty.
      */
-    void setChecksumType(const QByteArraytype);
+    void setChecksumType(const QByteArray &type);
 
     QByteArray checksumType() const;
 
@@ -60,15 +60,15 @@ public:
      *
      * done() is emitted when the calculation finishes.
      */
-    void start(const QStringfilePath);
+    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(SyncJournalDbjournal);
+    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 QStringpath, int checksumTypeId);
+    QByteArray compute(const QString &path, int checksumTypeId);
 
 private:
-    SyncJournalDb_journal;
+    SyncJournalDb *_journal;
 };
-
 }
index c78c59db694ac9226894d1a4b555c9f44a96e52b..e87f04b7cd87fd1eb8341854e24f8587b1361b1f 100644 (file)
@@ -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 ConfigFilecfg)
+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 charClientProxy::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?
     }
 }
-
-
 }
index 77884feffffa899f75fa1b84885d2c531a8d5081..923f060f78899b5535e55f7b4b991e84649aa61d 100644 (file)
@@ -44,23 +44,23 @@ public slots:
     void setupQtProxyFromConfig();
 
 private:
-    const charproxyTypeToCStr(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
index 22a500e5ca434568aa8b868b566e32ee12dab75d..a3bab5f1c50308a478094f0cf2543376a10f5163 100644 (file)
@@ -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 QVariantdefaultValue) 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 QStringconnection) 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();
-    ifinterval < 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 QStringconnection) 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;
-    ifinterval < 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 &param, 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 QStringkey, 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 QStringcPath)
+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 QStringcPasswd)
+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();
 }
-
 }
index 2f3a6beccc92a066c7aaa6a3ba5d77f49df3cc04..912b66a04b1e7e6acdff30fcd547e25795ee3e7c 100644 (file)
@@ -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 QStringconnection = 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 QStringcPath);
+    void setCertificatePath(const QString &cPath);
     QString certificatePasswd() const;
-    void setCertificatePasswd(const QStringcPasswd);
+    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 QStringkey, const QVariant &value);
+    QVariant getValue(const QString &param, 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<AbstractCredentials> SharedCreds;
 
-    static bool    _askedUser;
+    static bool _askedUser;
     static QString _oCVersion;
     static QString _confDir;
 };
-
 }
 #endif // CONFIGFILE_H
index bac43e3aa5d4e17bae5224cfa1e4a068658f3e97..c39f3cd7e2d129ab9ce6ae3522bc5822c633d9b0 100644 (file)
@@ -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<QByteArray>() << "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<PropfindJob *>(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 QStringversion)
+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 QImageimg)
+void ConnectionValidator::slotAvatarImage(const QImage &img)
 {
     _account->setAvatar(img);
     reportResult(Connected);
index e4e729701ae5d1fdcdffb728f5b8bbfcd8deb4d9..7254c9bcf60225be233c55823f4babc76266b791 100644 (file)
@@ -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 QUrlurl);
+    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 QStringversion);
+    bool setAndCheckServerVersion(const QString &version);
 
     QStringList _errors;
-    AccountPtr   _account;
+    AccountPtr _account;
     bool _isCheckingServerAndAuth;
 };
-
 }
 
 #endif // CONNECTIONVALIDATOR_H
index 836b5d1ba627bdcd4328b0b6e0055de34f4b819f..4af34d5e74812dfa7f7edc582fd68431c85dc5be 100644 (file)
@@ -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<QNetworkCookie> &list)
@@ -51,8 +51,7 @@ QDataStream &operator>>(QDataStream &stream, QList<QNetworkCookie> &list)
 
     quint32 count;
     stream >> count;
-    for(quint32 i = 0; i < count; ++i)
-    {
+    for (quint32 i = 0; i < count; ++i) {
         QByteArray value;
         stream >> value;
         QList<QNetworkCookie> newCookies = QNetworkCookie::parseCookies(value);
@@ -67,8 +66,8 @@ QDataStream &operator>>(QDataStream &stream, QList<QNetworkCookie> &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<QNetworkCookie>& cookieList, const QUrl& url)
+bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &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<QNetworkCookie> CookieJar::cookiesForUrl(const QUrl &url) const
@@ -124,7 +123,7 @@ void CookieJar::restore(const QString &fileName)
 QList<QNetworkCookie> CookieJar::removeExpired(const QList<QNetworkCookie> &cookies)
 {
     QList<QNetworkCookie> updatedList;
-    foreach(const QNetworkCookie &cookie, cookies) {
+    foreach (const QNetworkCookie &cookie, cookies) {
         if (cookie.expirationDate() > QDateTime::currentDateTime() && !cookie.isSessionCookie()) {
             updatedList << cookie;
         }
index 9759676b3a71b4376f1431a50ef66f089921ca01..83d9e3c50458980bf821807b23cee31bfbab1a2a 100644 (file)
@@ -43,7 +43,8 @@ public:
     void restore(const QString &fileName);
 
 signals:
-    void newCookiesForUrl(const QList<QNetworkCookie>& cookieList, const QUrl& url);
+    void newCookiesForUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url);
+
 private:
     QList<QNetworkCookie> removeExpired(const QList<QNetworkCookie> &cookies);
 };
index 4fe1541846b8c7d2cbc9021f40e2c1bbf3c58b8a..9fdef31734e4472fef007b97b7121becdf815098 100644 (file)
@@ -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
index 93047e2fcb0be9e0e0b6101f0ee179da0788a14d..d73d4534e28ccf33a878802a7a4aee0ef02935d2 100644 (file)
@@ -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(Accountaccount);
+    virtual void setAccount(Account *account);
 
     virtual QString authType() const = 0;
     virtual QString user() const = 0;
-    virtual QNetworkAccessManagergetQNAM() 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
index 34181a8b0d82d2d3272fe524387550e64947ed50..58b3cc24fa5d6da2d9f9fb3e9f66eefc6cb3a0b5 100644 (file)
@@ -25,8 +25,7 @@
 #include "account.h"
 #include "syncengine.h"
 
-namespace OCC
-{
+namespace OCC {
 
 
 } // namespace OCC
index 9a66fbd546aedfc0cb4f8bf0a78a10445e33b7fc..e2cf1a6ff1158c1398c31f8cc064a83b1e5a523f 100644 (file)
@@ -18,8 +18,7 @@
 
 #include "owncloudlib.h"
 
-namespace OCC
-{
+namespace OCC {
 
 } // namespace OCC
 
index 8caad01d54042df94d5d56cb42db62ea34e267bd..1e34c72e1c408adaf9913666c54f7f9e3a44c195 100644 (file)
@@ -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;
 }
 
-QNetworkAccessManagerDummyCredentials::getQNAM() const
+QNetworkAccessManager *DummyCredentials::getQNAM() const
 {
     return new AccessManager;
 }
@@ -55,6 +54,7 @@ void DummyCredentials::askFromUser()
 }
 
 void DummyCredentials::persist()
-{}
+{
+}
 
 } // namespace OCC
index 650da7a9c2ccefc5c9c22e469301bbe022b9e162..ad56a08dd5093419f5390f8ec9eb7875a6726ef3 100644 (file)
 
 #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;
-    QNetworkAccessManagergetQNAM() 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
index 6355d47885e805229f1c68a7e5a35ddb791a0d2b..5f5e880cc1768f792c8d4d677ee6a7652d8e1337 100644 (file)
 
 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(Accountaccount)
+void HttpCredentials::setAccount(Account *account)
 {
     AbstractCredentials::setAccount(account);
     if (_user.isEmpty()) {
@@ -116,12 +121,12 @@ void HttpCredentials::setAccount(Account* account)
     }
 }
 
-QNetworkAccessManagerHttpCredentials::getQNAM() const
+QNetworkAccessManager *HttpCredentials::getQNAM() const
 {
-    AccessManagerqnam = 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::Jobincoming)
+void HttpCredentials::slotReadClientCertPEMJobDone(QKeychain::Job *incoming)
 {
     // Store PEM in memory
-    ReadPasswordJob *readJob = static_cast<ReadPasswordJob*>(incoming);
+    ReadPasswordJob *readJob = static_cast<ReadPasswordJob *>(incoming);
     if (readJob->error() == NoError && readJob->binaryData().length() > 0) {
         QList<QSslCertificate> 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::Jobincoming)
+void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job *incoming)
 {
     // Store key in memory
-    ReadPasswordJob *readJob = static_cast<ReadPasswordJob*>(incoming);
+    ReadPasswordJob *readJob = static_cast<ReadPasswordJob *>(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<ReadPasswordJob*>(incomingJob);
+    QKeychain::ReadPasswordJob *job = static_cast<ReadPasswordJob *>(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
-    WritePasswordJobjob = 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);
-    WritePasswordJobjob = 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<WritePasswordJob*>(job);
+    WritePasswordJob *wjob = qobject_cast<WritePasswordJob *>(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
index 860329d9b4c1f05f68e970f03875b546461fcba2..14118e924bb66d098e4c45f9bf9134e7abb4ff20 100644 (file)
@@ -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;
-    QNetworkAccessManagergetQNAM() 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(Accountaccount) 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:
index 53b2cbc89d1557fa72596c28c8c3fd5cf349e580..9e5e5b39e9ae2a6a2972dedafa4b81e8c1e2c566 100644 (file)
 #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;
 }
 
-QNetworkAccessManagerTokenCredentials::getQNAM() const
+QNetworkAccessManager *TokenCredentials::getQNAM() const
 {
-    AccessManagerqnam = 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
index 27da7b8521be8acbdd22e458a7a9fc520210f03a..e170ea9dbb70c3949d60956c47b6df3994013a81 100644 (file)
@@ -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;
-    QNetworkAccessManagergetQNAM() 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;
index 9a8be41aa14a6569689aab697205280995d8b790..c4c3c874365dfc0d742f83e19d774c2cbb7ba3d2 100644 (file)
@@ -85,12 +85,11 @@ bool DiscoveryJob::isInSelectiveSyncBlackList(const char *path) const
 
 int DiscoveryJob::isInSelectiveSyncBlackListCallback(void *data, const char *path)
 {
-    return static_cast<DiscoveryJob*>(data)->isInSelectiveSyncBlackList(path);
+    return static_cast<DiscoveryJob *>(data)->isInSelectiveSyncBlackList(path);
 }
 
-bool DiscoveryJob::checkSelectiveSyncNewFolder(const QStringpath, 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<DiscoveryJob*>(data)->checkSelectiveSyncNewFolder(QString::fromUtf8(path), remotePerm);
+    return static_cast<DiscoveryJob *>(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<DiscoveryJob*>(userdata);
+    DiscoveryJob *updateJob = static_cast<DiscoveryJob *>(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<QByteArray> 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<QString,QString>)),
-                     this, SLOT(directoryListingIteratedSlot(QString,QMap<QString,QString>)));
-    QObject::connect(lsColJob, SIGNAL(finishedWithError(QNetworkReply*)), this, SLOT(lsJobFinishedWithErrorSlot(QNetworkReply*)));
+    QObject::connect(lsColJob, SIGNAL(directoryListingIterated(QString, QMap<QString, QString>)),
+        this, SLOT(directoryListingIteratedSlot(QString, QMap<QString, QString>)));
+    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<QString,QString> &map)
+static csync_vio_file_stat_t *propertyMapToFileStat(const QMap<QString, QString> &map)
 {
-    csync_vio_file_stat_tfile_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<QString,QString>
                 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<QString,QString>
     return file_stat;
 }
 
-void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap<QString,QString> &map)
+void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap<QString, QString> &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<FileStatPointer> &)),
-                     this, SLOT(singleDirectoryJobResultSlot(const QList<FileStatPointer> &)));
-    QObject::connect(_singleDirJob, SIGNAL(finishedWithError(int,QString)),
-                     this, SLOT(singleDirectoryJobFinishedWithErrorSlot(int,QString)));
+        this, SLOT(singleDirectoryJobResultSlot(const QList<FileStatPointer> &)));
+    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<FileStatPointer> & result)
+void DiscoveryMainThread::singleDirectoryJobResultSlot(const QList<FileStatPointer> &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<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size");
+    propfindJob->setProperties(QList<QByteArray>() << "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<FileStatPointer> &)), 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<DiscoveryJob*>(userdata);
+    DiscoveryJob *discoveryJob = static_cast<DiscoveryJob *>(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<DiscoveryJob*>(userdata);
+    DiscoveryJob *discoveryJob = static_cast<DiscoveryJob *>(userdata);
     if (discoveryJob) {
-        DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult*>(dhandle);
+        DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult *>(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<DiscoveryJob*>(userdata);
+    DiscoveryJob *discoveryJob = static_cast<DiscoveryJob *>(userdata);
     if (discoveryJob) {
-        DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult*> (dhandle);
+        DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult *>(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();
 }
-
 }
index c59134093125aa42d23cafd35d020de54d91d6e9..9603c39ab062628d1d88f3b221259fdbbcad76ab 100644 (file)
@@ -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<FileStatPointer> 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<FileStatPointer> &);
     void finishedWithError(int csyncErrnoCode, const QString &msg);
 private slots:
-    void directoryListingIteratedSlot(QString, const QMap<QString,QString>&);
+    void directoryListingIteratedSlot(QString, const QMap<QString, QString> &);
     void lsJobFinishedWithoutErrorSlot();
-    void lsJobFinishedWithErrorSlot(QNetworkReply*);
+    void lsJobFinishedWithErrorSlot(QNetworkReply *);
+
 private:
     QList<FileStatPointer> _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> _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 &pathqint64 *result);
 
     // From Job:
     void singleDirectoryJobResultSlot(const QList<FileStatPointer> &);
     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(DiscoveryJobdiscoveryJob, 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 charpath) 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);
 };
-
 }
index d9793ce0f06cec1737001c12bdeab8c1ddad79e0..7bd66ac9cdb9bc665162121fa7154cbd7761e1d5 100644 (file)
@@ -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);
 }
 
-ExcludedFilesExcludedFiles::instance()
+ExcludedFiles &ExcludedFiles::instance()
 {
-    static c_strlist_tglobalExcludes;
+    static c_strlist_t *globalExcludes;
     static ExcludedFiles inst(&globalExcludes);
     return inst;
 }
 
-void ExcludedFiles::addExcludeFilePath(const QStringpath)
+void ExcludedFiles::addExcludeFilePath(const QString &path)
 {
     _excludeFiles.insert(path);
 }
@@ -60,7 +60,7 @@ bool ExcludedFiles::reloadExcludes()
     *_excludesPtr = NULL;
 
     bool success = true;
-    foreach (const QStringfile, _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;
             }
 
index 97e3a98da37aef489ddc2a0cc1ccc1c8b141f3e0..f8a18cd8d64e946bf71bdf5ffc0e5ea1d6d63365 100644 (file)
@@ -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 QStringpath);
+    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<QString> _excludeFiles;
 };
 
index 21d9ccf5a8fb54717630127f0e3b0a4795161a01..c068f46943cdcbe25e8055e935ecf6a4fc6bda82 100644 (file)
@@ -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<wchar_t*>( c_utf8_path_to_locale(inpath.toUtf8() ) ) );
+    path = QString::fromWCharArray(static_cast<wchar_t *>(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 QStringfilename, 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 QStringfilename, 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 QStringfilename)
+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 QStringfilename, 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_tstat = 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 QStringfilename, 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 QStringfilename)
+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 QStringfileName,
-                             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 QStringfileName,
-                                     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 QStringoriginFileName,
-                               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 QStringoriginFileName,
-                                        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.
-    QStringerror = 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<LARGE_INTEGER*>(&seek);
+    LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER *>(&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 QStringfilename)
+static qint64 getSizeWithCsync(const QString &filename)
 {
     qint64 result = 0;
-    csync_vio_file_stat_tstat = 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 QStringfilename)
+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 QStringfilename)
+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<LPCWSTR>(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 QStringfileName)
+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) {
index 36ac8d599310dc3ed68dfd5c3948130c45bea0c8..7494bdbd4288bec859298f96352a26e233674ad6 100644 (file)
@@ -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);
 }
 
 /** @} */
-
 }
index 47b731eba515df55c7991ad4e628a33c136f7a44..46c2e95ba2d5e03f7aadf392c1966019c2e227b4 100644 (file)
@@ -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 QStringmsg)
+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("<nobr>File '%1'<br/>cannot be opened for writing.<br/><br/>"
-                                   "The log output can <b>not</b> be saved!</nobr>"))
-                        .arg(name));
+        postGuiMessage(tr("Error"),
+            QString(tr("<nobr>File '%1'<br/>cannot be opened for writing.<br/><br/>"
+                       "The log output can <b>not</b> be saved!</nobr>"))
+                .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);
     }
 }
index 926bb09e48296fa09b5ff6f15485c390d0c979b1..555abe52fbaedd71f6a0be72796f863e6db49292 100644 (file)
 
 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<Log>& logs() const {return _logs;}
+    const QList<Log> &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<Log> _logs;
-  bool       _showTime;
-  bool       _logWindowActivated;
-  QFile       _logFile;
-  bool        _doFileFlush;
-  int         _logExpire;
-  bool        _logDebug;
-  QScopedPointer<QTextStream> _logstream;
-  QMutex      _mutex;
-  QString     _logDirectory;
-
+    Logger(QObject *parent = 0);
+    ~Logger();
+    QList<Log> _logs;
+    bool _showTime;
+    bool _logWindowActivated;
+    QFile _logFile;
+    bool _doFileFlush;
+    int _logExpire;
+    bool _logDebug;
+    QScopedPointer<QTextStream> _logstream;
+    QMutex _mutex;
+    QString _logDirectory;
 };
 
 } // namespace OCC
index ca466bc42402ad1e8615d1c0209d888bce8cac59..613098dda7a80d41233ad8f59ca34d4c54fb14ad 100644 (file)
@@ -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<QByteArray, QByteArray> &extraHeaders, QObject *parent)
-    : AbstractNetworkJob(account, QString(), parent), _url(url), _extraHeaders(extraHeaders)
+    const QMap<QByteArray, QByteArray> &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 <D:collection> when pointing to <D:resourcetype><D:collection></D:resourcetype>..
-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<QString, qint64> *sizes, const QString& expectedPath)
+bool LsColXMLParser::parse(const QByteArray &xml, QHash<QString, qint64> *sizes, const QString &expectedPath)
 {
     // Parse DAV response
     QXmlStreamReader reader(xml);
@@ -258,7 +259,7 @@ bool LsColXMLParser::parse( const QByteArray& xml, QHash<QString, qint64> *sizes
                 } else if (reader.name() == "propstat") {
                     insidePropstat = false;
                     if (currentPropsHaveHttp200) {
-                        currentHttp200Properties = QMap<QString,QString>(currentTmpProperties);
+                        currentHttp200Properties = QMap<QString, QString>(currentTmpProperties);
                     }
                     currentTmpProperties.clear();
                     currentPropsHaveHttp200 = false;
@@ -281,7 +282,6 @@ bool LsColXMLParser::parse( const QByteArray& xml, QHash<QString, qint64> *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 += "    <oc:" + prop.mid(colIdx+1) + " />\n";
+                propStr += "    <oc:" + prop.mid(colIdx + 1) + " />\n";
             } else {
-                propStr += "    <" + prop.mid(colIdx+1) + " xmlns=\"" + ns + "\" />\n";
+                propStr += "    <" + prop.mid(colIdx + 1) + " xmlns=\"" + ns + "\" />\n";
             }
         } else {
             propStr += "    <d:" + prop + " />\n";
@@ -333,9 +334,8 @@ void LsColJob::start()
     QByteArray xml("<?xml version=\"1.0\" ?>\n"
                    "<d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\">\n"
                    "  <d:prop>\n"
-                   + propStr +
-                   "  </d:prop>\n"
-                   "</d:propfind>\n");
+        + propStr + "  </d:prop>\n"
+                    "</d:propfind>\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<QString,QString>&)),
-                 this, SIGNAL(directoryListingIterated(const QString&, const QMap<QString,QString>&)) );
-        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<QString, QString> &)),
+            this, SIGNAL(directoryListingIterated(const QString &, const QMap<QString, QString> &)));
+        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();
-    ifbody.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 += "    <d:" + prop + " />\n";
         }
@@ -539,9 +538,8 @@ void PropfindJob::start()
     QByteArray xml = "<?xml version=\"1.0\" ?>\n"
                      "<d:propfind xmlns:d=\"DAV:\">\n"
                      "  <d:prop>\n"
-                     + propStr +
-                     "  </d:prop>\n"
-                     "</d:propfind>\n";
+        + propStr + "  </d:prop>\n"
+                    "</d:propfind>\n";
 
     QBuffer *buf = new QBuffer(this);
     buf->setData(xml);
@@ -563,8 +561,8 @@ QList<QByteArray> 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 = "<?xml version=\"1.0\" ?>\n"
                      "<d:propertyupdate xmlns:d=\"DAV:\">\n"
                      "  <d:set><d:prop>\n"
-                     + propStr +
-                     "  </d:prop></d:set>\n"
-                     "</d:propertyupdate>\n";
+        + propStr + "  </d:prop></d:set>\n"
+                    "</d:propertyupdate>\n";
 
     QBuffer *buf = new QBuffer(this);
     buf->setData(xml);
@@ -703,8 +697,8 @@ QMap<QByteArray, QByteArray> 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<QString,QString> > params)
+void JsonApiJob::addQueryParams(QList<QPair<QString, QString>> 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<QPair<QString, QString> > params = _additionalParams;
+    QList<QPair<QString, QString>> 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( "<?xml version=\"1.0\"?>") ) {
+    if (jsonStr.contains("<?xml version=\"1.0\"?>")) {
         QRegExp rex("<statuscode>(\\d+)</statuscode>");
-        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();
         }
     }
index 4ddbf83e2dbbecdc6d675ed9a9cbdc0a3ddcb692..8929391f2fdb9da97eb1aec28c89027a20e550b5 100644 (file)
@@ -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, QObjectparent = 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<QString, qint64> *sizes, const QStringexpectedPath);
+    bool parse(const QByteArray &xml, QHash<QString, qint64> *sizes, const QString &expectedPath);
 
 signals:
     void directoryListingSubfolders(const QStringList &items);
-    void directoryListingIterated(const QString &name, const QMap<QString,QString> &properties);
+    void directoryListingIterated(const QString &name, const QMap<QString, QString> &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<QString,QString> &properties);
+    void directoryListingIterated(const QString &name, const QMap<QString, QString> &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<QByteArray, QByteArray> _extraHeaders;
+
 public:
     explicit MkColJob(AccountPtr account, const QString &path, QObject *parent = 0);
     explicit MkColJob(AccountPtr account, const QUrl &url,
-                      const QMap<QByteArray, QByteArray> &extraHeaders, QObject *parent = 0);
+        const QMap<QByteArray, QByteArray> &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<QString,QString> > params);
+    void addQueryParams(QList<QPair<QString, QString>> 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<QString,QString> > _additionalParams;
+    QList<QPair<QString, QString>> _additionalParams;
 };
 
 } // namespace OCC
index 2f18e45c587416a44d15fceebd4b90b4cd50b655..62f12f023202441358413ef07dea7499142bbc70 100644 (file)
@@ -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 QStringmsg)
+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 SyncFileItemVectoritems)
+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<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
+    QStack<QPair<QString /* directory name */, PropagateDirectory * /* job */>> directories;
     directories.push(qMakePair(QString(), _rootJob.data()));
-    QVector<PropagatorJob*> directoriesToRemove;
+    QVector<PropagatorJob *> 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<PropagateDirectory*>(directoriesToRemove.first());
+            PropagateDirectory *delDirJob = qobject_cast<PropagateDirectory *>(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 {
-                PropagateDirectorycurrentDirJob = 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 SyncOptionsOwncloudPropagator::syncOptions() const
+const SyncOptions &OwncloudPropagator::syncOptions() const
 {
     return _syncOptions;
 }
 
-void OwncloudPropagator::setSyncOptions(const SyncOptionssyncOptions)
+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 QStringfile)
+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<const wchar_t*>(file.utf16()), &FindFileData);
+    hFind = FindFirstFileW(reinterpret_cast<const wchar_t *>(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 QStringtmp_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<OwncloudPropagator*>(parent());
+    return qobject_cast<OwncloudPropagator *>(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 (PropagatorJobjob, _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<PropagateRemoteMkdir*>(_firstJob.data())) {
+            if (PropagateRemoteMkdir *mkdir = qobject_cast<PropagateRemoteMkdir *>(_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();
 }
-
 }
index 0f42635f1ef503ca9e933c2996f7f95e7ea17423..0e7dd573cc69dd7b335d4dbb2a99f091a238cbc6 100644 (file)
@@ -59,11 +59,12 @@ class OwncloudPropagator;
  *
  * @ingroup libsync
  */
-class PropagatorJob : public QObject {
+class PropagatorJob : public QObject
+{
     Q_OBJECT
 
 public:
-    explicit PropagatorJob(OwncloudPropagatorpropagator);
+    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 QStringmsg);
+    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<PropagateItemJob> _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<PropagatorJob *> _jobsToDo;
     SyncFileItemVector _tasksToDo;
     QVector<PropagatorJob *> _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<PropagateItemJob>_firstJob;
+    QScopedPointer<PropagateItemJob> _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 SyncOptionssyncOptions() const;
-    void setSyncOptions(const SyncOptionssyncOptions);
+    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<PropagateItemJob*> _activeJobList;
+    QList<PropagateItemJob *> _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 QStringfile);
+    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 QStringrelfile);
+    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 QStringrelfile);
+    bool hasCaseClashAccessibilityProblem(const QString &relfile);
 
-    QString getFilePath(const QStringtmp_file_name) const;
+    QString getFilePath(const QString &tmp_file_name) const;
 
-    PropagateItemJob *createJob(const SyncFileItemPtritem);
+    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<PropagateDirectory> _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<SyncJournalDb::PollInfo> _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<SyncJournalDb::PollInfo> &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
index f68dc7b0bbe6f1aeaee3cc59c35f9b463392f1ce..eb4a0e18115e13a876e0143dab39a96a0a616965 100644 (file)
@@ -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;
 }
-
 }
index db3a1ad1f89519013f46fa000d2605bad1287df7..5528fe92d3021a1cfe84840746e0ba8e228d59a7 100644 (file)
@@ -30,8 +30,8 @@
 
 namespace OCC {
 
-ownCloudTheme::ownCloudTheme() :
-    Theme()
+ownCloudTheme::ownCloudTheme()
+    Theme()
 {
 }
 
@@ -44,33 +44,31 @@ QString ownCloudTheme::about() const
 {
     QString devString;
     devString = trUtf8("<p>Version %2. For more information visit <a href=\"%3\">https://%4</a></p>"
-               "<p>For known issues and help, please visit: <a href=\"https://central.owncloud.org/c/help/desktop-file-sync\">https://central.owncloud.org</a></p>"
-               "<p><small>By Klaas Freitag, Daniel Molkentin, Olivier Goffart, Markus Götz, "
-               " Jan-Christoph Borchardt, and others.</small></p>"
-               "<p>Copyright ownCloud GmbH</p>"
-               "<p>Licensed under the GNU General Public License (GPL) Version 2.0<br/>"
-               "ownCloud and the ownCloud Logo are registered trademarks of ownCloud GmbH "
-               "in the United States, other countries, or both.</p>"
-               )
-            .arg(Utility::escape(MIRALL_VERSION_STRING),
-                 Utility::escape("https://" MIRALL_STRINGIFY(APPLICATION_DOMAIN)),
-                 Utility::escape(MIRALL_STRINGIFY(APPLICATION_DOMAIN)));
+                       "<p>For known issues and help, please visit: <a href=\"https://central.owncloud.org/c/help/desktop-file-sync\">https://central.owncloud.org</a></p>"
+                       "<p><small>By Klaas Freitag, Daniel Molkentin, Olivier Goffart, Markus Götz, "
+                       " Jan-Christoph Borchardt, and others.</small></p>"
+                       "<p>Copyright ownCloud GmbH</p>"
+                       "<p>Licensed under the GNU General Public License (GPL) Version 2.0<br/>"
+                       "ownCloud and the ownCloud Logo are registered trademarks of ownCloud GmbH "
+                       "in the United States, other countries, or both.</p>")
+                    .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");
 }
-
-
 }
-
index 0ad7f46d5ec905599a524cc0febbf87258545494..327c96e5f59236efb36003294c026826d6dff475 100644 (file)
@@ -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
index 620e9d5fdc9d81584c690e409941d3d1de4363db..6db35fda5b311d4b5844ab96d65e64e51cd17738 100644 (file)
 #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;
 }
 
-sqlite3SqlDatabase::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 QVariantvalue)
+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<const QString*>(value.constData());
+            const QString *str = static_cast<const QString *>(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<const ushort*>(sqlite3_column_text16(_stmt, index)));
+    return QString::fromUtf16(static_cast<const ushort *>(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<const char*>(sqlite3_column_blob(_stmt, index)),
-                       sqlite3_column_bytes(_stmt, index));
+    return QByteArray(static_cast<const char *>(sqlite3_column_blob(_stmt, index)),
+        sqlite3_column_bytes(_stmt, index));
 }
 
 QString SqlQuery::error() const
index 211e77fdd474df8f87836cbfa4d290cb2fe410f4..72c749091ed96a2fb3e980fb9c145307dff8f04c 100644 (file)
@@ -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;
-    sqlite3sqliteDb();
+    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(SqlDatabasedb);
-    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 QVariantvalue);
+    void bindValue(int pos, const QVariant &value);
     QString lastQuery() const;
     int numRowsAffected();
     void reset_and_clear_bindings();
index 6ed274730de5a2053283339309da3fbac518bb7f..8473bc3ada236a285be86743bffda3116b27e0d0 100644 (file)
 
 namespace OCC {
 
-ProgressDispatcherProgressDispatcher::_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)
 {
-    iffolder.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);
 }
-
-
 }
index 47d6d1b3cee1820a6c41cd13e2c392bbee90b451..05aa06b4ff274a3762b7c64525f198497c21d2e6 100644 (file)
@@ -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 ProgressDispatcherinstance();
+    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(QObjectparent = 0);
+    ProgressDispatcher(QObject *parent = 0);
 
     QElapsedTimer _timer;
-    static ProgressDispatcher_instance;
+    static ProgressDispatcher *_instance;
 };
-
 }
 #endif // PROGRESSDISPATCHER_H
index 7d05f3eb9cb669db9ace4849aeaf6239c2a99a3d..f20651a456859098e9bd049fa85d9768cafe4ca7 100644 (file)
@@ -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<QByteArray, QByteArray> &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<QByteArray, QByteArray> &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<QByteArray, QByteArray> &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<QByteArray, QByteArray> &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<QByteArray, QByteArray>::const_iterator it = _headers.begin(); it != _headers.end(); ++it) {
+    for (QMap<QByteArray, QByteArray>::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();
 }
-
-
 }
index 6e4cad115f633ce4054ef6a940dd46d75cb38a2a..69962131b5eb0232940984751a60645990cb455a 100644 (file)
@@ -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<QByteArray, QByteArray> _headers;
     QString _errorString;
     QByteArray _expectedEtagForResume;
@@ -41,24 +42,26 @@ class GETFileJob : public AbstractNetworkJob {
     QPointer<BandwidthManager> _bandwidthManager;
     bool _hasEmittedFinishedSignal;
     time_t _lastModified;
-public:
 
+public:
     // DOES NOT take ownership of the device.
-    explicit GETFileJob(AccountPtr account, const QStringpath, QFile *device,
-                        const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
-                        quint64 resumeStart, QObject* parent = 0);
+    explicit GETFileJob(AccountPtr account, const QString &path, QFile *device,
+        const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
+        quint64 resumeStart, QObject *parent = 0);
     // For directDownloadUrl:
-    explicit GETFileJob(AccountPtr account, const QUrl& url, QFile *device,
-                        const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
-                        quint64 resumeStart, QObject* parent = 0);
-    virtual ~GETFileJob() {
+    explicit GETFileJob(AccountPtr account, const QUrl &url, QFile *device,
+        const QMap<QByteArray, QByteArray> &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 QStrings) { _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;
 };
-
 }
index d0771e8d6b2842e74d9c4d1b4075a6b468033b76..d66cb2d91bb5514de5b5300d27475d8a79717ffe 100644 (file)
@@ -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);
 }
-
-
 }
-
index 54cd8a0eae152645180cddf77ba9b56a202b2f14..c4367b3acf0c89a8097fccde80f4ded0ee5f3c0b 100644 (file)
@@ -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<DeleteJob> _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();
-
 };
-
 }
index 7007eda066bca8dadcd19dc0d1f55d962ca2ea26..f293fa0a9d1a163b609eb70e9fedc065dcd91b90 100644 (file)
@@ -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<QByteArray>() << "getetag" << "http://owncloud.org/ns:id");
+        propfindJob->setProperties(QList<QByteArray>() << "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);
 }
-
-
-
 }
-
index c5bdc3164d93f10b5a93ae09c8edc2b977ee00c1..a89fbe99e3adfc5556c79af08e6a62afd79dfc1a 100644 (file)
@@ -22,14 +22,18 @@ namespace OCC {
  * @brief The PropagateRemoteMkdir class
  * @ingroup libsync
  */
-class PropagateRemoteMkdir : public PropagateItemJob {
+class PropagateRemoteMkdir : public PropagateItemJob
+{
     Q_OBJECT
     QPointer<AbstractNetworkJob> _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();
 };
-
 }
index 373f298b2c6c304509a592d6369ecf195be8b599..7f4f96c33c2dbff49a72ca10f98f49c5096aff92 100644 (file)
@@ -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<QByteArray, QByteArray> 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<QByteArray, QByteArray> 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;
 }
-
 }
-
index 6d9150d79f110c4790dfe92d24b9623b1048d9cd..3180712df0b357d0d1067cdb4cddf5ebc31308ad 100644 (file)
@@ -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<QByteArray, QByteArray> _extraHeaders;
+
 public:
-    explicit MoveJob(AccountPtr account, const QString& path, const QString &destination, QObject* parent = 0);
-    explicit MoveJob(AccountPtr account, const QUrlurl, const QString &destination,
-                     QMap<QByteArray, QByteArray> _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<QByteArray, QByteArray> _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<MoveJob> _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();
 };
-
 }
index 5467d1aa52e4dcc4d92879fde1dfb4365419e2b4..93849dff73c4a13c8ba9030920fbf14d15def3dc 100644 (file)
@@ -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<QByteArray, QByteArray>::const_iterator it = _headers.begin(); it != _headers.end(); ++it) {
+    for (QMap<QByteArray, QByteArray>::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 QStringfileName, 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 QStringpath)
+void PropagateUploadFileCommon::startPollJob(const QString &path)
 {
-    PollJobjob = 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(QObjectjob)
+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<QByteArray, QByteArray> 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<QByteArray, QByteArray> 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);
 }
-
-
 }
index 913155f8d671afb00616673bab3611c7268b7fd9..e9130d9340b951bdb60bb92ff916b5920efff2b6 100644 (file)
@@ -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 QStringfileName, qint64 start, qint64 size);
+    bool prepareAndOpen(const QString &fileName, qint64 start, qint64 size);
 
-    qint64 writeData(const char* , qint64 ) Q_DECL_OVERRIDE;
-    qint64 readData(chardata, 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<QByteArray, QByteArray> _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<QByteArray, QByteArray> &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<QByteArray, QByteArray> &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<QByteArray, QByteArray> &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<QByteArray, QByteArray> &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<AbstractNetworkJob*> _jobs; /// network jobs that are currently in transit
+    QVector<AbstractNetworkJob *> _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 QStringpath);
+    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<QByteArray, QByteArray> 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<int, ServerChunkInfo> _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<QString,QString> &properties);
+    void slotPropfindIterate(const QString &name, const QMap<QString, QString> &properties);
     void slotDeleteJobFinished();
     void slotMkColFinished(QNetworkReply::NetworkError);
     void slotPutFinished();
     void slotMoveJobFinished();
-    void slotUploadProgress(qint64,qint64);
+    void slotUploadProgress(qint64, qint64);
 };
-
-
 }
-
index 75635667d138778a797bbcf701aacebb567cdcd0..d6c213389d3d503a6f7bf7d55eb547cce7b4b81c 100644 (file)
@@ -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<QByteArray>() << "resourcetype" << "getcontentlength");
+        job->setProperties(QList<QByteArray>() << "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<QString,QString>)),
-                this, SLOT(slotPropfindIterate(QString,QMap<QString,QString>)));
+        connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
+            this, SLOT(slotPropfindFinishedWithError()));
+        connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *)));
+        connect(job, SIGNAL(directoryListingIterated(QString, QMap<QString, QString>)),
+            this, SLOT(slotPropfindIterate(QString, QMap<QString, QString>)));
         job->start();
         return;
     } else if (progressInfo._valid) {
@@ -108,13 +109,13 @@ void PropagateUploadFileNG::doStartUpload()
     startNewUpload();
 }
 
-void PropagateUploadFileNG::slotPropfindIterate(const QString &name, const QMap<QString,QString> &properties)
+void PropagateUploadFileNG::slotPropfindIterate(const QString &name, const QMap<QString, QString> &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<QByteArray, QByteArray> 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
-    PUTFileJobjob = 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<quint64>(
-                _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);
 }
-
 }
index 10f6a4fb2abdffb41d14a9eddbdb4480883695f7..f8a88020ddc61107556a2a27654828323faba5ee 100644 (file)
@@ -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
-    PUTFileJobjob = 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<PUTFileJob*>(job)) {
+            if (auto putJob = qobject_cast<PUTFileJob *>(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);
 }
-
 }
index 7c8c5a31a14189e6f588feef26762f84c5d7fe3e..bda94fa11f2d735d3038b7ab874704612b75c766 100644 (file)
@@ -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 QStringpath)
+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 QFileInfofi = 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);
 }
-
 }
index 2a30b3cec9eb0c5b25eef4d6cb72d524260f04e0..2f7c53df7858836a8b676dfb25af5dc267caa001 100644 (file)
@@ -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; }
 };
-
 }
index 9673d7a4cda780467baea6319152f4bf81133379..12d6c879cd4006e310eb5f7de353649f2ab9d902 100644 (file)
@@ -58,23 +58,23 @@ bool SyncEngine::s_anySyncRunning = false;
 
 qint64 SyncEngine::minimumFileAgeForUpload = 2000;
 
-SyncEngine::SyncEngine(AccountPtr account, const QStringlocalPath,
-                       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>("SyncFileItem");
     qRegisterMetaType<SyncFileItemPtr>("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 ifitem._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<QString> 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<SyncJournalDb::DownloadInfo> 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<QString> 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<QString> 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<SyncEngine*>(data)->treewalkFile( file, false );
+    return static_cast<SyncEngine *>(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<SyncEngine*>(data)->treewalkFile( file, true );
+    return static_cast<SyncEngine *>(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<SyncJournalDb::PollInfo> 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<OwncloudPropagator>(
-        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 SyncFileItemitem, 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 QStringoriginal)
+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<QString, QString>::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 QStringfile) 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 QStringfn)
+void SyncEngine::slotAddTouchedFile(const QString &fn)
 {
     QString file = QDir::cleanPath(fn);
 
@@ -1448,9 +1447,9 @@ void SyncEngine::slotClearTouchedFiles()
     _touchedFiles.clear();
 }
 
-qint64 SyncEngine::timeSinceFileTouched(const QStringfn) 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();
     }
 }
index 9cf30c8581ae91b70190ed22d2d8ad43fcf23c19..8652ef2cb0c6b04290735828ceaba5e8c615c790 100644 (file)
@@ -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 QStringfn) 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 SyncFileItemPtritem);
+    void slotItemCompleted(const SyncFileItemPtr &item);
     void slotFinished(bool success);
-    void slotProgress(const SyncFileItemitem, 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 QStringfn);
+    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> _discoveryMainThread;
-    QSharedPointer <OwncloudPropagator> _propagator;
+    QSharedPointer<OwncloudPropagator> _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 QStringfile) 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
index 157d03c05f7a5212f8886521a227c58edfa66589..6273dd5c966b3bea465dd0e23aa980bdc68ecb54 100644 (file)
 #include <csync.h>
 
 #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<SyncFileItem> SyncFileItemPtr;
-inline bool operator<(const SyncFileItemPtr& item1, const SyncFileItemPtr& item2) {
+inline bool operator<(const SyncFileItemPtr &item1, const SyncFileItemPtr &item2)
+{
     return *item1 < *item2;
 }
 
 typedef QVector<SyncFileItemPtr> SyncFileItemVector;
-
 }
 
 Q_DECLARE_METATYPE(OCC::SyncFileItem)
index 722a60785385c8abc5067b2f32044701e5d1388b..12a9977860aa51cf09fc970c9cbc002b2bdd8b9e 100644 (file)
 
 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");
     }
 
index cd9a409ae205b32452fdf506951adc1ddc9d7f0b..27006a57227fc4900c88a18f0489dfd2fa062dde 100644 (file)
@@ -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);
 }
 }
index a3f5030b8dc96359170f29d0f44de9c32b64f346..db1f778c20d7e87ac712e154e7536ab64fb31734 100644 (file)
@@ -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 SyncFileItemitem)
+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 SyncFileItemitem)
+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 QStringrelativePath)
+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 QStringfileName)
+void SyncFileStatusTracker::slotPathTouched(const QString &fileName)
 {
     QString folderPath = _syncEngine->localPath();
 
@@ -177,7 +177,7 @@ void SyncFileStatusTracker::decSyncCountAndEmitStatusChanged(const QString &rela
     }
 }
 
-void SyncFileStatusTracker::slotAboutToPropagate(SyncFileItemVectoritems)
+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 QStringpath)
+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 QStringrelativePath)
+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;
 }
-
 }
index 015f80cc278a8e5af22dcbb7de4791935241c958..12fe0b337cc8a2446e93891a2251b3d4b9ec533d 100644 (file)
@@ -35,32 +35,35 @@ class OWNCLOUDSYNC_EXPORT SyncFileStatusTracker : public QObject
 {
     Q_OBJECT
 public:
-    explicit SyncFileStatusTracker(SyncEnginesyncEngine);
-    SyncFileStatus fileStatus(const QStringrelativePath);
+    explicit SyncFileStatusTracker(SyncEngine *syncEngine);
+    SyncFileStatus fileStatus(const QString &relativePath);
 
 public slots:
-    void slotPathTouched(const QStringfileName);
+    void slotPathTouched(const QString &fileName);
 
 signals:
-    void fileStatusChanged(const QStringsystemFileName, SyncFileStatus fileStatus);
+    void fileStatusChanged(const QString &systemFileName, SyncFileStatus fileStatus);
 
 private slots:
-    void slotAboutToPropagate(SyncFileItemVectoritems);
-    void slotItemCompleted(const SyncFileItemPtritem);
+    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 QStringpath);
-    QString getSystemDestination(const QStringrelativePath);
+    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<QString, SyncFileStatus::SyncFileStatusTag> _syncProblems;
     QSet<QString> _dirtyPaths;
@@ -69,7 +72,6 @@ private:
     // A directory that starts/ends propagation will in turn increase/decrease its own parent by 1.
     QHash<QString, int> _syncCount;
 };
-
 }
 
 #endif
index 128ac50438b227b0e2bfafdd5fba15c33db8804f..c6b67fd067995d63e5a3b88c3c63532399079f18 100644 (file)
@@ -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 QUrlremoteUrl,
-                                  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.
-        ifmajor == 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 QStringfile)
+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 QStringfilename, 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();
-        ifrecursively) {
+        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 QStringfilename)
+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<QString>filepathsToKeep,
-                                    const QSet<QString>& prefixesToKeep)
+bool SyncJournalDb::postSyncCleanup(const QSet<QString> &filepathsToKeep,
+    const QSet<QString> &prefixesToKeep)
 {
     QMutexLocker locker(&_mutex);
 
-    if( !checkConnect() ) {
+    if (!checkConnect()) {
         return false;
     }
 
@@ -990,28 +983,28 @@ bool SyncJournalDb::postSyncCleanup(const QSet<QString>& 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 QStringfilename,
-                                             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 QStringfilename,
-                                        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 SyncJournalFileRecordrecord)
+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 QStringfile)
+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::DownloadInfo> SyncJournalDb::getAndDeleteStaleDownloadInfos(const QSet<QString>keep)
+QVector<SyncJournalDb::DownloadInfo> SyncJournalDb::getAndDeleteStaleDownloadInfos(const QSet<QString> &keep)
 {
     QVector<SyncJournalDb::DownloadInfo> 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 QStringfile)
+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<uint> SyncJournalDb::deleteStaleUploadInfos(const QSet<QString> &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::PollInfo> SyncJournalDb::getPollInfos()
 {
     QMutexLocker locker(&_mutex);
 
-    QVector< SyncJournalDb::PollInfo > res;
+    QVector<SyncJournalDb::PollInfo> 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::PollInfoinfo)
+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 QStringListlist)
+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 QStringpath)
+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 QStringfileName)
+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 QByteArraychecksumType)
+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 QStringcontext, 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
index cd45726449686b1c7d5a9323379fbd4030dc9617..21f68a549d89250c71ac2afba6ae66d1b53e098b 100644 (file)
@@ -37,53 +37,66 @@ class OWNCLOUDSYNC_EXPORT SyncJournalDb : public QObject
 {
     Q_OBJECT
 public:
-    explicit SyncJournalDb(const QStringdbFilePath, 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 QUrlremoteUrl,
-                              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 QStringfilename);
-    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 QStringfilename,
-                                  const QByteArray& contentChecksum,
-                                  const QByteArray& contentChecksumType);
-    bool updateLocalMetadata(const QStringfilename,
-                             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 QStringfile);
+    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<DownloadInfo> getAndDeleteStaleDownloadInfos(const QSet<QString>keep);
+    QVector<DownloadInfo> getAndDeleteStaleDownloadInfos(const QSet<QString> &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<uint> deleteStaleUploadInfos(const QSet<QString>keep);
+    QVector<uint> deleteStaleUploadInfos(const QSet<QString> &keep);
 
-    SyncJournalErrorBlacklistRecord errorBlacklistEntry( const QString& );
-    bool deleteStaleErrorBlacklistEntries(const QSet<QString>keep);
+    SyncJournalErrorBlacklistRecord errorBlacklistEntry(const QString &);
+    bool deleteStaleErrorBlacklistEntries(const QSet<QString> &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 QStringfileName);
+    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<QString>filepathsToKeep,
-                         const QSet<QString>& prefixesToKeep);
+    bool postSyncCleanup(const QSet<QString> &filepathsToKeep,
+        const QSet<QString> &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 QByteArraychecksumType);
+    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
index 3025a100228f40eeede3769092d51cffbd99e45b..6937789145ee670023a092ac65ab3688b3eba2a8 100644 (file)
@@ -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;
-    ifstat(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;
 }
-
 }
index 1debbacb76e68c0fa59ac52bcfcc2d2efc274768..f96e85b3baff673084d64bd36b7a997b7a50f87a 100644 (file)
@@ -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
index 625ebae2caf07beea28f7b395b10962ba1aeb1ac..de5c81c54b6a2056676044748122e1eaa120f7c5 100644 (file)
 #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 QStringfolder)
+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
index 0c630f737e92d5554f835d32f29467324ff67ddb..7c5e501aa62a0bce2ecc90d5e6ed8ebde2b5112c 100644 (file)
@@ -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 QStringfolder);
+    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 SyncFileItemPtrfirstItemNew() const { return _firstItemNew; }
-    const SyncFileItemPtrfirstItemDeleted() const { return _firstItemDeleted; }
-    const SyncFileItemPtrfirstItemUpdated() const { return _firstItemUpdated; }
-    const SyncFileItemPtrfirstItemRenamed() const { return _firstItemRenamed; }
-    const SyncFileItemPtrfirstConflictItem() const { return _firstConflictItem; }
-    const SyncFileItemPtrfirstItemError() 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
index 2f7b288a745ac0538497c8fb5d47945ff27e7786..9dd1c88a95f817177cd3eeded4ae2d675de5057a 100644 (file)
 #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 {
 
-ThemeTheme::_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<int> 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()",
-                   "<p><small>Built from Git revision <a href=\"%1\">%2</a>"
-                   " on %3, %4 using Qt %5, %6</small></p>")
-            .arg(githubPrefix+gitSha1).arg(gitSha1.left(6))
-            .arg(__DATE__).arg(__TIME__)
-            .arg(QString::fromAscii(qVersion()))
+        "<p><small>Built from Git revision <a href=\"%1\">%2</a>"
+        " on %3, %4 using Qt %5, %6</small></p>")
+                    .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("<p>Version %1. For more information please visit <a href='%2'>%3</a>.</p>")
-            .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("<p>Copyright ownCloud GmbH</p>");
     re += tr("<p>Distributed by %1 and licensed under the GNU General Public License (GPL) Version 2.0.<br/>"
              "%2 and the %2 logo are registered trademarks of %1 in the "
              "United States, other countries, or both.</p>")
-            .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
index a3fd81c70890038debb1d93afa7a006b8b4108e3..cc51251df5bfc26e41eb560a47d372270491d09d 100644 (file)
@@ -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 Themeinstance();
+    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/<type>.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 QStringname, 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<QString, QIcon> _iconCache;
 #endif
 };
-
 }
 #endif // _THEME_H
index 1f1139d9ef9a7dfb1f068eb0a8b64399599517a4..b3813f14bddb90950ed54bc89f77914498c9520b 100644 (file)
@@ -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 QStringguiName, 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<const wchar_t *>(path.utf16()), &freeBytes, NULL, NULL )) {
+    if (GetDiskFreeSpaceEx(reinterpret_cast<const wchar_t *>(path.utf16()), &freeBytes, NULL, NULL)) {
         return freeBytes.QuadPart;
     }
 #endif
     return -1;
 }
 
-QString Utility::compactFormatDouble(double value, int prec, const QStringunit)
+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 QDateTimet)
+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 QStringfName)
+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(QStringListfileNames)
+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<QString, QString> > &queryItems)
+    const QList<QPair<QString, QString>> &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<QSettings> Utility::settingsWithGroup(const QStringgroup, QObject *parent)
+std::unique_ptr<QSettings> Utility::settingsWithGroup(const QString &group, QObject *parent)
 {
     if (g_configFileName()->isEmpty()) {
         // cache file name
index c17c7a56cebf93ea3eb799c80eabbbda7d21338a..7c26f2ab22129682bab6a1c7bf321c9df6ac6cfd 100644 (file)
@@ -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 QStringguiName, 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 QStringunit = 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 QStringfName);
+    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<QString, quint64> _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(QStringListfileNames);
+    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<QString, QString> > &queryItems = (QList<QPair<QString, QString>>()));
+        const QUrl &url, const QString &concatPath,
+        const QList<QPair<QString, QString>> &queryItems = (QList<QPair<QString, QString>>()));
 
     /**  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<QSettings> settingsWithGroup(const QString& group, QObject* parent = 0);
+    OWNCLOUDSYNC_EXPORT std::unique_ptr<QSettings> settingsWithGroup(const QString &group, QObject *parent = 0);
 }
 /** @} */ // \addtogroup
-
 }
 #endif // UTILITY_H
index 19f3042ef91cf2104ccd55ea5141133701a505b0..5a71aa2afa4742620c2ca62ba2c3c139c7d0d3d1 100644 (file)
@@ -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 QStringguiName, 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);
index b1d3d96d699c4cd7841a80e57dda5a736d01ccca..e21c1cc75735198edf3bfc65c640cace3a3f418f 100644 (file)
  */
 
 #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
-    #include <QStandardPaths>
+#include <QStandardPaths>
 #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 QStringguiName, 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";
index b862e2e598e538634323608cfbbb9bab2d261e76..f46cde4d548127c61ac3469addf19290546b916d 100644 (file)
 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 QStringguiName, 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);
     }