Apply clang-format

This commit is contained in:
Christian Kamm 2017-05-17 10:55:42 +02:00 committed by ckamm
parent ae263d60bd
commit c8d0f788e0
235 changed files with 7256 additions and 7060 deletions

View File

@ -51,9 +51,12 @@
using namespace OCC;
static void nullMessageHandler(QtMsgType, const char *) {}
static void nullMessageHandler(QtMsgType, const char *)
{
}
struct CmdOptions {
struct CmdOptions
{
QString source_dir;
QString target_url;
QString config_directory;
@ -78,7 +81,7 @@ struct CmdOptions {
// So we have to use a global variable
CmdOptions *opts = 0;
const qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5*1000);
const qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5 * 1000);
class EchoDisabler
{
@ -105,6 +108,7 @@ public:
tcsetattr(STDIN_FILENO, TCSANOW, &tios);
#endif
}
private:
#ifdef Q_OS_WIN
DWORD mode = 0;
@ -123,25 +127,31 @@ QString queryPassword(const QString &user)
return QString::fromStdString(s);
}
class HttpCredentialsText : public HttpCredentials {
class HttpCredentialsText : public HttpCredentials
{
public:
HttpCredentialsText(const QString& user, const QString& password)
: HttpCredentials(user, password), // FIXME: not working with client certs yet (qknight)
_sslTrusted(false)
{}
HttpCredentialsText(const QString &user, const QString &password)
: HttpCredentials(user, password)
, // FIXME: not working with client certs yet (qknight)
_sslTrusted(false)
{
}
void askFromUser() Q_DECL_OVERRIDE {
void askFromUser() Q_DECL_OVERRIDE
{
_password = ::queryPassword(user());
_ready = true;
persist();
emit asked();
}
void setSSLTrusted( bool isTrusted ) {
void setSSLTrusted(bool isTrusted)
{
_sslTrusted = isTrusted;
}
bool sslIsTrusted() Q_DECL_OVERRIDE {
bool sslIsTrusted() Q_DECL_OVERRIDE
{
return _sslTrusted;
}
@ -180,22 +190,22 @@ void help()
std::cout << " --version, -v Display version and exit" << std::endl;
std::cout << "" << std::endl;
exit(0);
}
void showVersion() {
void showVersion()
{
const char *binaryName = APPLICATION_EXECUTABLE "cmd";
std::cout << binaryName << " version " << qPrintable(Theme::instance()->version()) << std::endl;
exit(0);
}
void parseOptions( const QStringList& app_args, CmdOptions *options )
void parseOptions(const QStringList &app_args, CmdOptions *options)
{
QStringList args(app_args);
int argCount = args.count();
if( argCount < 3 ) {
if (argCount < 3) {
if (argCount >= 2) {
const QString option = args.at(1);
if (option == "-v" || option == "--version") {
@ -212,7 +222,7 @@ void parseOptions( const QStringList& app_args, CmdOptions *options )
options->source_dir.append('/');
}
QFileInfo fi(options->source_dir);
if( !fi.exists() ) {
if (!fi.exists()) {
std::cerr << "Source dir '" << qPrintable(options->source_dir) << "' does not exist." << std::endl;
exit(1);
}
@ -220,47 +230,48 @@ void parseOptions( const QStringList& app_args, CmdOptions *options )
QStringListIterator it(args);
// skip file name;
if (it.hasNext()) it.next();
if (it.hasNext())
it.next();
while(it.hasNext()) {
while (it.hasNext()) {
const QString option = it.next();
if( option == "--httpproxy" && !it.peekNext().startsWith("-")) {
if (option == "--httpproxy" && !it.peekNext().startsWith("-")) {
options->proxy = it.next();
} else if( option == "-s" || option == "--silent") {
} else if (option == "-s" || option == "--silent") {
options->silent = true;
} else if( option == "--trust") {
} else if (option == "--trust") {
options->trustSSL = true;
} else if( option == "-n") {
} else if (option == "-n") {
options->useNetrc = true;
} else if( option == "-h") {
} else if (option == "-h") {
options->ignoreHiddenFiles = false;
} else if( option == "--non-interactive") {
} else if (option == "--non-interactive") {
options->interactive = false;
} else if( (option == "-u" || option == "--user") && !it.peekNext().startsWith("-") ) {
options->user = it.next();
} else if( (option == "-p" || option == "--password") && !it.peekNext().startsWith("-") ) {
options->password = it.next();
} else if( option == "--exclude" && !it.peekNext().startsWith("-") ) {
options->exclude = it.next();
} else if( option == "--unsyncedfolders" && !it.peekNext().startsWith("-") ) {
} else if ((option == "-u" || option == "--user") && !it.peekNext().startsWith("-")) {
options->user = it.next();
} else if ((option == "-p" || option == "--password") && !it.peekNext().startsWith("-")) {
options->password = it.next();
} else if (option == "--exclude" && !it.peekNext().startsWith("-")) {
options->exclude = it.next();
} else if (option == "--unsyncedfolders" && !it.peekNext().startsWith("-")) {
options->unsyncedfolders = it.next();
} else if( option == "--nonshib" ) {
} else if (option == "--nonshib") {
options->nonShib = true;
} else if( option == "--davpath" && !it.peekNext().startsWith("-") ) {
} else if (option == "--davpath" && !it.peekNext().startsWith("-")) {
options->davPath = it.next();
} else if( option == "--max-sync-retries" && !it.peekNext().startsWith("-") ) {
} else if (option == "--max-sync-retries" && !it.peekNext().startsWith("-")) {
options->restartTimes = it.next().toInt();
} else if( option == "--uplimit" && !it.peekNext().startsWith("-") ) {
} else if (option == "--uplimit" && !it.peekNext().startsWith("-")) {
options->uplimit = it.next().toInt() * 1000;
} else if( option == "--downlimit" && !it.peekNext().startsWith("-") ) {
} else if (option == "--downlimit" && !it.peekNext().startsWith("-")) {
options->downlimit = it.next().toInt() * 1000;
} else {
help();
}
}
if( options->target_url.isEmpty() || options->source_dir.isEmpty() ) {
if (options->target_url.isEmpty() || options->source_dir.isEmpty()) {
help();
}
}
@ -278,10 +289,10 @@ void selectiveSyncFixup(OCC::SyncJournalDb *journal, const QStringList &newList)
bool ok;
auto oldBlackListSet = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok).toSet();
if( ok ) {
if (ok) {
auto blackListSet = newList.toSet();
auto changes = (oldBlackListSet - blackListSet) + (blackListSet - oldBlackListSet);
foreach(const auto &it, changes) {
foreach (const auto &it, changes) {
journal->avoidReadFromDbOnNextSync(it);
}
@ -289,12 +300,13 @@ void selectiveSyncFixup(OCC::SyncJournalDb *journal, const QStringList &newList)
}
}
int main(int argc, char **argv) {
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
#ifdef Q_OS_WIN
// Ensure OpenSSL config file is only loaded from app directory
QString opensslConf = QCoreApplication::applicationDirPath()+QString("/openssl.cnf");
QString opensslConf = QCoreApplication::applicationDirPath() + QString("/openssl.cnf");
qputenv("OPENSSL_CONF", opensslConf.toLocal8Bit());
#endif
@ -312,7 +324,7 @@ int main(int argc, char **argv) {
options.downlimit = 0;
ClientProxy clientProxy;
parseOptions( app.arguments(), &options );
parseOptions(app.arguments(), &options);
csync_set_log_level(options.silent ? 1 : 11);
if (options.silent) {
@ -321,24 +333,24 @@ int main(int argc, char **argv) {
AccountPtr account = Account::create();
if( !account ) {
if (!account) {
qFatal("Could not initialize account!");
return EXIT_FAILURE;
}
// check if the webDAV path was added to the url and append if not.
if(!options.target_url.endsWith("/")) {
if (!options.target_url.endsWith("/")) {
options.target_url.append("/");
}
if( options.nonShib ) {
if (options.nonShib) {
account->setNonShib(true);
}
if(!options.davPath.isEmpty()) {
account->setDavPath( options.davPath );
if (!options.davPath.isEmpty()) {
account->setDavPath(options.davPath);
}
if( !options.target_url.contains( account->davPath() )) {
if (!options.target_url.contains(account->davPath())) {
options.target_url.append(account->davPath());
}
@ -353,34 +365,34 @@ int main(int argc, char **argv) {
QString user = url.userName();
QString password = url.password();
if (!options.user.isEmpty()) {
user = options.user;
}
if (!options.user.isEmpty()) {
user = options.user;
}
if (!options.password.isEmpty()) {
password = options.password;
}
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.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.interactive) {
if (user.isEmpty()) {
std::cout << "Please enter user name: ";
std::string s;
std::getline(std::cin, s);
user = QString::fromStdString(s);
}
if (password.isEmpty()) {
password = queryPassword(user);
}
}
// take the unmodified url to pass to csync_create()
QByteArray remUrl = options.target_url.toUtf8();
@ -405,7 +417,7 @@ int main(int argc, char **argv) {
HttpCredentialsText *cred = new HttpCredentialsText(user, password);
if( options.trustSSL ) {
if (options.trustSSL) {
cred->setSSLTrusted(true);
}
account->setUrl(url);
@ -438,17 +450,18 @@ restart_sync:
opts = &options;
if( !options.proxy.isNull() ) {
if (!options.proxy.isNull()) {
QString host;
int port = 0;
bool ok;
QStringList pList = options.proxy.split(':');
if(pList.count() == 3) {
if (pList.count() == 3) {
// http: //192.168.178.23 : 8080
// 0 1 2
host = pList.at(1);
if( host.startsWith("//") ) host.remove(0, 2);
if (host.startsWith("//"))
host.remove(0, 2);
port = pList.at(2).toInt(&ok);
@ -457,8 +470,8 @@ restart_sync:
}
} else {
clientProxy.setupQtProxyFromConfig();
QString url( options.target_url );
if( url.startsWith("owncloud")) {
QString url(options.target_url);
if (url.startsWith("owncloud")) {
url.remove(0, 8);
url = QString("http%1").arg(url);
}
@ -494,7 +507,7 @@ restart_sync:
engine.setNetworkLimits(options.uplimit, options.downlimit);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QObject::connect(&engine, &SyncEngine::finished,
[&app](bool result) { app.exit(result ? EXIT_SUCCESS : EXIT_FAILURE); });
[&app](bool result) { app.exit(result ? EXIT_SUCCESS : EXIT_FAILURE); });
#else
QObject::connect(&engine, SIGNAL(finished(bool)), &app, SLOT(quit()));
#endif
@ -507,11 +520,11 @@ restart_sync:
QString systemExcludeFile = ConfigFile::excludeFileFromSystem();
// Always try to load the user-provided exclude list if one is specified
if ( hasUserExcludeFile ) {
if (hasUserExcludeFile) {
engine.excludedFiles().addExcludeFilePath(options.exclude);
}
// Load the system list if available, or if there's no user-provided list
if ( !hasUserExcludeFile || QFile::exists(systemExcludeFile) ) {
if (!hasUserExcludeFile || QFile::exists(systemExcludeFile)) {
engine.excludedFiles().addExcludeFilePath(systemExcludeFile);
}
@ -537,4 +550,3 @@ restart_sync:
return resultCode;
}

View File

@ -22,12 +22,17 @@
* @brief Helper class for command line client
* @ingroup cmd
*/
class Cmd : public QObject {
class Cmd : public QObject
{
Q_OBJECT
public:
Cmd() : QObject() { }
Cmd()
: QObject()
{
}
public slots:
void transmissionProgressSlot() {
void transmissionProgressSlot()
{
}
};

View File

@ -25,25 +25,25 @@
namespace OCC {
namespace {
QString defaultKeyword = QLatin1String("default");
QString machineKeyword = QLatin1String("machine");
QString loginKeyword = QLatin1String("login");
QString passwordKeyword = QLatin1String("password");
QString defaultKeyword = QLatin1String("default");
QString machineKeyword = QLatin1String("machine");
QString loginKeyword = QLatin1String("login");
QString passwordKeyword = QLatin1String("password");
}
NetrcParser::NetrcParser(const QString &file)
{
_netrcLocation = file;
if (_netrcLocation.isEmpty()) {
_netrcLocation = QDir::homePath()+QLatin1String("/.netrc");
_netrcLocation = QDir::homePath() + QLatin1String("/.netrc");
}
}
void NetrcParser::tryAddEntryAndClear(QString& machine, LoginPair& pair, bool& isDefault) {
void NetrcParser::tryAddEntryAndClear(QString &machine, LoginPair &pair, bool &isDefault)
{
if (isDefault) {
_default = pair;
} else if (!machine.isEmpty() && !pair.first.isEmpty()){
} else if (!machine.isEmpty() && !pair.first.isEmpty()) {
_entries.insert(machine, pair);
}
pair = qMakePair(QString(), QString());
@ -87,7 +87,6 @@ bool NetrcParser::parse()
} else if (key == passwordKeyword) {
pair.second = value;
} // ignore unsupported tokens
}
tryAddEntryAndClear(machine, pair, isDefault);

View 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;
}
}

View 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

View File

@ -20,18 +20,17 @@
#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
// 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}")
// << 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();

View 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 auto& accountId, settings->childGroups()) {
foreach (const auto &accountId, settings->childGroups()) {
settings->beginGroup(accountId);
if (auto acc = loadAccountHelper(*settings)) {
acc->_id = accountId;
@ -78,40 +78,44 @@ bool AccountManager::restore()
bool AccountManager::restoreFromLegacySettings()
{
qCInfo(lcAccountManager) << "Migrate: restoreFromLegacySettings, checking settings group"
<< Theme::instance()->appName();
<< Theme::instance()->appName();
// try to open the correctly themed settings
auto settings = Utility::settingsWithGroup(Theme::instance()->appName());
// if the settings file could not be opened, the childKeys list is empty
// then try to load settings from a very old place
if( settings->childKeys().isEmpty() ) {
if (settings->childKeys().isEmpty()) {
// Now try to open the original ownCloud settings to see if they exist.
QString oCCfgFile = QDir::fromNativeSeparators( settings->fileName() );
QString oCCfgFile = QDir::fromNativeSeparators(settings->fileName());
// replace the last two segments with ownCloud/owncloud.cfg
oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/'));
oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/'));
oCCfgFile = oCCfgFile.left(oCCfgFile.lastIndexOf('/'));
oCCfgFile = oCCfgFile.left(oCCfgFile.lastIndexOf('/'));
oCCfgFile += QLatin1String("/ownCloud/owncloud.cfg");
qCInfo(lcAccountManager) << "Migrate: checking old config " << oCCfgFile;
QFileInfo fi( oCCfgFile );
if( fi.isReadable() ) {
QFileInfo fi(oCCfgFile);
if (fi.isReadable()) {
std::unique_ptr<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(Account* a)
void AccountManager::saveAccount(Account *a)
{
qCInfo(lcAccountManager) << "Saving account" << a->url().toString();
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
@ -155,7 +159,7 @@ void AccountManager::saveAccount(Account* a)
qCInfo(lcAccountManager) << "Saved account settings, status:" << settings->status();
}
void AccountManager::saveAccountState(AccountState* a)
void AccountManager::saveAccountState(AccountState *a)
{
qCInfo(lcAccountManager) << "Saving account state" << a->account()->url().toString();
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
@ -167,7 +171,7 @@ void AccountManager::saveAccountState(AccountState* a)
qCInfo(lcAccountManager) << "Saved account state settings, status:" << settings->status();
}
void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool saveCredentials)
void AccountManager::saveAccountHelper(Account *acc, QSettings &settings, bool saveCredentials)
{
settings.setValue(QLatin1String(urlC), acc->_url.toString());
settings.setValue(QLatin1String(serverVersionC), acc->_serverVersion);
@ -179,7 +183,7 @@ void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool s
// re-persisting them)
acc->_credentials->persist();
}
Q_FOREACH(QString key, acc->_settingsMap.keys()) {
Q_FOREACH (QString key, acc->_settingsMap.keys()) {
settings.setValue(key, acc->_settingsMap.value(key));
}
settings.setValue(QLatin1String(authTypeC), acc->_credentials->authType());
@ -193,17 +197,17 @@ void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool s
settings.beginGroup(QLatin1String("General"));
qCInfo(lcAccountManager) << "Saving " << acc->approvedCerts().count() << " unknown certs.";
QByteArray certs;
Q_FOREACH( const QSslCertificate& cert, acc->approvedCerts() ) {
Q_FOREACH (const QSslCertificate &cert, acc->approvedCerts()) {
certs += cert.toPem() + '\n';
}
if (!certs.isEmpty()) {
settings.setValue( QLatin1String(caCertsKeyC), certs );
settings.setValue(QLatin1String(caCertsKeyC), certs);
}
settings.endGroup();
// Save cookies.
if (acc->_am) {
CookieJar* jar = qobject_cast<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(QSettings& settings)
AccountPtr AccountManager::loadAccountHelper(QSettings &settings)
{
auto urlConfig = settings.value(QLatin1String(urlC));
if (!urlConfig.isValid()) {
@ -236,7 +240,7 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings)
QString overrideUrl = Theme::instance()->overrideServerUrl();
QString forceAuth = Theme::instance()->forceConfigAuthType();
if(!forceAuth.isEmpty() && !overrideUrl.isEmpty() ) {
if (!forceAuth.isEmpty() && !overrideUrl.isEmpty()) {
// If forceAuth is set, this might also mean the overrideURL has changed.
// See enterprise issues #1126
acc->setUrl(overrideUrl);
@ -252,7 +256,7 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings)
// We want to only restore settings for that auth type and the user value
acc->_settingsMap.insert(QLatin1String(userC), settings.value(userC));
QString authTypePrefix = authType + "_";
Q_FOREACH(QString key, settings.childKeys()) {
Q_FOREACH (QString key, settings.childKeys()) {
if (!key.startsWith(authTypePrefix))
continue;
acc->_settingsMap.insert(key, settings.value(key));
@ -268,9 +272,9 @@ AccountPtr AccountManager::loadAccountHelper(QSettings& settings)
return acc;
}
AccountStatePtr AccountManager::account(const QString& name)
AccountStatePtr AccountManager::account(const QString &name)
{
foreach (const auto& acc, _accounts) {
foreach (const auto &acc, _accounts) {
if (acc->account()->displayName() == name) {
return acc;
}
@ -278,7 +282,7 @@ AccountStatePtr AccountManager::account(const QString& name)
return AccountStatePtr();
}
AccountState *AccountManager::addAccount(const AccountPtr& newAccount)
AccountState *AccountManager::addAccount(const AccountPtr &newAccount)
{
auto id = newAccount->id();
if (id.isEmpty() || !isAccountIdAvailable(id)) {
@ -291,10 +295,12 @@ AccountState *AccountManager::addAccount(const AccountPtr& newAccount)
return newAccountState;
}
void AccountManager::deleteAccount(AccountState* account)
void AccountManager::deleteAccount(AccountState *account)
{
auto it = std::find(_accounts.begin(), _accounts.end(), account);
if (it == _accounts.end()) { return; }
if (it == _accounts.end()) {
return;
}
auto copy = *it; // keep a reference to the shared pointer so it does not delete it just yet
_accounts.erase(it);
@ -310,8 +316,8 @@ AccountPtr AccountManager::createAccount()
{
AccountPtr acc = Account::create();
acc->setSslErrorHandler(new SslDialogErrorHandler);
connect(acc.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator*)),
ProxyAuthHandler::instance(), SLOT(handleProxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
connect(acc.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)),
ProxyAuthHandler::instance(), SLOT(handleProxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)));
return acc;
}
@ -325,9 +331,9 @@ void AccountManager::shutdown()
}
}
bool AccountManager::isAccountIdAvailable(const QString& id) const
bool AccountManager::isAccountIdAvailable(const QString &id) const
{
foreach (const auto& acc, _accounts) {
foreach (const auto &acc, _accounts) {
if (acc->account()->id() == id) {
return false;
}
@ -347,15 +353,14 @@ QString AccountManager::generateFreeAccountId() const
}
}
void AccountManager::addAccountState(AccountState* accountState)
void AccountManager::addAccountState(AccountState *accountState)
{
QObject::connect(accountState->account().data(),
SIGNAL(wantsAccountSaved(Account*)),
SLOT(saveAccount(Account*)));
SIGNAL(wantsAccountSaved(Account *)),
SLOT(saveAccount(Account *)));
AccountStatePtr ptr(accountState);
_accounts << ptr;
emit accountAdded(accountState);
}
}

View 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 QString& name);
AccountStatePtr account(const QString &name);
/**
* Delete the AccountState
@ -78,23 +79,23 @@ public:
private:
// saving and loading Account to settings
void saveAccountHelper(Account* account, QSettings& settings, bool saveCredentials = true);
AccountPtr loadAccountHelper(QSettings& settings);
void saveAccountHelper(Account *account, QSettings &settings, bool saveCredentials = true);
AccountPtr loadAccountHelper(QSettings &settings);
bool restoreFromLegacySettings();
bool isAccountIdAvailable(const QString& id) const;
bool isAccountIdAvailable(const QString &id) const;
QString generateFreeAccountId() const;
// Adds an account to the tracked list, emitting accountAdded()
void addAccountState(AccountState* accountState);
void addAccountState(AccountState *accountState);
public slots:
/// Saves account data, not including the credentials
void saveAccount(Account* a);
void saveAccount(Account *a);
/// Saves account state data, not including the account
void saveAccountState(AccountState* a);
void saveAccountState(AccountState *a);
Q_SIGNALS:
@ -105,5 +106,4 @@ private:
AccountManager() {}
QList<AccountStatePtr> _accounts;
};
}

View 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;"
"}";
"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)
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 QModelIndex& indx)
void AccountSettings::slotFolderListClicked(const QModelIndex &indx)
{
if (indx.data(FolderStatusDelegate::AddButton).toBool()) {
// "Add Folder Sync Connection"
@ -288,9 +286,9 @@ void AccountSettings::slotFolderListClicked(const QModelIndex& indx)
slotAddFolder();
} else {
QToolTip::showText(
QCursor::pos(),
_model->data(indx, Qt::ToolTipRole).toString(),
this);
QCursor::pos(),
_model->data(indx, Qt::ToolTipRole).toString(),
this);
}
return;
}
@ -304,8 +302,8 @@ void AccountSettings::slotFolderListClicked(const QModelIndex& indx)
}
// Expand root items on single click
if(_accountState && _accountState->state() == AccountState::Connected ) {
bool expanded = ! (ui->_folderList->isExpanded(indx));
if (_accountState && _accountState->state() == AccountState::Connected) {
bool expanded = !(ui->_folderList->isExpanded(indx));
ui->_folderList->setExpanded(indx, expanded);
}
}
@ -326,16 +324,16 @@ void AccountSettings::slotAddFolder()
void AccountSettings::slotFolderWizardAccepted()
{
FolderWizard *folderWizard = qobject_cast<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 (Folder* current = folderMan->currentSyncFolder()) {
if (Folder *current = folderMan->currentSyncFolder()) {
folderMan->terminateSyncProcess();
folderMan->scheduleFolder(current);
}
@ -540,17 +540,17 @@ void AccountSettings::slotForceSyncCurrentFolder()
void AccountSettings::slotOpenOC()
{
if( _OCUrl.isValid() )
QDesktopServices::openUrl( _OCUrl );
if (_OCUrl.isValid())
QDesktopServices::openUrl(_OCUrl);
}
void AccountSettings::slotUpdateQuota(qint64 total, qint64 used)
{
if( total > 0 ) {
if (total > 0) {
ui->quotaProgressBar->setVisible(true);
ui->quotaProgressBar->setEnabled(true);
// workaround the label only accepting ints (which may be only 32 bit wide)
const double percent = used/(double)total*100;
const double percent = used / (double)total * 100;
const int percentInt = qMin(qRound(percent), 100);
ui->quotaProgressBar->setValue(percentInt);
QString usedStr = Utility::octetsToString(used);
@ -588,7 +588,7 @@ void AccountSettings::slotAccountStateChanged(int state)
QString server = QString::fromLatin1("<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 QString& link)
void AccountSettings::slotLinkActivated(const QString &link)
{
// Parse folder alias and filename from the link, calculate the index
// and select it if it exists.
const QStringList li = link.split(QLatin1String("?folder="));
if( li.count() > 1) {
if (li.count() > 1) {
QString myFolder = li[0];
const QString alias = li[1];
if(myFolder.endsWith(QLatin1Char('/'))) myFolder.chop(1);
if (myFolder.endsWith(QLatin1Char('/')))
myFolder.chop(1);
// Make sure the folder itself is expanded
Folder *f = FolderMan::instance()->folder(alias);
QModelIndex folderIndx = _model->indexForPath(f, QString());
if( !ui->_folderList->isExpanded(folderIndx)) {
if (!ui->_folderList->isExpanded(folderIndx)) {
ui->_folderList->setExpanded(folderIndx, true);
}
QModelIndex indx = _model->indexForPath(f, myFolder);
if( indx.isValid() ) {
if (indx.isValid()) {
// make sure all the parents are expanded
for (auto i = indx.parent(); i.isValid(); i = i.parent()) {
if( !ui->_folderList->isExpanded(i)) {
if (!ui->_folderList->isExpanded(i)) {
ui->_folderList->setExpanded(i, true);
}
}
@ -689,20 +690,20 @@ void AccountSettings::refreshSelectiveSyncStatus()
}
bool ok;
auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok);
auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok);
QString p;
foreach(const auto &it, undecidedList) {
foreach (const auto &it, undecidedList) {
// FIXME: add the folder alias in a hoover hint.
// folder->alias() + QLatin1String("/")
if( cnt++ ) {
if (cnt++) {
msg += QLatin1String(", ");
}
QString myFolder = (it);
if( myFolder.endsWith('/')) {
if (myFolder.endsWith('/')) {
myFolder.chop(1);
}
QModelIndex theIndx = _model->indexForPath(folder, myFolder);
if(theIndx.isValid()) {
if (theIndx.isValid()) {
msg += QString::fromLatin1("<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);
QPushButton* yesButton =
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(QEvent* e)
bool AccountSettings::event(QEvent *e)
{
if (e->type() == QEvent::Hide || e->type() == QEvent::Show) {
_quotaInfo.setActive(isVisible());

View 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);
AccountState* accountsState() { return _accountState; }
AccountState *accountsState() { return _accountState; }
protected slots:
void slotAddFolder();
@ -84,15 +84,15 @@ protected slots:
void slotOpenAccountWizard();
void slotAccountAdded(AccountState *);
void refreshSelectiveSyncStatus();
void slotCustomContextMenuRequested(const QPoint&);
void slotFolderListClicked( const QModelIndex& indx );
void slotCustomContextMenuRequested(const QPoint &);
void slotFolderListClicked(const QModelIndex &indx);
void doExpand();
void slotLinkActivated(const QString &link);
private:
void showConnectionLabel(const QString& message,
QStringList errors = QStringList());
bool event(QEvent*) Q_DECL_OVERRIDE;
void showConnectionLabel(const QString &message,
QStringList errors = QStringList());
bool event(QEvent *) Q_DECL_OVERRIDE;
void createAccountToolbox();
/// Returns the alias of the selected folder, empty string if none
@ -101,7 +101,7 @@ private:
Ui::AccountSettings *ui;
FolderStatusModel *_model;
QUrl _OCUrl;
QUrl _OCUrl;
bool _wasDisabledBefore;
AccountState *_accountState;
QuotaInfo _quotaInfo;

View 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 QStringList& errors)
void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList &errors)
{
if (isSignedOut()) {
qCWarning(lcAccountState) << "Signed out, ignoring" << connectionStatusString(status) << _account->url().toString();
@ -223,14 +222,13 @@ void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status sta
if (_connectionStatus != status) {
qCInfo(lcAccountState) << "AccountState connection status change: "
<< connectionStatusString(_connectionStatus) << "->"
<< connectionStatusString(status);
<< connectionStatusString(_connectionStatus) << "->"
<< connectionStatusString(status);
_connectionStatus = status;
}
_connectionErrors = errors;
switch (status)
{
switch (status) {
case ConnectionValidator::Connected:
if (_state != Connected) {
setState(Connected);
@ -280,7 +278,7 @@ void AccountState::slotInvalidCredentials()
_waitingForNewCredentials = true;
}
void AccountState::slotCredentialsFetched(AbstractCredentials* credentials)
void AccountState::slotCredentialsFetched(AbstractCredentials *credentials)
{
if (!credentials->ready()) {
// No exiting credentials found in the keychain
@ -300,7 +298,7 @@ void AccountState::slotCredentialsFetched(AbstractCredentials* credentials)
checkConnectivity();
}
void AccountState::slotCredentialsAsked(AbstractCredentials* credentials)
void AccountState::slotCredentialsAsked(AbstractCredentials *credentials)
{
_waitingForNewCredentials = false;
@ -346,5 +344,4 @@ QString AccountState::shortDisplayNameForSettings(int width) const
}
} // namespace OCC

View 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(QSettings& settings);
void writeToSettings(QSettings &settings);
AccountPtr account() const;
@ -134,10 +135,10 @@ signals:
void isConnectedChanged();
protected Q_SLOTS:
void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList& errors);
void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList &errors);
void slotInvalidCredentials();
void slotCredentialsFetched(AbstractCredentials* creds);
void slotCredentialsAsked(AbstractCredentials* creds);
void slotCredentialsFetched(AbstractCredentials *creds);
void slotCredentialsAsked(AbstractCredentials *creds);
private:
AccountPtr _account;
@ -148,10 +149,9 @@ private:
QElapsedTimer _timeSinceLastETagCheck;
QPointer<ConnectionValidator> _connectionValidator;
};
}
Q_DECLARE_METATYPE(OCC::AccountState*)
Q_DECLARE_METATYPE(OCC::AccountState *)
Q_DECLARE_METATYPE(OCC::AccountStatePtr)
#endif //ACCOUNTINFO_H

View File

@ -17,20 +17,20 @@
#include "activitydata.h"
namespace OCC
{
namespace OCC {
bool operator<( const Activity& rhs, const Activity& lhs ) {
bool operator<(const Activity &rhs, const Activity &lhs)
{
return rhs._dateTime.toMSecsSinceEpoch() > lhs._dateTime.toMSecsSinceEpoch();
}
bool operator==( const Activity& rhs, const Activity& lhs ) {
return (rhs._type == lhs._type && rhs._id== lhs._id && rhs._accName == lhs._accName);
bool operator==(const Activity &rhs, const Activity &lhs)
{
return (rhs._type == lhs._type && rhs._id == lhs._id && rhs._accName == lhs._accName);
}
Activity::Identifier Activity::ident() const {
return Identifier( _id, _accName );
Activity::Identifier Activity::ident() const
{
return Identifier(_id, _accName);
}
}

View 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

View 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);
}

View 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 };
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;
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

View 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(AccountState* s)
void ActivityListModel::startFetchJob(AccountState *s)
{
if( !s->isConnected() ) {
if (!s->isConnected()) {
return;
}
JsonApiJob *job = new JsonApiJob(s->account(), QLatin1String("ocs/v1.php/cloud/activity"), this);
QObject::connect(job, SIGNAL(jsonReceived(QJsonDocument, int)),
this, SLOT(slotActivitiesReceived(QJsonDocument, int)));
this, SLOT(slotActivitiesReceived(QJsonDocument, int)));
job->setProperty("AccountStatePtr", QVariant::fromValue<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 QJsonDocument& json, int statusCode)
void ActivityListModel::slotActivitiesReceived(const QJsonDocument &json, int statusCode)
{
auto activities = json.object().value("ocs").toObject().value("data").toArray();
@ -155,17 +153,17 @@ void ActivityListModel::slotActivitiesReceived(const QJsonDocument& json, int st
_currentlyFetching.remove(ast);
foreach( auto activ, activities ) {
foreach (auto activ, activities) {
auto json = activ.toObject();
Activity a;
a._type = Activity::ActivityType;
a._accName = ast->account()->displayName();
a._id = json.value("id").toInt();
a._subject = json.value("subject").toString();
a._message = json.value("message").toString();
a._file = json.value("file").toString();
a._link = QUrl(json.value("link").toString());
a._accName = ast->account()->displayName();
a._id = json.value("id").toInt();
a._subject = json.value("subject").toString();
a._message = json.value("message").toString();
a._file = json.value("file").toString();
a._link = QUrl(json.value("link").toString());
a._dateTime = QDateTime::fromString(json.value("date").toString(), Qt::ISODate);
list.append(a);
}
@ -182,11 +180,11 @@ void ActivityListModel::combineActivityLists()
{
ActivityList resultList;
foreach( ActivityList list, _activityLists.values() ) {
foreach (ActivityList list, _activityLists.values()) {
resultList.append(list);
}
std::sort( resultList.begin(), resultList.end() );
std::sort(resultList.begin(), resultList.end());
beginResetModel();
_finalList.clear();
@ -201,9 +199,8 @@ void ActivityListModel::fetchMore(const QModelIndex &)
{
QList<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);
}
}
}

View 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 QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
bool canFetchMore(const QModelIndex& ) const Q_DECL_OVERRIDE;
void fetchMore(const QModelIndex&) Q_DECL_OVERRIDE;
bool canFetchMore(const QModelIndex &) const Q_DECL_OVERRIDE;
void fetchMore(const QModelIndex &) Q_DECL_OVERRIDE;
ActivityList activityList() { return _finalList; }
public slots:
void slotRefreshActivity(AccountState* ast);
void slotRemoveAccount( AccountState *ast );
void slotRefreshActivity(AccountState *ast);
void slotRemoveAccount(AccountState *ast);
private slots:
void slotActivitiesReceived(const QJsonDocument& json, int statusCode);
void slotActivitiesReceived(const QJsonDocument &json, int statusCode);
signals:
void activityJobStatusCode(AccountState* ast, int statusCode);
void activityJobStatusCode(AccountState *ast, int statusCode);
private:
void startFetchJob(AccountState* s);
void startFetchJob(AccountState *s);
void combineActivityLists();
QMap<AccountState*, ActivityList> _activityLists;
QMap<AccountState *, ActivityList> _activityLists;
ActivityList _finalList;
QSet<AccountState*> _currentlyFetching;
QSet<AccountState *> _currentlyFetching;
};
}
#endif // ACTIVITYLISTMODEL_H

View File

@ -50,14 +50,14 @@
namespace OCC {
ActivityWidget::ActivityWidget(QWidget *parent) :
QWidget(parent),
_ui(new Ui::ActivityWidget),
_notificationRequestsRunning(0)
ActivityWidget::ActivityWidget(QWidget *parent)
: QWidget(parent)
, _ui(new Ui::ActivityWidget)
, _notificationRequestsRunning(0)
{
_ui->setupUi(this);
// Adjust copyToClipboard() when making changes here!
// Adjust copyToClipboard() when making changes here!
#if defined(Q_OS_MAC)
_ui->_activityList->setMinimumWidth(400);
#endif
@ -83,19 +83,19 @@ ActivityWidget::ActivityWidget(QWidget *parent) :
showLabels();
connect(_model, SIGNAL(activityJobStatusCode(AccountState*,int)),
this, SLOT(slotAccountActivityStatus(AccountState*,int)));
connect(_model, SIGNAL(activityJobStatusCode(AccountState *, int)),
this, SLOT(slotAccountActivityStatus(AccountState *, int)));
_copyBtn = _ui->_dialogButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
_copyBtn->setToolTip( tr("Copy the activity list to the clipboard."));
_copyBtn->setToolTip(tr("Copy the activity list to the clipboard."));
connect(_copyBtn, SIGNAL(clicked()), SIGNAL(copyToClipboard()));
connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(rowsInserted()));
connect(_model, SIGNAL(rowsInserted(QModelIndex, int, int)), SIGNAL(rowsInserted()));
connect( _ui->_activityList, SIGNAL(activated(QModelIndex)), this,
SLOT(slotOpenFile(QModelIndex)));
connect(_ui->_activityList, SIGNAL(activated(QModelIndex)), this,
SLOT(slotOpenFile(QModelIndex)));
connect( &_removeTimer, SIGNAL(timeout()), this, SLOT(slotCheckToCleanWidgets()) );
connect(&_removeTimer, SIGNAL(timeout()), this, SLOT(slotCheckToCleanWidgets()));
_removeTimer.setInterval(1000);
}
@ -113,10 +113,10 @@ void ActivityWidget::slotRefreshNotifications(AccountState *ptr)
{
// start a server notification handler if no notification requests
// are running
if( _notificationRequestsRunning == 0 ) {
if (_notificationRequestsRunning == 0) {
ServerNotificationHandler *snh = new ServerNotificationHandler;
connect(snh, SIGNAL(newNotificationList(ActivityList)), this,
SLOT(slotBuildNotificationDisplay(ActivityList)));
SLOT(slotBuildNotificationDisplay(ActivityList)));
snh->slotFetchNotifications(ptr);
} else {
@ -124,7 +124,7 @@ void ActivityWidget::slotRefreshNotifications(AccountState *ptr)
}
}
void ActivityWidget::slotRemoveAccount( AccountState *ptr )
void ActivityWidget::slotRemoveAccount(AccountState *ptr)
{
_model->slotRemoveAccount(ptr);
}
@ -139,8 +139,8 @@ void ActivityWidget::showLabels()
t.clear();
QSetIterator<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 ActivityList& list)
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() ) {
if( accNotified.contains(host)) {
accNotified[host] = accNotified[host]+1;
if (!host.isEmpty()) {
if (accNotified.contains(host)) {
accNotified[host] = accNotified[host] + 1;
} else {
accNotified[host] = 1;
}
@ -313,31 +313,31 @@ void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list)
// check if there are widgets that have no corresponding activity from
// the server any more. Collect them in a list
QList< Activity::Identifier > strayCats;
foreach( auto id, _widgetForNotifId.keys() ) {
QList<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";
if( validVerbs.contains(verb)) {
if (validVerbs.contains(verb)) {
AccountStatePtr acc = AccountManager::instance()->account(accountName);
if( acc ) {
if (acc) {
NotificationConfirmJob *job = new NotificationConfirmJob(acc->account());
QUrl l(link);
job->setLinkAndVerb(l, verb);
job->setWidget(theSender);
connect( job, SIGNAL( networkError(QNetworkReply*)),
this, SLOT(slotNotifyNetworkError(QNetworkReply*)));
connect( job, SIGNAL( jobFinished(QString, int)),
this, SLOT(slotNotifyServerFinished(QString, int)) );
connect(job, SIGNAL(networkError(QNetworkReply *)),
this, SLOT(slotNotifyNetworkError(QNetworkReply *)));
connect(job, SIGNAL(jobFinished(QString, int)),
this, SLOT(slotNotifyServerFinished(QString, int)));
job->start();
// count the number of running notification requests. If this member var
@ -403,18 +405,18 @@ void ActivityWidget::slotSendNotificationRequest(const QString& accountName, con
}
}
void ActivityWidget::endNotificationRequest( NotificationWidget *widget, int replyCode )
void ActivityWidget::endNotificationRequest(NotificationWidget *widget, int replyCode)
{
_notificationRequestsRunning--;
if( widget ) {
if (widget) {
widget->slotNotificationRequestFinished(replyCode);
}
}
void ActivityWidget::slotNotifyNetworkError( QNetworkReply *reply)
void ActivityWidget::slotNotifyNetworkError(QNetworkReply *reply)
{
NotificationConfirmJob *job = qobject_cast<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 Activity& blacklistActivity)
void ActivityWidget::slotRequestCleanupAndBlacklist(const Activity &blacklistActivity)
{
if ( ! _blacklistedNotifications.contains(blacklistActivity) ) {
if (!_blacklistedNotifications.contains(blacklistActivity)) {
_blacklistedNotifications.append(blacklistActivity);
}
NotificationWidget *widget = _widgetForNotifId[ blacklistActivity.ident() ];
NotificationWidget *widget = _widgetForNotifId[blacklistActivity.ident()];
scheduleWidgetToRemove(widget);
}
void ActivityWidget::scheduleWidgetToRemove(NotificationWidget *widget, int milliseconds)
{
if( !widget ) {
if (!widget) {
return;
}
// in five seconds from now, remove the widget.
@ -467,7 +468,7 @@ void ActivityWidget::scheduleWidgetToRemove(NotificationWidget *widget, int mill
if (!it.isValid() || it > removeTime) {
it = removeTime;
}
if( !_removeTimer.isActive() ) {
if (!_removeTimer.isActive()) {
_removeTimer.start();
}
}
@ -482,7 +483,7 @@ void ActivityWidget::slotCheckToCleanWidgets()
QDateTime t = it.value();
NotificationWidget *widget = it.key();
if( currentTime > t ) {
if (currentTime > t) {
// found one to remove!
Activity::Identifier id = widget->activity().ident();
_widgetForNotifId.remove(id);
@ -493,12 +494,12 @@ void ActivityWidget::slotCheckToCleanWidgets()
}
}
if( _widgetsToRemove.isEmpty() ) {
if (_widgetsToRemove.isEmpty()) {
_removeTimer.stop();
}
// check to see if the whole notification pane should be hidden
if( _widgetForNotifId.isEmpty() ) {
if (_widgetForNotifId.isEmpty()) {
_ui->_notifyLabel->setHidden(true);
_ui->_notifyScroll->setHidden(true);
}
@ -508,7 +509,7 @@ void ActivityWidget::slotCheckToCleanWidgets()
/* ==================================================================== */
ActivitySettings::ActivitySettings(QWidget *parent)
:QWidget(parent)
: QWidget(parent)
{
QHBoxLayout *hbox = new QHBoxLayout(this);
setLayout(hbox);
@ -520,14 +521,14 @@ ActivitySettings::ActivitySettings(QWidget *parent)
_activityTabId = _tab->insertTab(0, _activityWidget, Theme::instance()->applicationIcon(), tr("Server Activity"));
connect(_activityWidget, SIGNAL(copyToClipboard()), this, SLOT(slotCopyToClipboard()));
connect(_activityWidget, SIGNAL(hideActivityTab(bool)), this, SLOT(setActivityTabHidden(bool)));
connect(_activityWidget, SIGNAL(guiLog(QString,QString)), this, SIGNAL(guiLog(QString,QString)));
connect(_activityWidget, SIGNAL(guiLog(QString, QString)), this, SIGNAL(guiLog(QString, QString)));
connect(_activityWidget, SIGNAL(newNotification()), SLOT(slotShowActivityTab()));
_protocolWidget = new ProtocolWidget(this);
_tab->insertTab(1, _protocolWidget, Theme::instance()->syncStateIcon(SyncResult::Success), tr("Sync Protocol"));
connect(_protocolWidget, SIGNAL(copyToClipboard()), this, SLOT(slotCopyToClipboard()));
connect(_protocolWidget, SIGNAL(issueItemCountUpdated(int)),
this, SLOT(slotShowIssueItemCount(int)));
this, SLOT(slotShowIssueItemCount(int)));
// Add the not-synced list into the tab
QWidget *w = new QWidget;
@ -537,7 +538,7 @@ ActivitySettings::ActivitySettings(QWidget *parent)
QDialogButtonBox *dlgButtonBox = new QDialogButtonBox(this);
vbox2->addWidget(dlgButtonBox);
QPushButton *_copyBtn = dlgButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
_copyBtn->setToolTip( tr("Copy the activity list to the clipboard."));
_copyBtn->setToolTip(tr("Copy the activity list to the clipboard."));
_copyBtn->setEnabled(true);
connect(_copyBtn, SIGNAL(clicked()), this, SLOT(slotCopyToClipboard()));
@ -550,7 +551,7 @@ ActivitySettings::ActivitySettings(QWidget *parent)
_tab->setCornerWidget(_progressIndicator);
connect(&_notificationCheckTimer, SIGNAL(timeout()),
this, SLOT(slotRegularNotificationCheck()));
this, SLOT(slotRegularNotificationCheck()));
// connect a model signal to stop the animation.
connect(_activityWidget, SIGNAL(rowsInserted()), _progressIndicator, SLOT(stopAnimation()));
@ -559,20 +560,20 @@ ActivitySettings::ActivitySettings(QWidget *parent)
_tab->setCurrentIndex(1);
}
void ActivitySettings::setNotificationRefreshInterval( quint64 interval )
void ActivitySettings::setNotificationRefreshInterval(quint64 interval)
{
qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval/1000 << " sec interval";
qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval / 1000 << " sec interval";
_notificationCheckTimer.start(interval);
}
void ActivitySettings::setActivityTabHidden(bool hidden)
{
if( hidden && _activityTabId > -1 ) {
if (hidden && _activityTabId > -1) {
_tab->removeTab(_activityTabId);
_activityTabId = -1;
}
if( !hidden && _activityTabId == -1 ) {
if (!hidden && _activityTabId == -1) {
_activityTabId = _tab->insertTab(0, _activityWidget, Theme::instance()->applicationIcon(), tr("Server Activity"));
}
}
@ -580,7 +581,7 @@ void ActivitySettings::setActivityTabHidden(bool hidden)
void ActivitySettings::slotShowIssueItemCount(int cnt)
{
QString cntText = tr("Not Synced");
if( cnt ) {
if (cnt) {
//: %1 is the number of not synced files.
cntText = tr("Not Synced (%1)").arg(cnt);
}
@ -602,46 +603,46 @@ void ActivitySettings::slotCopyToClipboard()
int idx = _tab->currentIndex();
QString message;
if( idx == 0 ) {
if (idx == 0) {
// the activity widget
_activityWidget->storeActivityList(ts);
message = tr("The server activity list has been copied to the clipboard.");
} else if(idx == 1 ) {
} else if (idx == 1) {
// the protocol widget
_protocolWidget->storeSyncActivity(ts);
message = tr("The sync activity list has been copied to the clipboard.");
} else if(idx == 2 ) {
} else if (idx == 2) {
// issues Widget
message = tr("The list of unsynced items has been copied to the clipboard.");
_protocolWidget->storeSyncIssues(ts);
_protocolWidget->storeSyncIssues(ts);
}
QApplication::clipboard()->setText(text);
emit guiLog(tr("Copied to clipboard"), message);
}
void ActivitySettings::slotRemoveAccount( AccountState *ptr )
void ActivitySettings::slotRemoveAccount(AccountState *ptr)
{
_activityWidget->slotRemoveAccount(ptr);
}
void ActivitySettings::slotRefresh( AccountState* ptr )
void ActivitySettings::slotRefresh(AccountState *ptr)
{
// QElapsedTimer isn't actually constructed as invalid.
if ( !_timeSinceLastCheck.contains(ptr) ) {
if (!_timeSinceLastCheck.contains(ptr)) {
_timeSinceLastCheck[ptr].invalidate();
}
QElapsedTimer & timer = _timeSinceLastCheck[ptr];
QElapsedTimer &timer = _timeSinceLastCheck[ptr];
// Fetch Activities only if visible and if last check is longer than 15 secs ago
if( timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD ) {
if (timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD) {
qCDebug(lcActivity) << "Do not check as last check is only secs ago: " << timer.elapsed() / 1000;
return;
}
if( ptr && ptr->isConnected() ) {
if( isVisible() || !timer.isValid() ) {
if (ptr && ptr->isConnected()) {
if (isVisible() || !timer.isValid()) {
_progressIndicator->startAnimation();
_activityWidget->slotRefreshActivities( ptr);
_activityWidget->slotRefreshActivities(ptr);
}
_activityWidget->slotRefreshNotifications(ptr);
timer.start();
@ -656,7 +657,7 @@ void ActivitySettings::slotRegularNotificationCheck()
}
}
bool ActivitySettings::event(QEvent* e)
bool ActivitySettings::event(QEvent *e)
{
if (e->type() == QEvent::Show) {
AccountManager *am = AccountManager::instance();
@ -669,8 +670,5 @@ bool ActivitySettings::event(QEvent* e)
ActivitySettings::~ActivitySettings()
{
}
}

View 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(AccountState* ptr);
void slotRefreshActivities(AccountState *ptr);
void slotRefreshNotifications(AccountState *ptr);
void slotRemoveAccount( AccountState *ptr );
void slotRemoveAccount(AccountState *ptr);
void slotAccountActivityStatus(AccountState *ast, int statusCode);
void slotRequestCleanupAndBlacklist(const Activity& blacklistActivity);
void slotRequestCleanupAndBlacklist(const Activity &blacklistActivity);
signals:
void guiLog(const QString&, const QString&);
void guiLog(const QString &, const QString &);
void copyToClipboard();
void rowsInserted();
void hideActivityTab(bool);
void newNotification();
private slots:
void slotBuildNotificationDisplay(const ActivityList& list);
void slotSendNotificationRequest(const QString &accountName, const QString& link, const QByteArray &verb);
void slotNotifyNetworkError( QNetworkReply* );
void slotNotifyServerFinished( const QString& reply, int replyCode );
void endNotificationRequest(NotificationWidget *widget , int replyCode);
void slotBuildNotificationDisplay(const ActivityList &list);
void slotSendNotificationRequest(const QString &accountName, const QString &link, const QByteArray &verb);
void slotNotifyNetworkError(QNetworkReply *);
void slotNotifyServerFinished(const QString &reply, int replyCode);
void endNotificationRequest(NotificationWidget *widget, int replyCode);
void scheduleWidgetToRemove(NotificationWidget *widget, int milliseconds = 4500);
void slotCheckToCleanWidgets();
@ -100,12 +100,12 @@ private:
QPushButton *_copyBtn;
QSet<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(QEvent* e) Q_DECL_OVERRIDE;
bool event(QEvent *e) Q_DECL_OVERRIDE;
QTabWidget *_tab;
int _activityTabId;
@ -159,9 +158,8 @@ private:
ActivityWidget *_activityWidget;
ProtocolWidget *_protocolWidget;
QProgressIndicator *_progressIndicator;
QTimer _notificationCheckTimer;
QHash<AccountState*, QElapsedTimer> _timeSinceLastCheck;
QTimer _notificationCheckTimer;
QHash<AccountState *, QElapsedTimer> _timeSinceLastCheck;
};
}
#endif // ActivityWIDGET_H

View 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();
}
}

View 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

View 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;
ExcludedFiles& excludes = ExcludedFiles::instance();
excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::SystemScope) );
excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::UserScope) );
ExcludedFiles &excludes = ExcludedFiles::instance();
excludes.addExcludeFilePath(cfg.excludeFile(ConfigFile::SystemScope));
excludes.addExcludeFilePath(cfg.excludeFile(ConfigFile::UserScope));
excludes.reloadExcludes();
_folderManager.reset(new FolderMan);
connect(this, SIGNAL(messageReceived(QString, QObject*)), SLOT(slotParseMessage(QString, QObject*)));
connect(this, SIGNAL(messageReceived(QString, QObject *)), SLOT(slotParseMessage(QString, QObject *)));
if (!AccountManager::instance()->restore()) {
// If there is an error reading the account settings, try again
@ -171,11 +171,12 @@ Application::Application(int &argc, char **argv) :
if (!AccountManager::instance()->restore()) {
qCCritical(lcApplication) << "Could not read the account settings, quitting";
QMessageBox::critical(
0,
tr("Error accessing the configuration file"),
tr("There was an error while accessing the configuration "
"file at %1.").arg(ConfigFile().configFile()),
tr("Quit ownCloud"));
0,
tr("Error accessing the configuration file"),
tr("There was an error while accessing the configuration "
"file at %1.")
.arg(ConfigFile().configFile()),
tr("Quit ownCloud"));
QTimer::singleShot(0, qApp, SLOT(quit()));
return;
}
@ -186,50 +187,50 @@ Application::Application(int &argc, char **argv) :
setQuitOnLastWindowClosed(false);
_theme->setSystrayUseMonoIcons(cfg.monoIcons());
connect (_theme, SIGNAL(systrayUseMonoIconsChanged(bool)), SLOT(slotUseMonoIconsChanged(bool)));
connect(_theme, SIGNAL(systrayUseMonoIconsChanged(bool)), SLOT(slotUseMonoIconsChanged(bool)));
FolderMan::instance()->setupFolders();
_proxy.setupQtProxyFromConfig(); // folders have to be defined first, than we set up the Qt proxy.
_gui = new ownCloudGui(this);
if( _showLogWindow ) {
if (_showLogWindow) {
_gui->slotToggleLogBrowser(); // _showLogWindow is set in parseOptions.
}
// Enable word wrapping of QInputDialog (#4197)
setStyleSheet("QInputDialog QLabel { qproperty-wordWrap:1; }");
connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)),
SLOT(slotAccountStateAdded(AccountState*)));
connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)),
SLOT(slotAccountStateRemoved(AccountState*)));
foreach (auto ai , AccountManager::instance()->accounts()) {
connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)),
SLOT(slotAccountStateAdded(AccountState *)));
connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)),
SLOT(slotAccountStateRemoved(AccountState *)));
foreach (auto ai, AccountManager::instance()->accounts()) {
slotAccountStateAdded(ai.data());
}
connect(FolderMan::instance()->socketApi(), SIGNAL(shareCommandReceived(QString, QString, bool)),
_gui, SLOT(slotShowShareDialog(QString, QString, bool)));
_gui, SLOT(slotShowShareDialog(QString, QString, bool)));
// startup procedure.
connect(&_checkConnectionTimer, SIGNAL(timeout()), this, SLOT(slotCheckConnection()));
_checkConnectionTimer.setInterval(ConnectionValidator::DefaultCallingIntervalMsec); // check for connection every 32 seconds.
_checkConnectionTimer.start();
// Also check immediately
QTimer::singleShot( 0, this, SLOT( slotCheckConnection() ));
QTimer::singleShot(0, this, SLOT(slotCheckConnection()));
// Can't use onlineStateChanged because it is always true on modern systems because of many interfaces
connect(&_networkConfigurationManager, SIGNAL(configurationChanged(QNetworkConfiguration)),
this, SLOT(slotSystemOnlineConfigurationChanged(QNetworkConfiguration)));
this, SLOT(slotSystemOnlineConfigurationChanged(QNetworkConfiguration)));
// Update checks
UpdaterScheduler *updaterScheduler = new UpdaterScheduler(this);
connect(updaterScheduler, SIGNAL(updaterAnnouncement(QString, QString)),
_gui, SLOT(slotShowTrayMessage(QString, QString)));
_gui, SLOT(slotShowTrayMessage(QString, QString)));
connect(updaterScheduler, SIGNAL(requestRestart()),
_folderManager.data(), SLOT(slotScheduleAppRestart()));
_folderManager.data(), SLOT(slotScheduleAppRestart()));
// Cleanup at Quit.
connect (this, SIGNAL(aboutToQuit()), SLOT(slotCleanup()));
connect(this, SIGNAL(aboutToQuit()), SLOT(slotCleanup()));
}
Application::~Application()
@ -248,19 +249,19 @@ void Application::slotAccountStateRemoved(AccountState *accountState)
{
if (_gui) {
disconnect(accountState, SIGNAL(stateChanged(int)),
_gui, SLOT(slotAccountStateChanged()));
disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
_gui, SLOT(slotTrayMessageIfServerUnsupported(Account*)));
_gui, SLOT(slotAccountStateChanged()));
disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
_gui, SLOT(slotTrayMessageIfServerUnsupported(Account *)));
}
if (_folderManager) {
disconnect(accountState, SIGNAL(stateChanged(int)),
_folderManager.data(), SLOT(slotAccountStateChanged()));
disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
_folderManager.data(), SLOT(slotServerVersionChanged(Account*)));
_folderManager.data(), SLOT(slotAccountStateChanged()));
disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
_folderManager.data(), SLOT(slotServerVersionChanged(Account *)));
}
// if there is no more account, show the wizard.
if( AccountManager::instance()->accounts().isEmpty() ) {
if (AccountManager::instance()->accounts().isEmpty()) {
// allow to add a new account if there is non any more. Always think
// about single account theming!
OwncloudSetupWizard::runWizard(this, SLOT(slotownCloudWizardDone(int)));
@ -270,13 +271,13 @@ void Application::slotAccountStateRemoved(AccountState *accountState)
void Application::slotAccountStateAdded(AccountState *accountState)
{
connect(accountState, SIGNAL(stateChanged(int)),
_gui, SLOT(slotAccountStateChanged()));
connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
_gui, SLOT(slotTrayMessageIfServerUnsupported(Account*)));
_gui, SLOT(slotAccountStateChanged()));
connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
_gui, SLOT(slotTrayMessageIfServerUnsupported(Account *)));
connect(accountState, SIGNAL(stateChanged(int)),
_folderManager.data(), SLOT(slotAccountStateChanged()));
connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
_folderManager.data(), SLOT(slotServerVersionChanged(Account*)));
_folderManager.data(), SLOT(slotAccountStateChanged()));
connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
_folderManager.data(), SLOT(slotServerVersionChanged(Account *)));
_gui->slotTrayMessageIfServerUnsupported(accountState->account().data());
}
@ -303,13 +304,13 @@ void Application::slotSystemOnlineConfigurationChanged(QNetworkConfiguration cnf
void Application::slotCheckConnection()
{
auto list = AccountManager::instance()->accounts();
foreach (const auto &accountState , list) {
foreach (const auto &accountState, list) {
AccountState::State state = accountState->state();
// Don't check if we're manually signed out or
// when the error is permanent.
if (state != AccountState::SignedOut
&& state != AccountState::ConfigurationError) {
&& state != AccountState::ConfigurationError) {
accountState->checkConnectivity();
}
}
@ -327,7 +328,7 @@ void Application::slotCrash()
Utility::crash();
}
void Application::slotownCloudWizardDone( int res )
void Application::slotownCloudWizardDone(int res)
{
AccountManager *accountMan = AccountManager::instance();
FolderMan *folderMan = FolderMan::instance();
@ -335,7 +336,7 @@ void Application::slotownCloudWizardDone( int res )
// During the wizard, scheduling of new syncs is disabled
folderMan->setSyncEnabled(true);
if( res == QDialog::Accepted ) {
if (res == QDialog::Accepted) {
// Check connectivity of the newly created account
_checkConnectionTimer.start();
slotCheckConnection();
@ -345,7 +346,7 @@ void Application::slotownCloudWizardDone( int res )
#ifdef Q_OS_MAC
// Don't auto start when not being 'installed'
shouldSetAutoStart = shouldSetAutoStart
&& QCoreApplication::applicationDirPath().startsWith("/Applications/");
&& QCoreApplication::applicationDirPath().startsWith("/Applications/");
#endif
Utility::setLaunchOnStartup(_theme->appName(), _theme->appNameGUI(), shouldSetAutoStart);
@ -364,11 +365,7 @@ void Application::setupLogging()
Logger::instance()->enterNextLogFile();
qCInfo(lcApplication) << QString::fromLatin1( "################## %1 locale:[%2] ui_lang:[%3] version:[%4] os:[%5]").arg(_theme->appName())
.arg( QLocale::system().name() )
.arg(property("ui_lang").toString())
.arg(_theme->version())
.arg(Utility::platformName());
qCInfo(lcApplication) << QString::fromLatin1("################## %1 locale:[%2] ui_lang:[%3] version:[%4] os:[%5]").arg(_theme->appName()).arg(QLocale::system().name()).arg(property("ui_lang").toString()).arg(_theme->version()).arg(Utility::platformName());
}
void Application::slotUseMonoIconsChanged(bool)
@ -376,7 +373,7 @@ void Application::slotUseMonoIconsChanged(bool)
_gui->slotComputeOverallSyncStatus();
}
void Application::slotParseMessage(const QString &msg, QObject*)
void Application::slotParseMessage(const QString &msg, QObject *)
{
if (msg.startsWith(QLatin1String("MSG_PARSEOPTIONS:"))) {
const int lengthOfMsgPrefix = 17;
@ -384,8 +381,8 @@ void Application::slotParseMessage(const QString &msg, QObject*)
parseOptions(options);
setupLogging();
} else if (msg.startsWith(QLatin1String("MSG_SHOWSETTINGS"))) {
qCInfo(lcApplication) << "Running for" << _startedAt.elapsed()/1000.0 << "sec";
if (_startedAt.elapsed() < 10*1000) {
qCInfo(lcApplication) << "Running for" << _startedAt.elapsed() / 1000.0 << "sec";
if (_startedAt.elapsed() < 10 * 1000) {
// This call is mirrored with the one in int main()
qCWarning(lcApplication) << "Ignoring MSG_SHOWSETTINGS, possibly double-invocation of client via session restore and auto start";
return;
@ -398,7 +395,8 @@ void Application::parseOptions(const QStringList &options)
{
QStringListIterator it(options);
// skip file name;
if (it.hasNext()) it.next();
if (it.hasNext())
it.next();
//parse options; if help or bad option exit
while (it.hasNext()) {
@ -406,18 +404,17 @@ void Application::parseOptions(const QStringList &options)
if (option == QLatin1String("--help") || option == QLatin1String("-h")) {
setHelp();
break;
} else if (option == QLatin1String("--logwindow") ||
option == QLatin1String("-l")) {
} else if (option == QLatin1String("--logwindow") || option == QLatin1String("-l")) {
_showLogWindow = true;
} else if (option == QLatin1String("--logfile")) {
if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
_logFile = it.next();
_logFile = it.next();
} else {
showHint("Log file not specified");
}
} else if (option == QLatin1String("--logdir")) {
if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
_logDir = it.next();
_logDir = it.next();
} else {
showHint("Log dir not specified");
}
@ -434,7 +431,7 @@ void Application::parseOptions(const QStringList &options)
} else if (option == QLatin1String("--confdir")) {
if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
QString confDir = it.next();
if (!ConfigFile::setConfDir( confDir )) {
if (!ConfigFile::setConfDir(confDir)) {
showHint("Invalid path passed to --confdir");
}
} else {
@ -485,11 +482,14 @@ void Application::showHelp()
<< QLatin1String(" version ")
<< _theme->version().toLatin1().constData() << endl;
stream << QLatin1String("File synchronisation desktop utility.") << endl << endl
stream << QLatin1String("File synchronisation desktop utility.") << endl
<< endl
<< QLatin1String(optionsC);
if (_theme->appName() == QLatin1String("ownCloud"))
stream << endl << "For more information, see http://www.owncloud.org" << endl << endl;
stream << endl
<< "For more information, see http://www.owncloud.org" << endl
<< endl;
displayHelpText(helpText);
}
@ -548,13 +548,13 @@ QString substLang(const QString &lang)
void Application::setupTranslations()
{
QStringList uiLanguages;
// uiLanguages crashes on Windows with 4.8.0 release builds
#if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN))
uiLanguages = QLocale::system().uiLanguages();
#else
// older versions need to fall back to the systems locale
uiLanguages << QLocale::system().name();
#endif
// uiLanguages crashes on Windows with 4.8.0 release builds
#if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN))
uiLanguages = QLocale::system().uiLanguages();
#else
// older versions need to fall back to the systems locale
uiLanguages << QLocale::system().name();
#endif
QString enforcedLocale = Theme::instance()->enforcedLocale();
if (!enforcedLocale.isEmpty())
@ -564,13 +564,12 @@ void Application::setupTranslations()
QTranslator *qtTranslator = new QTranslator(this);
QTranslator *qtkeychainTranslator = new QTranslator(this);
foreach(QString lang, uiLanguages) {
foreach (QString lang, uiLanguages) {
lang.replace(QLatin1Char('-'), QLatin1Char('_')); // work around QTBUG-25973
lang = substLang(lang);
const QString trPath = applicationTrPath();
const QString trFile = QLatin1String("client_") + lang;
if (translator->load(trFile, trPath) ||
lang.startsWith(QLatin1String("en"))) {
if (translator->load(trFile, trPath) || lang.startsWith(QLatin1String("en"))) {
// Permissive approach: Qt and keychain translations
// may be missing, but Qt translations must be there in order
// for us to accept the language. Otherwise, we try with the next.
@ -626,4 +625,3 @@ void Application::showSettingsDialog()
} // namespace OCC

View 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;

View 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);

View 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;
};

View File

@ -15,18 +15,20 @@
namespace OCC {
namespace Mac {
/**
/**
* @brief CocoaInitializer provides an AutoRelease Pool via RIIA for use in main()
* @ingroup gui
*/
class CocoaInitializer {
public:
CocoaInitializer();
~CocoaInitializer();
private:
class Private;
Private *d;
};
class CocoaInitializer
{
public:
CocoaInitializer();
~CocoaInitializer();
private:
class Private;
Private *d;
};
} // namespace Mac
} // namespace OCC

View File

@ -22,30 +22,28 @@
#include "creds/shibbolethcredentials.h"
#endif
namespace OCC
{
namespace OCC {
Q_LOGGING_CATEGORY(lcGuiCredentials, "gui.credentials", QtInfoMsg)
namespace CredentialsFactory
{
namespace CredentialsFactory {
AbstractCredentials* create(const QString& type)
{
// empty string might happen for old version of configuration
if (type == "http" || type == "") {
return new HttpCredentialsGui;
} else if (type == "dummy") {
return new DummyCredentials;
AbstractCredentials *create(const QString &type)
{
// empty string might happen for old version of configuration
if (type == "http" || type == "") {
return new HttpCredentialsGui;
} else if (type == "dummy") {
return new DummyCredentials;
#ifndef NO_SHIBBOLETH
} else if (type == "shibboleth") {
return new ShibbolethCredentials;
} else if (type == "shibboleth") {
return new ShibbolethCredentials;
#endif
} else {
qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type));
return new DummyCredentials;
} else {
qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type));
return new DummyCredentials;
}
}
}
} // ns CredentialsFactory

View 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

View 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 Account* account)
QString HttpCredentialsGui::requestAppPasswordText(const Account *account)
{
int version = account->serverVersionInt();
QString path;

View File

@ -16,18 +16,24 @@
#pragma once
#include "creds/httpcredentials.h"
namespace OCC
{
namespace OCC {
/**
* @brief The HttpCredentialsGui class
* @ingroup gui
*/
class HttpCredentialsGui : public HttpCredentials {
class HttpCredentialsGui : public HttpCredentials
{
Q_OBJECT
public:
explicit HttpCredentialsGui() : HttpCredentials() {}
HttpCredentialsGui(const QString& user, const QString& password, const QSslCertificate& certificate, const QSslKey& key) : HttpCredentials(user, password, certificate, key) {}
explicit HttpCredentialsGui()
: HttpCredentials()
{
}
HttpCredentialsGui(const QString &user, const QString &password, const QSslCertificate &certificate, const QSslKey &key)
: HttpCredentials(user, password, certificate, key)
{
}
void askFromUser() Q_DECL_OVERRIDE;
Q_INVOKABLE void askFromUserAsync();
@ -35,4 +41,3 @@ public:
};
} // namespace OCC

View File

@ -23,7 +23,7 @@ namespace OCC {
Q_DECLARE_LOGGING_CATEGORY(lcShibboleth)
ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent)
ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject *parent)
: JsonApiJob(account, QLatin1String("ocs/v1.php/cloud/user"), parent)
{
setIgnoreCredentialFailure(true);
@ -32,11 +32,10 @@ ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent)
void ShibbolethUserJob::slotJsonReceived(const QJsonDocument &json, int statusCode)
{
if( statusCode != 100 ) {
if (statusCode != 100) {
qCWarning(lcShibboleth) << "JSON Api call resulted in status code != 100";
}
QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString();
QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString();
emit userFetched(user);
}
}

View File

@ -18,17 +18,17 @@
class QJsonDocument;
namespace OCC
{
namespace OCC {
/**
* @brief Fetch the user name of the shibboleth connection
* @ingroup gui
*/
class ShibbolethUserJob : public JsonApiJob {
class ShibbolethUserJob : public JsonApiJob
{
Q_OBJECT
public:
explicit ShibbolethUserJob(AccountPtr account, QObject* parent = 0);
explicit ShibbolethUserJob(AccountPtr account, QObject *parent = 0);
signals:
// is always emitted when the job is finished. user is empty in case of error.
@ -40,4 +40,3 @@ private slots:
} // namespace OCC

View File

@ -31,26 +31,28 @@
#include "configfile.h"
namespace {
const char ShibbolethWebViewGeometryC[] = "ShibbolethWebView/Geometry";
const char ShibbolethWebViewGeometryC[] = "ShibbolethWebView/Geometry";
}
namespace OCC
{
namespace OCC {
class UserAgentWebPage : public QWebPage {
public:
UserAgentWebPage(QObject *parent) : QWebPage(parent)
class UserAgentWebPage : public QWebPage
{
public:
UserAgentWebPage(QObject *parent)
: QWebPage(parent)
{
if (!qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty()) {
settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
}
}
QString userAgentForUrl(const QUrl &url ) const {
QString userAgentForUrl(const QUrl &url) const
{
return QWebPage::userAgentForUrl(url) + " " + Utility::userAgentString();
}
};
ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget* parent)
ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget *parent)
: QWebView(parent)
, _account(account)
, _accepted(false)
@ -60,31 +62,31 @@ ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget* parent)
setWindowFlags(Qt::Dialog);
setAttribute(Qt::WA_DeleteOnClose);
QWebPage* page = new UserAgentWebPage(this);
QWebPage *page = new UserAgentWebPage(this);
connect(page, SIGNAL(loadStarted()),
this, SLOT(slotLoadStarted()));
this, SLOT(slotLoadStarted()));
connect(page, SIGNAL(loadFinished(bool)),
this, SLOT(slotLoadFinished(bool)));
this, SLOT(slotLoadFinished(bool)));
// Make sure to accept the same SSL certificate issues as the regular QNAM we use for syncing
QObject::connect(page->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*,QList<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);

View 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

View File

@ -35,37 +35,36 @@
using namespace QKeychain;
namespace OCC
{
namespace OCC {
Q_LOGGING_CATEGORY(lcShibboleth, "gui.credentials.shibboleth", QtInfoMsg)
namespace
{
namespace {
// Not "user" because it has a special meaning for http
const char userC[] = "shib_user";
const char shibCookieNameC[] = "_shibsession_";
// Not "user" because it has a special meaning for http
const char userC[] = "shib_user";
const char shibCookieNameC[] = "_shibsession_";
} // ns
ShibbolethCredentials::ShibbolethCredentials()
: AbstractCredentials(),
_url(),
_ready(false),
_stillValid(false),
_browser(0)
{}
ShibbolethCredentials::ShibbolethCredentials(const QNetworkCookie& cookie)
: _ready(true),
_stillValid(true),
_browser(0),
_shibCookie(cookie)
: AbstractCredentials()
, _url()
, _ready(false)
, _stillValid(false)
, _browser(0)
{
}
void ShibbolethCredentials::setAccount(Account* account)
ShibbolethCredentials::ShibbolethCredentials(const QNetworkCookie &cookie)
: _ready(true)
, _stillValid(true)
, _browser(0)
, _shibCookie(cookie)
{
}
void ShibbolethCredentials::setAccount(Account *account)
{
AbstractCredentials::setAccount(account);
@ -91,15 +90,15 @@ QString ShibbolethCredentials::user() const
return _user;
}
QNetworkAccessManager* ShibbolethCredentials::getQNAM() const
QNetworkAccessManager *ShibbolethCredentials::getQNAM() const
{
QNetworkAccessManager* qnam(new AccessManager);
connect(qnam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(slotReplyFinished(QNetworkReply*)));
QNetworkAccessManager *qnam(new AccessManager);
connect(qnam, SIGNAL(finished(QNetworkReply *)),
this, SLOT(slotReplyFinished(QNetworkReply *)));
return qnam;
}
void ShibbolethCredentials::slotReplyFinished(QNetworkReply* r)
void ShibbolethCredentials::slotReplyFinished(QNetworkReply *r)
{
if (!_browser.isNull()) {
return;
@ -133,7 +132,7 @@ void ShibbolethCredentials::fetchFromKeychain()
job->setSettings(Utility::settingsWithGroup(Theme::instance()->appName(), job).release());
job->setInsecureFallback(false);
job->setKey(keychainKey(_account->url().toString(), user()));
connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadJobDone(QKeychain::Job*)));
connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadJobDone(QKeychain::Job *)));
job->start();
}
}
@ -161,11 +160,11 @@ void ShibbolethCredentials::invalidateToken()
{
_ready = false;
CookieJar *jar = static_cast<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 QNetworkCookie& shibCookie)
void ShibbolethCredentials::onShibbolethCookieReceived(const QNetworkCookie &shibCookie)
{
storeShibCookie(shibCookie);
_shibCookie = shibCookie;
@ -198,8 +197,8 @@ void ShibbolethCredentials::slotFetchUser()
{
// We must first do a request to webdav so the session is enabled.
// (because for some reason we can't access the API without that.. a bug in the server maybe?)
EntityExistsJob* job = new EntityExistsJob(_account->sharedFromThis(), _account->davPath(), this);
connect(job, SIGNAL(exists(QNetworkReply*)), this, SLOT(slotFetchUserHelper()));
EntityExistsJob *job = new EntityExistsJob(_account->sharedFromThis(), _account->davPath(), this);
connect(job, SIGNAL(exists(QNetworkReply *)), this, SLOT(slotFetchUserHelper()));
job->setIgnoreCredentialFailure(true);
job->start();
}
@ -241,7 +240,7 @@ void ShibbolethCredentials::slotBrowserRejected()
void ShibbolethCredentials::slotReadJobDone(QKeychain::Job *job)
{
if (job->error() == QKeychain::NoError) {
ReadPasswordJob *readJob = static_cast<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(Account* account)
QList<QNetworkCookie> ShibbolethCredentials::accountCookies(Account *account)
{
return account->networkAccessManager()->cookieJar()->cookiesForUrl(account->davUrl());
}
QNetworkCookie ShibbolethCredentials::findShibCookie(Account* account, 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;
}

View File

@ -25,13 +25,12 @@
#include "creds/abstractcredentials.h"
namespace QKeychain {
class Job;
class Job;
}
class QAuthenticator;
namespace OCC
{
namespace OCC {
Q_DECLARE_LOGGING_CATEGORY(lcShibboleth)
@ -43,7 +42,7 @@ class ShibbolethWebView;
*/
class ShibbolethCredentials : public AbstractCredentials
{
Q_OBJECT
Q_OBJECT
public:
ShibbolethCredentials();
@ -51,10 +50,10 @@ public:
/* create credentials for an already connected account */
ShibbolethCredentials(const QNetworkCookie &cookie);
void setAccount(Account* account) Q_DECL_OVERRIDE;
void setAccount(Account *account) Q_DECL_OVERRIDE;
QString authType() const Q_DECL_OVERRIDE;
QString user() const Q_DECL_OVERRIDE;
QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE;
QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE;
bool ready() const Q_DECL_OVERRIDE;
void fetchFromKeychain() Q_DECL_OVERRIDE;
void askFromUser() Q_DECL_OVERRIDE;
@ -70,16 +69,16 @@ public:
static QByteArray shibCookieName();
private Q_SLOTS:
void onShibbolethCookieReceived(const QNetworkCookie&);
void onShibbolethCookieReceived(const QNetworkCookie &);
void slotBrowserRejected();
void slotReadJobDone(QKeychain::Job*);
void slotReplyFinished(QNetworkReply*);
void slotUserFetched(const QString& user);
void slotReadJobDone(QKeychain::Job *);
void slotReplyFinished(QNetworkReply *);
void slotUserFetched(const QString &user);
void slotFetchUser();
void slotFetchUserHelper();
Q_SIGNALS:
void newCookie(const QNetworkCookie& cookie);
void newCookie(const QNetworkCookie &cookie);
private:
void storeShibCookie(const QNetworkCookie &cookie);

View File

@ -47,20 +47,20 @@ namespace OCC {
Q_LOGGING_CATEGORY(lcFolder, "gui.folder", QtInfoMsg)
Folder::Folder(const FolderDefinition& definition,
AccountState* accountState,
QObject* parent)
Folder::Folder(const FolderDefinition &definition,
AccountState *accountState,
QObject *parent)
: QObject(parent)
, _accountState(accountState)
, _definition(definition)
, _csyncUnavail(false)
, _proxyDirty(true)
, _lastSyncDuration(0)
, _consecutiveFailingSyncs(0)
, _consecutiveFollowUpSyncs(0)
, _journal(_definition.absoluteJournalPath())
, _fileLog(new SyncRunFileLog)
, _saveBackwardsCompatible(false)
, _accountState(accountState)
, _definition(definition)
, _csyncUnavail(false)
, _proxyDirty(true)
, _lastSyncDuration(0)
, _consecutiveFailingSyncs(0)
, _consecutiveFollowUpSyncs(0)
, _journal(_definition.absoluteJournalPath())
, _fileLog(new SyncRunFileLog)
, _saveBackwardsCompatible(false)
{
qsrand(QTime::currentTime().msec());
_timeSinceLastSyncStart.start();
@ -87,30 +87,30 @@ Folder::Folder(const FolderDefinition& definition,
connect(_accountState.data(), SIGNAL(isConnectedChanged()), this, SIGNAL(canSyncChanged()));
connect(_engine.data(), SIGNAL(rootEtag(QString)), this, SLOT(etagRetreivedFromSyncEngine(QString)));
connect(_engine.data(), SIGNAL(started()), SLOT(slotSyncStarted()), Qt::QueuedConnection);
connect(_engine.data(), SIGNAL(started()), SLOT(slotSyncStarted()), Qt::QueuedConnection);
connect(_engine.data(), SIGNAL(finished(bool)), SLOT(slotSyncFinished(bool)), Qt::QueuedConnection);
connect(_engine.data(), SIGNAL(csyncError(QString)), SLOT(slotSyncError(QString)), Qt::QueuedConnection);
connect(_engine.data(), SIGNAL(csyncUnavailable()), SLOT(slotCsyncUnavailable()), Qt::QueuedConnection);
//direct connection so the message box is blocking the sync.
connect(_engine.data(), SIGNAL(aboutToRemoveAllFiles(SyncFileItem::Direction,bool*)),
SLOT(slotAboutToRemoveAllFiles(SyncFileItem::Direction,bool*)));
connect(_engine.data(), SIGNAL(aboutToRestoreBackup(bool*)),
SLOT(slotAboutToRestoreBackup(bool*)));
connect(_engine.data(), SIGNAL(folderDiscovered(bool,QString)), this, SLOT(slotFolderDiscovered(bool,QString)));
connect(_engine.data(), SIGNAL(aboutToRemoveAllFiles(SyncFileItem::Direction, bool *)),
SLOT(slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool *)));
connect(_engine.data(), SIGNAL(aboutToRestoreBackup(bool *)),
SLOT(slotAboutToRestoreBackup(bool *)));
connect(_engine.data(), SIGNAL(folderDiscovered(bool, QString)), this, SLOT(slotFolderDiscovered(bool, QString)));
connect(_engine.data(), SIGNAL(transmissionProgress(ProgressInfo)), this, SLOT(slotTransmissionProgress(ProgressInfo)));
connect(_engine.data(), SIGNAL(itemCompleted(const SyncFileItemPtr &)),
this, SLOT(slotItemCompleted(const SyncFileItemPtr &)));
connect(_engine.data(), SIGNAL(newBigFolder(QString,bool)),
this, SLOT(slotNewBigFolderDiscovered(QString,bool)));
this, SLOT(slotItemCompleted(const SyncFileItemPtr &)));
connect(_engine.data(), SIGNAL(newBigFolder(QString, bool)),
this, SLOT(slotNewBigFolderDiscovered(QString, bool)));
connect(_engine.data(), SIGNAL(seenLockedFile(QString)), FolderMan::instance(), SLOT(slotSyncOnceFileUnlocks(QString)));
connect(_engine.data(), SIGNAL(aboutToPropagate(SyncFileItemVector&)),
SLOT(slotLogPropagationStart()));
connect(_engine.data(), SIGNAL(aboutToPropagate(SyncFileItemVector &)),
SLOT(slotLogPropagationStart()));
_scheduleSelfTimer.setSingleShot(true);
_scheduleSelfTimer.setInterval(SyncEngine::minimumFileAgeForUpload);
connect(&_scheduleSelfTimer, SIGNAL(timeout()),
SLOT(slotScheduleThisFolder()));
SLOT(slotScheduleThisFolder()));
}
Folder::~Folder()
@ -127,23 +127,23 @@ void Folder::checkLocalPath()
if (_canonicalLocalPath.isEmpty()) {
qCWarning(lcFolder) << "Broken symlink:" << _definition.localPath;
_canonicalLocalPath = _definition.localPath;
} else if( !_canonicalLocalPath.endsWith('/') ) {
} else if (!_canonicalLocalPath.endsWith('/')) {
_canonicalLocalPath.append('/');
}
if( fi.isDir() && fi.isReadable() ) {
if (fi.isDir() && fi.isReadable()) {
qCDebug(lcFolder) << "Checked local path ok";
} else {
// Check directory again
if( !FileSystem::fileExists(_definition.localPath, fi) ) {
if (!FileSystem::fileExists(_definition.localPath, fi)) {
_syncResult.appendErrorString(tr("Local folder %1 does not exist.").arg(_definition.localPath));
_syncResult.setStatus( SyncResult::SetupError );
} else if( !fi.isDir() ) {
_syncResult.setStatus(SyncResult::SetupError);
} else if (!fi.isDir()) {
_syncResult.appendErrorString(tr("%1 should be a folder but is not.").arg(_definition.localPath));
_syncResult.setStatus( SyncResult::SetupError );
} else if( !fi.isReadable() ) {
_syncResult.setStatus(SyncResult::SetupError);
} else if (!fi.isReadable()) {
_syncResult.appendErrorString(tr("%1 is not readable.").arg(_definition.localPath));
_syncResult.setStatus( SyncResult::SetupError );
_syncResult.setStatus(SyncResult::SetupError);
}
}
}
@ -175,7 +175,7 @@ QString Folder::shortGuiLocalPath() const
{
QString p = _definition.localPath;
QString home = QDir::homePath();
if( ! home.endsWith('/') ) {
if (!home.endsWith('/')) {
home.append('/');
}
if (p.startsWith(home)) {
@ -203,8 +203,8 @@ QString Folder::cleanPath() const
{
QString cleanedPath = QDir::cleanPath(_canonicalLocalPath);
if(cleanedPath.length() == 3 && cleanedPath.endsWith(":/"))
cleanedPath.remove(2,1);
if (cleanedPath.length() == 3 && cleanedPath.endsWith(":/"))
cleanedPath.remove(2, 1);
return cleanedPath;
}
@ -226,7 +226,7 @@ QUrl Folder::remoteUrl() const
bool Folder::syncPaused() const
{
return _definition.paused;
return _definition.paused;
}
bool Folder::canSync() const
@ -234,7 +234,7 @@ bool Folder::canSync() const
return !syncPaused() && accountState()->isConnected();
}
void Folder::setSyncPaused( bool paused )
void Folder::setSyncPaused(bool paused)
{
if (paused == _definition.paused) {
return;
@ -243,7 +243,7 @@ void Folder::setSyncPaused( bool paused )
_definition.paused = paused;
saveToSettings();
if( !paused ) {
if (!paused) {
setSyncState(SyncResult::NotYetStarted);
} else {
setSyncState(SyncResult::Paused);
@ -260,13 +260,13 @@ void Folder::setSyncState(SyncResult::Status state)
SyncResult Folder::syncResult() const
{
return _syncResult;
return _syncResult;
}
void Folder::prepareToSync()
{
_syncResult.reset();
_syncResult.setStatus( SyncResult::NotYetStarted );
_syncResult.setStatus(SyncResult::NotYetStarted);
}
void Folder::slotRunEtagJob()
@ -281,7 +281,7 @@ void Folder::slotRunEtagJob()
}
if (!canSync()) {
qCInfo(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state());
qCInfo(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state());
return;
}
@ -289,14 +289,14 @@ void Folder::slotRunEtagJob()
// sync if it's different.
_requestEtagJob = new RequestEtagJob(account, remotePath(), this);
_requestEtagJob->setTimeout(60*1000);
_requestEtagJob->setTimeout(60 * 1000);
// check if the etag is different when retrieved
QObject::connect(_requestEtagJob, SIGNAL(etagRetreived(QString)), this, SLOT(etagRetreived(QString)));
FolderMan::instance()->slotScheduleETagJob(alias(), _requestEtagJob);
// The _requestEtagJob is auto deleting itself on finish. Our guard pointer _requestEtagJob will then be null.
}
void Folder::etagRetreived(const QString& etag)
void Folder::etagRetreived(const QString &etag)
{
// re-enable sync if it was disabled because network was down
FolderMan::instance()->setSyncEnabled(true);
@ -310,7 +310,7 @@ void Folder::etagRetreived(const QString& etag)
_accountState->tagLastSuccessfullETagRequest();
}
void Folder::etagRetreivedFromSyncEngine(const QString& etag)
void Folder::etagRetreivedFromSyncEngine(const QString &etag)
{
qCInfo(lcFolder) << "Root etag from during sync:" << etag;
accountState()->tagLastSuccessfullETagRequest();
@ -320,42 +320,42 @@ void Folder::etagRetreivedFromSyncEngine(const QString& etag)
void Folder::showSyncResultPopup()
{
if( _syncResult.firstItemNew() ) {
createGuiLog( _syncResult.firstItemNew()->_file, LogStatusNew, _syncResult.numNewItems() );
if (_syncResult.firstItemNew()) {
createGuiLog(_syncResult.firstItemNew()->_file, LogStatusNew, _syncResult.numNewItems());
}
if( _syncResult.firstItemDeleted() ) {
createGuiLog( _syncResult.firstItemDeleted()->_file, LogStatusRemove, _syncResult.numRemovedItems() );
if (_syncResult.firstItemDeleted()) {
createGuiLog(_syncResult.firstItemDeleted()->_file, LogStatusRemove, _syncResult.numRemovedItems());
}
if( _syncResult.firstItemUpdated() ) {
createGuiLog( _syncResult.firstItemUpdated()->_file, LogStatusUpdated, _syncResult.numUpdatedItems() );
if (_syncResult.firstItemUpdated()) {
createGuiLog(_syncResult.firstItemUpdated()->_file, LogStatusUpdated, _syncResult.numUpdatedItems());
}
if( _syncResult.firstItemRenamed() ) {
if (_syncResult.firstItemRenamed()) {
LogStatus status(LogStatusRename);
// if the path changes it's rather a move
QDir renTarget = QFileInfo(_syncResult.firstItemRenamed()->_renameTarget).dir();
QDir renSource = QFileInfo(_syncResult.firstItemRenamed()->_file).dir();
if(renTarget != renSource) {
if (renTarget != renSource) {
status = LogStatusMove;
}
createGuiLog( _syncResult.firstItemRenamed()->_originalFile, status,
_syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget );
createGuiLog(_syncResult.firstItemRenamed()->_originalFile, status,
_syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget);
}
if( _syncResult.firstConflictItem() ) {
createGuiLog( _syncResult.firstConflictItem()->_file, LogStatusConflict, _syncResult.numConflictItems() );
if (_syncResult.firstConflictItem()) {
createGuiLog(_syncResult.firstConflictItem()->_file, LogStatusConflict, _syncResult.numConflictItems());
}
if (int errorCount = _syncResult.numErrorItems()) {
createGuiLog( _syncResult.firstItemError()->_file, LogStatusError, errorCount );
createGuiLog(_syncResult.firstItemError()->_file, LogStatusError, errorCount);
}
qCInfo(lcFolder) << "Folder sync result: " << int(_syncResult.status());
}
void Folder::createGuiLog( const QString& filename, LogStatus status, int count,
const QString& renameTarget )
void Folder::createGuiLog(const QString &filename, LogStatus status, int count,
const QString &renameTarget)
{
if(count > 0) {
if (count > 0) {
Logger *logger = Logger::instance();
QString file = QDir::toNativeSeparators(filename);
@ -363,58 +363,58 @@ void Folder::createGuiLog( const QString& filename, LogStatus status, int count,
switch (status) {
case LogStatusRemove:
if( count > 1 ) {
text = tr("%1 and %n other file(s) have been removed.", "", count-1).arg(file);
if (count > 1) {
text = tr("%1 and %n other file(s) have been removed.", "", count - 1).arg(file);
} else {
text = tr("%1 has been removed.", "%1 names a file.").arg(file);
}
break;
case LogStatusNew:
if( count > 1 ) {
text = tr("%1 and %n other file(s) have been downloaded.", "", count-1).arg(file);
if (count > 1) {
text = tr("%1 and %n other file(s) have been downloaded.", "", count - 1).arg(file);
} else {
text = tr("%1 has been downloaded.", "%1 names a file.").arg(file);
}
break;
case LogStatusUpdated:
if( count > 1 ) {
text = tr("%1 and %n other file(s) have been updated.", "", count-1).arg(file);
if (count > 1) {
text = tr("%1 and %n other file(s) have been updated.", "", count - 1).arg(file);
} else {
text = tr("%1 has been updated.", "%1 names a file.").arg(file);
}
break;
case LogStatusRename:
if( count > 1 ) {
text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count-1).arg(file, renameTarget);
if (count > 1) {
text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count - 1).arg(file, renameTarget);
} else {
text = tr("%1 has been renamed to %2.", "%1 and %2 name files.").arg(file, renameTarget);
}
break;
case LogStatusMove:
if( count > 1 ) {
text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count-1).arg(file, renameTarget);
if (count > 1) {
text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count - 1).arg(file, renameTarget);
} else {
text = tr("%1 has been moved to %2.").arg(file, renameTarget);
}
break;
case LogStatusConflict:
if( count > 1 ) {
text = tr("%1 has and %n other file(s) have sync conflicts.", "", count-1).arg(file);
if (count > 1) {
text = tr("%1 has and %n other file(s) have sync conflicts.", "", count - 1).arg(file);
} else {
text = tr("%1 has a sync conflict. Please check the conflict file!").arg(file);
}
break;
case LogStatusError:
if( count > 1 ) {
text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count-1).arg(file);
if (count > 1) {
text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count - 1).arg(file);
} else {
text = tr("%1 could not be synced due to an error. See the log for details.").arg(file);
}
break;
}
if( !text.isEmpty() ) {
logger->postOptionalGuiLog( tr("Sync Activity"), text );
if (!text.isEmpty()) {
logger->postOptionalGuiLog(tr("Sync Activity"), text);
}
}
}
@ -425,8 +425,8 @@ int Folder::slotDiscardDownloadProgress()
QDir folderpath(_definition.localPath);
QSet<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 QString& path)
void Folder::slotWatchedPathChanged(const QString &path)
{
// The folder watcher fires a lot of bogus notifications during
// a sync operation, both for actual user files and the database
// and log. Therefore we check notifications against operations
// the sync is doing to filter out our own changes.
// The folder watcher fires a lot of bogus notifications during
// a sync operation, both for actual user files and the database
// and log. Therefore we check notifications against operations
// the sync is doing to filter out our own changes.
#ifdef Q_OS_MAC
Q_UNUSED(path)
// On OSX the folder watcher does not report changes done by our
// own process. Therefore nothing needs to be done here!
// On OSX the folder watcher does not report changes done by our
// own process. Therefore nothing needs to be done here!
#else
// Use the path to figure out whether it was our own change
const auto maxNotificationDelay = 15*1000;
const auto maxNotificationDelay = 15 * 1000;
qint64 time = _engine->timeSinceFileTouched(path);
if (time != -1 && time < maxNotificationDelay) {
return;
@ -472,10 +472,9 @@ void Folder::slotWatchedPathChanged(const QString& path)
if (path.startsWith(this->path())) {
auto relativePath = path.mid(this->path().size());
auto record = _journal.getFileRecord(relativePath);
if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize,
Utility::qDateTimeToTime_t(record._modtime))) {
if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize, Utility::qDateTimeToTime_t(record._modtime))) {
qCInfo(lcFolder) << "Ignoring spurious notification for file" << relativePath;
return; // probably a spurious notification
return; // probably a spurious notification
}
}
@ -501,7 +500,7 @@ void Folder::saveToSettings() const
// where two folders for different accounts point at the same
// local folders.
bool oneAccountOnly = true;
foreach (Folder* other, FolderMan::instance()->map()) {
foreach (Folder *other, FolderMan::instance()->map()) {
if (other != this && other->cleanPath() == this->cleanPath()) {
oneAccountOnly = false;
break;
@ -531,12 +530,12 @@ void Folder::removeFromSettings() const
settings->remove(FolderMan::escapeAlias(_definition.alias));
}
bool Folder::isFileExcludedAbsolute(const QString& fullPath) const
bool Folder::isFileExcludedAbsolute(const QString &fullPath) const
{
return _engine->excludedFiles().isExcluded(fullPath, path(), _definition.ignoreHiddenFiles);
}
bool Folder::isFileExcludedRelative(const QString& relativePath) const
bool Folder::isFileExcludedRelative(const QString &relativePath) const
{
return _engine->excludedFiles().isExcluded(path() + relativePath, path(), _definition.ignoreHiddenFiles);
}
@ -545,7 +544,7 @@ void Folder::slotTerminateSync()
{
qCInfo(lcFolder) << "folder " << alias() << " Terminating!";
if( _engine->isSyncRunning() ) {
if (_engine->isSyncRunning()) {
_engine->abort();
setSyncState(SyncResult::SyncAbortRequested);
@ -567,8 +566,8 @@ void Folder::wipe()
_journal.close(); // close the sync journal
QFile file(stateDbFile);
if( file.exists() ) {
if( !file.remove()) {
if (file.exists()) {
if (!file.remove()) {
qCWarning(lcFolder) << "Failed to remove existing csync StateDB " << stateDbFile;
} else {
qCInfo(lcFolder) << "wipe: Removed csync StateDB " << stateDbFile;
@ -578,10 +577,10 @@ void Folder::wipe()
}
// Also remove other db related files
QFile::remove( stateDbFile + ".ctmp" );
QFile::remove( stateDbFile + "-shm" );
QFile::remove( stateDbFile + "-wal" );
QFile::remove( stateDbFile + "-journal" );
QFile::remove(stateDbFile + ".ctmp");
QFile::remove(stateDbFile + "-shm");
QFile::remove(stateDbFile + "-wal");
QFile::remove(stateDbFile + "-journal");
if (canSync())
FolderMan::instance()->socketApi()->slotRegisterPath(alias());
@ -599,7 +598,7 @@ bool Folder::setIgnoredFiles()
_engine->excludedFiles().addExcludeFilePath(systemList);
QString userList = cfg.excludeFile(ConfigFile::UserScope);
if( QFile::exists(userList) ) {
if (QFile::exists(userList)) {
qCInfo(lcFolder) << "Adding user defined ignore list to csync:" << userList;
_engine->excludedFiles().addExcludeFilePath(userList);
}
@ -631,16 +630,15 @@ void Folder::startSync(const QStringList &pathList)
_csyncUnavail = false;
_timeSinceLastSyncStart.restart();
_syncResult.setStatus( SyncResult::SyncPrepare );
_syncResult.setStatus(SyncResult::SyncPrepare);
emit syncStateChange();
qCInfo(lcFolder) << "*** Start syncing " << remoteUrl().toString() << " - client version"
<< qPrintable(Theme::instance()->version());
<< qPrintable(Theme::instance()->version());
_fileLog->start(path());
if (!setIgnoredFiles())
{
if (!setIgnoredFiles()) {
slotSyncError(tr("Could not read system exclude file"));
QMetaObject::invokeMethod(this, "slotSyncFinished", Qt::QueuedConnection, Q_ARG(bool, false));
return;
@ -714,7 +712,7 @@ void Folder::setDirtyNetworkLimits()
int uploadLimit = -75; // 75%
int useUpLimit = cfg.useUploadLimit();
if ( useUpLimit >= 1) {
if (useUpLimit >= 1) {
uploadLimit = cfg.uploadLimit() * 1000;
} else if (useUpLimit == 0) {
uploadLimit = 0;
@ -724,7 +722,7 @@ void Folder::setDirtyNetworkLimits()
}
void Folder::slotSyncError(const QString& err)
void Folder::slotSyncError(const QString &err)
{
_syncResult.appendErrorString(err);
}
@ -744,14 +742,14 @@ void Folder::slotCsyncUnavailable()
void Folder::slotSyncFinished(bool success)
{
qCInfo(lcFolder) << "Client version" << qPrintable(Theme::instance()->version())
<< " Qt" << qVersion()
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
<< " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data()
<< " Qt" << qVersion()
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
<< " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data()
#endif
;
;
bool syncError = !_syncResult.errorStrings().isEmpty();
if( syncError ) {
if (syncError) {
qCWarning(lcFolder) << "SyncEngine finished with ERROR";
} else {
qCInfo(lcFolder) << "SyncEngine finished without problem.";
@ -766,9 +764,9 @@ void Folder::slotSyncFinished(bool success)
} else if (_csyncUnavail) {
_syncResult.setStatus(SyncResult::Error);
qCWarning(lcFolder) << "csync not available.";
} else if( _syncResult.foundFilesNotSynced() ) {
} else if (_syncResult.foundFilesNotSynced()) {
_syncResult.setStatus(SyncResult::Problem);
} else if( _definition.paused ) {
} else if (_definition.paused) {
// Maybe the sync was terminated because the user paused the folder
_syncResult.setStatus(SyncResult::Paused);
} else {
@ -777,12 +775,9 @@ void Folder::slotSyncFinished(bool success)
// Count the number of syncs that have failed in a row.
if (_syncResult.status() == SyncResult::Success
|| _syncResult.status() == SyncResult::Problem)
{
|| _syncResult.status() == SyncResult::Problem) {
_consecutiveFailingSyncs = 0;
}
else
{
} else {
_consecutiveFailingSyncs++;
qCInfo(lcFolder) << "the last" << _consecutiveFailingSyncs << "syncs failed";
}
@ -800,7 +795,7 @@ void Folder::slotSyncFinished(bool success)
// file system change notifications are ignored for that folder. And it takes
// some time under certain conditions to make the file system notifications
// all come in.
QTimer::singleShot(200, this, SLOT(slotEmitFinishedDelayed() ));
QTimer::singleShot(200, this, SLOT(slotEmitFinishedDelayed()));
_lastSyncDuration = _timeSinceLastSyncStart.elapsed();
_timeSinceLastSyncDone.restart();
@ -809,14 +804,13 @@ void Folder::slotSyncFinished(bool success)
if (anotherSyncNeeded == ImmediateFollowUp) {
_consecutiveFollowUpSyncs++;
qCInfo(lcFolder) << "another sync was requested by the finished sync, this has"
<< "happened" << _consecutiveFollowUpSyncs << "times";
<< "happened" << _consecutiveFollowUpSyncs << "times";
} else {
_consecutiveFollowUpSyncs = 0;
}
// Maybe force a follow-up sync to take place, but only a couple of times.
if (anotherSyncNeeded == ImmediateFollowUp && _consecutiveFollowUpSyncs <= 3)
{
if (anotherSyncNeeded == ImmediateFollowUp && _consecutiveFollowUpSyncs <= 3) {
// Sometimes another sync is requested because a local file is still
// changing, so wait at least a small amount of time before syncing
// the folder again.
@ -826,7 +820,7 @@ void Folder::slotSyncFinished(bool success)
void Folder::slotEmitFinishedDelayed()
{
emit syncFinished( _syncResult );
emit syncFinished(_syncResult);
}
@ -851,11 +845,11 @@ void Folder::slotTransmissionProgress(const ProgressInfo &pi)
void Folder::slotItemCompleted(const SyncFileItemPtr &item)
{
// add new directories or remove gone away dirs to the watcher
if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NEW ) {
FolderMan::instance()->addMonitorPath( alias(), path()+item->_file );
if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NEW) {
FolderMan::instance()->addMonitorPath(alias(), path() + item->_file);
}
if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_REMOVE ) {
FolderMan::instance()->removeMonitorPath( alias(), path()+item->_file );
if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
FolderMan::instance()->removeMonitorPath(alias(), path() + item->_file);
}
_syncResult.processCompletedItem(item);
@ -883,16 +877,16 @@ void Folder::slotNewBigFolderDiscovered(const QString &newF, bool isExternal)
// And add the entry to the undecided list and signal the UI
auto undecidedList = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok1);
if( ok1 ) {
if (ok1) {
if (!undecidedList.contains(newFolder)) {
undecidedList.append(newFolder);
journal->setSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, undecidedList);
emit newBigFolderDiscovered(newFolder);
}
QString message = !isExternal ?
(tr("A new folder larger than %1 MB has been added: %2.\n")
.arg(ConfigFile().newBigFolderSizeLimit().second).arg(newF))
: (tr("A folder from an external storage has been added.\n"));
QString message = !isExternal ? (tr("A new folder larger than %1 MB has been added: %2.\n")
.arg(ConfigFile().newBigFolderSizeLimit().second)
.arg(newF))
: (tr("A folder from an external storage has been added.\n"));
message += tr("Please go in the settings to select it if you wish to download it.");
auto logger = Logger::instance();
@ -928,21 +922,20 @@ void Folder::slotAboutToRemoveAllFiles(SyncFileItem::Direction dir, bool *cancel
if (!cfgFile.promptDeleteFiles())
return;
QString msg = dir == SyncFileItem::Down ?
tr("All files in the sync folder '%1' folder were deleted on the server.\n"
"These deletes will be synchronized to your local sync folder, making such files "
"unavailable unless you have a right to restore. \n"
"If you decide to keep the files, they will be re-synced with the server if you have rights to do so.\n"
"If you decide to delete the files, they will be unavailable to you, unless you are the owner.") :
tr("All the files in your local sync folder '%1' were deleted. These deletes will be "
"synchronized with your server, making such files unavailable unless restored.\n"
"Are you sure you want to sync those actions with the server?\n"
"If this was an accident and you decide to keep your files, they will be re-synced from the server.");
QString msg = dir == SyncFileItem::Down ? tr("All files in the sync folder '%1' folder were deleted on the server.\n"
"These deletes will be synchronized to your local sync folder, making such files "
"unavailable unless you have a right to restore. \n"
"If you decide to keep the files, they will be re-synced with the server if you have rights to do so.\n"
"If you decide to delete the files, they will be unavailable to you, unless you are the owner.")
: tr("All the files in your local sync folder '%1' were deleted. These deletes will be "
"synchronized with your server, making such files unavailable unless restored.\n"
"Are you sure you want to sync those actions with the server?\n"
"If this was an accident and you decide to keep your files, they will be re-synced from the server.");
QMessageBox msgBox(QMessageBox::Warning, tr("Remove All Files?"),
msg.arg(shortGuiLocalPath()));
msg.arg(shortGuiLocalPath()));
msgBox.setWindowFlags(msgBox.windowFlags() | Qt::WindowStaysOnTopHint);
msgBox.addButton(tr("Remove all files"), QMessageBox::DestructiveRole);
QPushButton* keepBtn = msgBox.addButton(tr("Keep files"), QMessageBox::AcceptRole);
QPushButton *keepBtn = msgBox.addButton(tr("Keep files"), QMessageBox::AcceptRole);
if (msgBox.exec() == -1) {
*cancel = true;
return;
@ -965,10 +958,10 @@ void Folder::slotAboutToRestoreBackup(bool *restore)
"file in an earlier state. "
"Do you want to keep your local most recent files as conflict files?");
QMessageBox msgBox(QMessageBox::Warning, tr("Backup detected"),
msg.arg(shortGuiLocalPath()));
msg.arg(shortGuiLocalPath()));
msgBox.setWindowFlags(msgBox.windowFlags() | Qt::WindowStaysOnTopHint);
msgBox.addButton(tr("Normal Synchronisation"), QMessageBox::DestructiveRole);
QPushButton* keepBtn = msgBox.addButton(tr("Keep Local Files as Conflict"), QMessageBox::AcceptRole);
QPushButton *keepBtn = msgBox.addButton(tr("Keep Local Files as Conflict"), QMessageBox::AcceptRole);
if (msgBox.exec() == -1) {
*restore = true;
@ -978,7 +971,7 @@ void Folder::slotAboutToRestoreBackup(bool *restore)
}
void FolderDefinition::save(QSettings& settings, const FolderDefinition& folder)
void FolderDefinition::save(QSettings &settings, const FolderDefinition &folder)
{
settings.beginGroup(FolderMan::escapeAlias(folder.alias));
settings.setValue(QLatin1String("localPath"), folder.localPath);
@ -989,8 +982,8 @@ void FolderDefinition::save(QSettings& settings, const FolderDefinition& folder)
settings.endGroup();
}
bool FolderDefinition::load(QSettings& settings, const QString& alias,
FolderDefinition* folder)
bool FolderDefinition::load(QSettings &settings, const QString &alias,
FolderDefinition *folder)
{
settings.beginGroup(alias);
folder->alias = FolderMan::unescapeAlias(alias);
@ -1011,7 +1004,7 @@ bool FolderDefinition::load(QSettings& settings, const QString& alias,
return true;
}
QString FolderDefinition::prepareLocalPath(const QString& path)
QString FolderDefinition::prepareLocalPath(const QString &path)
{
QString p = QDir::fromNativeSeparators(path);
if (!p.endsWith(QLatin1Char('/'))) {
@ -1045,4 +1038,3 @@ QString FolderDefinition::defaultJournalPath(AccountPtr account)
}
} // namespace OCC

View 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 QString& path);
static QString prepareLocalPath(const QString &path);
/// Ensure starting / and no ending /.
static QString prepareTargetPath(const QString& path);
static QString prepareTargetPath(const QString &path);
/// journalPath relative to localPath.
QString absoluteJournalPath() const;
@ -91,17 +92,17 @@ class Folder : public QObject
Q_OBJECT
public:
Folder(const FolderDefinition& definition, AccountState* accountState, QObject* parent = 0L);
Folder(const FolderDefinition &definition, AccountState *accountState, QObject *parent = 0L);
~Folder();
typedef QMap<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.
*/
AccountState* accountState() const { return _accountState.data(); }
AccountState *accountState() const { return _accountState.data(); }
/**
* alias or nickname
@ -140,7 +141,7 @@ public:
/**
* switch sync on or off
*/
void setSyncPaused( bool );
void setSyncPaused(bool);
bool syncPaused() const;
@ -160,56 +161,56 @@ public:
/**
* return the last sync result with error message and status
*/
SyncResult syncResult() const;
SyncResult syncResult() const;
/**
/**
* set the config file name.
*/
void setConfigFile( const QString& );
QString configFile();
void setConfigFile(const QString &);
QString configFile();
/**
/**
* This is called if the sync folder definition is removed. Do cleanups here.
*/
virtual void wipe();
virtual void wipe();
void setSyncState(SyncResult::Status state);
void setSyncState(SyncResult::Status state);
void setDirtyNetworkLimits();
void setDirtyNetworkLimits();
/**
/**
* Ignore syncing of hidden files or not. This is defined in the
* folder definition
*/
bool ignoreHiddenFiles();
void setIgnoreHiddenFiles(bool ignore);
bool ignoreHiddenFiles();
void setIgnoreHiddenFiles(bool ignore);
// Used by the Socket API
SyncJournalDb *journalDb() { return &_journal; }
SyncEngine &syncEngine() { return *_engine; }
// Used by the Socket API
SyncJournalDb *journalDb() { return &_journal; }
SyncEngine &syncEngine() { return *_engine; }
RequestEtagJob *etagJob() { return _requestEtagJob; }
qint64 msecSinceLastSync() const { return _timeSinceLastSyncDone.elapsed(); }
qint64 msecLastSyncDuration() const { return _lastSyncDuration; }
int consecutiveFollowUpSyncs() const { return _consecutiveFollowUpSyncs; }
int consecutiveFailingSyncs() const { return _consecutiveFailingSyncs; }
RequestEtagJob *etagJob() { return _requestEtagJob; }
qint64 msecSinceLastSync() const { return _timeSinceLastSyncDone.elapsed(); }
qint64 msecLastSyncDuration() const { return _lastSyncDuration; }
int consecutiveFollowUpSyncs() const { return _consecutiveFollowUpSyncs; }
int consecutiveFailingSyncs() const { return _consecutiveFailingSyncs; }
/// Saves the folder data in the account's settings.
void saveToSettings() const;
/// Removes the folder from the account's settings.
void removeFromSettings() const;
/// Saves the folder data in the account's settings.
void saveToSettings() const;
/// Removes the folder from the account's settings.
void removeFromSettings() const;
/**
/**
* Returns whether a file inside this folder should be excluded.
*/
bool isFileExcludedAbsolute(const QString& fullPath) const;
bool isFileExcludedAbsolute(const QString &fullPath) const;
/**
/**
* Returns whether a file inside this folder should be excluded.
*/
bool isFileExcludedRelative(const QString& relativePath) const;
bool isFileExcludedRelative(const QString &relativePath) const;
/** Calls schedules this folder on the FolderMan after a short delay.
/** Calls schedules this folder on the FolderMan after a short delay.
*
* This should be used in situations where a sync should be triggered
* because a local file was modified. Syncs don't upload files that were
@ -218,72 +219,72 @@ public:
*
* The delay doesn't reset with subsequent calls.
*/
void scheduleThisFolderSoon();
void scheduleThisFolderSoon();
/**
/**
* Migration: When this flag is true, this folder will save to
* the backwards-compatible 'Folders' section in the config file.
*/
void setSaveBackwardsCompatible(bool save);
void setSaveBackwardsCompatible(bool save);
signals:
void syncStateChange();
void syncStarted();
void syncFinished(const SyncResult &result);
void progressInfo(const ProgressInfo& progress);
void progressInfo(const ProgressInfo &progress);
void newBigFolderDiscovered(const QString &); // A new folder bigger than the threshold was discovered
void syncPausedChanged(Folder*, bool paused);
void syncPausedChanged(Folder *, bool paused);
void canSyncChanged();
/**
* Fires for each change inside this folder that wasn't caused
* by sync activity.
*/
void watchedFileChangedExternally(const QString& path);
void watchedFileChangedExternally(const QString &path);
public slots:
/**
/**
* terminate the current sync run
*/
void slotTerminateSync();
void slotTerminateSync();
// connected to the corresponding signals in the SyncEngine
void slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool*);
void slotAboutToRestoreBackup(bool*);
// connected to the corresponding signals in the SyncEngine
void slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool *);
void slotAboutToRestoreBackup(bool *);
/**
/**
* Starts a sync operation
*
* If the list of changed files is known, it is passed.
*/
void startSync(const QStringList &pathList = QStringList());
void startSync(const QStringList &pathList = QStringList());
void setProxyDirty(bool value);
bool proxyDirty();
void setProxyDirty(bool value);
bool proxyDirty();
int slotDiscardDownloadProgress();
int downloadInfoCount();
int slotWipeErrorBlacklist();
int errorBlackListEntryCount();
int slotDiscardDownloadProgress();
int downloadInfoCount();
int slotWipeErrorBlacklist();
int errorBlackListEntryCount();
/**
/**
* Triggered by the folder watcher when a file/dir in this folder
* changes. Needs to check whether this change should trigger a new
* sync run to be scheduled.
*/
void slotWatchedPathChanged(const QString& path);
void slotWatchedPathChanged(const QString &path);
private slots:
void slotSyncStarted();
void slotSyncError(const QString& );
void slotSyncError(const QString &);
void slotCsyncUnavailable();
void slotSyncFinished(bool);
void slotFolderDiscovered(bool local, QString folderName);
void slotTransmissionProgress(const ProgressInfo& pi);
void slotItemCompleted(const SyncFileItemPtr&);
void slotTransmissionProgress(const ProgressInfo &pi);
void slotItemCompleted(const SyncFileItemPtr &);
void slotRunEtagJob();
void etagRetreived(const QString &);
@ -319,8 +320,8 @@ private:
LogStatusUpdated
};
void createGuiLog(const QString& filename, LogStatus status, int count,
const QString& renameTarget = QString::null );
void createGuiLog(const QString &filename, LogStatus status, int count,
const QString &renameTarget = QString::null);
AccountStatePtr _accountState;
FolderDefinition _definition;
@ -328,25 +329,25 @@ private:
SyncResult _syncResult;
QScopedPointer<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

File diff suppressed because it is too large Load Diff

View File

@ -63,7 +63,7 @@ class FolderMan : public QObject
Q_OBJECT
public:
~FolderMan();
static FolderMan* instance();
static FolderMan *instance();
int setupFolders();
int setupFoldersMigration();
@ -72,51 +72,51 @@ public:
/** Adds a folder for an account, ensures the journal is gone and saves it in the settings.
*/
Folder* addFolder(AccountState* accountState, const FolderDefinition& folderDefinition);
Folder *addFolder(AccountState *accountState, const FolderDefinition &folderDefinition);
/** Removes a folder */
void removeFolder( Folder* );
void removeFolder(Folder *);
/** Returns the folder which the file or directory stored in path is in */
Folder* folderForPath(const QString& path);
Folder *folderForPath(const QString &path);
/**
* returns a list of local files that exist on the local harddisk for an
* incoming relative server path. The method checks with all existing sync
* folders.
*/
QStringList findFileInLocalFolders( const QString& relPath, const AccountPtr acc );
QStringList findFileInLocalFolders(const QString &relPath, const AccountPtr acc);
/** Returns the folder by alias or NULL if no folder with the alias exists. */
Folder *folder( const QString& );
Folder *folder(const QString &);
/**
* Migrate accounts from owncloud < 2.0
* Creates a folder for a specific configuration, identified by alias.
*/
Folder* setupFolderFromOldConfigFile(const QString &, AccountState *account );
Folder *setupFolderFromOldConfigFile(const QString &, AccountState *account);
/**
* Ensures that a given directory does not contain a sync journal file.
*
* @returns false if the journal could not be removed, true otherwise.
*/
static bool ensureJournalGone(const QString& journalDbFile);
static bool ensureJournalGone(const QString &journalDbFile);
/** Creates a new and empty local directory. */
bool startFromScratch( const QString& );
bool startFromScratch(const QString &);
QString statusToString(SyncResult::Status, bool paused ) const;
QString statusToString(SyncResult::Status, bool paused) const;
static SyncResult accountStatus( const QList<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 QUrl& serverUrl = QUrl(), bool forNewDirectory = false) const;
QString checkPathValidityForNewFolder(const QString &path, const QUrl &serverUrl = QUrl(), bool forNewDirectory = false) const;
/**
* Attempts to find a non-existing, acceptable path for creating a new sync folder.
@ -155,12 +155,12 @@ public:
/**
* Access to the current queue of scheduled folders.
*/
QQueue<Folder*> scheduleQueue() const;
QQueue<Folder *> scheduleQueue() const;
/**
* Access to the currently syncing folder.
*/
Folder* currentSyncFolder() const;
Folder *currentSyncFolder() const;
/** Removes all folders */
int unloadAndDeleteAllFolders();
@ -169,13 +169,13 @@ public:
* If enabled is set to false, no new folders will start to sync.
* The current one will finish.
*/
void setSyncEnabled( bool );
void setSyncEnabled(bool);
/** Queues a folder for syncing. */
void scheduleFolder(Folder*);
void scheduleFolder(Folder *);
/** Puts a folder in the very front of the queue. */
void scheduleFolderNext(Folder*);
void scheduleFolderNext(Folder *);
/** Queues all folders for syncing. */
void scheduleAllFolders();
@ -196,7 +196,7 @@ signals:
*
* Attention: The folder may be zero. Do a general update of the state then.
*/
void folderSyncStateChange(Folder*);
void folderSyncStateChange(Folder *);
/**
* Indicates when the schedule queue changes.
@ -227,31 +227,31 @@ public slots:
* Automatically detemines the folder that's responsible for the file.
* See slotWatchedFileUnlocked().
*/
void slotSyncOnceFileUnlocks(const QString& path);
void slotSyncOnceFileUnlocks(const QString &path);
// slot to schedule an ETag job (from Folder only)
void slotScheduleETagJob ( const QString &alias, RequestEtagJob *job);
void slotScheduleETagJob(const QString &alias, RequestEtagJob *job);
private slots:
void slotFolderSyncPaused(Folder *, bool paused);
void slotFolderCanSyncChanged();
void slotFolderSyncStarted();
void slotFolderSyncFinished( const SyncResult& );
void slotFolderSyncFinished(const SyncResult &);
void slotRunOneEtagJob();
void slotEtagJobDestroyed (QObject*);
void slotEtagJobDestroyed(QObject *);
// slot to take the next folder from queue and start syncing.
void slotStartScheduledFolderSync();
void slotEtagPollTimerTimeout();
void slotRemoveFoldersForAccount(AccountState* accountState);
void slotRemoveFoldersForAccount(AccountState *accountState);
// Wraps the Folder::syncStateChange() signal into the
// FolderMan::folderSyncStateChange(Folder*) signal.
void slotForwardFolderSyncStateChange();
void slotServerVersionChanged(Account* account);
void slotServerVersionChanged(Account *account);
/**
* A file whose locks were being monitored has become unlocked.
@ -259,7 +259,7 @@ private slots:
* This schedules the folder for synchronization that contains
* the file with the given path.
*/
void slotWatchedFileUnlocked(const QString& path);
void slotWatchedFileUnlocked(const QString &path);
/**
* Schedules folders whose time to sync has come.
@ -270,38 +270,37 @@ private slots:
void slotScheduleFolderByTime();
private:
/** Adds a new folder, does not add it to the account settings and
* does not set an account on the new folder.
*/
Folder* addFolderInternal(FolderDefinition folderDefinition,
AccountState* accountState);
Folder *addFolderInternal(FolderDefinition folderDefinition,
AccountState *accountState);
/* unloads a folder object, does not delete it */
void unloadFolder( Folder * );
void unloadFolder(Folder *);
/** Will start a sync after a bit of delay. */
void startScheduledSyncSoon();
// finds all folder configuration files
// and create the folders
QString getBackupName( QString fullPathName ) const;
void registerFolderMonitor( Folder *folder );
QString getBackupName(QString fullPathName) const;
void registerFolderMonitor(Folder *folder);
// restarts the application (Linux only)
void restartApplication();
void setupFoldersHelper(QSettings& settings, AccountStatePtr account, bool backwardsCompatible);
void setupFoldersHelper(QSettings &settings, AccountStatePtr account, bool backwardsCompatible);
QSet<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);

View 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;
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
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.
if( warningCount > 0 && syncOngoing) {
if (warningCount > 0 && syncOngoing) {
QRect warnRect;
warnRect.setLeft(iconRect.left());
warnRect.setTop(iconRect.bottom()-17);
warnRect.setTop(iconRect.bottom() - 17);
warnRect.setWidth(16);
warnRect.setHeight(16);
QIcon warnIcon(":/client/resources/warning");
QPixmap pm = warnIcon.pixmap(16,16, syncEnabled ? QIcon::Normal : QIcon::Disabled );
QPixmap pm = warnIcon.pixmap(16, 16, syncEnabled ? QIcon::Normal : QIcon::Disabled);
warnRect = QStyle::visualRect(option.direction, option.rect, warnRect);
painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()),pm );
painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()), pm);
}
auto palette = option.palette;
@ -221,7 +224,8 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
? QPalette::Normal : QPalette::Disabled;
? QPalette::Normal
: QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
@ -235,44 +239,44 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &
painter->drawText(QStyle::visualRect(option.direction, option.rect, aliasRect), textAlign, elidedAlias);
const bool showProgess = !overallString.isEmpty() || !itemString.isEmpty();
if(!showProgess) {
if (!showProgess) {
painter->setFont(subFont);
QString elidedRemotePathText = subFm.elidedText(
tr("Synchronizing with local folder"),
Qt::ElideRight, remotePathRect.width());
tr("Synchronizing with local folder"),
Qt::ElideRight, remotePathRect.width());
painter->drawText(QStyle::visualRect(option.direction, option.rect, remotePathRect),
textAlign, elidedRemotePathText);
textAlign, elidedRemotePathText);
QString elidedPathText = subFm.elidedText(pathText, Qt::ElideMiddle, localPathRect.width());
painter->drawText(QStyle::visualRect(option.direction, option.rect, localPathRect),
textAlign, elidedPathText);
textAlign, elidedPathText);
}
// paint an error overlay if there is an error string
int h = iconRect.bottom();
if( !errorTexts.isEmpty() ) {
if (!errorTexts.isEmpty()) {
h += margin;
QRect errorRect = localPathRect;
errorRect.setLeft( iconRect.left());
errorRect.setTop( h );
errorRect.setLeft(iconRect.left());
errorRect.setTop(h);
errorRect.setHeight(errorTexts.count() * subFm.height() + 2 * margin);
errorRect.setRight( option.rect.right() - margin );
errorRect.setRight(option.rect.right() - margin);
painter->setBrush( QColor(0xbb, 0x4d, 0x4d) );
painter->setPen( QColor(0xaa, 0xaa, 0xaa));
painter->setBrush(QColor(0xbb, 0x4d, 0x4d));
painter->setPen(QColor(0xaa, 0xaa, 0xaa));
painter->drawRoundedRect(QStyle::visualRect(option.direction, option.rect, errorRect),
4, 4);
painter->setPen( Qt::white );
4, 4);
painter->setPen(Qt::white);
painter->setFont(errorFont);
QRect errorTextRect( errorRect.left() + margin,
QRect errorTextRect(errorRect.left() + margin,
errorRect.top() + margin,
errorRect.width() - 2 * margin,
subFm.height() );
subFm.height());
foreach( QString eText, errorTexts ) {
foreach (QString eText, errorTexts) {
painter->drawText(QStyle::visualRect(option.direction, option.rect, errorTextRect), textAlign,
subFm.elidedText( eText, Qt::ElideLeft, errorTextRect.width()));
subFm.elidedText(eText, Qt::ElideLeft, errorTextRect.width()));
errorTextRect.translate(0, errorTextRect.height());
}
@ -290,36 +294,36 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &
// Overall Progress Bar.
QRect pBRect;
pBRect.setTop( remotePathRect.top() );
pBRect.setLeft( nextToIcon );
pBRect.setTop(remotePathRect.top());
pBRect.setLeft(nextToIcon);
pBRect.setHeight(barHeight);
pBRect.setWidth( overallWidth - 2 * margin );
pBRect.setWidth(overallWidth - 2 * margin);
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
QStyleOptionProgressBarV2 pBarOpt;
#else
QStyleOptionProgressBar pBarOpt;
#endif
pBarOpt.state = option.state | QStyle::State_Horizontal;
pBarOpt.minimum = 0;
pBarOpt.maximum = 100;
pBarOpt.state = option.state | QStyle::State_Horizontal;
pBarOpt.minimum = 0;
pBarOpt.maximum = 100;
pBarOpt.progress = overallPercent;
pBarOpt.orientation = Qt::Horizontal;
pBarOpt.rect = QStyle::visualRect(option.direction, option.rect, pBRect);
QApplication::style()->drawControl( QStyle::CE_ProgressBar, &pBarOpt, painter );
QApplication::style()->drawControl(QStyle::CE_ProgressBar, &pBarOpt, painter);
// Overall Progress Text
QRect overallProgressRect;
overallProgressRect.setTop( pBRect.bottom() + margin );
overallProgressRect.setHeight( fileNameTextHeight );
overallProgressRect.setLeft( pBRect.left() );
overallProgressRect.setWidth( pBRect.width() );
overallProgressRect.setTop(pBRect.bottom() + margin);
overallProgressRect.setHeight(fileNameTextHeight);
overallProgressRect.setLeft(pBRect.left());
overallProgressRect.setWidth(pBRect.width());
painter->setFont(progressFont);
painter->drawText(QStyle::visualRect(option.direction, option.rect, overallProgressRect),
Qt::AlignLeft | Qt::AlignVCenter, overallString);
Qt::AlignLeft | Qt::AlignVCenter, overallString);
// painter->drawRect(overallProgressRect);
painter->restore();
@ -338,12 +342,12 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &
btnOpt.rect = optionsButtonVisualRect;
btnOpt.icon = m_moreIcon;
btnOpt.iconSize = btnOpt.rect.size();
QApplication::style()->drawComplexControl( QStyle::CC_ToolButton, &btnOpt, painter );
QApplication::style()->drawComplexControl(QStyle::CC_ToolButton, &btnOpt, painter);
}
}
bool FolderStatusDelegate::editorEvent ( QEvent * event, QAbstractItemModel * model,
const QStyleOptionViewItem & option, const QModelIndex & index )
bool FolderStatusDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
const QStyleOptionViewItem &option, const QModelIndex &index)
{
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
@ -360,13 +364,12 @@ QRect FolderStatusDelegate::optionsButtonRect(QRect within, Qt::LayoutDirection
opt.text = QLatin1String("...");
QSize textSize = fm.size(Qt::TextShowMnemonic, opt.text);
opt.rect.setSize(textSize);
QSize size = QApplication::style()->sizeFromContents(QStyle::CT_ToolButton, &opt, textSize).
expandedTo(QApplication::globalStrut());
QSize size = QApplication::style()->sizeFromContents(QStyle::CT_ToolButton, &opt, textSize).expandedTo(QApplication::globalStrut());
int margin = QApplication::style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
QRect r(QPoint(within.right() - size.width() - margin,
within.top() + within.height()/2 - size.height()/2),
size);
within.top() + within.height() / 2 - size.height() / 2),
size);
return QStyle::visualRect(direction, within, r);
}

View 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

View 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)
{
return QString::compare(lhs._folder->shortGuiRemotePathOrAppName(),
rhs._folder->shortGuiRemotePathOrAppName(),
Qt::CaseInsensitive) < 0;
}
void FolderStatusModel::setAccountState(const AccountState* accountState)
static bool sortByFolderHeader(const FolderStatusModel::SubFolderInfo &lhs, const FolderStatusModel::SubFolderInfo &rhs)
{
return QString::compare(lhs._folder->shortGuiRemotePathOrAppName(),
rhs._folder->shortGuiRemotePathOrAppName(),
Qt::CaseInsensitive)
< 0;
}
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.
if( status == SyncResult::Problem) {
return theme->syncStateIcon( SyncResult::Success);
if (status == SyncResult::Problem) {
return theme->syncStateIcon(SyncResult::Success);
} else {
return theme->syncStateIcon( status );
return theme->syncStateIcon(status);
}
}
}
@ -273,9 +286,9 @@ QVariant FolderStatusModel::data(const QModelIndex &index, int role) const
return QVariant();
}
bool FolderStatusModel::setData(const QModelIndex& index, const QVariant& value, int role)
bool FolderStatusModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(role == Qt::CheckStateRole) {
if (role == Qt::CheckStateRole) {
auto info = infoForIndex(index);
Qt::CheckState checked = static_cast<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 QModelIndex& parent) const
int FolderStatusModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid()) {
if( Theme::instance()->singleSyncFolder() && _folders.count() != 0) {
if (Theme::instance()->singleSyncFolder() && _folders.count() != 0) {
// "Add folder" button not visible in the singleSyncFolder configuration.
return _folders.count();
}
@ -363,9 +375,9 @@ int FolderStatusModel::rowCount(const QModelIndex& parent) const
return info->_subs.count();
}
FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex& index) const
FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex &index) const
{
if (auto sub = static_cast<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 QString& path) const
QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString &path) const
{
if( !f ) {
if (!f) {
return QModelIndex();
}
@ -409,9 +421,9 @@ QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) cons
if (slashPos == -1) {
// first level folder
for (int i = 0; i < _folders.size(); ++i) {
auto& info = _folders.at(i);
auto &info = _folders.at(i);
if (info._folder == f) {
if( path.isEmpty() ) { // the folder object
if (path.isEmpty()) { // the folder object
return index(i, 0);
}
for (int j = 0; j < info._subs.size(); ++j) {
@ -440,7 +452,7 @@ QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) cons
return QModelIndex();
}
for (int i = 0; i < parentInfo->_subs.size(); ++i) {
if (parentInfo->_subs.at(i)._name == path.mid(slashPos + 1)) {
if (parentInfo->_subs.at(i)._name == path.mid(slashPos + 1)) {
return index(i, 0, parent);
}
}
@ -448,51 +460,51 @@ QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) cons
return QModelIndex();
}
QModelIndex FolderStatusModel::index(int row, int column, const QModelIndex& parent) const
QModelIndex FolderStatusModel::index(int row, int column, const QModelIndex &parent) const
{
if (!parent.isValid()) {
return createIndex(row, column/*, nullptr*/);
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);
}
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 QModelIndex& child) const
QModelIndex FolderStatusModel::parent(const QModelIndex &child) const
{
if (!child.isValid()) {
return QModelIndex();
}
switch(classify(child)) {
case RootFolder:
case AddButton:
return QModelIndex();
case SubFolder:
case FetchLabel:
break;
switch (classify(child)) {
case RootFolder:
case AddButton:
return QModelIndex();
case SubFolder:
case FetchLabel:
break;
}
auto pathIdx = static_cast<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 QModelIndex& parent) const
bool FolderStatusModel::hasChildren(const QModelIndex &parent) const
{
if (!parent.isValid())
return true;
@ -523,11 +535,11 @@ bool FolderStatusModel::hasChildren(const QModelIndex& parent) const
}
bool FolderStatusModel::canFetchMore(const QModelIndex& parent) const
bool FolderStatusModel::canFetchMore(const QModelIndex &parent) const
{
if (!_accountState) {
return false;
}
return false;
}
if (_accountState->state() != AccountState::Connected) {
return false;
}
@ -542,7 +554,7 @@ bool FolderStatusModel::canFetchMore(const QModelIndex& parent) const
}
void FolderStatusModel::fetchMore(const QModelIndex& parent)
void FolderStatusModel::fetchMore(const QModelIndex &parent)
{
auto info = infoForIndex(parent);
@ -558,26 +570,28 @@ void FolderStatusModel::fetchMore(const QModelIndex& parent)
path += info->_path;
}
LsColJob *job = new LsColJob(_accountState->account(), path, this);
job->setProperties(QList<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, 0, 0);
parentInfo->_lastErrorString.clear();
parentInfo->_hasError = false;
parentInfo->_fetchingLabel = false;
@ -625,7 +639,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list)
}
auto selectiveSyncUndecidedList = parentInfo->_folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok2);
if( !(ok1 && ok2) ) {
if (!(ok1 && ok2)) {
qCWarning(lcFolderStatus) << "Could not retrieve selective sync info from journal";
return;
}
@ -647,7 +661,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list)
QVector<SubFolderInfo> newSubs;
newSubs.reserve(sortedSubfolders.size());
foreach (const QString& path, sortedSubfolders) {
foreach (const QString &path, sortedSubfolders) {
auto relativePath = path.mid(pathToRemove.size());
if (parentInfo->_folder->isFileExcludedRelative(relativePath)) {
continue;
@ -670,7 +684,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list)
} else if (parentInfo->_checked == Qt::Checked) {
newInfo._checked = Qt::Checked;
} else {
foreach(const QString &str , selectiveSyncBlackList) {
foreach (const QString &str, selectiveSyncBlackList) {
if (str == relativePath || str == QLatin1String("/")) {
newInfo._checked = Qt::Unchecked;
break;
@ -690,7 +704,7 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list)
// Remove all the items from the selectiveSyncUndecidedSet that starts with this path
QString relativePathNext = relativePath;
relativePathNext[relativePathNext.length()-1].unicode()++;
relativePathNext[relativePathNext.length() - 1].unicode()++;
auto it2 = selectiveSyncUndecidedSet.lower_bound(relativePathNext);
selectiveSyncUndecidedSet.erase(it, it2);
}
@ -706,23 +720,23 @@ void FolderStatusModel::slotUpdateDirectories(const QStringList &list)
suggestExpand(idx.child(*it, 0));
}
/* We need lambda function for the following code.
/* We need lambda function for the following code.
* It's just a small feature that will be missing if the comiler is too old */
#if !(defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && !defined(Q_CC_CLANG)) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 405)
/* Try to remove the the undecided lists the items that are not on the server. */
auto it = std::remove_if(selectiveSyncUndecidedList.begin(), selectiveSyncUndecidedList.end(),
[&](const QString &s) { return selectiveSyncUndecidedSet.count(s); } );
[&](const QString &s) { return selectiveSyncUndecidedSet.count(s); });
if (it != selectiveSyncUndecidedList.end()) {
selectiveSyncUndecidedList.erase(it, selectiveSyncUndecidedList.end());
parentInfo->_folder->journalDb()->setSelectiveSyncList(
SyncJournalDb::SelectiveSyncUndecidedList, selectiveSyncUndecidedList);
SyncJournalDb::SelectiveSyncUndecidedList, selectiveSyncUndecidedList);
emit dirtyChanged();
}
#endif
}
void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply* r)
void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply *r)
{
auto job = qobject_cast<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();
if (!root)
return QStringList();
switch(root->_checked) {
case Qt::Unchecked:
return QStringList(root->_path);
case Qt::Checked:
return QStringList();
case Qt::PartiallyChecked:
break;
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;
}
auto& pi = _folders[folderIndex]._progress;
auto &pi = _folders[folderIndex]._progress;
SyncResult::Status state = f->syncResult().status();
if (!f->canSync()) {
// Reset progress info.
pi = SubFolderInfo::Progress();
} else if (state == SyncResult::NotYetStarted) {
FolderMan* folderMan = FolderMan::instance();
FolderMan *folderMan = FolderMan::instance();
int pos = folderMan->scheduleQueue().indexOf(f);
if (folderMan->currentSyncFolder()
&& folderMan->currentSyncFolder() != f) {
&& folderMan->currentSyncFolder() != f) {
pos += 1;
}
QString message;
@ -1050,7 +1079,7 @@ void FolderStatusModel::slotFolderSyncStateChange(Folder *f)
if (state == SyncResult::Success && f->syncResult().folderStructureWasChanged()) {
// There is a new or a removed folder. reset all data
auto & info = _folders[folderIndex];
auto &info = _folders[folderIndex];
info.resetSubs(this, index(folderIndex));
}
}
@ -1058,7 +1087,7 @@ void FolderStatusModel::slotFolderSyncStateChange(Folder *f)
void FolderStatusModel::slotFolderScheduleQueueChanged()
{
// Update messages on waiting folders.
foreach (Folder* f, FolderMan::instance()->map()) {
foreach (Folder *f, FolderMan::instance()->map()) {
slotFolderSyncStateChange(f);
}
}
@ -1079,7 +1108,7 @@ void FolderStatusModel::slotSyncAllPendingBigFolders()
bool ok;
auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok);
if( !ok ) {
if (!ok) {
qCWarning(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
@ -1091,18 +1120,18 @@ void FolderStatusModel::slotSyncAllPendingBigFolders()
// Remove all undecided folders from the blacklist
auto blackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
if( !ok ) {
if (!ok) {
qCWarning(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
foreach (const auto& undecidedFolder, undecidedList) {
foreach (const auto &undecidedFolder, undecidedList) {
blackList.removeAll(undecidedFolder);
}
folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, blackList);
// Add all undecided folders to the white list
auto whiteList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok);
if( !ok ) {
if (!ok) {
qCWarning(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
@ -1151,7 +1180,9 @@ void FolderStatusModel::slotNewBigFolder()
break;
}
}
if (folderIndex < 0) { return; }
if (folderIndex < 0) {
return;
}
_folders[folderIndex].resetSubs(this, index(folderIndex));
@ -1164,10 +1195,9 @@ void FolderStatusModel::slotShowFetchProgress()
QMutableMapIterator<QPersistentModelIndex, QElapsedTimer> it(_fetchingItems);
while (it.hasNext()) {
it.next();
if (it.value().elapsed() > 800)
{
if (it.value().elapsed() > 800) {
auto idx = it.key();
auto* info = infoForIndex(idx);
auto *info = infoForIndex(idx);
if (info && info->_fetching) {
bool add = !info->hasLabel();
if (add) {
@ -1188,12 +1218,12 @@ bool FolderStatusModel::SubFolderInfo::hasLabel() const
return _hasError || _fetchingLabel;
}
void FolderStatusModel::SubFolderInfo::resetSubs(FolderStatusModel* model, QModelIndex index)
void FolderStatusModel::SubFolderInfo::resetSubs(FolderStatusModel *model, QModelIndex index)
{
_fetched = false;
_fetching = false;
if (hasLabel()) {
model->beginRemoveRows(index, 0 ,0);
model->beginRemoveRows(index, 0, 0);
_fetchingLabel = false;
_hasError = false;
model->endRemoveRows();

View File

@ -37,25 +37,35 @@ class FolderStatusModel : public QAbstractItemModel
{
Q_OBJECT
public:
FolderStatusModel(QObject * parent = 0);
FolderStatusModel(QObject *parent = 0);
~FolderStatusModel();
void setAccountState(const AccountState* accountState);
void setAccountState(const AccountState *accountState);
Qt::ItemFlags flags( const QModelIndex& ) const Q_DECL_OVERRIDE;
Qt::ItemFlags flags(const QModelIndex &) const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) Q_DECL_OVERRIDE;
int columnCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
int rowCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
QModelIndex parent(const QModelIndex& child) const Q_DECL_OVERRIDE;
bool canFetchMore(const QModelIndex& parent) const Q_DECL_OVERRIDE;
void fetchMore(const QModelIndex& parent) Q_DECL_OVERRIDE;
bool hasChildren(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
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 {
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);
void resetSubs(FolderStatusModel *model, QModelIndex index);
struct Progress {
Progress() : _warningCount(0), _overallPercent(0) {}
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(Folder* f);
void slotFolderSyncStateChange(Folder *f);
void slotFolderScheduleQueueChanged();
void slotNewBigFolder();
@ -131,10 +151,10 @@ private slots:
void slotShowFetchProgress();
private:
QStringList createBlackList(OCC::FolderStatusModel::SubFolderInfo* root,
const QStringList& oldBlackList) const;
const AccountState* _accountState;
bool _dirty; // If the selective sync checkboxes were changed
QStringList createBlackList(OCC::FolderStatusModel::SubFolderInfo *root,
const QStringList &oldBlackList) const;
const AccountState *_accountState;
bool _dirty; // If the selective sync checkboxes were changed
/**
* Keeps track of items that are fetching data from the server.
@ -146,7 +166,9 @@ private:
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
//the roles argument was added in Qt5
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>())
{ emit QAbstractItemModel::dataChanged(topLeft,bottomRight); }
{
emit QAbstractItemModel::dataChanged(topLeft, bottomRight);
}
#endif
signals:

View File

@ -39,9 +39,9 @@ namespace OCC {
Q_LOGGING_CATEGORY(lcFolderWatcher, "gui.folderwatcher", QtInfoMsg)
FolderWatcher::FolderWatcher(const QString &root, Folder* folder)
: QObject(folder),
_folder(folder)
FolderWatcher::FolderWatcher(const QString &root, Folder *folder)
: QObject(folder)
, _folder(folder)
{
_d.reset(new FolderWatcherPrivate(this, root));
@ -49,12 +49,15 @@ FolderWatcher::FolderWatcher(const QString &root, Folder* folder)
}
FolderWatcher::~FolderWatcher()
{ }
bool FolderWatcher::pathIsIgnored( const QString& path )
{
if( path.isEmpty() ) return true;
if( !_folder ) return false;
}
bool FolderWatcher::pathIsIgnored(const QString &path)
{
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

View File

@ -58,7 +58,7 @@ public:
/**
* @param root Path of the root of the folder
*/
FolderWatcher(const QString &root, Folder* folder = 0L);
FolderWatcher(const QString &root, Folder *folder = 0L);
virtual ~FolderWatcher();
/**
@ -66,11 +66,11 @@ public:
* Those need to be notified when a directory is added or removed while the watcher is disabled.
* This is a no-op for backends that are recursive
*/
void addPath(const QString&);
void removePath(const QString&);
void addPath(const QString &);
void removePath(const QString &);
/* Check if the path is ignored. */
bool pathIsIgnored( const QString& path );
bool pathIsIgnored(const QString &path);
signals:
/** Emitted when one of the watched directories or one
@ -78,12 +78,12 @@ signals:
void pathChanged(const QString &path);
/** Emitted if an error occurs */
void error(const QString& error);
void error(const QString &error);
protected slots:
// called from the implementations to indicate a change in path
void changeDetected( const QString& path);
void changeDetected( const QStringList& paths);
void changeDetected(const QString &path);
void changeDetected(const QStringList &paths);
protected:
QHash<QString, int> _pendingPathes;
@ -92,11 +92,10 @@ private:
QScopedPointer<FolderWatcherPrivate> _d;
QTime _timer;
QSet<QString> _lastPaths;
Folder* _folder;
Folder *_folder;
friend class FolderWatcherPrivate;
};
}
#endif

View File

@ -26,33 +26,31 @@
namespace OCC {
FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path)
: QObject(),
_parent(p),
_folder(path)
FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path)
: QObject()
, _parent(p)
, _folder(path)
{
_fd = inotify_init();
if (_fd != -1) {
_socket.reset( new QSocketNotifier(_fd, QSocketNotifier::Read) );
_socket.reset(new QSocketNotifier(_fd, QSocketNotifier::Read));
connect(_socket.data(), SIGNAL(activated(int)), SLOT(slotReceivedNotification(int)));
} else {
qCWarning(lcFolderWatcher) << "notify_init() failed: " << strerror(errno);
}
QMetaObject::invokeMethod(this, "slotAddFolderRecursive", Q_ARG(QString, path));
}
FolderWatcherPrivate::~FolderWatcherPrivate()
{
}
// attention: result list passed by reference!
bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullList )
bool FolderWatcherPrivate::findFoldersBelow(const QDir &dir, QStringList &fullList)
{
bool ok = true;
if( !(dir.exists() && dir.isReadable()) ) {
if (!(dir.exists() && dir.isReadable())) {
qCDebug(lcFolderWatcher) << "Non existing path coming in: " << dir.absolutePath();
ok = false;
} else {
@ -63,8 +61,8 @@ bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullL
QStringList::const_iterator constIterator;
for (constIterator = pathes.constBegin(); constIterator != pathes.constEnd();
++constIterator) {
const QString fullPath(dir.path()+QLatin1String("/")+(*constIterator));
++constIterator) {
const QString fullPath(dir.path() + QLatin1String("/") + (*constIterator));
fullList.append(fullPath);
ok = findFoldersBelow(QDir(fullPath), fullList);
}
@ -73,16 +71,14 @@ bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullL
return ok;
}
void FolderWatcherPrivate::inotifyRegisterPath(const QString& path)
void FolderWatcherPrivate::inotifyRegisterPath(const QString &path)
{
if( !path.isEmpty()) {
if (!path.isEmpty()) {
int wd = inotify_add_watch(_fd, path.toUtf8().constData(),
IN_CLOSE_WRITE | IN_ATTRIB | IN_MOVE |
IN_CREATE |IN_DELETE | IN_DELETE_SELF |
IN_MOVE_SELF |IN_UNMOUNT |IN_ONLYDIR);
if( wd > -1 ) {
IN_CLOSE_WRITE | IN_ATTRIB | IN_MOVE | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT | IN_ONLYDIR);
if (wd > -1) {
_watches.insert(wd, path);
}
}
}
}
@ -97,16 +93,16 @@ void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path)
const QStringList watchedFolders = _watches.values();
QStringList allSubfolders;
if( !findFoldersBelow(QDir(path), allSubfolders)) {
if (!findFoldersBelow(QDir(path), allSubfolders)) {
qCWarning(lcFolderWatcher) << "Could not traverse all sub folders";
}
QStringListIterator subfoldersIt(allSubfolders);
while (subfoldersIt.hasNext()) {
QString subfolder = subfoldersIt.next();
QDir folder (subfolder);
QDir folder(subfolder);
if (folder.exists() && !watchedFolders.contains(folder.absolutePath())) {
subdirs++;
if( _parent->pathIsIgnored(subfolder) ) {
if (_parent->pathIsIgnored(subfolder)) {
qCDebug(lcFolderWatcher) << "* Not adding" << folder.path();
continue;
}
@ -116,7 +112,7 @@ void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path)
}
}
if (subdirs >0) {
if (subdirs > 0) {
qCDebug(lcFolderWatcher) << " `-> and" << subdirs << "subdirectories";
}
}
@ -124,15 +120,15 @@ void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path)
void FolderWatcherPrivate::slotReceivedNotification(int fd)
{
int len;
struct inotify_event* event;
struct inotify_event *event;
int i;
int error;
QVarLengthArray<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 QString& path)
void FolderWatcherPrivate::addPath(const QString &path)
{
slotAddFolderRecursive(path);
}
void FolderWatcherPrivate::removePath(const QString& path)
void FolderWatcherPrivate::removePath(const QString &path)
{
int wid = -1;
// Remove the inotify watch.
QHash<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);
}

View 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 QString& path);
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

View File

@ -22,12 +22,11 @@
#include <QStringList>
namespace OCC {
FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path)
: _parent(p),
_folder(path)
FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path)
: _parent(p)
, _folder(path)
{
this->startWatching();
}
@ -40,23 +39,22 @@ FolderWatcherPrivate::~FolderWatcherPrivate()
}
static void callback(
ConstFSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPathsVoid,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
ConstFSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPathsVoid,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
Q_UNUSED(streamRef)
Q_UNUSED(eventFlags)
Q_UNUSED(eventIds)
const FSEventStreamEventFlags c_interestingFlags
= kFSEventStreamEventFlagItemCreated // for new folder/file
| kFSEventStreamEventFlagItemRemoved // for rm
| kFSEventStreamEventFlagItemInodeMetaMod // for mtime change
| kFSEventStreamEventFlagItemRenamed // also coming for moves to trash in finder
| kFSEventStreamEventFlagItemModified; // for content change
const FSEventStreamEventFlags c_interestingFlags = kFSEventStreamEventFlagItemCreated // for new folder/file
| kFSEventStreamEventFlagItemRemoved // for rm
| kFSEventStreamEventFlagItemInodeMetaMod // for mtime change
| kFSEventStreamEventFlagItemRenamed // also coming for moves to trash in finder
| kFSEventStreamEventFlagItemModified; // for content change
//We ignore other flags, e.g. for owner change, xattr change, Finder label change etc
qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::callback by OS X";
@ -80,39 +78,37 @@ static void callback(
paths.append(fn);
}
reinterpret_cast<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

View 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

View File

@ -26,23 +26,21 @@
namespace OCC {
void WatcherThread::watchChanges(size_t fileNotifyBufferSize,
bool* increaseBufferSize)
bool *increaseBufferSize)
{
*increaseBufferSize = false;
QString longPath = FileSystem::longWinPath(_path);
_directory = CreateFileW(
(wchar_t*) longPath.utf16(),
(wchar_t *)longPath.utf16(),
FILE_LIST_DIRECTORY,
FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL
);
NULL);
if (_directory == INVALID_HANDLE_VALUE)
{
if (_directory == INVALID_HANDLE_VALUE) {
DWORD errorCode = GetLastError();
qCWarning(lcFolderWatcher) << "Failed to create handle for" << _path << ", error:" << errorCode;
_directory = 0;
@ -53,7 +51,7 @@ void WatcherThread::watchChanges(size_t fileNotifyBufferSize,
overlapped.hEvent = _resultEvent;
// QVarLengthArray ensures the stack-buffer is aligned like double and qint64.
QVarLengthArray<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 QString& path)
FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path)
: _parent(p)
{
_thread = new WatcherThread(path);
connect(_thread, SIGNAL(changed(const QString&)),
_parent,SLOT(changeDetected(const QString&)));
connect(_thread, SIGNAL(changed(const QString &)),
_parent, SLOT(changeDetected(const QString &)));
_thread->start();
}

View 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 QString& path);
FolderWatcherPrivate(FolderWatcher *p, const QString &path);
~FolderWatcherPrivate();
void addPath(const QString &) {}
@ -77,7 +80,6 @@ private:
FolderWatcher *_parent;
WatcherThread *_thread;
};
}
#endif // MIRALL_FOLDERWATCHER_WIN_H

View 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 AccountPtr& account)
: FormatWarningsWizardPage(),
_account(account)
FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr &account)
: FormatWarningsWizardPage()
, _account(account)
{
_ui.setupUi(this);
registerField(QLatin1String("sourceFolder*"), _ui.localFolderLineEdit);
@ -67,7 +66,7 @@ FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr& account)
QString defaultPath = QDir::homePath() + QLatin1Char('/') + Theme::instance()->appName();
defaultPath = FolderMan::instance()->findGoodPathForNewSyncFolder(defaultPath, account->url());
_ui.localFolderLineEdit->setText( QDir::toNativeSeparators( defaultPath ) );
_ui.localFolderLineEdit->setText(QDir::toNativeSeparators(defaultPath));
_ui.localFolderLineEdit->setToolTip(tr("Enter the path to the local folder."));
_ui.warnLabel->setTextFormat(Qt::RichText);
@ -76,45 +75,43 @@ FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr& account)
FolderWizardLocalPath::~FolderWizardLocalPath()
{
}
void FolderWizardLocalPath::initializePage()
{
_ui.warnLabel->hide();
_ui.warnLabel->hide();
}
void FolderWizardLocalPath::cleanupPage()
{
_ui.warnLabel->hide();
_ui.warnLabel->hide();
}
bool FolderWizardLocalPath::isComplete() const
{
QUrl serverUrl = _account->url();
serverUrl.setUserName( _account->credentials()->user() );
serverUrl.setUserName(_account->credentials()->user());
QString errorStr = FolderMan::instance()->checkPathValidityForNewFolder(
QDir::fromNativeSeparators(_ui.localFolderLineEdit->text()), serverUrl);
bool isOk = errorStr.isEmpty();
QStringList warnStrings;
if (!isOk) {
warnStrings << errorStr;
}
_ui.warnLabel->setWordWrap(true);
if( isOk ) {
_ui.warnLabel->hide();
_ui.warnLabel->setText( QString::null );
} else {
_ui.warnLabel->show();
QString warnings = formatWarnings(warnStrings);
_ui.warnLabel->setText( warnings );
}
return isOk;
_ui.warnLabel->setWordWrap(true);
if (isOk) {
_ui.warnLabel->hide();
_ui.warnLabel->setText(QString::null);
} else {
_ui.warnLabel->show();
QString warnings = formatWarnings(warnStrings);
_ui.warnLabel->setText(warnings);
}
return isOk;
}
void FolderWizardLocalPath::slotChooseLocalFolder()
@ -125,13 +122,14 @@ void FolderWizardLocalPath::slotChooseLocalFolder()
// open the first entry of the home dir. Otherwise the dir picker comes
// up with the closed home dir icon, stupid Qt default...
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks,
QDir::DirsFirst|QDir::Name);
QDir::DirsFirst | QDir::Name);
if(dirs.count() > 0) sf += "/"+dirs.at(0); // Take the first dir in home dir.
if (dirs.count() > 0)
sf += "/" + dirs.at(0); // Take the first dir in home dir.
QString dir = QFileDialog::getExistingDirectory(this,
tr("Select the source folder"),
sf);
tr("Select the source folder"),
sf);
if (!dir.isEmpty()) {
// set the last directory component name as alias
_ui.localFolderLineEdit->setText(QDir::toNativeSeparators(dir));
@ -140,10 +138,10 @@ void FolderWizardLocalPath::slotChooseLocalFolder()
}
// =================================================================================
FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr& account)
FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr &account)
: FormatWarningsWizardPage()
,_warnWasVisible(false)
,_account(account)
, _warnWasVisible(false)
, _account(account)
{
_ui.setupUi(this);
@ -154,8 +152,8 @@ FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr& account)
connect(_ui.addFolderButton, SIGNAL(clicked()), SLOT(slotAddRemoteFolder()));
connect(_ui.refreshButton, SIGNAL(clicked()), SLOT(slotRefreshFolders()));
connect(_ui.folderTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(slotItemExpanded(QTreeWidgetItem*)));
connect(_ui.folderTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(slotCurrentItemChanged(QTreeWidgetItem*)));
connect(_ui.folderTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem *)), SLOT(slotItemExpanded(QTreeWidgetItem *)));
connect(_ui.folderTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), SLOT(slotCurrentItemChanged(QTreeWidgetItem *)));
connect(_ui.folderEntry, SIGNAL(textEdited(QString)), SLOT(slotFolderEntryEdited(QString)));
_lscolTimer.setInterval(500);
@ -163,7 +161,7 @@ FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr& account)
connect(&_lscolTimer, SIGNAL(timeout()), SLOT(slotLsColFolderEntry()));
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
_ui.folderTreeWidget->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
_ui.folderTreeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
// Make sure that there will be a scrollbar when the contents is too wide
_ui.folderTreeWidget->header()->setStretchLastSection(false);
#endif
@ -182,14 +180,15 @@ void FolderWizardRemotePath::slotAddRemoteFolder()
dlg->setWindowTitle(tr("Create Remote Folder"));
dlg->setLabelText(tr("Enter the name of the new folder to be created below '%1':")
.arg(parent));
.arg(parent));
dlg->open(this, SLOT(slotCreateRemoteFolder(QString)));
dlg->setAttribute(Qt::WA_DeleteOnClose);
}
void FolderWizardRemotePath::slotCreateRemoteFolder(const QString &folder)
{
if( folder.isEmpty() ) return;
if (folder.isEmpty())
return;
QTreeWidgetItem *current = _ui.folderTreeWidget->currentItem();
QString fullPath;
@ -201,8 +200,8 @@ void FolderWizardRemotePath::slotCreateRemoteFolder(const QString &folder)
MkColJob *job = new MkColJob(_account, fullPath, this);
/* check the owncloud configuration file and query the ownCloud */
connect(job, SIGNAL(finished(QNetworkReply::NetworkError)),
SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError)));
connect(job, SIGNAL(networkError(QNetworkReply*)), SLOT(slotHandleMkdirNetworkError(QNetworkReply*)));
SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError)));
connect(job, SIGNAL(networkError(QNetworkReply *)), SLOT(slotHandleMkdirNetworkError(QNetworkReply *)));
job->start();
}
@ -220,22 +219,22 @@ void FolderWizardRemotePath::slotCreateRemoteFolderFinished(QNetworkReply::Netwo
void FolderWizardRemotePath::slotHandleMkdirNetworkError(QNetworkReply *reply)
{
qCWarning(lcWizard) << "webdav mkdir request failed:" << reply->error();
if( !_account->credentials()->stillValid(reply) ) {
if (!_account->credentials()->stillValid(reply)) {
showWarn(tr("Authentication failed accessing %1").arg(Theme::instance()->appNameGUI()));
} else {
showWarn(tr("Failed to create the folder on %1. Please check manually.")
.arg(Theme::instance()->appNameGUI()));
.arg(Theme::instance()->appNameGUI()));
}
}
void FolderWizardRemotePath::slotHandleLsColNetworkError(QNetworkReply */*reply*/)
void FolderWizardRemotePath::slotHandleLsColNetworkError(QNetworkReply * /*reply*/)
{
auto job = qobject_cast<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 QString& path, pathTrail) {
foreach (const QString &path, pathTrail) {
if (!it) {
return false;
}
@ -320,7 +319,8 @@ void FolderWizardRemotePath::slotUpdateDirectories(const QStringList &list)
foreach (QString path, sortedList) {
path.remove(webdavFolder);
QStringList paths = path.split('/');
if (paths.last().isEmpty()) paths.removeLast();
if (paths.last().isEmpty())
paths.removeLast();
recursiveInsert(root, paths, path);
}
root->setExpanded(true);
@ -352,7 +352,7 @@ void FolderWizardRemotePath::slotCurrentItemChanged(QTreeWidgetItem *item)
emit completeChanged();
}
void FolderWizardRemotePath::slotFolderEntryEdited(const QString& text)
void FolderWizardRemotePath::slotFolderEntryEdited(const QString &text)
{
if (selectByPath(text)) {
_lscolTimer.stop();
@ -373,19 +373,19 @@ void FolderWizardRemotePath::slotLsColFolderEntry()
// No error handling, no updating, we do this manually
// because of extra logic in the typed-path case.
disconnect(job, 0, this, 0);
connect(job, SIGNAL(finishedWithError(QNetworkReply*)),
SLOT(slotTypedPathError(QNetworkReply*)));
connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
SLOT(slotTypedPathError(QNetworkReply *)));
connect(job, SIGNAL(directoryListingSubfolders(QStringList)),
SLOT(slotTypedPathFound(QStringList)));
SLOT(slotTypedPathFound(QStringList)));
}
void FolderWizardRemotePath::slotTypedPathFound(const QStringList& subpaths)
void FolderWizardRemotePath::slotTypedPathFound(const QStringList &subpaths)
{
slotUpdateDirectories(subpaths);
selectByPath(_ui.folderEntry->text());
}
void FolderWizardRemotePath::slotTypedPathError(QNetworkReply* reply)
void FolderWizardRemotePath::slotTypedPathError(QNetworkReply *reply)
{
// Ignore 404s, otherwise users will get annoyed by error popups
// when not typing fast enough. It's still clear that a given path
@ -400,14 +400,14 @@ void FolderWizardRemotePath::slotTypedPathError(QNetworkReply* reply)
slotHandleLsColNetworkError(reply);
}
LsColJob* FolderWizardRemotePath::runLsColJob(const QString& path)
LsColJob *FolderWizardRemotePath::runLsColJob(const QString &path)
{
LsColJob *job = new LsColJob(_account, path, this);
job->setProperties(QList<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 AccountPtr& account)
FolderWizardSelectiveSync::FolderWizardSelectiveSync(const AccountPtr &account)
{
QVBoxLayout *layout = new QVBoxLayout(this);
_selectiveSync = new SelectiveSyncWidget(account, this);
@ -496,11 +495,11 @@ FolderWizardSelectiveSync::~FolderWizardSelectiveSync()
void FolderWizardSelectiveSync::initializePage()
{
QString targetPath = wizard()->property("targetPath").toString();
QString targetPath = wizard()->property("targetPath").toString();
if (targetPath.startsWith('/')) {
targetPath = targetPath.mid(1);
}
QString alias = QFileInfo(targetPath).fileName();
QString alias = QFileInfo(targetPath).fileName();
if (alias.isEmpty())
alias = Theme::instance()->appName();
QStringList initialBlacklist;
@ -519,8 +518,8 @@ bool FolderWizardSelectiveSync::validatePage()
void FolderWizardSelectiveSync::cleanupPage()
{
QString targetPath = wizard()->property("targetPath").toString();
QString alias = QFileInfo(targetPath).fileName();
QString targetPath = wizard()->property("targetPath").toString();
QString alias = QFileInfo(targetPath).fileName();
if (alias.isEmpty())
alias = Theme::instance()->appName();
_selectiveSync->setFolderInfo(targetPath, alias);
@ -528,8 +527,6 @@ void FolderWizardSelectiveSync::cleanupPage()
}
// ====================================================================================
@ -538,20 +535,20 @@ void FolderWizardSelectiveSync::cleanupPage()
*/
FolderWizard::FolderWizard(AccountPtr account, QWidget *parent)
: QWizard(parent),
_folderWizardSourcePage(new FolderWizardLocalPath(account)),
_folderWizardTargetPage(0),
_folderWizardSelectiveSyncPage(new FolderWizardSelectiveSync(account))
: QWizard(parent)
, _folderWizardSourcePage(new FolderWizardLocalPath(account))
, _folderWizardTargetPage(0)
, _folderWizardSelectiveSyncPage(new FolderWizardSelectiveSync(account))
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setPage(Page_Source, _folderWizardSourcePage );
setPage(Page_Source, _folderWizardSourcePage);
if (!Theme::instance()->singleSyncFolder()) {
_folderWizardTargetPage = new FolderWizardRemotePath(account);
setPage(Page_Target, _folderWizardTargetPage );
setPage(Page_Target, _folderWizardTargetPage);
}
setPage(Page_SelectiveSync, _folderWizardSelectiveSyncPage);
setWindowTitle( tr("Add Folder Sync Connection") );
setWindowTitle(tr("Add Folder Sync Connection"));
setOptions(QWizard::CancelButtonOnLeft);
setButtonText(QWizard::FinishButton, tr("Add Sync Connection"));
}
@ -562,4 +559,3 @@ FolderWizard::~FolderWizard()
} // end namespace

View 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 AccountPtr& account);
explicit FolderWizardLocalPath(const AccountPtr &account);
~FolderWizardLocalPath();
virtual bool isComplete() const Q_DECL_OVERRIDE;
void initializePage() Q_DECL_OVERRIDE;
void cleanupPage() Q_DECL_OVERRIDE;
void setFolderMap( const Folder::Map &fm ) { _folderMap = fm; }
void setFolderMap(const Folder::Map &fm) { _folderMap = fm; }
protected slots:
void slotChooseLocalFolder();
@ -76,7 +77,7 @@ class FolderWizardRemotePath : public FormatWarningsWizardPage
{
Q_OBJECT
public:
explicit FolderWizardRemotePath(const AccountPtr& account);
explicit FolderWizardRemotePath(const AccountPtr &account);
~FolderWizardRemotePath();
virtual bool isComplete() const Q_DECL_OVERRIDE;
@ -86,22 +87,23 @@ public:
protected slots:
void showWarn( const QString& = QString() ) const;
void showWarn(const QString & = QString()) const;
void slotAddRemoteFolder();
void slotCreateRemoteFolder(const QString&);
void slotCreateRemoteFolder(const QString &);
void slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error);
void slotHandleMkdirNetworkError(QNetworkReply*);
void slotHandleLsColNetworkError(QNetworkReply*);
void slotUpdateDirectories(const QStringList&);
void slotHandleMkdirNetworkError(QNetworkReply *);
void slotHandleLsColNetworkError(QNetworkReply *);
void slotUpdateDirectories(const QStringList &);
void slotRefreshFolders();
void slotItemExpanded(QTreeWidgetItem*);
void slotCurrentItemChanged(QTreeWidgetItem*);
void slotFolderEntryEdited(const QString& text);
void slotItemExpanded(QTreeWidgetItem *);
void slotCurrentItemChanged(QTreeWidgetItem *);
void slotFolderEntryEdited(const QString &text);
void slotLsColFolderEntry();
void slotTypedPathFound(const QStringList& subpaths);
void slotTypedPathError(QNetworkReply* reply);
void slotTypedPathFound(const QStringList &subpaths);
void slotTypedPathError(QNetworkReply *reply);
private:
LsColJob* runLsColJob(const QString& path);
LsColJob *runLsColJob(const QString &path);
void recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path);
bool selectByPath(QString path);
Ui_FolderWizardTargetPage _ui;
@ -118,7 +120,7 @@ class FolderWizardSelectiveSync : public QWizardPage
{
Q_OBJECT
public:
explicit FolderWizardSelectiveSync(const AccountPtr& account);
explicit FolderWizardSelectiveSync(const AccountPtr &account);
~FolderWizardSelectiveSync();
virtual bool validatePage() Q_DECL_OVERRIDE;
@ -128,7 +130,6 @@ public:
private:
SelectiveSyncWidget *_selectiveSync;
};
/**
@ -139,7 +140,6 @@ class FolderWizard : public QWizard
{
Q_OBJECT
public:
enum {
Page_Source,
Page_Target,
@ -150,7 +150,6 @@ public:
~FolderWizard();
private:
FolderWizardLocalPath *_folderWizardSourcePage;
FolderWizardRemotePath *_folderWizardTargetPage;
FolderWizardSelectiveSync *_folderWizardSelectiveSyncPage;

View File

@ -36,15 +36,15 @@
namespace OCC {
GeneralSettings::GeneralSettings(QWidget *parent) :
QWidget(parent),
_ui(new Ui::GeneralSettings),
_currentlyLoading(false)
GeneralSettings::GeneralSettings(QWidget *parent)
: QWidget(parent)
, _ui(new Ui::GeneralSettings)
, _currentlyLoading(false)
{
_ui->setupUi(this);
connect(_ui->desktopNotificationsCheckBox, SIGNAL(toggled(bool)),
SLOT(slotToggleOptionalDesktopNotifications(bool)));
SLOT(slotToggleOptionalDesktopNotifications(bool)));
_ui->autostartCheckBox->setChecked(Utility::hasLaunchOnStartup(Theme::instance()->appName()));
connect(_ui->autostartCheckBox, SIGNAL(toggled(bool)), SLOT(slotToggleLaunchOnStartup(bool)));
@ -78,8 +78,8 @@ GeneralSettings::GeneralSettings(QWidget *parent) :
* align properly vertically , fixes bug #3758
*/
int m0, m1, m2, m3;
_ui->horizontalLayout_3->getContentsMargins( &m0, &m1, &m2, &m3 );
_ui->horizontalLayout_3->setContentsMargins(0, m1, m2, m3 );
_ui->horizontalLayout_3->getContentsMargins(&m0, &m1, &m2, &m3);
_ui->horizontalLayout_3->setContentsMargins(0, m1, m2, m3);
// OEM themes are not obliged to ship mono icons, so there
// is no point in offering an option
@ -88,7 +88,7 @@ GeneralSettings::GeneralSettings(QWidget *parent) :
connect(_ui->ignoredFilesButton, SIGNAL(clicked()), SLOT(slotIgnoreFilesEditor()));
// accountAdded means the wizard was finished and the wizard might change some options.
connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)), this, SLOT(loadMiscSettings()));
connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)), this, SLOT(loadMiscSettings()));
}
GeneralSettings::~GeneralSettings()
@ -97,13 +97,14 @@ GeneralSettings::~GeneralSettings()
delete _syncLogDialog;
}
QSize GeneralSettings::sizeHint() const {
QSize GeneralSettings::sizeHint() const
{
return QSize(ownCloudGui::settingsDialogSize().width(), QWidget::sizeHint().height());
}
void GeneralSettings::loadMiscSettings()
{
#if QT_VERSION < QT_VERSION_CHECK( 5, 4, 0 )
#if QT_VERSION < QT_VERSION_CHECK(5, 4, 0)
QScopedValueRollback<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);

View 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;

View 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 (Folder* folder, folderMan->map()) {
foreach (Folder *folder, folderMan->map()) {
folder->journalDb()->forceRemoteDiscoveryNextSync();
folderMan->scheduleFolder(folder);
}
@ -138,8 +138,8 @@ void IgnoreListEditor::slotAddPattern()
{
bool okClicked;
QString pattern = QInputDialog::getText(this, tr("Add Ignore Pattern"),
tr("Add a new ignore pattern:"),
QLineEdit::Normal, QString(), &okClicked);
tr("Add a new ignore pattern:"),
QLineEdit::Normal, QString(), &okClicked);
if (!okClicked || pattern.isEmpty())
return;

View 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 QString& file, bool readOnly);
int addPattern(const QString& pattern, bool deletable, bool readOnly);
void readIgnoreFile(const QString &file, bool readOnly);
int addPattern(const QString &pattern, bool deletable, bool readOnly);
QString readOnlyTooltip;
Ui::IgnoreListEditor *ui;
};

View File

@ -24,15 +24,15 @@ Q_LOGGING_CATEGORY(lcLockWatcher, "gui.lockwatcher", QtInfoMsg)
static const int check_frequency = 20 * 1000; // ms
LockWatcher::LockWatcher(QObject* parent)
LockWatcher::LockWatcher(QObject *parent)
: QObject(parent)
{
connect(&_timer, SIGNAL(timeout()),
SLOT(checkFiles()));
SLOT(checkFiles()));
_timer.start(check_frequency);
}
void LockWatcher::addFile(const QString& path)
void LockWatcher::addFile(const QString &path)
{
qCInfo(lcLockWatcher) << "Watching for lock of" << path << "being released";
_watchedPaths.insert(path);
@ -42,7 +42,7 @@ void LockWatcher::checkFiles()
{
QSet<QString> unlocked;
foreach (const QString& path, _watchedPaths) {
foreach (const QString &path, _watchedPaths) {
if (!FileSystem::isFileLocked(path)) {
qCInfo(lcLockWatcher) << "Lock of" << path << "was released";
emit fileUnlocked(path);

View File

@ -42,19 +42,19 @@ class LockWatcher : public QObject
{
Q_OBJECT
public:
explicit LockWatcher(QObject* parent = 0);
explicit LockWatcher(QObject *parent = 0);
/** Start watching a file.
*
* If the file is not locked later on, the fileUnlocked signal will be
* emitted once.
*/
void addFile(const QString& path);
void addFile(const QString &path);
signals:
/** Emitted when one of the watched files is no longer
* being locked. */
void fileUnlocked(const QString& path);
void fileUnlocked(const QString &path);
private slots:
void checkFiles();
@ -63,5 +63,4 @@ private:
QSet<QString> _watchedPaths;
QTimer _timer;
};
}

View 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()

View 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

View 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();
}

View 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;

View File

@ -21,7 +21,7 @@
namespace OCC {
namespace Ui {
class NetworkSettings;
class NetworkSettings;
}
/**

View 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 QUrl& link, const QByteArray &verb)
void NotificationConfirmJob::setLinkAndVerb(const QUrl &link, const QByteArray &verb)
{
_link = link;
_verb = verb;
}
void NotificationConfirmJob::setWidget( NotificationWidget *widget )
void NotificationConfirmJob::setWidget(NotificationWidget *widget)
{
_widget = widget;
}
@ -47,7 +47,7 @@ NotificationWidget *NotificationConfirmJob::widget()
void NotificationConfirmJob::start()
{
if( !_link.isValid() ) {
if (!_link.isValid()) {
qCWarning(lcNotifications) << "Attempt to trigger invalid URL: " << _link.toString();
return;
}
@ -66,17 +66,15 @@ bool NotificationConfirmJob::finished()
// FIXME: check for the reply code!
const QString replyStr = reply()->readAll();
if( replyStr.contains( "<?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;
}
}

View 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 QUrl& link, const QByteArray &verb);
void setLinkAndVerb(const QUrl &link, const QByteArray &verb);
/**
* @brief Start the OCS request
@ -59,7 +59,7 @@ public:
* it when the job has finished
* @param widget pointer to the notification widget to store
*/
void setWidget( NotificationWidget *widget );
void setWidget(NotificationWidget *widget);
/**
* @brief widget - get the associated notification widget as stored
@ -85,7 +85,6 @@ private:
QUrl _link;
NotificationWidget *_widget;
};
}
#endif // NotificationConfirmJob_H

View 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 Activity& activity)
void NotificationWidget::setActivity(const Activity &activity)
{
_myActivity = activity;
@ -40,8 +41,8 @@ void NotificationWidget::setActivity(const Activity& activity)
ASSERT(!_accountName.isEmpty());
// _ui._headerLabel->setText( );
_ui._subjectLabel->setVisible( !activity._subject.isEmpty() );
_ui._messageLabel->setVisible( !activity._message.isEmpty() );
_ui._subjectLabel->setVisible(!activity._subject.isEmpty());
_ui._messageLabel->setVisible(!activity._message.isEmpty());
_ui._subjectLabel->setText(activity._subject);
_ui._messageLabel->setText(activity._message);
@ -55,20 +56,20 @@ void NotificationWidget::setActivity(const Activity& activity)
_ui._timeLabel->setText(tText);
// always remove the buttons
foreach( auto button, _ui._buttonBox->buttons() ) {
foreach (auto button, _ui._buttonBox->buttons()) {
_ui._buttonBox->removeButton(button);
}
_buttons.clear();
// display buttons for the links
if( activity._links.isEmpty() ) {
if (activity._links.isEmpty()) {
// in case there is no action defined, do a close button.
QPushButton *b = _ui._buttonBox->addButton( QDialogButtonBox::Close );
QPushButton *b = _ui._buttonBox->addButton(QDialogButtonBox::Close);
b->setDefault(true);
connect(b, SIGNAL(clicked()), this, SLOT(slotButtonClicked()));
_buttons.append(b);
} else {
foreach( auto link, activity._links ) {
foreach (auto link, activity._links) {
QPushButton *b = _ui._buttonBox->addButton(link._label, QDialogButtonBox::AcceptRole);
b->setDefault(link._isPrimary);
connect(b, SIGNAL(clicked()), this, SLOT(slotButtonClicked()));
@ -86,18 +87,18 @@ void NotificationWidget::slotButtonClicked()
{
QObject *buttonWidget = QObject::sender();
int index = -1;
if( buttonWidget ) {
if (buttonWidget) {
// find the button that was clicked, it has to be in the list
// of buttons that were added to the button box before.
for( int i = 0; i < _buttons.count(); i++ ) {
if( _buttons.at(i) == buttonWidget ) {
for (int i = 0; i < _buttons.count(); i++) {
if (_buttons.at(i) == buttonWidget) {
index = i;
}
_buttons.at(i)->setEnabled(false);
}
// if the button was found, the link must be called
if( index > -1 && _myActivity._links.count() == 0 ) {
if (index > -1 && _myActivity._links.count() == 0) {
// no links, that means it was the close button
// empty link. Just close and remove the widget.
QString doneText = tr("Closing in a few seconds...");
@ -106,14 +107,14 @@ void NotificationWidget::slotButtonClicked()
return;
}
if( index > -1 && index < _myActivity._links.count() ) {
if (index > -1 && index < _myActivity._links.count()) {
ActivityLink triggeredLink = _myActivity._links.at(index);
_actionLabel = triggeredLink._label;
if( ! triggeredLink._link.isEmpty() ) {
qCInfo(lcNotifications) << "Notification Link: "<< triggeredLink._verb << triggeredLink._link;
if (!triggeredLink._link.isEmpty()) {
qCInfo(lcNotifications) << "Notification Link: " << triggeredLink._verb << triggeredLink._link;
_progressIndi->startAnimation();
emit sendNotificationRequest( _accountName, triggeredLink._link, triggeredLink._verb );
emit sendNotificationRequest(_accountName, triggeredLink._link, triggeredLink._verb);
}
}
}
@ -128,9 +129,9 @@ void NotificationWidget::slotNotificationRequestFinished(int statusCode)
QString timeStr = locale.toString(QTime::currentTime());
// the ocs API returns stat code 100 if it succeeded.
if( statusCode != OCS_SUCCESS_STATUS_CODE ) {
if (statusCode != OCS_SUCCESS_STATUS_CODE) {
qCWarning(lcNotifications) << "Notification Request to Server failed, leave button visible.";
for( i = 0; i < _buttons.count(); i++ ) {
for (i = 0; i < _buttons.count(); i++) {
_buttons.at(i)->setEnabled(true);
}
//: The second parameter is a time, such as 'failed at 09:58pm'
@ -142,10 +143,8 @@ void NotificationWidget::slotNotificationRequestFinished(int statusCode)
//: The second parameter is a time, such as 'selected at 09:58pm'
doneText = tr("'%1' selected at %2").arg(_actionLabel, timeStr);
}
_ui._timeLabel->setText( doneText );
_ui._timeLabel->setText(doneText);
_progressIndi->stopAnimation();
}
}

View 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

View 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 auto& item, items) {
foreach (const auto &item, items) {
result.append(qMakePair(
QUrl::toPercentEncoding(item.first),
QUrl::toPercentEncoding(item.second)));
@ -80,7 +80,7 @@ void OcsJob::start()
} else if (_verb == "POST" || _verb == "PUT") {
// Url encode the _postParams and put them in a buffer.
QByteArray postData;
Q_FOREACH(auto tmp, _params) {
Q_FOREACH (auto tmp, _params) {
if (!postData.isEmpty()) {
postData.append("&");
}
@ -107,22 +107,22 @@ bool OcsJob::finished()
QJsonParseError error;
auto json = QJsonDocument::fromJson(replyData, &error);
if (error.error != QJsonParseError::NoError) {
qCWarning(lcOcs) << "Could not parse reply to"
<< _verb
<< Utility::concatUrlPath(account()->url(), path())
<< _params
<< error.errorString()
<< ":" << replyData;
qCWarning(lcOcs) << "Could not parse reply to"
<< _verb
<< Utility::concatUrlPath(account()->url(), path())
<< _params
<< error.errorString()
<< ":" << replyData;
}
QString message;
const int statusCode = getJsonReturnCode(json, message);
if (!_passStatusCodes.contains(statusCode)) {
qCWarning(lcOcs) << "Reply to"
<< _verb
<< Utility::concatUrlPath(account()->url(), path())
<< _params
<< "has unexpected status code:" << statusCode << replyData;
<< _verb
<< Utility::concatUrlPath(account()->url(), path())
<< _params
<< "has unexpected status code:" << statusCode << replyData;
emit ocsError(statusCode, message);
} else {
emit jobFinished(json);
@ -139,5 +139,4 @@ int OcsJob::getJsonReturnCode(const QJsonDocument &json, QString &message)
return code;
}
}

View 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 QByteArray& verb);
void setVerb(const QByteArray &verb);
/**
* Add a new parameter to the request.
@ -59,7 +59,7 @@ protected:
* @param name The name of the parameter
* @param value The value of the parameter
*/
void addParam(const QString& name, const QString &value);
void addParam(const QString &name, const QString &value);
/**
* Set the post parameters
@ -67,7 +67,7 @@ protected:
* @param postParams list of pairs to add (urlEncoded) to the body of the
* request
*/
void setPostParams(const QList<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

View File

@ -17,17 +17,16 @@
namespace OCC {
OcsShareeJob::OcsShareeJob(AccountPtr account)
: OcsJob(account)
: OcsJob(account)
{
setPath("ocs/v1.php/apps/files_sharing/api/v1/sharees");
connect(this, SIGNAL(jobFinished(QJsonDocument)), SLOT(jobDone(QJsonDocument)));
}
void OcsShareeJob::getSharees(const QString &search,
const QString &itemType,
int page,
int perPage)
const QString &itemType,
int page,
int perPage)
{
setVerb("GET");
@ -43,5 +42,4 @@ void OcsShareeJob::jobDone(const QJsonDocument &reply)
{
emit shareeJobFinished(reply);
}
}

View 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

View 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);
}
}

View 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 QString& path = "");
void getShares(const QString &path = "");
/**
* Delete the current Share
@ -57,7 +57,7 @@ public:
* @param date The expire date, if this date is invalid the expire date
* will be removed
*/
void setExpireDate(const QString &shareId, const QDate& date);
void setExpireDate(const QString &shareId, const QDate &date);
/**
* Set the password of a share
@ -65,7 +65,7 @@ public:
* @param password The password of the share, if the password is empty the
* share will be removed
*/
void setPassword(const QString &shareId, const QString& password);
void setPassword(const QString &shareId, const QString &password);
/**
* Set the share to be public upload
@ -84,8 +84,8 @@ public:
*
* @param permissions
*/
void setPermissions(const QString &shareId,
const Share::Permissions permissions);
void setPermissions(const QString &shareId,
const Share::Permissions permissions);
/**
* Create a new link share
@ -94,9 +94,9 @@ public:
* @param name The name of the link share, empty name auto-generates one
* @param password Optionally a password for the share
*/
void createLinkShare(const QString& path,
const QString& name,
const QString& password);
void createLinkShare(const QString &path,
const QString &name,
const QString &password);
/**
* Create a new share
@ -106,10 +106,10 @@ public:
* @param shareWith The uid/gid/federated id to share with
* @param permissions The permissions the share will have
*/
void createShare(const QString& path,
const Share::ShareType shareType,
const QString& shareWith = "",
const Share::Permissions permissions = SharePermissionRead);
void createShare(const QString &path,
const Share::ShareType shareType,
const QString &shareWith = "",
const Share::Permissions permissions = SharePermissionRead);
/**
* Returns information on the items shared with the current user.
@ -134,7 +134,6 @@ private slots:
private:
QVariant _value;
};
}
#endif // OCSSHAREJOB_H

View 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)
}
}
}
}

View File

@ -22,10 +22,10 @@
#include "owncloudsetupwizard.h"
#include "sharedialog.h"
#if defined(Q_OS_MAC)
# include "settingsdialogmac.h"
# include "macwindow.h" // qtmacgoodies
#include "settingsdialogmac.h"
#include "macwindow.h" // qtmacgoodies
#else
# include "settingsdialog.h"
#include "settingsdialog.h"
#endif
#include "logger.h"
#include "logbrowser.h"
@ -48,30 +48,33 @@ namespace OCC {
const char propertyAccountC[] = "oc_account";
ownCloudGui::ownCloudGui(Application *parent) :
QObject(parent),
_tray(0),
ownCloudGui::ownCloudGui(Application *parent)
: QObject(parent)
, _tray(0)
,
#if defined(Q_OS_MAC)
_settingsDialog(new SettingsDialogMac(this)),
_settingsDialog(new SettingsDialogMac(this))
,
#else
_settingsDialog(new SettingsDialog(this)),
_settingsDialog(new SettingsDialog(this))
,
#endif
_logBrowser(0),
_contextMenuVisibleOsx(false),
_recentActionsMenu(0),
_qdbusmenuWorkaround(false),
_folderOpenActionMapper(new QSignalMapper(this)),
_recentItemsMapper(new QSignalMapper(this)),
_app(parent)
_logBrowser(0)
, _contextMenuVisibleOsx(false)
, _recentActionsMenu(0)
, _qdbusmenuWorkaround(false)
, _folderOpenActionMapper(new QSignalMapper(this))
, _recentItemsMapper(new QSignalMapper(this))
, _app(parent)
{
_tray = new Systray();
_tray->setParent(this);
// for the beginning, set the offline icon until the account was verified
_tray->setIcon( Theme::instance()->folderOfflineIcon(/*systray?*/ true, /*currently visible?*/ false));
_tray->setIcon(Theme::instance()->folderOfflineIcon(/*systray?*/ true, /*currently visible?*/ false));
connect(_tray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
SLOT(slotTrayClicked(QSystemTrayIcon::ActivationReason)));
SLOT(slotTrayClicked(QSystemTrayIcon::ActivationReason)));
setupActions();
setupContextMenu();
@ -80,30 +83,30 @@ ownCloudGui::ownCloudGui(Application *parent) :
/* use a signal mapper to map the open requests to the alias names */
connect(_folderOpenActionMapper, SIGNAL(mapped(QString)),
this, SLOT(slotFolderOpenAction(QString)));
this, SLOT(slotFolderOpenAction(QString)));
connect(_recentItemsMapper, SIGNAL(mapped(QString)),
this, SLOT(slotOpenPath(QString)));
this, SLOT(slotOpenPath(QString)));
ProgressDispatcher *pd = ProgressDispatcher::instance();
connect( pd, SIGNAL(progressInfo(QString,ProgressInfo)), this,
SLOT(slotUpdateProgress(QString,ProgressInfo)) );
connect(pd, SIGNAL(progressInfo(QString, ProgressInfo)), this,
SLOT(slotUpdateProgress(QString, ProgressInfo)));
FolderMan *folderMan = FolderMan::instance();
connect( folderMan, SIGNAL(folderSyncStateChange(Folder*)),
this,SLOT(slotSyncStateChange(Folder*)));
connect(folderMan, SIGNAL(folderSyncStateChange(Folder *)),
this, SLOT(slotSyncStateChange(Folder *)));
connect( AccountManager::instance(), SIGNAL(accountAdded(AccountState*)),
SLOT(updateContextMenuNeeded()));
connect( AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)),
SLOT(updateContextMenuNeeded()));
connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)),
SLOT(updateContextMenuNeeded()));
connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)),
SLOT(updateContextMenuNeeded()));
connect( Logger::instance(), SIGNAL(guiLog(QString,QString)),
SLOT(slotShowTrayMessage(QString,QString)));
connect( Logger::instance(), SIGNAL(optionalGuiLog(QString,QString)),
SLOT(slotShowOptionalTrayMessage(QString,QString)));
connect( Logger::instance(), SIGNAL(guiMessage(QString,QString)),
SLOT(slotShowGuiMessage(QString,QString)));
connect(Logger::instance(), SIGNAL(guiLog(QString, QString)),
SLOT(slotShowTrayMessage(QString, QString)));
connect(Logger::instance(), SIGNAL(optionalGuiLog(QString, QString)),
SLOT(slotShowOptionalTrayMessage(QString, QString)));
connect(Logger::instance(), SIGNAL(guiMessage(QString, QString)),
SLOT(slotShowGuiMessage(QString, QString)));
setupOverlayIcons();
}
@ -127,21 +130,21 @@ void ownCloudGui::setupOverlayIcons()
" end try\n"
"end tell\n");
QString osascript = "/usr/bin/osascript";
QStringList processArguments;
// processArguments << "-l" << "AppleScript";
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 {
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(Account* account)
void ownCloudGui::slotTrayMessageIfServerUnsupported(Account *account)
{
if (account->serverVersionUnsupported()) {
slotShowTrayMessage(
tr("Unsupported Server Version"),
tr("The server on account %1 runs an old and unsupported version %2. "
"Using this client with unsupported server versions is untested and "
"potentially dangerous. Proceed at your own risk.")
.arg(account->displayName(), account->serverVersion()));
tr("Unsupported Server Version"),
tr("The server on account %1 runs an old and unsupported version %2. "
"Using this client with unsupported server versions is untested and "
"potentially dangerous. Proceed at your own risk.")
.arg(account->displayName(), account->serverVersion()));
}
}
@ -265,7 +268,7 @@ void ownCloudGui::slotComputeOverallSyncStatus()
problemAccounts.append(a);
}
}
foreach (Folder* f, FolderMan::instance()->map()) {
foreach (Folder *f, FolderMan::instance()->map()) {
if (!f->syncPaused()) {
allPaused = false;
}
@ -279,15 +282,13 @@ void ownCloudGui::slotComputeOverallSyncStatus()
foreach (AccountStatePtr a, problemAccounts) {
accountNames.append(a->account()->displayName());
}
_tray->setToolTip(tr("Disconnected from %1").arg(
accountNames.join(QLatin1String(", "))));
_tray->setToolTip(tr("Disconnected from %1").arg(accountNames.join(QLatin1String(", "))));
#else
QStringList messages;
messages.append(tr("Disconnected from accounts:"));
foreach (AccountStatePtr a, problemAccounts) {
QString message = tr("Account %1: %2").arg(
a->account()->displayName(), a->stateString(a->state()));
if (! a->connectionErrors().empty()) {
QString message = tr("Account %1: %2").arg(a->account()->displayName(), a->stateString(a->state()));
if (!a->connectionErrors().empty()) {
message += QLatin1String("\n");
message += a->connectionErrors().join(QLatin1String("\n"));
}
@ -315,14 +316,14 @@ void ownCloudGui::slotComputeOverallSyncStatus()
SyncResult overallResult = FolderMan::accountStatus(map.values());
// create the tray blob message, check if we have an defined state
if( overallResult.status() != SyncResult::Undefined ) {
if( map.count() > 0 ) {
if (overallResult.status() != SyncResult::Undefined) {
if (map.count() > 0) {
#ifdef Q_OS_WIN
// Windows has a 128-char tray tooltip length limit.
trayMessage = folderMan->statusToString(overallResult.status(), false);
#else
QStringList allStatusStrings;
foreach(Folder* folder, map.values()) {
foreach (Folder *folder, map.values()) {
QString folderMessage = folderMan->statusToString(folder->syncResult().status(), folder->syncPaused());
allStatusStrings += tr("Folder %1: %2").arg(folder->shortGuiLocalPath(), folderMessage);
}
@ -332,13 +333,13 @@ void ownCloudGui::slotComputeOverallSyncStatus()
trayMessage = tr("No sync folders configured.");
}
QIcon statusIcon = Theme::instance()->syncStateIcon( overallResult.status(), true, contextMenuVisible());
_tray->setIcon( statusIcon );
QIcon statusIcon = Theme::instance()->syncStateIcon(overallResult.status(), true, contextMenuVisible());
_tray->setIcon(statusIcon);
_tray->setToolTip(trayMessage);
} else {
// undefined because there are no folders.
QIcon icon = Theme::instance()->syncStateIcon(SyncResult::Problem, true, contextMenuVisible());
_tray->setIcon( icon );
_tray->setIcon(icon);
_tray->setToolTip(tr("There are no sync folders configured."));
}
}
@ -360,7 +361,7 @@ void ownCloudGui::addAccountContextMenu(AccountStatePtr accountState, QMenu *men
bool singleSyncFolder = folderMan->map().size() == 1 && Theme::instance()->singleSyncFolder();
bool onePaused = false;
bool allPaused = true;
foreach (Folder* folder, folderMan->map()) {
foreach (Folder *folder, folderMan->map()) {
if (folder->accountState() != accountState.data()) {
continue;
}
@ -377,36 +378,35 @@ void ownCloudGui::addAccountContextMenu(AccountStatePtr accountState, QMenu *men
menu->addAction(tr("Managed Folders:"))->setDisabled(true);
}
QAction *action = new QAction( tr("Open folder '%1'").arg(folder->shortGuiLocalPath()), menu );
connect(action, SIGNAL(triggered()),_folderOpenActionMapper, SLOT(map()));
_folderOpenActionMapper->setMapping( action, folder->alias() );
QAction *action = new QAction(tr("Open folder '%1'").arg(folder->shortGuiLocalPath()), menu);
connect(action, SIGNAL(triggered()), _folderOpenActionMapper, SLOT(map()));
_folderOpenActionMapper->setMapping(action, folder->alias());
menu->addAction(action);
}
menu->addSeparator();
if (separateMenu) {
if (onePaused) {
QAction* enable = menu->addAction(tr("Unpause all folders"));
enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(enable, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders()));
}
if (!allPaused) {
QAction* enable = menu->addAction(tr("Pause all folders"));
enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(enable, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders()));
}
if (accountState->isSignedOut()) {
QAction* signin = menu->addAction(tr("Log in..."));
signin->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(signin, SIGNAL(triggered()), this, SLOT(slotLogin()));
} else {
QAction* signout = menu->addAction(tr("Log out"));
signout->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(signout, SIGNAL(triggered()), this, SLOT(slotLogout()));
}
}
menu->addSeparator();
if (separateMenu) {
if (onePaused) {
QAction *enable = menu->addAction(tr("Unpause all folders"));
enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(enable, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders()));
}
if (!allPaused) {
QAction *enable = menu->addAction(tr("Pause all folders"));
enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(enable, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders()));
}
if (accountState->isSignedOut()) {
QAction *signin = menu->addAction(tr("Log in..."));
signin->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(signin, SIGNAL(triggered()), this, SLOT(slotLogin()));
} else {
QAction *signout = menu->addAction(tr("Log out"));
signout->setProperty(propertyAccountC, QVariant::fromValue(accountState));
connect(signout, SIGNAL(triggered()), this, SLOT(slotLogout()));
}
}
}
void ownCloudGui::slotContextMenuAboutToShow()
@ -469,7 +469,7 @@ void ownCloudGui::setupContextMenu()
}
_contextMenu.reset(new QMenu());
_contextMenu->setTitle(Theme::instance()->appNameGUI() );
_contextMenu->setTitle(Theme::instance()->appNameGUI());
_recentActionsMenu = new QMenu(tr("Recent Changes"), _contextMenu.data());
@ -484,21 +484,21 @@ void ownCloudGui::setupContextMenu()
return;
}
// Enables workarounds for bugs introduced in Qt 5.5.0
// In particular QTBUG-47863 #3672 (tray menu fails to update and
// becomes unresponsive) and QTBUG-48068 #3722 (click signal is
// emitted several times)
// The Qt version check intentionally uses 5.0.0 (where platformMenu()
// was introduced) instead of 5.5.0 to avoid issues where the Qt
// version used to build is different from the one used at runtime.
// If we build with 5.6.1 or newer, we can skip this because the
// bugs should be fixed there.
// Enables workarounds for bugs introduced in Qt 5.5.0
// In particular QTBUG-47863 #3672 (tray menu fails to update and
// becomes unresponsive) and QTBUG-48068 #3722 (click signal is
// emitted several times)
// The Qt version check intentionally uses 5.0.0 (where platformMenu()
// was introduced) instead of 5.5.0 to avoid issues where the Qt
// version used to build is different from the one used at runtime.
// If we build with 5.6.1 or newer, we can skip this because the
// bugs should be fixed there.
#ifdef Q_OS_LINUX
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && (QT_VERSION < QT_VERSION_CHECK(5, 6, 0))
if (qVersion() == QByteArray("5.5.0")) {
QObject* platformMenu = reinterpret_cast<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) {
QMenu* accountMenu = new QMenu(account->account()->displayName(), _contextMenu.data());
QMenu *accountMenu = new QMenu(account->account()->displayName(), _contextMenu.data());
_accountMenus.append(accountMenu);
_contextMenu->addMenu(accountMenu);
@ -614,7 +616,7 @@ void ownCloudGui::updateContextMenu()
_contextMenu->addAction(_actionHelp);
}
if(_actionCrash) {
if (_actionCrash) {
_contextMenu->addAction(_actionCrash);
}
@ -626,7 +628,7 @@ void ownCloudGui::updateContextMenu()
} else {
text = tr("Unpause synchronization");
}
QAction* action = _contextMenu->addAction(text);
QAction *action = _contextMenu->addAction(text);
connect(action, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders()));
}
if (atLeastOneNotPaused) {
@ -636,7 +638,7 @@ void ownCloudGui::updateContextMenu()
} else {
text = tr("Pause synchronization");
}
QAction* action = _contextMenu->addAction(text);
QAction *action = _contextMenu->addAction(text);
connect(action, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders()));
}
if (atLeastOneSignedIn) {
@ -690,7 +692,7 @@ void ownCloudGui::updateContextMenuNeeded()
void ownCloudGui::slotShowTrayMessage(const QString &title, const QString &msg)
{
if( _tray )
if (_tray)
_tray->showMessage(title, msg);
else
qCWarning(lcApplication) << "Tray not ready: " << msg;
@ -708,10 +710,10 @@ void ownCloudGui::slotShowOptionalTrayMessage(const QString &title, const QStrin
/*
* open the folder with the given Alias
*/
void ownCloudGui::slotFolderOpenAction( const QString& alias )
void ownCloudGui::slotFolderOpenAction(const QString &alias)
{
Folder *f = FolderMan::instance()->folder(alias);
if( f ) {
if (f) {
qCInfo(lcApplication) << "opening local url " << f->path();
QUrl url = QUrl::fromLocalFile(f->path());
@ -731,11 +733,11 @@ void ownCloudGui::slotFolderOpenAction( const QString& alias )
void ownCloudGui::setupActions()
{
_actionStatus = new QAction(tr("Unknown status"), this);
_actionStatus->setEnabled( false );
_actionStatus->setEnabled(false);
_actionSettings = new QAction(tr("Settings..."), this);
_actionNewAccountWizard = new QAction(tr("New account..."), this);
_actionRecent = new QAction(tr("Details..."), this);
_actionRecent->setEnabled( true );
_actionRecent->setEnabled(true);
QObject::connect(_actionRecent, SIGNAL(triggered(bool)), SLOT(slotShowSyncProtocol()));
QObject::connect(_actionSettings, SIGNAL(triggered(bool)), SLOT(slotShowSettings()));
@ -750,20 +752,19 @@ void ownCloudGui::setupActions()
_actionLogout = new QAction(tr("Log out"), this);
connect(_actionLogout, SIGNAL(triggered()), this, SLOT(slotLogout()));
if(_app->debugMode()) {
if (_app->debugMode()) {
_actionCrash = new QAction(tr("Crash now", "Only shows in debug mode to allow testing the crash handler"), this);
connect(_actionCrash, SIGNAL(triggered()), _app, SLOT(slotCrash()));
} else {
_actionCrash = 0;
}
}
void ownCloudGui::slotRebuildRecentMenus()
{
_recentActionsMenu->clear();
if (!_recentItemsActions.isEmpty()) {
foreach(QAction *a, _recentItemsActions) {
foreach (QAction *a, _recentItemsActions) {
_recentActionsMenu->addAction(a);
}
_recentActionsMenu->addSeparator();
@ -776,53 +777,53 @@ void ownCloudGui::slotRebuildRecentMenus()
/// Returns true if the completion of a given item should show up in the
/// 'Recent Activity' menu
static bool shouldShowInRecentsMenu(const SyncFileItem& item)
static bool shouldShowInRecentsMenu(const SyncFileItem &item)
{
return
!Progress::isIgnoredKind(item._status)
&& item._instruction != CSYNC_INSTRUCTION_EVAL
&& item._instruction != CSYNC_INSTRUCTION_NONE;
return !Progress::isIgnoredKind(item._status)
&& item._instruction != CSYNC_INSTRUCTION_EVAL
&& item._instruction != CSYNC_INSTRUCTION_NONE;
}
void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo& progress)
void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo &progress)
{
Q_UNUSED(folder);
if (!progress._currentDiscoveredFolder.isEmpty()) {
_actionStatus->setText( tr("Checking for changes in '%1'")
.arg( progress._currentDiscoveredFolder ));
} else if (progress.totalSize() == 0 ) {
_actionStatus->setText(tr("Checking for changes in '%1'")
.arg(progress._currentDiscoveredFolder));
} else if (progress.totalSize() == 0) {
quint64 currentFile = progress.currentFile();
quint64 totalFileCount = qMax(progress.totalFiles(), currentFile);
QString msg;
if (progress.trustEta()) {
msg = tr("Syncing %1 of %2 (%3 left)")
.arg( currentFile ).arg( totalFileCount )
.arg( Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta) );
.arg(currentFile)
.arg(totalFileCount)
.arg(Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta));
} else {
msg = tr("Syncing %1 of %2")
.arg( currentFile ).arg( totalFileCount );
.arg(currentFile)
.arg(totalFileCount);
}
_actionStatus->setText( msg );
_actionStatus->setText(msg);
} else {
QString totalSizeStr = Utility::octetsToString( progress.totalSize() );
QString totalSizeStr = Utility::octetsToString(progress.totalSize());
QString msg;
if (progress.trustEta()) {
msg = tr("Syncing %1 (%2 left)")
.arg( totalSizeStr, Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta) );
.arg(totalSizeStr, Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta));
} else {
msg = tr("Syncing %1")
.arg( totalSizeStr );
.arg(totalSizeStr);
}
_actionStatus->setText( msg );
_actionStatus->setText(msg);
}
_actionRecent->setIcon( QIcon() ); // Fixme: Set a "in-progress"-item eventually.
_actionRecent->setIcon(QIcon()); // Fixme: Set a "in-progress"-item eventually.
if (!progress._lastCompletedItem.isEmpty()
&& shouldShowInRecentsMenu(progress._lastCompletedItem)) {
&& shouldShowInRecentsMenu(progress._lastCompletedItem)) {
if (Progress::isWarningKind(progress._lastCompletedItem._status)) {
// display a warn icon if warnings happened.
QIcon warnIcon(":/client/resources/warning");
@ -856,8 +857,8 @@ void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo&
}
if (progress.isUpdatingEstimates()
&& progress.completedFiles() >= progress.totalFiles()
&& progress._currentDiscoveredFolder.isEmpty()) {
&& progress.completedFiles() >= progress.totalFiles()
&& progress._currentDiscoveredFolder.isEmpty()) {
QTimer::singleShot(2000, this, SLOT(slotDisplayIdle()));
}
}
@ -909,7 +910,7 @@ void ownCloudGui::slotNewAccountWizard()
void ownCloudGui::setPauseOnAllFoldersHelper(bool pause)
{
QList<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 (Folder* f, FolderMan::instance()->map()) {
foreach (Folder *f, FolderMan::instance()->map()) {
if (accounts.contains(f->accountState())) {
f->setSyncPaused(pause);
if (pause) {
@ -943,11 +944,11 @@ void ownCloudGui::slotShowSettings()
if (_settingsDialog.isNull()) {
_settingsDialog =
#if defined(Q_OS_MAC)
new SettingsDialogMac(this);
new SettingsDialogMac(this);
#else
new SettingsDialog(this);
new SettingsDialog(this);
#endif
_settingsDialog->setAttribute( Qt::WA_DeleteOnClose, true );
_settingsDialog->setAttribute(Qt::WA_DeleteOnClose, true);
_settingsDialog->show();
}
raiseDialog(_settingsDialog.data());
@ -966,8 +967,10 @@ void ownCloudGui::slotShutdown()
// that saving the geometries happens ASAP during a OS shutdown
// those do delete on close
if (!_settingsDialog.isNull()) _settingsDialog->close();
if (!_logBrowser.isNull()) _logBrowser->deleteLater();
if (!_settingsDialog.isNull())
_settingsDialog->close();
if (!_logBrowser.isNull())
_logBrowser->deleteLater();
}
void ownCloudGui::slotToggleLogBrowser()
@ -978,7 +981,7 @@ void ownCloudGui::slotToggleLogBrowser()
// ## TODO: allow new log name maybe?
}
if (_logBrowser->isVisible() ) {
if (_logBrowser->isVisible()) {
_logBrowser->hide();
} else {
raiseDialog(_logBrowser);
@ -997,9 +1000,9 @@ void ownCloudGui::slotHelp()
QDesktopServices::openUrl(QUrl(Theme::instance()->helpUrl()));
}
void ownCloudGui::raiseDialog( QWidget *raiseWidget )
void ownCloudGui::raiseDialog(QWidget *raiseWidget)
{
if( raiseWidget && raiseWidget->parentWidget() == 0) {
if (raiseWidget && raiseWidget->parentWidget() == 0) {
// Qt has a bug which causes parent-less dialogs to pop-under.
raiseWidget->showNormal();
raiseWidget->raise();
@ -1026,10 +1029,10 @@ void ownCloudGui::raiseDialog( QWidget *raiseWidget )
e.xclient.data.l[4] = 0l;
Display *display = QX11Info::display();
XSendEvent(display,
RootWindow(display, DefaultScreen(display)),
False, // propagate
SubstructureRedirectMask|SubstructureNotifyMask,
&e);
RootWindow(display, DefaultScreen(display)),
False, // propagate
SubstructureRedirectMask | SubstructureNotifyMask,
&e);
#endif
}
}
@ -1054,9 +1057,9 @@ void ownCloudGui::slotShowShareDialog(const QString &sharePath, const QString &l
// The correct value will be found with a propfind from ShareDialog.
// (we want to show the dialog directly, not wait for the propfind first)
SharePermissions maxSharingPermissions =
SharePermissionRead
| SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete
| SharePermissionShare;
SharePermissionRead
| SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete
| SharePermissionShare;
if (!resharingAllowed) {
maxSharingPermissions = 0;
}
@ -1069,20 +1072,20 @@ void ownCloudGui::slotShowShareDialog(const QString &sharePath, const QString &l
} else {
qCInfo(lcApplication) << "Opening share dialog" << sharePath << localPath << maxSharingPermissions;
w = new ShareDialog(accountState, sharePath, localPath, maxSharingPermissions);
w->setAttribute( Qt::WA_DeleteOnClose, true );
w->setAttribute(Qt::WA_DeleteOnClose, true);
_shareDialogs[localPath] = w;
connect(w, SIGNAL(destroyed(QObject*)), SLOT(slotRemoveDestroyedShareDialogs()));
connect(w, SIGNAL(destroyed(QObject *)), SLOT(slotRemoveDestroyedShareDialogs()));
}
raiseDialog(w);
}
void ownCloudGui::slotRemoveDestroyedShareDialogs()
{
QMutableMapIterator<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();
}
}

View 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 ProgressInfo& progress);
void slotUpdateProgress(const QString &folder, const ProgressInfo &progress);
void slotShowGuiMessage(const QString &title, const QString &message);
void slotFoldersChanged();
void slotShowSettings();
void slotShowSyncProtocol();
void slotShutdown();
void slotSyncStateChange(Folder*);
void slotTrayClicked( QSystemTrayIcon::ActivationReason reason );
void slotSyncStateChange(Folder *);
void slotTrayClicked(QSystemTrayIcon::ActivationReason reason);
void slotToggleLogBrowser();
void slotOpenOwnCloud();
void slotOpenSettingsDialog();
void slotHelp();
void slotOpenPath(const QString& path);
void slotOpenPath(const QString &path);
void slotAccountStateChanged();
void slotTrayMessageIfServerUnsupported(Account *account);
void slotShowShareDialog(const QString &sharePath, const QString &localPath, bool resharingAllowed);
@ -100,7 +100,7 @@ private slots:
private:
void setPauseOnAllFoldersHelper(bool pause);
void setupActions();
void addAccountContextMenu(AccountStatePtr accountState, QMenu* menu, bool separateMenu);
void addAccountContextMenu(AccountStatePtr accountState, QMenu *menu, bool separateMenu);
QPointer<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;

View File

@ -40,24 +40,24 @@
namespace OCC {
OwncloudSetupWizard::OwncloudSetupWizard(QObject* parent) :
QObject( parent ),
_ocWizard(new OwncloudWizard),
_remoteFolder()
OwncloudSetupWizard::OwncloudSetupWizard(QObject *parent)
: QObject(parent)
, _ocWizard(new OwncloudWizard)
, _remoteFolder()
{
connect( _ocWizard, SIGNAL(determineAuthType(const QString&)),
this, SLOT(slotDetermineAuthType(const QString&)));
connect( _ocWizard, SIGNAL(connectToOCUrl( const QString& ) ),
this, SLOT(slotConnectToOCUrl( const QString& )));
connect( _ocWizard, SIGNAL(createLocalAndRemoteFolders(QString, QString)),
this, SLOT(slotCreateLocalAndRemoteFolders(QString, QString)));
connect(_ocWizard, SIGNAL(determineAuthType(const QString &)),
this, SLOT(slotDetermineAuthType(const QString &)));
connect(_ocWizard, SIGNAL(connectToOCUrl(const QString &)),
this, SLOT(slotConnectToOCUrl(const QString &)));
connect(_ocWizard, SIGNAL(createLocalAndRemoteFolders(QString, QString)),
this, SLOT(slotCreateLocalAndRemoteFolders(QString, QString)));
/* basicSetupFinished might be called from a reply from the network.
slotAssistantFinished might destroy the temporary QNetworkAccessManager.
Therefore Qt::QueuedConnection is required */
connect( _ocWizard, SIGNAL(basicSetupFinished(int)),
this, SLOT(slotAssistantFinished(int)), Qt::QueuedConnection);
connect( _ocWizard, SIGNAL(finished(int)), SLOT(deleteLater()));
connect( _ocWizard, SIGNAL(skipFolderConfiguration()), SLOT(slotSkipFolderConfiguration()));
connect(_ocWizard, SIGNAL(basicSetupFinished(int)),
this, SLOT(slotAssistantFinished(int)), Qt::QueuedConnection);
connect(_ocWizard, SIGNAL(finished(int)), SLOT(deleteLater()));
connect(_ocWizard, SIGNAL(skipFolderConfiguration()), SLOT(slotSkipFolderConfiguration()));
}
OwncloudSetupWizard::~OwncloudSetupWizard()
@ -67,14 +67,14 @@ OwncloudSetupWizard::~OwncloudSetupWizard()
static QPointer<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 QUrl& url, 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;
}
QNetworkReply* reply = job->reply();
QNetworkReply *reply = job->reply();
// If there were redirects on the *authed* requests, also store
// the updated server URL, similar to redirects on status.php.
@ -323,13 +324,13 @@ void OwncloudSetupWizard::slotAuthError()
"'%1'. The URL is bad, the server is misconfigured.")
.arg(Utility::escape(redirectUrl.toString()));
// A 404 is actually a success: we were authorized to know that the folder does
// not exist. It will be created later...
// A 404 is actually a success: we were authorized to know that the folder does
// not exist. It will be created later...
} else if (reply->error() == QNetworkReply::ContentNotFoundError) {
_ocWizard->successfulStep();
return;
// Provide messages for other errors, such as invalid credentials.
// Provide messages for other errors, such as invalid credentials.
} else if (reply->error() != QNetworkReply::NoError) {
if (!_ocWizard->account()->credentials()->stillValid(reply)) {
errorMsg = tr("Access forbidden by server. To verify that you have proper access, "
@ -339,7 +340,7 @@ void OwncloudSetupWizard::slotAuthError()
errorMsg = job->errorStringParsingBody();
}
// Something else went wrong, maybe the response was 200 but with invalid data.
// Something else went wrong, maybe the response was 200 but with invalid data.
} else {
errorMsg = tr("There was an invalid response to an authenticated webdav request");
}
@ -351,9 +352,9 @@ void OwncloudSetupWizard::slotAuthError()
_ocWizard->displayError(errorMsg, _ocWizard->currentId() == WizardCommon::Page_ServerSetup && checkDowngradeAdvised(reply));
}
bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply* reply)
bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply *reply)
{
if(reply->url().scheme() != QLatin1String("https")) {
if (reply->url().scheme() != QLatin1String("https")) {
return false;
}
@ -374,13 +375,13 @@ bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply* reply)
return true;
}
void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFolder, const QString& remoteFolder)
void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString &localFolder, const QString &remoteFolder)
{
qCInfo(lcWizard) << "Setup local sync folder for new oC connection " << localFolder;
const QDir fi( localFolder );
const QDir fi(localFolder);
bool nextStep = true;
if( fi.exists() ) {
if (fi.exists()) {
FileSystem::setFolderMinimumPermissions(localFolder);
// there is an existing local folder. If its non empty, it can only be synced if the
// ownCloud is newly created.
@ -389,9 +390,9 @@ void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFo
.arg(Utility::escape(localFolder)));
} else {
QString res = tr("Creating local sync folder %1...").arg(localFolder);
if( fi.mkpath( localFolder ) ) {
if (fi.mkpath(localFolder)) {
FileSystem::setFolderMinimumPermissions(localFolder);
Utility::setupFavLink( localFolder );
Utility::setupFavLink(localFolder);
res += tr("ok");
} else {
res += tr("failed.");
@ -399,14 +400,14 @@ void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFo
_ocWizard->displayError(tr("Could not create local folder %1").arg(Utility::escape(localFolder)), false);
nextStep = false;
}
_ocWizard->appendToConfigurationLog( res );
_ocWizard->appendToConfigurationLog(res);
}
if (nextStep) {
EntityExistsJob *job = new EntityExistsJob(_ocWizard->account(), _ocWizard->account()->davPath() + remoteFolder, this);
connect(job, SIGNAL(exists(QNetworkReply*)), SLOT(slotRemoteFolderExists(QNetworkReply*)));
connect(job, SIGNAL(exists(QNetworkReply *)), SLOT(slotRemoteFolderExists(QNetworkReply *)));
job->start();
} else {
finalizeSetup( false );
finalizeSetup(false);
}
}
@ -418,10 +419,10 @@ void OwncloudSetupWizard::slotRemoteFolderExists(QNetworkReply *reply)
QString error;
QNetworkReply::NetworkError errId = reply->error();
if( errId == QNetworkReply::NoError ) {
if (errId == QNetworkReply::NoError) {
qCInfo(lcWizard) << "Remote folder found, all cool!";
} else if( errId == QNetworkReply::ContentNotFoundError ) {
if( _remoteFolder.isEmpty() ) {
} else if (errId == QNetworkReply::ContentNotFoundError) {
if (_remoteFolder.isEmpty()) {
error = tr("No remote folder specified!");
ok = false;
} else {
@ -432,23 +433,23 @@ void OwncloudSetupWizard::slotRemoteFolderExists(QNetworkReply *reply)
ok = false;
}
if( !ok ) {
if (!ok) {
_ocWizard->displayError(Utility::escape(error), false);
}
finalizeSetup( ok );
finalizeSetup(ok);
}
void OwncloudSetupWizard::createRemoteFolder()
{
_ocWizard->appendToConfigurationLog( tr("creating folder on ownCloud: %1" ).arg( _remoteFolder ));
_ocWizard->appendToConfigurationLog(tr("creating folder on ownCloud: %1").arg(_remoteFolder));
MkColJob *job = new MkColJob(_ocWizard->account(), _remoteFolder, this);
connect(job, SIGNAL(finished(QNetworkReply::NetworkError)), SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError)));
job->start();
}
void OwncloudSetupWizard::slotCreateRemoteFolderFinished( QNetworkReply::NetworkError error )
void OwncloudSetupWizard::slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error)
{
qCDebug(lcWizard) << "** webdav mkdir request finished " << error;
// disconnect(ownCloudInfo::instance(), SIGNAL(webdavColCreated(QNetworkReply::NetworkError)),
@ -456,70 +457,73 @@ void OwncloudSetupWizard::slotCreateRemoteFolderFinished( QNetworkReply::Network
bool success = true;
if( error == QNetworkReply::NoError ) {
_ocWizard->appendToConfigurationLog( tr("Remote folder %1 created successfully.").arg(_remoteFolder));
} else if( error == 202 ) {
_ocWizard->appendToConfigurationLog( tr("The remote folder %1 already exists. Connecting it for syncing.").arg(_remoteFolder));
} else if( error > 202 && error < 300 ) {
_ocWizard->displayError( tr("The folder creation resulted in HTTP error code %1").arg((int)error ), false);
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>"));
_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()

View 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(QNetworkReply* reply);
bool checkDowngradeAdvised(QNetworkReply *reply);
OwncloudWizard* _ocWizard;
OwncloudWizard *_ocWizard;
QString _initLocalFolder;
QString _remoteFolder;
};
}
#endif // OWNCLOUDSETUPWIZARD_H

View File

@ -35,19 +35,19 @@
namespace OCC {
ProtocolWidget::ProtocolWidget(QWidget *parent) :
QWidget(parent),
IgnoredIndicatorRole( Qt::UserRole +1 ),
_ui(new Ui::ProtocolWidget)
ProtocolWidget::ProtocolWidget(QWidget *parent)
: QWidget(parent)
, IgnoredIndicatorRole(Qt::UserRole + 1)
, _ui(new Ui::ProtocolWidget)
{
_ui->setupUi(this);
connect(ProgressDispatcher::instance(), SIGNAL(progressInfo(QString,ProgressInfo)),
this, SLOT(slotProgressInfo(QString,ProgressInfo)));
connect(ProgressDispatcher::instance(), SIGNAL(itemCompleted(QString,SyncFileItemPtr)),
this, SLOT(slotItemCompleted(QString,SyncFileItemPtr)));
connect(ProgressDispatcher::instance(), SIGNAL(progressInfo(QString, ProgressInfo)),
this, SLOT(slotProgressInfo(QString, ProgressInfo)));
connect(ProgressDispatcher::instance(), SIGNAL(itemCompleted(QString, SyncFileItemPtr)),
this, SLOT(slotItemCompleted(QString, SyncFileItemPtr)));
connect(_ui->_treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)), SLOT(slotOpenFile(QTreeWidgetItem*,int)));
connect(_ui->_treeWidget, SIGNAL(itemActivated(QTreeWidgetItem *, int)), SLOT(slotOpenFile(QTreeWidgetItem *, int)));
// Adjust copyToClipboard() when making changes here!
QStringList header;
@ -62,7 +62,7 @@ ProtocolWidget::ProtocolWidget(QWidget *parent) :
timestampColumnExtra = 20; // font metrics are broken on Windows, see #4721
#endif
_ui->_treeWidget->setHeaderLabels( header );
_ui->_treeWidget->setHeaderLabels(header);
int timestampColumnWidth =
_ui->_treeWidget->fontMetrics().width(timeString(QDateTime::currentDateTime()))
+ timestampColumnExtra;
@ -78,7 +78,7 @@ ProtocolWidget::ProtocolWidget(QWidget *parent) :
_ui->_headerLabel->setText(tr("Local sync protocol"));
QPushButton *copyBtn = _ui->_dialogButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
copyBtn->setToolTip( tr("Copy the activity list to the clipboard."));
copyBtn->setToolTip(tr("Copy the activity list to the clipboard."));
copyBtn->setEnabled(true);
connect(copyBtn, SIGNAL(clicked()), SIGNAL(copyToClipboard()));
@ -87,19 +87,19 @@ ProtocolWidget::ProtocolWidget(QWidget *parent) :
// be embedded into another gui element.
_issueItemView = new QTreeWidget(this);
header.removeLast();
_issueItemView->setHeaderLabels( header );
_issueItemView->setHeaderLabels(header);
timestampColumnWidth =
ActivityItemDelegate::rowHeight() // icon
+ _issueItemView->fontMetrics().width(timeString(QDateTime::currentDateTime()))
+ timestampColumnExtra;
ActivityItemDelegate::rowHeight() // icon
+ _issueItemView->fontMetrics().width(timeString(QDateTime::currentDateTime()))
+ timestampColumnExtra;
_issueItemView->setColumnWidth(0, timestampColumnWidth);
_issueItemView->setColumnWidth(1, 180);
_issueItemView->setColumnCount(4);
_issueItemView->setRootIsDecorated(false);
_issueItemView->setTextElideMode(Qt::ElideMiddle);
_issueItemView->header()->setObjectName("ActivityErrorListHeader");
connect(_issueItemView, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
SLOT(slotOpenFile(QTreeWidgetItem*,int)));
connect(_issueItemView, SIGNAL(itemActivated(QTreeWidgetItem *, int)),
SLOT(slotOpenFile(QTreeWidgetItem *, int)));
}
ProtocolWidget::~ProtocolWidget()
@ -117,24 +117,24 @@ void ProtocolWidget::showEvent(QShowEvent *ev)
void ProtocolWidget::hideEvent(QHideEvent *ev)
{
ConfigFile cfg;
cfg.saveGeometryHeader(_ui->_treeWidget->header() );
cfg.saveGeometryHeader(_ui->_treeWidget->header());
QWidget::hideEvent(ev);
}
void ProtocolWidget::cleanItems(const QString& folder)
void ProtocolWidget::cleanItems(const QString &folder)
{
// The issue list is a state, clear it and let the next sync fill it
// with ignored files and propagation errors.
int itemCnt = _issueItemView->topLevelItemCount();
for( int cnt = itemCnt-1; cnt >=0 ; cnt-- ) {
for (int cnt = itemCnt - 1; cnt >= 0; cnt--) {
QTreeWidgetItem *item = _issueItemView->topLevelItem(cnt);
QString itemFolder = item->data(2, Qt::UserRole).toString();
if( itemFolder == folder ) {
if (itemFolder == folder) {
delete item;
}
}
// update the tabtext
emit( issueItemCountUpdated(_issueItemView->topLevelItemCount()) );
emit(issueItemCountUpdated(_issueItemView->topLevelItemCount()));
}
QString ProtocolWidget::timeString(QDateTime dt, QLocale::FormatType format) const
@ -146,7 +146,7 @@ QString ProtocolWidget::timeString(QDateTime dt, QLocale::FormatType format) con
return loc.toString(dt, dtFormat);
}
void ProtocolWidget::slotOpenFile( QTreeWidgetItem *item, int )
void ProtocolWidget::slotOpenFile(QTreeWidgetItem *item, int)
{
QString folderName = item->data(2, Qt::UserRole).toString();
QString fileName = item->text(1);
@ -161,7 +161,7 @@ void ProtocolWidget::slotOpenFile( QTreeWidgetItem *item, int )
}
}
QTreeWidgetItem* ProtocolWidget::createCompletedTreewidgetItem(const QString& folder, const SyncFileItem& item)
QTreeWidgetItem *ProtocolWidget::createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item)
{
auto f = FolderMan::instance()->folder(folder);
if (!f) {
@ -186,14 +186,14 @@ QTreeWidgetItem* ProtocolWidget::createCompletedTreewidgetItem(const QString& fo
QIcon icon;
if (item._status == SyncFileItem::NormalError
|| item._status == SyncFileItem::FatalError) {
|| item._status == SyncFileItem::FatalError) {
icon = Theme::instance()->syncStateIcon(SyncResult::Error);
} else if (Progress::isWarningKind(item._status)) {
icon = Theme::instance()->syncStateIcon(SyncResult::Problem);
}
if (ProgressInfo::isSizeDependent(item)) {
columns << Utility::octetsToString( item._size );
columns << Utility::octetsToString(item._size);
}
QTreeWidgetItem *twitem = new QTreeWidgetItem(columns);
@ -206,14 +206,14 @@ QTreeWidgetItem* ProtocolWidget::createCompletedTreewidgetItem(const QString& fo
twitem->setIcon(0, icon);
twitem->setToolTip(0, longTimeStr);
twitem->setToolTip(1, item._file);
twitem->setToolTip(3, message );
twitem->setData(2, Qt::UserRole, folder);
twitem->setToolTip(3, message);
twitem->setData(2, Qt::UserRole, folder);
return twitem;
}
void ProtocolWidget::slotProgressInfo( const QString& folder, const ProgressInfo& progress )
void ProtocolWidget::slotProgressInfo(const QString &folder, const ProgressInfo &progress)
{
if( !progress.isUpdatingEstimates() ) {
if (!progress.isUpdatingEstimates()) {
// The sync is restarting, clean the old items
cleanItems(folder);
} else if (progress.completedFiles() >= progress.totalFiles()) {
@ -224,14 +224,14 @@ void ProtocolWidget::slotProgressInfo( const QString& folder, const ProgressInfo
void ProtocolWidget::slotItemCompleted(const QString &folder, const SyncFileItemPtr &item)
{
QTreeWidgetItem *line = createCompletedTreewidgetItem(folder, *item);
if(line) {
if( item->hasErrorStatus() ) {
if (line) {
if (item->hasErrorStatus()) {
_issueItemView->insertTopLevelItem(0, line);
emit issueItemCountUpdated(_issueItemView->topLevelItemCount());
} else {
// Limit the number of items
int itemCnt = _ui->_treeWidget->topLevelItemCount();
while(itemCnt > 2000) {
while (itemCnt > 2000) {
delete _ui->_treeWidget->takeTopLevelItem(itemCnt - 1);
itemCnt--;
}
@ -241,38 +241,38 @@ void ProtocolWidget::slotItemCompleted(const QString &folder, const SyncFileItem
}
void ProtocolWidget::storeSyncActivity(QTextStream& ts)
void ProtocolWidget::storeSyncActivity(QTextStream &ts)
{
int topLevelItems = _ui->_treeWidget->topLevelItemCount();
for (int i = 0; i < topLevelItems; i++) {
QTreeWidgetItem *child = _ui->_treeWidget->topLevelItem(i);
ts << right
// time stamp
// time stamp
<< qSetFieldWidth(20)
<< child->data(0,Qt::DisplayRole).toString()
// separator
<< child->data(0, Qt::DisplayRole).toString()
// separator
<< qSetFieldWidth(0) << ","
// file name
// file name
<< qSetFieldWidth(64)
<< child->data(1,Qt::DisplayRole).toString()
// separator
<< child->data(1, Qt::DisplayRole).toString()
// separator
<< qSetFieldWidth(0) << ","
// folder
// folder
<< qSetFieldWidth(30)
<< child->data(2, Qt::DisplayRole).toString()
// separator
// separator
<< qSetFieldWidth(0) << ","
// action
// action
<< qSetFieldWidth(15)
<< child->data(3, Qt::DisplayRole).toString()
// separator
// separator
<< qSetFieldWidth(0) << ","
// size
// size
<< qSetFieldWidth(10)
<< child->data(4, Qt::DisplayRole).toString()
<< qSetFieldWidth(0)
@ -280,37 +280,36 @@ void ProtocolWidget::storeSyncActivity(QTextStream& ts)
}
}
void ProtocolWidget::storeSyncIssues(QTextStream& ts)
void ProtocolWidget::storeSyncIssues(QTextStream &ts)
{
int topLevelItems = _issueItemView->topLevelItemCount();
for (int i = 0; i < topLevelItems; i++) {
QTreeWidgetItem *child = _issueItemView->topLevelItem(i);
ts << right
// time stamp
// time stamp
<< qSetFieldWidth(20)
<< child->data(0,Qt::DisplayRole).toString()
// separator
<< child->data(0, Qt::DisplayRole).toString()
// separator
<< qSetFieldWidth(0) << ","
// file name
// file name
<< qSetFieldWidth(64)
<< child->data(1,Qt::DisplayRole).toString()
// separator
<< child->data(1, Qt::DisplayRole).toString()
// separator
<< qSetFieldWidth(0) << ","
// folder
// folder
<< qSetFieldWidth(30)
<< child->data(2, Qt::DisplayRole).toString()
// separator
// separator
<< qSetFieldWidth(0) << ","
// action
// action
<< qSetFieldWidth(15)
<< child->data(3, Qt::DisplayRole).toString()
<< qSetFieldWidth(0)
<< endl;
}
}
}

View 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(QTextStream& ts);
void storeSyncIssues(QTextStream& ts);
void storeSyncActivity(QTextStream &ts);
void storeSyncIssues(QTextStream &ts);
public slots:
void slotProgressInfo( const QString& folder, const ProgressInfo& progress );
void slotItemCompleted( const QString& folder, const SyncFileItemPtr& item);
void slotOpenFile( QTreeWidgetItem* item, int );
void slotProgressInfo(const QString &folder, const ProgressInfo &progress);
void slotItemCompleted(const QString &folder, const SyncFileItemPtr &item);
void slotOpenFile(QTreeWidgetItem *item, int);
protected:
void showEvent(QShowEvent *);
@ -64,10 +64,10 @@ signals:
void issueItemCountUpdated(int);
private:
void setSyncResultStatus(const SyncResult& result );
void cleanItems( const QString& folder );
void setSyncResultStatus(const SyncResult &result);
void cleanItems(const QString &folder);
QTreeWidgetItem* createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item );
QTreeWidgetItem *createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item);
QString timeString(QDateTime dt, QLocale::FormatType format = QLocale::NarrowFormat) const;
@ -75,6 +75,5 @@ private:
Ui::ProtocolWidget *_ui;
QTreeWidget *_issueItemView;
};
}
#endif // PROTOCOLWIDGET_H

View 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);
}

View 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 QString& address);
void setProxyAddress(const QString &address);
QString username() const;
QString password() const;

View File

@ -27,7 +27,7 @@ using namespace OCC;
Q_LOGGING_CATEGORY(lcProxy, "gui.credentials.proxy", QtInfoMsg)
ProxyAuthHandler* ProxyAuthHandler::instance()
ProxyAuthHandler *ProxyAuthHandler::instance()
{
static ProxyAuthHandler inst;
return &inst;
@ -53,8 +53,8 @@ ProxyAuthHandler::~ProxyAuthHandler()
}
void ProxyAuthHandler::handleProxyAuthenticationRequired(
const QNetworkProxy& proxy,
QAuthenticator* authenticator)
const QNetworkProxy &proxy,
QAuthenticator *authenticator)
{
if (!_dialog) {
return;
@ -73,7 +73,7 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired(
// If the user explicitly configured the proxy in the
// network settings, don't ask about it.
if (_configFile->proxyType() == QNetworkProxy::HttpProxy
|| _configFile->proxyType() == QNetworkProxy::Socks5Proxy) {
|| _configFile->proxyType() == QNetworkProxy::Socks5Proxy) {
_blocked = true;
}
}
@ -83,9 +83,9 @@ void ProxyAuthHandler::handleProxyAuthenticationRequired(
}
// Find the responsible QNAM if possible.
QNetworkAccessManager* sending_qnam = 0;
QNetworkAccessManager *sending_qnam = 0;
QWeakPointer<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(QObject* obj)
void ProxyAuthHandler::slotSenderDestroyed(QObject *obj)
{
_gaveCredentialsTo.remove(obj);
}
@ -195,8 +194,8 @@ bool ProxyAuthHandler::getCredsFromKeychain()
_readPasswordJob->setInsecureFallback(false);
_readPasswordJob->setKey(keychainPasswordKey());
_readPasswordJob->setAutoDelete(false);
connect(_readPasswordJob.data(), SIGNAL(finished(QKeychain::Job*)),
SLOT(slotKeychainJobDone()));
connect(_readPasswordJob.data(), SIGNAL(finished(QKeychain::Job *)),
SLOT(slotKeychainJobDone()));
_keychainJobRunning = true;
_readPasswordJob->start();
}
@ -237,13 +236,13 @@ void ProxyAuthHandler::storeCredsInKeychain()
_settings->setValue(keychainUsernameKey(), _username);
WritePasswordJob* job = new WritePasswordJob(Theme::instance()->appName(), this);
WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName(), this);
job->setSettings(_settings.data());
job->setInsecureFallback(false);
job->setKey(keychainPasswordKey());
job->setTextData(_password);
job->setAutoDelete(false);
connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotKeychainJobDone()));
connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotKeychainJobDone()));
_keychainJobRunning = true;
job->start();

View File

@ -47,18 +47,18 @@ class ProxyAuthHandler : public QObject
Q_OBJECT
public:
static ProxyAuthHandler* instance();
static ProxyAuthHandler *instance();
virtual ~ProxyAuthHandler();
public slots:
/// Intended for QNetworkAccessManager::proxyAuthenticationRequired()
void handleProxyAuthenticationRequired(const QNetworkProxy& proxy,
QAuthenticator* authenticator);
void handleProxyAuthenticationRequired(const QNetworkProxy &proxy,
QAuthenticator *authenticator);
private slots:
void slotKeychainJobDone();
void slotSenderDestroyed(QObject*);
void slotSenderDestroyed(QObject *);
private:
ProxyAuthHandler();
@ -107,7 +107,7 @@ private:
/// To distinguish between a new QNAM asking for credentials and credentials
/// failing for an existing QNAM, we keep track of the senders of the
/// proxyAuthRequired signal here.
QSet<QObject*> _gaveCredentialsTo;
QSet<QObject *> _gaveCredentialsTo;
};
} // namespace OCC

View 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();
}
}

View 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

View File

@ -34,24 +34,34 @@
namespace OCC {
class SelectiveSyncTreeViewItem : public QTreeWidgetItem {
class SelectiveSyncTreeViewItem : public QTreeWidgetItem
{
public:
SelectiveSyncTreeViewItem(int type = QTreeWidgetItem::Type)
: QTreeWidgetItem(type) { }
: QTreeWidgetItem(type)
{
}
SelectiveSyncTreeViewItem(const QStringList &strings, int type = QTreeWidgetItem::Type)
: QTreeWidgetItem(strings, type) { }
: QTreeWidgetItem(strings, type)
{
}
SelectiveSyncTreeViewItem(QTreeWidget *view, int type = QTreeWidgetItem::Type)
: QTreeWidgetItem(view, type) { }
: QTreeWidgetItem(view, type)
{
}
SelectiveSyncTreeViewItem(QTreeWidgetItem *parent, int type = QTreeWidgetItem::Type)
: QTreeWidgetItem(parent, type) { }
: QTreeWidgetItem(parent, type)
{
}
private:
bool operator<(const QTreeWidgetItem &other)const {
bool operator<(const QTreeWidgetItem &other) const
{
int column = treeWidget()->sortColumn();
if (column == 1) {
return data(1, Qt::UserRole).toLongLong() < other.data(1, Qt::UserRole).toLongLong();
}
return QTreeWidgetItem::operator <(other);
return QTreeWidgetItem::operator<(other);
}
};
@ -73,10 +83,10 @@ SelectiveSyncWidget::SelectiveSyncWidget(AccountPtr account, QWidget *parent)
layout->addWidget(_folderTree);
connect(_folderTree, SIGNAL(itemExpanded(QTreeWidgetItem*)),
SLOT(slotItemExpanded(QTreeWidgetItem*)));
connect(_folderTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
SLOT(slotItemChanged(QTreeWidgetItem*,int)));
connect(_folderTree, SIGNAL(itemExpanded(QTreeWidgetItem *)),
SLOT(slotItemExpanded(QTreeWidgetItem *)));
connect(_folderTree, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
SLOT(slotItemChanged(QTreeWidgetItem *, int)));
_folderTree->setSortingEnabled(true);
_folderTree->sortByColumn(0, Qt::AscendingOrder);
_folderTree->setColumnCount(2);
@ -84,7 +94,7 @@ SelectiveSyncWidget::SelectiveSyncWidget(AccountPtr account, QWidget *parent)
_folderTree->header()->setSectionResizeMode(0, QHeaderView::QHeaderView::ResizeToContents);
_folderTree->header()->setSectionResizeMode(1, QHeaderView::QHeaderView::ResizeToContents);
#else
_folderTree->header()->resizeSection(0, sizeHint().width()/2);
_folderTree->header()->resizeSection(0, sizeHint().width() / 2);
#endif
_folderTree->header()->setStretchLastSection(true);
_folderTree->headerItem()->setText(0, tr("Name"));
@ -99,18 +109,19 @@ QSize SelectiveSyncWidget::sizeHint() const
void SelectiveSyncWidget::refreshFolders()
{
LsColJob *job = new LsColJob(_account, _folderPath, this);
job->setProperties(QList<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(QTreeWidgetItem* parent, QStringList pathTrail, QString path, qint64 size)
void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path, qint64 size)
{
QFileIconProvider prov;
QIcon folderIcon = prov.icon(QFileIconProvider::Folder);
@ -144,13 +155,13 @@ void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem* parent, QStringList p
parent->setToolTip(0, path);
parent->setData(0, Qt::UserRole, path);
} else {
SelectiveSyncTreeViewItem *item = static_cast<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(QTreeWidgetItem* root) const
QStringList SelectiveSyncWidget::createBlackList(QTreeWidgetItem *root) const
{
if (!root) {
root = _folderTree->topLevelItem(0);
}
if (!root) return QStringList();
if (!root)
return QStringList();
switch(root->checkState(0)) {
switch (root->checkState(0)) {
case Qt::Unchecked:
return QStringList(root->data(0, Qt::UserRole).toString() + "/");
case Qt::Checked:
case Qt::Checked:
return QStringList();
case Qt::PartiallyChecked:
break;
@ -368,7 +383,7 @@ QStringList SelectiveSyncWidget::createBlackList(QTreeWidgetItem* root) const
} else {
// We did not load from the server so we re-use the one from the old black list
QString path = root->data(0, Qt::UserRole).toString();
foreach (const QString & it, _oldBlackList) {
foreach (const QString &it, _oldBlackList) {
if (it.startsWith(path))
result += it;
}
@ -381,28 +396,30 @@ QStringList SelectiveSyncWidget::oldBlackList() const
return _oldBlackList;
}
qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem* root)
qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem *root)
{
if (!root) {
root = _folderTree->topLevelItem(0);
}
if (!root) return -1;
if (!root)
return -1;
switch(root->checkState(0)) {
case Qt::Unchecked:
return 0;
case Qt::Checked:
return root->data(1, Qt::UserRole).toLongLong();
case Qt::PartiallyChecked:
break;
switch (root->checkState(0)) {
case Qt::Unchecked:
return 0;
case Qt::Checked:
return root->data(1, Qt::UserRole).toLongLong();
case Qt::PartiallyChecked:
break;
}
qint64 result = 0;
if (root->childCount()) {
for (int i = 0; i < root->childCount(); ++i) {
auto r = estimatedSize(root->child(i));
if (r < 0) return r;
if (r < 0)
return r;
result += r;
}
} else {
@ -413,25 +430,27 @@ qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem* root)
}
SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, Folder* folder, QWidget* parent, Qt::WindowFlags f)
: QDialog(parent, f), _folder(folder),
_okButton(0) // defined in init()
SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget *parent, Qt::WindowFlags f)
: QDialog(parent, f)
, _folder(folder)
, _okButton(0) // defined in init()
{
bool ok;
init(account);
QStringList selectiveSyncList = _folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
if( ok ) {
_selectiveSync->setFolderInfo(_folder->remotePath(), _folder->alias(),selectiveSyncList);
if (ok) {
_selectiveSync->setFolderInfo(_folder->remotePath(), _folder->alias(), selectiveSyncList);
} else {
_okButton->setEnabled(false);
}
// Make sure we don't get crashes if the folder is destroyed while we are still open
connect(_folder, SIGNAL(destroyed(QObject*)), this, SLOT(deleteLater()));
connect(_folder, SIGNAL(destroyed(QObject *)), this, SLOT(deleteLater()));
}
SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, const QString &folder,
const QStringList& blacklist, QWidget* parent, Qt::WindowFlags f)
: QDialog(parent, f), _folder(0)
const QStringList &blacklist, QWidget *parent, Qt::WindowFlags f)
: QDialog(parent, f)
, _folder(0)
{
init(account);
_selectiveSync->setFolderInfo(folder, folder, blacklist);
@ -457,7 +476,7 @@ void SelectiveSyncDialog::accept()
if (_folder) {
bool ok;
auto oldBlackListSet = _folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok).toSet();
if( ! ok ) {
if (!ok) {
return;
}
QStringList blackList = _selectiveSync->createBlackList();
@ -472,7 +491,7 @@ void SelectiveSyncDialog::accept()
// (the ones that are no longer in the blacklist)
auto blackListSet = blackList.toSet();
auto changes = (oldBlackListSet - blackListSet) + (blackListSet - oldBlackListSet);
foreach(const auto &it, changes) {
foreach (const auto &it, changes) {
_folder->journalDb()->avoidReadFromDbOnNextSync(it);
}
@ -495,6 +514,4 @@ qint64 SelectiveSyncDialog::estimatedSize()
{
return _selectiveSync->estimatedSize();
}
}

View 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, QWidget* parent = 0);
explicit SelectiveSyncWidget(AccountPtr account, QWidget *parent = 0);
/// Returns a list of blacklisted paths, each including the trailing /
QStringList createBlackList(QTreeWidgetItem* root = 0) const;
QStringList createBlackList(QTreeWidgetItem *root = 0) const;
/** Returns the oldBlackList passed into setFolderInfo(), except that
* a "/" entry is expanded to all top-level folder names.
@ -47,18 +48,19 @@ public:
// oldBlackList is a list of excluded paths, each including a trailing /
void setFolderInfo(const QString &folderPath, const QString &rootName,
const QStringList &oldBlackList = QStringList());
const QStringList &oldBlackList = QStringList());
QSize sizeHint() const Q_DECL_OVERRIDE;
private slots:
void slotUpdateDirectories(QStringList);
void slotItemExpanded(QTreeWidgetItem *);
void slotItemChanged(QTreeWidgetItem*,int);
void slotLscolFinishedWithError(QNetworkReply*);
void slotItemChanged(QTreeWidgetItem *, int);
void slotLscolFinishedWithError(QNetworkReply *);
private:
void refreshFolders();
void recursiveInsert(QTreeWidgetItem* parent, QStringList pathTrail, QString path, qint64 size);
void recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path, qint64 size);
AccountPtr _account;
@ -76,14 +78,15 @@ private:
* @brief The SelectiveSyncDialog class
* @ingroup gui
*/
class SelectiveSyncDialog : public QDialog {
class SelectiveSyncDialog : public QDialog
{
Q_OBJECT
public:
// Dialog for a specific folder (used from the account settings button)
explicit SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget* parent = 0, Qt::WindowFlags f = 0);
explicit SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget *parent = 0, Qt::WindowFlags f = 0);
// Dialog for the whole account (Used from the wizard)
explicit SelectiveSyncDialog(AccountPtr account, const QString &folder, const QStringList &blacklist, QWidget* parent = 0, Qt::WindowFlags f = 0);
explicit SelectiveSyncDialog(AccountPtr account, const QString &folder, const QStringList &blacklist, QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual void accept() Q_DECL_OVERRIDE;
@ -94,7 +97,6 @@ public:
qint64 estimatedSize();
private:
void init(const AccountPtr &account);
SelectiveSyncWidget *_selectiveSync;
@ -102,5 +104,4 @@ private:
Folder *_folder;
QPushButton *_okButton;
};
}

View File

@ -20,30 +20,26 @@
#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 QJsonDocument& json, int statusCode)
void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument &json, int statusCode)
{
if( statusCode != 200 ) {
if (statusCode != 200) {
qCWarning(lcServerNotification) << "Notifications failed with status code " << statusCode;
deleteLater();
return;
@ -69,40 +65,39 @@ void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument& j
auto notifies = json.object().value("ocs").toObject().value("data").toArray();
AccountState* ai = qvariant_cast<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();
foreach( auto action, actions) {
foreach (auto action, actions) {
auto actionJson = action.toObject();
ActivityLink al;
al._label = QUrl::fromPercentEncoding(actionJson.value("label").toString().toUtf8());
al._link = actionJson.value("link").toString();
al._verb = actionJson.value("type").toString().toUtf8();
al._link = actionJson.value("link").toString();
al._verb = actionJson.value("type").toString().toUtf8();
al._isPrimary = actionJson.value("primary").toBool();
a._links.append(al);
}
list.append(a);
}
emit newNotificationList( list );
emit newNotificationList(list);
deleteLater();
}
}

View 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 QJsonDocument& json, int statusCode);
void slotNotificationsReceived(const QJsonDocument &json, int statusCode);
private:
QPointer<JsonApiJob> _notificationJob;
};
}
#endif // SERVERNOTIFICATIONHANDLER_H

View File

@ -43,19 +43,19 @@
#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());
if( account && _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;
}
QToolButton* btn = new QToolButton(parent);
QToolButton *btn = new QToolButton(parent);
btn->setDefaultAction(this);
btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
btn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
// btn->setMinimumWidth(qMax<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);

View 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

View 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()
}
}
}
}

View 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

View 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);
}
}
}

View 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

View 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);
}
}

Some files were not shown because too many files have changed in this diff Show More