From: Jocelyn Turcotte Date: Wed, 16 Aug 2017 06:36:52 +0000 (+0200) Subject: Move Utility to a new common static library X-Git-Tag: archive/raspbian/3.16.7-1_deb13u1+rpi1~1^2~701^2~137 X-Git-Url: https://dgit.raspbian.org/?a=commitdiff_plain;h=bfc7ea562de41a7c6b14b7ef9674c8b8e769f096;p=nextcloud-desktop.git Move Utility to a new common static library Now that csync builds as C++, this will avoid having to implement functionalities needed by csync mandatorily in csync itself. This library is built as part of libocsync and symbols exported through it. This requires a relicense of Utility as LGPL. All classes moved into this library from src/libsync will need to be relicensed as well. --- diff --git a/CMakeLists.txt b/CMakeLists.txt index 976f19aec..4b1d4f203 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,7 +41,13 @@ endif() include(Warnings) include(${CMAKE_SOURCE_DIR}/VERSION.cmake) +# For config.h include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}) +# Allows includes based on src/ like #include "common/utility.h" or #include "csync/csync.h" +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_CURRENT_BINARY_DIR}/src +) # disable the crashreporter if libcrashreporter-qt is not available or we're building for ARM if( CMAKE_SYSTEM_PROCESSOR MATCHES "arm" OR NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/3rdparty/libcrashreporter-qt/CMakeLists.txt") @@ -211,13 +217,8 @@ endif() file( GLOB TRANS_FILES ${CMAKE_SOURCE_DIR}/translations/client_*.ts) set(TRANSLATIONS ${TRANS_FILES}) -if(UNIT_TESTING) - # Make sure we set this before recursing into child folders. - set(WITH_TESTING ON) - include(CTest) - enable_testing() - add_subdirectory(test) -endif(UNIT_TESTING) +# Make sure we set this before recursing into child folders. +set(WITH_TESTING ${UNIT_TESTING}) add_subdirectory(src) if(NOT BUILD_LIBRARIES_ONLY) @@ -227,7 +228,14 @@ add_subdirectory(doc/dev) add_subdirectory(admin) endif(NOT BUILD_LIBRARIES_ONLY) +if(UNIT_TESTING) + include(CTest) + enable_testing() + add_subdirectory(test) +endif(UNIT_TESTING) + configure_file(config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h) +configure_file(version.h.in ${CMAKE_CURRENT_BINARY_DIR}/version.h) if(BUILD_OWNCLOUD_OSX_BUNDLE) install(FILES sync-exclude.lst DESTINATION ${OWNCLOUD_OSX_BUNDLE}/Contents/Resources/) diff --git a/src/cmd/simplesslerrorhandler.cpp b/src/cmd/simplesslerrorhandler.cpp index 18a03293a..437438507 100644 --- a/src/cmd/simplesslerrorhandler.cpp +++ b/src/cmd/simplesslerrorhandler.cpp @@ -12,7 +12,7 @@ * for more details. */ #include "configfile.h" -#include "utility.h" +#include "common/utility.h" #include "account.h" #include "simplesslerrorhandler.h" diff --git a/src/common/README b/src/common/README new file mode 100644 index 000000000..16698585c --- /dev/null +++ b/src/common/README @@ -0,0 +1,2 @@ +This folder contains code covered by the CLA being licensed as LGPL. +This allows it to be linked together with the rest of the LGPL code in csync. diff --git a/src/common/common.cmake b/src/common/common.cmake new file mode 100644 index 000000000..a26e76d74 --- /dev/null +++ b/src/common/common.cmake @@ -0,0 +1,6 @@ +# Just list files to build as part of the csync dynamic lib. +# Essentially they could be in the same directory but are separate to +# help keep track of the different code licenses. +set(common_SOURCES + ${CMAKE_CURRENT_LIST_DIR}/utility.cpp +) diff --git a/src/common/utility.cpp b/src/common/utility.cpp new file mode 100644 index 000000000..8bc2f2d35 --- /dev/null +++ b/src/common/utility.cpp @@ -0,0 +1,571 @@ +/* + * Copyright (C) by Klaas Freitag + * Copyright (C) by Daniel Molkentin + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "config.h" + +#include "common/utility.h" +#include "version.h" + +// Note: This file must compile without QtGui +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) +#include +#else +#include +#endif +#if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) +#include +#endif +#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) +#include +#endif + + +#ifdef Q_OS_UNIX +#include +#include +#include +#endif + +#include +#include + +#if defined(Q_OS_WIN) +#include "utility_win.cpp" +#elif defined(Q_OS_MAC) +#include "utility_mac.cpp" +#else +#include "utility_unix.cpp" +#endif + +namespace OCC { + +Q_LOGGING_CATEGORY(lcUtility, "sync.utility", QtInfoMsg) + +bool Utility::writeRandomFile(const QString &fname, int size) +{ + int maxSize = 10 * 10 * 1024; + qsrand(QDateTime::currentMSecsSinceEpoch()); + + if (size == -1) + size = qrand() % maxSize; + + QString randString; + for (int i = 0; i < size; i++) { + int r = qrand() % 128; + randString.append(QChar(r)); + } + + QFile file(fname); + if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { + QTextStream out(&file); + out << randString; + // optional, as QFile destructor will already do it: + file.close(); + return true; + } + return false; +} + +QString Utility::formatFingerprint(const QByteArray &fmhash, bool colonSeparated) +{ + QByteArray hash; + int steps = fmhash.length() / 2; + for (int i = 0; i < steps; i++) { + hash.append(fmhash[i * 2]); + hash.append(fmhash[i * 2 + 1]); + hash.append(' '); + } + + QString fp = QString::fromLatin1(hash.trimmed()); + if (colonSeparated) { + fp.replace(QChar(' '), QChar(':')); + } + + return fp; +} + +void Utility::setupFavLink(const QString &folder) +{ + setupFavLink_private(folder); +} + +QString Utility::octetsToString(qint64 octets) +{ +#define THE_FACTOR 1024 + static const qint64 kb = THE_FACTOR; + static const qint64 mb = THE_FACTOR * kb; + static const qint64 gb = THE_FACTOR * mb; + + QString s; + qreal value = octets; + + // Whether we care about decimals: only for GB/MB and only + // if it's less than 10 units. + bool round = true; + + // do not display terra byte with the current units, as when + // the MB, GB and KB units were made, there was no TB, + // see the JEDEC standard + // https://en.wikipedia.org/wiki/JEDEC_memory_standards + if (octets >= gb) { + s = QCoreApplication::translate("Utility", "%L1 GB"); + value /= gb; + round = false; + } else if (octets >= mb) { + s = QCoreApplication::translate("Utility", "%L1 MB"); + value /= mb; + round = false; + } else if (octets >= kb) { + s = QCoreApplication::translate("Utility", "%L1 KB"); + value /= kb; + } else { + s = QCoreApplication::translate("Utility", "%L1 B"); + } + + if (value > 9.95) + round = true; + + if (round) + return s.arg(qRound(value)); + + return s.arg(value, 0, 'g', 2); +} + +// Qtified version of get_platforms() in csync_owncloud.c +static QLatin1String platform() +{ +#if defined(Q_OS_WIN) + return QLatin1String("Windows"); +#elif defined(Q_OS_MAC) + return QLatin1String("Macintosh"); +#elif defined(Q_OS_LINUX) + return QLatin1String("Linux"); +#elif defined(__DragonFly__) // Q_OS_FREEBSD also defined + return QLatin1String("DragonFlyBSD"); +#elif defined(Q_OS_FREEBSD) || defined(Q_OS_FREEBSD_KERNEL) + return QLatin1String("FreeBSD"); +#elif defined(Q_OS_NETBSD) + return QLatin1String("NetBSD"); +#elif defined(Q_OS_OPENBSD) + return QLatin1String("OpenBSD"); +#elif defined(Q_OS_SOLARIS) + return QLatin1String("Solaris"); +#else + return QLatin1String("Unknown OS"); +#endif +} + +QByteArray Utility::userAgentString() +{ + QString re = QString::fromLatin1("Mozilla/5.0 (%1) mirall/%2") + .arg(platform(), QLatin1String(MIRALL_VERSION_STRING)); + + QLatin1String appName(APPLICATION_SHORTNAME); + + // this constant "ownCloud" is defined in the default OEM theming + // that is used for the standard client. If it is changed there, + // it needs to be adjusted here. + if (appName != QLatin1String("ownCloud")) { + re += QString(" (%1)").arg(appName); + } + return re.toLatin1(); +} + +bool Utility::hasLaunchOnStartup(const QString &appName) +{ + return hasLaunchOnStartup_private(appName); +} + +void Utility::setLaunchOnStartup(const QString &appName, const QString &guiName, bool enable) +{ + setLaunchOnStartup_private(appName, guiName, enable); +} + +qint64 Utility::freeDiskSpace(const QString &path) +{ +#if defined(Q_OS_MAC) || defined(Q_OS_FREEBSD) || defined(Q_OS_FREEBSD_KERNEL) || defined(Q_OS_NETBSD) || defined(Q_OS_OPENBSD) + struct statvfs stat; + if (statvfs(path.toLocal8Bit().data(), &stat) == 0) { + return (qint64)stat.f_bavail * stat.f_frsize; + } +#elif defined(Q_OS_UNIX) + struct statvfs64 stat; + if (statvfs64(path.toLocal8Bit().data(), &stat) == 0) { + return (qint64)stat.f_bavail * stat.f_frsize; + } +#elif defined(Q_OS_WIN) + ULARGE_INTEGER freeBytes; + freeBytes.QuadPart = 0L; + if (GetDiskFreeSpaceEx(reinterpret_cast(path.utf16()), &freeBytes, NULL, NULL)) { + return freeBytes.QuadPart; + } +#endif + return -1; +} + +QString Utility::compactFormatDouble(double value, int prec, const QString &unit) +{ + QLocale locale = QLocale::system(); + QChar decPoint = locale.decimalPoint(); + QString str = locale.toString(value, 'f', prec); + while (str.endsWith('0') || str.endsWith(decPoint)) { + if (str.endsWith(decPoint)) { + str.chop(1); + break; + } + str.chop(1); + } + if (!unit.isEmpty()) + str += (QLatin1Char(' ') + unit); + return str; +} + +QString Utility::escape(const QString &in) +{ +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + return Qt::escape(in); +#else + return in.toHtmlEscaped(); +#endif +} + +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) +// In Qt 4, QThread::sleep functions are protected. +// This is a hack to make them visible in this namespace. +struct QThread : ::QThread +{ + using ::QThread::sleep; + using ::QThread::usleep; +}; +#endif + +void Utility::sleep(int sec) +{ + QThread::sleep(sec); +} + +void Utility::usleep(int usec) +{ + QThread::usleep(usec); +} + +bool Utility::fsCasePreserving() +{ +#ifdef WITH_TESTING + QByteArray env = qgetenv("OWNCLOUD_TEST_CASE_PRESERVING"); + if (!env.isEmpty()) + return env.toInt(); +#endif + + return isWindows() || isMac(); +} + +bool Utility::fileNamesEqual(const QString &fn1, const QString &fn2) +{ + const QDir fd1(fn1); + const QDir fd2(fn2); + + // Attention: If the path does not exist, canonicalPath returns "" + // ONLY use this function with existing pathes. + const QString a = fd1.canonicalPath(); + const QString b = fd2.canonicalPath(); + bool re = !a.isEmpty() && QString::compare(a, b, fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive) == 0; + return re; +} + +QDateTime Utility::qDateTimeFromTime_t(qint64 t) +{ + return QDateTime::fromMSecsSinceEpoch(t * 1000); +} + +qint64 Utility::qDateTimeToTime_t(const QDateTime &t) +{ + return t.toMSecsSinceEpoch() / 1000; +} + +namespace { + struct Period + { + const char *name; + quint64 msec; + + QString description(quint64 value) const + { + return QCoreApplication::translate( + "Utility", name, 0, QCoreApplication::UnicodeUTF8, + value); + } + }; +// QTBUG-3945 and issue #4855: QT_TRANSLATE_NOOP does not work with plural form because lupdate +// limitation unless we fake more arguments +// (it must be in the form ("context", "source", "comment", n) +#undef QT_TRANSLATE_NOOP +#define QT_TRANSLATE_NOOP(ctx, str, ...) str + Q_DECL_CONSTEXPR Period periods[] = { + { QT_TRANSLATE_NOOP("Utility", "%n year(s)", 0, _), 365 * 24 * 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n month(s)", 0, _), 30 * 24 * 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n day(s)", 0, _), 24 * 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n hour(s)", 0, _), 3600 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n minute(s)", 0, _), 60 * 1000LL }, + { QT_TRANSLATE_NOOP("Utility", "%n second(s)", 0, _), 1000LL }, + { 0, 0 } + }; +} // anonymous namespace + +QString Utility::durationToDescriptiveString2(quint64 msecs) +{ + int p = 0; + while (periods[p + 1].name && msecs < periods[p].msec) { + p++; + } + + auto firstPart = periods[p].description(int(msecs / periods[p].msec)); + + if (!periods[p + 1].name) { + return firstPart; + } + + quint64 secondPartNum = qRound(double(msecs % periods[p].msec) / periods[p + 1].msec); + + if (secondPartNum == 0) { + return firstPart; + } + + return QCoreApplication::translate("Utility", "%1 %2").arg(firstPart, periods[p + 1].description(secondPartNum)); +} + +QString Utility::durationToDescriptiveString1(quint64 msecs) +{ + int p = 0; + while (periods[p + 1].name && msecs < periods[p].msec) { + p++; + } + + quint64 amount = qRound(double(msecs) / periods[p].msec); + return periods[p].description(amount); +} + +QString Utility::fileNameForGuiUse(const QString &fName) +{ + if (isMac()) { + QString n(fName); + return n.replace(QChar(':'), QChar('/')); + } + return fName; +} + +bool Utility::hasDarkSystray() +{ + return hasDarkSystray_private(); +} + + +QString Utility::platformName() +{ + QString re("Windows"); + +#if QT_VERSION < QT_VERSION_CHECK(5, 4, 0) + if (isMac()) { + re = QLatin1String("MacOSX"); + } else if (isLinux()) { + re = QLatin1String("Linux"); + } else if (isBSD()) { + re = QLatin1String("BSD"); + } else if (isUnix()) { + re = QLatin1String("Unix"); + } +#else + re = QSysInfo::prettyProductName(); +#endif + return re; +} + +void Utility::crash() +{ + volatile int *a = (int *)(NULL); + *a = 1; +} + +// read the output of the owncloud --version command from the owncloud +// version that is on disk. This works for most versions of the client, +// because clients that do not yet know the --version flag return the +// version in the first line of the help output :-) +// +// This version only delivers output on linux, as Mac and Win get their +// restarting from the installer. +QByteArray Utility::versionOfInstalledBinary(const QString &command) +{ + QByteArray re; + if (isLinux()) { + QString binary(command); + if (binary.isEmpty()) { + binary = qApp->arguments()[0]; + } + QStringList params; + params << QLatin1String("--version"); + QProcess process; + process.start(binary, params); + process.waitForFinished(); // sets current thread to sleep and waits for pingProcess end + re = process.readAllStandardOutput(); + int newline = re.indexOf(QChar('\n')); + if (newline > 0) { + re.truncate(newline); + } + } + return re; +} + +QString Utility::timeAgoInWords(const QDateTime &dt, const QDateTime &from) +{ + QDateTime now = QDateTime::currentDateTimeUtc(); + + if (from.isValid()) { + now = from; + } + + if (dt.daysTo(now) > 0) { + int dtn = dt.daysTo(now); + return QObject::tr("%n day(s) ago", "", dtn); + } else { + qint64 secs = dt.secsTo(now); + if (secs < 0) { + return QObject::tr("in the future"); + } + if (floor(secs / 3600.0) > 0) { + int hours = floor(secs / 3600.0); + return (QObject::tr("%n hour(s) ago", "", hours)); + } else { + int minutes = qRound(secs / 60.0); + if (minutes == 0) { + if (secs < 5) { + return QObject::tr("now"); + } else { + return QObject::tr("Less than a minute ago"); + } + } + return (QObject::tr("%n minute(s) ago", "", minutes)); + } + } + return QObject::tr("Some time ago"); +} + +/* --------------------------------------------------------------------------- */ + +static const char STOPWATCH_END_TAG[] = "_STOPWATCH_END"; + +void Utility::StopWatch::start() +{ + _startTime = QDateTime::currentDateTime(); + _timer.start(); +} + +quint64 Utility::StopWatch::stop() +{ + addLapTime(QLatin1String(STOPWATCH_END_TAG)); + quint64 duration = _timer.elapsed(); + _timer.invalidate(); + return duration; +} + +void Utility::StopWatch::reset() +{ + _timer.invalidate(); + _startTime.setMSecsSinceEpoch(0); + _lapTimes.clear(); +} + +quint64 Utility::StopWatch::addLapTime(const QString &lapName) +{ + if (!_timer.isValid()) { + start(); + } + quint64 re = _timer.elapsed(); + _lapTimes[lapName] = re; + return re; +} + +QDateTime Utility::StopWatch::startTime() const +{ + return _startTime; +} + +QDateTime Utility::StopWatch::timeOfLap(const QString &lapName) const +{ + quint64 t = durationOfLap(lapName); + if (t) { + QDateTime re(_startTime); + return re.addMSecs(t); + } + + return QDateTime(); +} + +quint64 Utility::StopWatch::durationOfLap(const QString &lapName) const +{ + return _lapTimes.value(lapName, 0); +} + +void Utility::sortFilenames(QStringList &fileNames) +{ +#if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) + QCollator collator; + collator.setNumericMode(true); + collator.setCaseSensitivity(Qt::CaseInsensitive); + qSort(fileNames.begin(), fileNames.end(), collator); +#elif QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + fileNames.sort(Qt::CaseInsensitive); +#else + fileNames.sort(); +#endif +} + +QUrl Utility::concatUrlPath(const QUrl &url, const QString &concatPath, + const QList> &queryItems) +{ + QString path = url.path(); + if (!concatPath.isEmpty()) { + // avoid '//' + if (path.endsWith('/') && concatPath.startsWith('/')) { + path.chop(1); + } // avoid missing '/' + else if (!path.endsWith('/') && !concatPath.startsWith('/')) { + path += QLatin1Char('/'); + } + path += concatPath; // put the complete path together + } + + QUrl tmpUrl = url; + tmpUrl.setPath(path); + if (queryItems.size() > 0) { + tmpUrl.setQueryItems(queryItems); + } + return tmpUrl; +} + +} // namespace OCC diff --git a/src/common/utility.h b/src/common/utility.h new file mode 100644 index 000000000..c1063a45c --- /dev/null +++ b/src/common/utility.h @@ -0,0 +1,225 @@ +/* + * Copyright (C) by Klaas Freitag + * Copyright (C) by Daniel Molkentin + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef UTILITY_H +#define UTILITY_H + +#include "ocsynclib.h" +#include +#include +#include +#include +#include +#include +#include +#include + +class QSettings; + +namespace OCC { + +Q_DECLARE_LOGGING_CATEGORY(lcUtility) + +/** \addtogroup libsync + * @{ + */ +namespace Utility { + OCSYNC_EXPORT void sleep(int sec); + OCSYNC_EXPORT void usleep(int usec); + OCSYNC_EXPORT QString formatFingerprint(const QByteArray &, bool colonSeparated = true); + OCSYNC_EXPORT void setupFavLink(const QString &folder); + OCSYNC_EXPORT bool writeRandomFile(const QString &fname, int size = -1); + OCSYNC_EXPORT QString octetsToString(qint64 octets); + OCSYNC_EXPORT QByteArray userAgentString(); + OCSYNC_EXPORT bool hasLaunchOnStartup(const QString &appName); + OCSYNC_EXPORT void setLaunchOnStartup(const QString &appName, const QString &guiName, bool launch); + + /** + * Return the amount of free space available. + * + * \a path must point to a directory + */ + OCSYNC_EXPORT qint64 freeDiskSpace(const QString &path); + + /** + * @brief compactFormatDouble - formats a double value human readable. + * + * @param value the value to format. + * @param prec the precision. + * @param unit an optional unit that is appended if present. + * @return the formatted string. + */ + OCSYNC_EXPORT QString compactFormatDouble(double value, int prec, const QString &unit = QString::null); + + // porting methods + OCSYNC_EXPORT QString escape(const QString &); + + // conversion function QDateTime <-> time_t (because the ones builtin work on only unsigned 32bit) + OCSYNC_EXPORT QDateTime qDateTimeFromTime_t(qint64 t); + OCSYNC_EXPORT qint64 qDateTimeToTime_t(const QDateTime &t); + + /** + * @brief Convert milliseconds duration to human readable string. + * @param quint64 msecs the milliseconds to convert to string. + * @return an HMS representation of the milliseconds value. + * + * durationToDescriptiveString1 describes the duration in a single + * unit, like "5 minutes" or "2 days". + * + * durationToDescriptiveString2 uses two units where possible, so + * "5 minutes 43 seconds" or "1 month 3 days". + */ + OCSYNC_EXPORT QString durationToDescriptiveString1(quint64 msecs); + OCSYNC_EXPORT QString durationToDescriptiveString2(quint64 msecs); + + /** + * @brief hasDarkSystray - determines whether the systray is dark or light. + * + * Use this to check if the OS has a dark or a light systray. + * + * The value might change during the execution of the program + * (e.g. on OS X 10.10). + * + * @return bool which is true for systems with dark systray. + */ + OCSYNC_EXPORT bool hasDarkSystray(); + + // convenience OS detection methods + inline bool isWindows(); + inline bool isMac(); + inline bool isUnix(); + inline bool isLinux(); // use with care + inline bool isBSD(); // use with care, does not match OS X + + OCSYNC_EXPORT QString platformName(); + // crash helper for --debug + OCSYNC_EXPORT void crash(); + + // Case preserving file system underneath? + // if this function returns true, the file system is case preserving, + // that means "test" means the same as "TEST" for filenames. + // if false, the two cases are two different files. + OCSYNC_EXPORT bool fsCasePreserving(); + + // Check if two pathes that MUST exist are equal. This function + // uses QDir::canonicalPath() to judge and cares for the systems + // case sensitivity. + OCSYNC_EXPORT bool fileNamesEqual(const QString &fn1, const QString &fn2); + + // Call the given command with the switch --version and rerun the first line + // of the output. + // If command is empty, the function calls the running application which, on + // Linux, might have changed while this one is running. + // For Mac and Windows, it returns QString() + OCSYNC_EXPORT QByteArray versionOfInstalledBinary(const QString &command = QString()); + + OCSYNC_EXPORT QString fileNameForGuiUse(const QString &fName); + + /** + * @brief timeAgoInWords - human readable time span + * + * Use this to get a string that describes the timespan between the first and + * the second timestamp in a human readable and understandable form. + * + * If the second parameter is ommitted, the current time is used. + */ + OCSYNC_EXPORT QString timeAgoInWords(const QDateTime &dt, const QDateTime &from = QDateTime()); + + class OCSYNC_EXPORT StopWatch + { + private: + QMap _lapTimes; + QDateTime _startTime; + QElapsedTimer _timer; + + public: + void start(); + quint64 stop(); + quint64 addLapTime(const QString &lapName); + void reset(); + + // out helpers, return the measured times. + QDateTime startTime() const; + QDateTime timeOfLap(const QString &lapName) const; + quint64 durationOfLap(const QString &lapName) const; + }; + + /** + * @brief Sort a QStringList in a way that's appropriate for filenames + */ + OCSYNC_EXPORT void sortFilenames(QStringList &fileNames); + + /** Appends concatPath and queryItems to the url */ + OCSYNC_EXPORT QUrl concatUrlPath( + const QUrl &url, const QString &concatPath, + const QList> &queryItems = (QList>())); + + /** Returns a new settings pre-set in a specific group. The Settings will be created + with the given parent. If no parent is specified, the caller must destroy the settings */ + OCSYNC_EXPORT std::unique_ptr settingsWithGroup(const QString &group, QObject *parent = 0); +} +/** @} */ // \addtogroup + +inline bool Utility::isWindows() +{ +#ifdef Q_OS_WIN + return true; +#else + return false; +#endif +} + +inline bool Utility::isMac() +{ +#ifdef Q_OS_MAC + return true; +#else + return false; +#endif +} + +inline bool Utility::isUnix() +{ +#ifdef Q_OS_UNIX + return true; +#else + return false; +#endif +} + +inline bool Utility::isLinux() +{ +#if defined(Q_OS_LINUX) + return true; +#else + return false; +#endif +} + +inline bool Utility::isBSD() +{ +#if defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) || defined(Q_OS_OPENBSD) + return true; +#else + return false; +#endif +} + +} +#endif // UTILITY_H diff --git a/src/common/utility_mac.cpp b/src/common/utility_mac.cpp new file mode 100644 index 000000000..6c789b17a --- /dev/null +++ b/src/common/utility_mac.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (C) by Daniel Molkentin + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +namespace OCC { + +static void setupFavLink_private(const QString &folder) +{ + // Finder: Place under "Places"/"Favorites" on the left sidebar + CFStringRef folderCFStr = CFStringCreateWithCString(0, folder.toUtf8().data(), kCFStringEncodingUTF8); + CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); + + LSSharedFileListRef placesItems = LSSharedFileListCreate(0, kLSSharedFileListFavoriteItems, 0); + if (placesItems) { + //Insert an item to the list. + LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(placesItems, + kLSSharedFileListItemLast, 0, 0, + urlRef, 0, 0); + if (item) + CFRelease(item); + } + CFRelease(placesItems); + CFRelease(folderCFStr); + CFRelease(urlRef); +} + +bool hasLaunchOnStartup_private(const QString &) +{ + // this is quite some duplicate code with setLaunchOnStartup, at some point we should fix this FIXME. + bool returnValue = false; + QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath(); + CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); + CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); + LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); + if (loginItems) { + // We need to iterate over the items and check which one is "ours". + UInt32 seedValue; + CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue); + CFStringRef appUrlRefString = CFURLGetString(urlRef); // no need for release + for (int i = 0; i < CFArrayGetCount(itemsArray); i++) { + LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); + CFURLRef itemUrlRef = NULL; + + if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { + CFStringRef itemUrlString = CFURLGetString(itemUrlRef); + if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { + returnValue = true; + } + CFRelease(itemUrlRef); + } + } + CFRelease(itemsArray); + } + CFRelease(loginItems); + CFRelease(folderCFStr); + CFRelease(urlRef); + return returnValue; +} + +void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) +{ + Q_UNUSED(appName) + Q_UNUSED(guiName) + QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath(); + CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); + CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); + LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); + + if (loginItems && enable) { + //Insert an item to the list. + LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems, + kLSSharedFileListItemLast, 0, 0, + urlRef, 0, 0); + if (item) + CFRelease(item); + CFRelease(loginItems); + } else if (loginItems && !enable) { + // We need to iterate over the items and check which one is "ours". + UInt32 seedValue; + CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue); + CFStringRef appUrlRefString = CFURLGetString(urlRef); + for (int i = 0; i < CFArrayGetCount(itemsArray); i++) { + LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); + CFURLRef itemUrlRef = NULL; + + if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { + CFStringRef itemUrlString = CFURLGetString(itemUrlRef); + if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { + LSSharedFileListItemRemove(loginItems, item); // remove it! + } + CFRelease(itemUrlRef); + } + } + CFRelease(itemsArray); + CFRelease(loginItems); + }; + + CFRelease(folderCFStr); + CFRelease(urlRef); +} + +static bool hasDarkSystray_private() +{ + bool returnValue = false; + CFStringRef interfaceStyleKey = CFSTR("AppleInterfaceStyle"); + CFStringRef interfaceStyle = NULL; + CFStringRef darkInterfaceStyle = CFSTR("Dark"); + interfaceStyle = (CFStringRef)CFPreferencesCopyAppValue(interfaceStyleKey, + kCFPreferencesCurrentApplication); + if (interfaceStyle != NULL) { + returnValue = (kCFCompareEqualTo == CFStringCompare(interfaceStyle, darkInterfaceStyle, 0)); + CFRelease(interfaceStyle); + } + return returnValue; +} + +} // namespace OCC diff --git a/src/common/utility_unix.cpp b/src/common/utility_unix.cpp new file mode 100644 index 000000000..eecef1778 --- /dev/null +++ b/src/common/utility_unix.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (C) by Klaas Freitag + * Copyright (C) by Daniel Molkentin + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) +#include +#endif + +namespace OCC { + +static void setupFavLink_private(const QString &folder) +{ + // Nautilus: add to ~/.gtk-bookmarks + QFile gtkBookmarks(QDir::homePath() + QLatin1String("/.gtk-bookmarks")); + QByteArray folderUrl = "file://" + folder.toUtf8(); + if (gtkBookmarks.open(QFile::ReadWrite)) { + QByteArray places = gtkBookmarks.readAll(); + if (!places.contains(folderUrl)) { + places += folderUrl; + gtkBookmarks.reset(); + gtkBookmarks.write(places + '\n'); + } + } +} + +// returns the autostart directory the linux way +// and respects the XDG_CONFIG_HOME env variable +QString getUserAutostartDir_private() +{ +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + QString config = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation); +#else + QString config = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); + + if (config.isEmpty()) { + config = QDir::homePath() + QLatin1String("/.config"); + } +#endif + config += QLatin1String("/autostart/"); + return config; +} + +bool hasLaunchOnStartup_private(const QString &appName) +{ + QString desktopFileLocation = getUserAutostartDir_private() + appName + QLatin1String(".desktop"); + return QFile::exists(desktopFileLocation); +} + +void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) +{ + QString userAutoStartPath = getUserAutostartDir_private(); + QString desktopFileLocation = userAutoStartPath + appName + QLatin1String(".desktop"); + if (enable) { + if (!QDir().exists(userAutoStartPath) && !QDir().mkpath(userAutoStartPath)) { + qCWarning(lcUtility) << "Could not create autostart folder"; + return; + } + QFile iniFile(desktopFileLocation); + if (!iniFile.open(QIODevice::WriteOnly)) { + qCWarning(lcUtility) << "Could not write auto start entry" << desktopFileLocation; + return; + } + QTextStream ts(&iniFile); + ts.setCodec("UTF-8"); + ts << QLatin1String("[Desktop Entry]") << endl + << QLatin1String("Name=") << guiName << endl + << QLatin1String("GenericName=") << QLatin1String("File Synchronizer") << endl + << QLatin1String("Exec=") << QCoreApplication::applicationFilePath() << endl + << QLatin1String("Terminal=") << "false" << endl + << QLatin1String("Icon=") << appName.toLower() << endl // always use lowercase for icons + << QLatin1String("Categories=") << QLatin1String("Network") << endl + << QLatin1String("Type=") << QLatin1String("Application") << endl + << QLatin1String("StartupNotify=") << "false" << endl + << QLatin1String("X-GNOME-Autostart-enabled=") << "true" << endl; + } else { + if (!QFile::remove(desktopFileLocation)) { + qCWarning(lcUtility) << "Could not remove autostart desktop file"; + } + } +} + +static inline bool hasDarkSystray_private() +{ + return true; +} + +} // namespace OCC diff --git a/src/common/utility_win.cpp b/src/common/utility_win.cpp new file mode 100644 index 000000000..f7fef1019 --- /dev/null +++ b/src/common/utility_win.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (C) by Daniel Molkentin + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define _WIN32_WINNT 0x0600 +#define WINVER 0x0600 +#include +#include +#include +#include +#include +#include +#include + +static const char runPathC[] = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"; + +namespace OCC { + +static void setupFavLink_private(const QString &folder) +{ + // First create a Desktop.ini so that the folder and favorite link show our application's icon. + QFile desktopIni(folder + QLatin1String("/Desktop.ini")); + if (desktopIni.exists()) { + qCWarning(lcUtility) << desktopIni.fileName() << "already exists, not overwriting it to set the folder icon."; + } else { + qCInfo(lcUtility) << "Creating" << desktopIni.fileName() << "to set a folder icon in Explorer."; + desktopIni.open(QFile::WriteOnly); + desktopIni.write("[.ShellClassInfo]\r\nIconResource="); + desktopIni.write(QDir::toNativeSeparators(qApp->applicationFilePath()).toUtf8()); + desktopIni.write(",0\r\n"); + desktopIni.close(); + } + + // Windows Explorer: Place under "Favorites" (Links) + QString linkName; + QDir folderDir(QDir::fromNativeSeparators(folder)); + + /* Use new WINAPI functions */ + PWSTR path; + + if (SHGetKnownFolderPath(FOLDERID_Links, 0, NULL, &path) == S_OK) { + QString links = QDir::fromNativeSeparators(QString::fromWCharArray(path)); + linkName = QDir(links).filePath(folderDir.dirName() + QLatin1String(".lnk")); + CoTaskMemFree(path); + } + qCInfo(lcUtility) << "Creating favorite link from" << folder << "to" << linkName; + if (!QFile::link(folder, linkName)) + qCWarning(lcUtility) << "linking" << folder << "to" << linkName << "failed!"; +} + + +bool hasLaunchOnStartup_private(const QString &appName) +{ + QString runPath = QLatin1String(runPathC); + QSettings settings(runPath, QSettings::NativeFormat); + return settings.contains(appName); +} + +void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) +{ + Q_UNUSED(guiName); + QString runPath = QLatin1String(runPathC); + QSettings settings(runPath, QSettings::NativeFormat); + if (enable) { + settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/', '\\')); + } else { + settings.remove(appName); + } +} + +static inline bool hasDarkSystray_private() +{ + return true; +} + +} // namespace OCC diff --git a/src/csync/CMakeLists.txt b/src/csync/CMakeLists.txt index 09f320202..b9c772507 100644 --- a/src/csync/CMakeLists.txt +++ b/src/csync/CMakeLists.txt @@ -20,6 +20,7 @@ include(MacroCopyFile) find_package(SQLite3 3.8.0 REQUIRED) include(ConfigureChecks.cmake) +include(../common/common.cmake) include_directories(${CMAKE_CURRENT_BINARY_DIR}) @@ -117,11 +118,10 @@ include_directories( ${CSYNC_PRIVATE_INCLUDE_DIRS} ) -add_library(${CSYNC_LIBRARY} SHARED ${csync_SRCS}) +add_library(${CSYNC_LIBRARY} SHARED ${common_SOURCES} ${csync_SRCS}) #add_library(${CSYNC_LIBRARY}_static STATIC ${csync_SRCS}) generate_export_header( ${CSYNC_LIBRARY} - BASE_NAME ${CSYNC_LIBRARY} EXPORT_MACRO_NAME OCSYNC_EXPORT EXPORT_FILE_NAME ocsynclib.h ) @@ -129,6 +129,16 @@ generate_export_header( ${CSYNC_LIBRARY} target_link_libraries(${CSYNC_LIBRARY} ${CSYNC_LINK_LIBRARIES}) #target_link_libraries(${CSYNC_LIBRARY}_static ${CSYNC_LINK_LIBRARIES}) +find_package(Qt5Core REQUIRED) +qt5_use_modules(${CSYNC_LIBRARY} Core) + +# For src/common/utility_mac.cpp +if (APPLE) + find_library(FOUNDATION_LIBRARY NAMES Foundation) + find_library(CORESERVICES_LIBRARY NAMES CoreServices) + target_link_libraries(${CSYNC_LIBRARY} ${FOUNDATION_LIBRARY} ${CORESERVICES_LIBRARY}) +endif() + set_target_properties( ${CSYNC_LIBRARY} PROPERTIES diff --git a/src/csync/std/CMakeLists.txt b/src/csync/std/CMakeLists.txt index 8cfd48531..ef7a25bd3 100644 --- a/src/csync/std/CMakeLists.txt +++ b/src/csync/std/CMakeLists.txt @@ -36,9 +36,5 @@ include_directories( add_library(${CSTDLIB_LIBRARY} STATIC ${cstdlib_SRCS}) if(NOT WIN32) add_definitions( -fPIC ) - qt5_use_modules(${CSTDLIB_LIBRARY} Core) -endif() -if(NOT HAVE_FNMATCH AND WIN32) - # needed for PathMatchSpec for our fnmatch replacement - target_link_libraries(${CSTDLIB_LIBRARY} ${SHLWAPI_LIBRARY}) endif() +qt5_use_modules(${CSTDLIB_LIBRARY} Core) diff --git a/src/gui/accountmanager.cpp b/src/gui/accountmanager.cpp index fe8d98127..a62e1f30f 100644 --- a/src/gui/accountmanager.cpp +++ b/src/gui/accountmanager.cpp @@ -13,6 +13,7 @@ */ #include "accountmanager.h" +#include "configfile.h" #include "sslerrordialog.h" #include "proxyauthhandler.h" #include @@ -47,7 +48,7 @@ AccountManager *AccountManager::instance() bool AccountManager::restore() { - auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); + auto settings = ConfigFile::settingsWithGroup(QLatin1String(accountsC)); if (settings->status() != QSettings::NoError) { qCWarning(lcAccountManager) << "Could not read settings from" << settings->fileName() << settings->status(); @@ -81,7 +82,7 @@ bool AccountManager::restoreFromLegacySettings() << Theme::instance()->appName(); // try to open the correctly themed settings - auto settings = Utility::settingsWithGroup(Theme::instance()->appName()); + auto settings = ConfigFile::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 @@ -134,7 +135,7 @@ bool AccountManager::restoreFromLegacySettings() void AccountManager::save(bool saveCredentials) { - auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); + auto settings = ConfigFile::settingsWithGroup(QLatin1String(accountsC)); settings->setValue(QLatin1String(versionC), 2); foreach (const auto &acc, _accounts) { settings->beginGroup(acc->account()->id()); @@ -150,7 +151,7 @@ void AccountManager::save(bool saveCredentials) void AccountManager::saveAccount(Account *a) { qCInfo(lcAccountManager) << "Saving account" << a->url().toString(); - auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); + auto settings = ConfigFile::settingsWithGroup(QLatin1String(accountsC)); settings->beginGroup(a->id()); saveAccountHelper(a, *settings, false); // don't save credentials they might not have been loaded yet settings->endGroup(); @@ -162,7 +163,7 @@ void AccountManager::saveAccount(Account *a) void AccountManager::saveAccountState(AccountState *a) { qCInfo(lcAccountManager) << "Saving account state" << a->account()->url().toString(); - auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); + auto settings = ConfigFile::settingsWithGroup(QLatin1String(accountsC)); settings->beginGroup(a->account()->id()); a->writeToSettings(*settings); settings->endGroup(); @@ -308,7 +309,7 @@ void AccountManager::deleteAccount(AccountState *account) account->account()->credentials()->forgetSensitiveData(); QFile::remove(account->account()->cookieJarPath()); - auto settings = Utility::settingsWithGroup(QLatin1String(accountsC)); + auto settings = ConfigFile::settingsWithGroup(QLatin1String(accountsC)); settings->remove(account->account()->id()); emit accountRemoved(account); diff --git a/src/gui/accountsettings.cpp b/src/gui/accountsettings.cpp index a5a5e105d..453ace412 100644 --- a/src/gui/accountsettings.cpp +++ b/src/gui/accountsettings.cpp @@ -21,7 +21,7 @@ #include "folderwizard.h" #include "folderstatusmodel.h" #include "folderstatusdelegate.h" -#include "utility.h" +#include "common/utility.h" #include "application.h" #include "configfile.h" #include "account.h" diff --git a/src/gui/accountstate.cpp b/src/gui/accountstate.cpp index 63316f6d2..a13b8c227 100644 --- a/src/gui/accountstate.cpp +++ b/src/gui/accountstate.cpp @@ -356,7 +356,7 @@ void AccountState::slotCredentialsAsked(AbstractCredentials *credentials) std::unique_ptr AccountState::settings() { - auto s = Utility::settingsWithGroup(QLatin1String("Accounts")); + auto s = ConfigFile::settingsWithGroup(QLatin1String("Accounts")); s->beginGroup(_account->id()); return s; } diff --git a/src/gui/accountstate.h b/src/gui/accountstate.h index ce36c94fb..03f17795f 100644 --- a/src/gui/accountstate.h +++ b/src/gui/accountstate.h @@ -17,8 +17,8 @@ #define ACCOUNTINFO_H #include +#include #include -#include "utility.h" #include "connectionvalidator.h" #include "creds/abstractcredentials.h" #include diff --git a/src/gui/activityitemdelegate.cpp b/src/gui/activityitemdelegate.cpp index 8de739eb7..ee59e422d 100644 --- a/src/gui/activityitemdelegate.cpp +++ b/src/gui/activityitemdelegate.cpp @@ -18,7 +18,6 @@ #include "folderstatusmodel.h" #include "folderman.h" #include "accountstate.h" -#include "utility.h" #include #include diff --git a/src/gui/activitywidget.cpp b/src/gui/activitywidget.cpp index c4e82884b..d9acc999f 100644 --- a/src/gui/activitywidget.cpp +++ b/src/gui/activitywidget.cpp @@ -21,7 +21,6 @@ #include "activitywidget.h" #include "syncresult.h" #include "logger.h" -#include "utility.h" #include "theme.h" #include "folderman.h" #include "syncfileitem.h" diff --git a/src/gui/application.cpp b/src/gui/application.cpp index f06054b3f..37d24cec7 100644 --- a/src/gui/application.cpp +++ b/src/gui/application.cpp @@ -30,7 +30,6 @@ #include "socketapi.h" #include "sslerrordialog.h" #include "theme.h" -#include "utility.h" #include "clientproxy.h" #include "sharedialog.h" #include "accountmanager.h" diff --git a/src/gui/creds/shibbolethcredentials.cpp b/src/gui/creds/shibbolethcredentials.cpp index b7fca6dd3..44c0e217a 100644 --- a/src/gui/creds/shibbolethcredentials.cpp +++ b/src/gui/creds/shibbolethcredentials.cpp @@ -26,6 +26,7 @@ #include "accessmanager.h" #include "account.h" +#include "configfile.h" #include "theme.h" #include "cookiejar.h" #include "owncloudgui.h" @@ -131,7 +132,7 @@ void ShibbolethCredentials::fetchFromKeychain() } else { _url = _account->url(); ReadPasswordJob *job = new ReadPasswordJob(Theme::instance()->appName()); - job->setSettings(Utility::settingsWithGroup(Theme::instance()->appName(), job).release()); + job->setSettings(ConfigFile::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 *))); @@ -250,7 +251,7 @@ void ShibbolethCredentials::slotReadJobDone(QKeychain::Job *job) addToCookieJar(_shibCookie); } // access - job->setSettings(Utility::settingsWithGroup(Theme::instance()->appName(), job).release()); + job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release()); _ready = true; _stillValid = true; @@ -309,7 +310,7 @@ QByteArray ShibbolethCredentials::shibCookieName() void ShibbolethCredentials::storeShibCookie(const QNetworkCookie &cookie) { WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName()); - job->setSettings(Utility::settingsWithGroup(Theme::instance()->appName(), job).release()); + job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release()); // we don't really care if it works... //connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteJobDone(QKeychain::Job*))); job->setKey(keychainKey(_account->url().toString(), user())); @@ -320,7 +321,7 @@ void ShibbolethCredentials::storeShibCookie(const QNetworkCookie &cookie) void ShibbolethCredentials::removeShibCookie() { DeletePasswordJob *job = new DeletePasswordJob(Theme::instance()->appName()); - job->setSettings(Utility::settingsWithGroup(Theme::instance()->appName(), job).release()); + job->setSettings(ConfigFile::settingsWithGroup(Theme::instance()->appName(), job).release()); job->setKey(keychainKey(_account->url().toString(), user())); job->start(); } diff --git a/src/gui/folder.cpp b/src/gui/folder.cpp index 4ca5de844..6446a06ed 100644 --- a/src/gui/folder.cpp +++ b/src/gui/folder.cpp @@ -24,7 +24,6 @@ #include "networkjobs.h" #include "syncjournalfilerecord.h" #include "syncresult.h" -#include "utility.h" #include "clientproxy.h" #include "syncengine.h" #include "syncrunfilelog.h" diff --git a/src/gui/folderman.cpp b/src/gui/folderman.cpp index a1f1286a9..bb56db2ef 100644 --- a/src/gui/folderman.cpp +++ b/src/gui/folderman.cpp @@ -199,7 +199,7 @@ int FolderMan::setupFolders() { unloadAndDeleteAllFolders(); - auto settings = Utility::settingsWithGroup(QLatin1String("Accounts")); + auto settings = ConfigFile::settingsWithGroup(QLatin1String("Accounts")); const auto accountsWithSettings = settings->childGroups(); if (accountsWithSettings.isEmpty()) { int r = setupFoldersMigration(); diff --git a/src/gui/folderstatusdelegate.cpp b/src/gui/folderstatusdelegate.cpp index da41cbf93..1d5ad0a14 100644 --- a/src/gui/folderstatusdelegate.cpp +++ b/src/gui/folderstatusdelegate.cpp @@ -18,7 +18,6 @@ #include "folderstatusmodel.h" #include "folderman.h" #include "accountstate.h" -#include "utility.h" #include #include diff --git a/src/gui/folderstatusmodel.cpp b/src/gui/folderstatusmodel.cpp index ac32dc865..59ad76589 100644 --- a/src/gui/folderstatusmodel.cpp +++ b/src/gui/folderstatusmodel.cpp @@ -15,7 +15,6 @@ #include "folderstatusmodel.h" #include "folderman.h" #include "accountstate.h" -#include "utility.h" #include "asserts.h" #include #include diff --git a/src/gui/generalsettings.cpp b/src/gui/generalsettings.cpp index 853fd730b..a79036771 100644 --- a/src/gui/generalsettings.cpp +++ b/src/gui/generalsettings.cpp @@ -18,7 +18,6 @@ #include "theme.h" #include "configfile.h" #include "application.h" -#include "utility.h" #include "configfile.h" #include "owncloudsetupwizard.h" #include "accountmanager.h" diff --git a/src/gui/issueswidget.cpp b/src/gui/issueswidget.cpp index 4803f17a4..f434f3cd2 100644 --- a/src/gui/issueswidget.cpp +++ b/src/gui/issueswidget.cpp @@ -21,7 +21,6 @@ #include "configfile.h" #include "syncresult.h" #include "logger.h" -#include "utility.h" #include "theme.h" #include "folderman.h" #include "syncfileitem.h" diff --git a/src/gui/main.cpp b/src/gui/main.cpp index 4c5970a57..4ee4201ab 100644 --- a/src/gui/main.cpp +++ b/src/gui/main.cpp @@ -23,7 +23,7 @@ #include "application.h" #include "theme.h" -#include "utility.h" +#include "common/utility.h" #include "cocoainitializer.h" #include "updater/updater.h" diff --git a/src/gui/networksettings.cpp b/src/gui/networksettings.cpp index ff99524e1..2f35614a1 100644 --- a/src/gui/networksettings.cpp +++ b/src/gui/networksettings.cpp @@ -18,7 +18,6 @@ #include "theme.h" #include "configfile.h" #include "application.h" -#include "utility.h" #include "configfile.h" #include "folderman.h" diff --git a/src/gui/notificationwidget.cpp b/src/gui/notificationwidget.cpp index 7d1132c6a..0457857b8 100644 --- a/src/gui/notificationwidget.cpp +++ b/src/gui/notificationwidget.cpp @@ -14,7 +14,7 @@ #include "notificationwidget.h" #include "QProgressIndicator.h" -#include "utility.h" +#include "common/utility.h" #include "asserts.h" #include diff --git a/src/gui/openfilemanager.cpp b/src/gui/openfilemanager.cpp index d06402eca..e466bdc49 100644 --- a/src/gui/openfilemanager.cpp +++ b/src/gui/openfilemanager.cpp @@ -14,7 +14,7 @@ */ #include "openfilemanager.h" -#include "utility.h" +#include "common/utility.h" #include #include #include diff --git a/src/gui/owncloudgui.cpp b/src/gui/owncloudgui.cpp index 65350f367..cb0cafbd8 100644 --- a/src/gui/owncloudgui.cpp +++ b/src/gui/owncloudgui.cpp @@ -17,7 +17,6 @@ #include "theme.h" #include "folderman.h" #include "configfile.h" -#include "utility.h" #include "progressdispatcher.h" #include "owncloudsetupwizard.h" #include "sharedialog.h" diff --git a/src/gui/owncloudsetupwizard.cpp b/src/gui/owncloudsetupwizard.cpp index dcd510f78..3ee02c73a 100644 --- a/src/gui/owncloudsetupwizard.cpp +++ b/src/gui/owncloudsetupwizard.cpp @@ -24,7 +24,6 @@ #include "owncloudsetupwizard.h" #include "configfile.h" #include "folderman.h" -#include "utility.h" #include "accessmanager.h" #include "account.h" #include "networkjobs.h" diff --git a/src/gui/protocolwidget.cpp b/src/gui/protocolwidget.cpp index 2f177a1c6..c55ab6789 100644 --- a/src/gui/protocolwidget.cpp +++ b/src/gui/protocolwidget.cpp @@ -21,7 +21,6 @@ #include "configfile.h" #include "syncresult.h" #include "logger.h" -#include "utility.h" #include "theme.h" #include "folderman.h" #include "syncfileitem.h" diff --git a/src/gui/socketapi.cpp b/src/gui/socketapi.cpp index f2616d378..11a971128 100644 --- a/src/gui/socketapi.cpp +++ b/src/gui/socketapi.cpp @@ -20,7 +20,6 @@ #include "configfile.h" #include "folderman.h" #include "folder.h" -#include "utility.h" #include "theme.h" #include "syncjournalfilerecord.h" #include "syncengine.h" diff --git a/src/gui/sslbutton.cpp b/src/gui/sslbutton.cpp index 89401c31e..cf6a2af7d 100644 --- a/src/gui/sslbutton.cpp +++ b/src/gui/sslbutton.cpp @@ -15,7 +15,6 @@ #include "sslbutton.h" #include "account.h" #include "accountstate.h" -#include "utility.h" #include "theme.h" #include diff --git a/src/gui/sslerrordialog.cpp b/src/gui/sslerrordialog.cpp index 4f6be75d6..809be80aa 100644 --- a/src/gui/sslerrordialog.cpp +++ b/src/gui/sslerrordialog.cpp @@ -12,7 +12,6 @@ * for more details. */ #include "configfile.h" -#include "utility.h" #include "sslerrordialog.h" #include diff --git a/src/gui/syncrunfilelog.cpp b/src/gui/syncrunfilelog.cpp index d0a5259f1..79099cd66 100644 --- a/src/gui/syncrunfilelog.cpp +++ b/src/gui/syncrunfilelog.cpp @@ -15,7 +15,7 @@ #include #include "syncrunfilelog.h" -#include "utility.h" +#include "common/utility.h" #include "filesystem.h" #include diff --git a/src/gui/updater/ocupdater.cpp b/src/gui/updater/ocupdater.cpp index bac0da503..b904ed189 100644 --- a/src/gui/updater/ocupdater.cpp +++ b/src/gui/updater/ocupdater.cpp @@ -14,7 +14,7 @@ #include "theme.h" #include "configfile.h" -#include "utility.h" +#include "common/utility.h" #include "accessmanager.h" #include "updater/ocupdater.h" diff --git a/src/gui/updater/sparkleupdater_mac.mm b/src/gui/updater/sparkleupdater_mac.mm index 96704e81f..1b0a48648 100644 --- a/src/gui/updater/sparkleupdater_mac.mm +++ b/src/gui/updater/sparkleupdater_mac.mm @@ -20,8 +20,6 @@ #include "updater/sparkleupdater.h" -#include "utility.h" - // Does not work yet @interface DelegateObject : NSObject - (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle; diff --git a/src/gui/updater/updater.cpp b/src/gui/updater/updater.cpp index 2529b261a..8294bb4be 100644 --- a/src/gui/updater/updater.cpp +++ b/src/gui/updater/updater.cpp @@ -19,9 +19,9 @@ #include "updater/sparkleupdater.h" #include "updater/ocupdater.h" -#include "version.h" #include "theme.h" -#include "utility.h" +#include "common/utility.h" +#include "version.h" #include "config.h" diff --git a/src/gui/wizard/owncloudconnectionmethoddialog.cpp b/src/gui/wizard/owncloudconnectionmethoddialog.cpp index f0d670480..6bb865ffe 100644 --- a/src/gui/wizard/owncloudconnectionmethoddialog.cpp +++ b/src/gui/wizard/owncloudconnectionmethoddialog.cpp @@ -14,7 +14,6 @@ */ #include "wizard/owncloudconnectionmethoddialog.h" -#include "utility.h" #include namespace OCC { diff --git a/src/libsync/CMakeLists.txt b/src/libsync/CMakeLists.txt index 865dad895..a475aa3c0 100644 --- a/src/libsync/CMakeLists.txt +++ b/src/libsync/CMakeLists.txt @@ -1,8 +1,6 @@ project(libsync) set(CMAKE_AUTOMOC TRUE) -configure_file( version.h.in "${CMAKE_CURRENT_BINARY_DIR}/version.h" ) - include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) # csync is required. include_directories(${CMAKE_SOURCE_DIR}/src/csync @@ -59,7 +57,6 @@ set(libsync_SRCS syncjournalfilerecord.cpp syncresult.cpp theme.cpp - utility.cpp ownsql.cpp checksums.cpp excludedfiles.cpp diff --git a/src/libsync/accessmanager.cpp b/src/libsync/accessmanager.cpp index fb131b02c..67603f623 100644 --- a/src/libsync/accessmanager.cpp +++ b/src/libsync/accessmanager.cpp @@ -25,7 +25,7 @@ #include "cookiejar.h" #include "accessmanager.h" -#include "utility.h" +#include "common/utility.h" namespace OCC { diff --git a/src/libsync/account.h b/src/libsync/account.h index de1cd0293..fa2ccb8f9 100644 --- a/src/libsync/account.h +++ b/src/libsync/account.h @@ -28,7 +28,7 @@ #include #include -#include "utility.h" +#include "common/utility.h" #include #include "capabilities.h" diff --git a/src/libsync/bandwidthmanager.cpp b/src/libsync/bandwidthmanager.cpp index 2cd8d70a6..97cbddd21 100644 --- a/src/libsync/bandwidthmanager.cpp +++ b/src/libsync/bandwidthmanager.cpp @@ -16,7 +16,7 @@ #include "propagatedownload.h" #include "propagateupload.h" #include "propagatorjobs.h" -#include "utility.h" +#include "common/utility.h" #ifdef Q_OS_WIN #include diff --git a/src/libsync/clientproxy.h b/src/libsync/clientproxy.h index 923f060f7..169e1fb6e 100644 --- a/src/libsync/clientproxy.h +++ b/src/libsync/clientproxy.h @@ -21,7 +21,8 @@ #include #include -#include "utility.h" +#include "common/utility.h" +#include "owncloudlib.h" namespace OCC { diff --git a/src/libsync/configfile.cpp b/src/libsync/configfile.cpp index a3bab5f1c..0fa6b77ff 100644 --- a/src/libsync/configfile.cpp +++ b/src/libsync/configfile.cpp @@ -16,7 +16,7 @@ #include "configfile.h" #include "theme.h" -#include "utility.h" +#include "common/utility.h" #include "asserts.h" #include "creds/abstractcredentials.h" @@ -703,4 +703,19 @@ void ConfigFile::setCertificatePasswd(const QString &cPasswd) settings.setValue(QLatin1String(certPasswd), cPasswd); settings.sync(); } + +Q_GLOBAL_STATIC(QString, g_configFileName) + +std::unique_ptr ConfigFile::settingsWithGroup(const QString &group, QObject *parent) +{ + if (g_configFileName()->isEmpty()) { + // cache file name + ConfigFile cfg; + *g_configFileName() = cfg.configFile(); + } + std::unique_ptr settings(new QSettings(*g_configFileName(), QSettings::IniFormat, parent)); + settings->beginGroup(group); + return settings; +} + } diff --git a/src/libsync/configfile.h b/src/libsync/configfile.h index 912b66a04..b9eda8eb0 100644 --- a/src/libsync/configfile.h +++ b/src/libsync/configfile.h @@ -16,7 +16,9 @@ #define CONFIGFILE_H #include "owncloudlib.h" +#include #include +#include #include #include @@ -137,6 +139,10 @@ public: QString certificatePasswd() const; void setCertificatePasswd(const QString &cPasswd); + /** Returns a new settings pre-set in a specific group. The Settings will be created + with the given parent. If no parent is specified, the caller must destroy the settings */ + static std::unique_ptr settingsWithGroup(const QString &group, QObject *parent = 0); + protected: QVariant getPolicySetting(const QString &policy, const QVariant &defaultValue = QVariant()) const; void storeData(const QString &group, const QString &key, const QVariant &value); diff --git a/src/libsync/creds/credentialscommon.cpp b/src/libsync/creds/credentialscommon.cpp index 58b3cc24f..b56b8193d 100644 --- a/src/libsync/creds/credentialscommon.cpp +++ b/src/libsync/creds/credentialscommon.cpp @@ -21,7 +21,7 @@ #include "creds/credentialscommon.h" -#include "utility.h" +#include "common/utility.h" #include "account.h" #include "syncengine.h" diff --git a/src/libsync/creds/httpcredentials.cpp b/src/libsync/creds/httpcredentials.cpp index 0f71f445e..53215de2a 100644 --- a/src/libsync/creds/httpcredentials.cpp +++ b/src/libsync/creds/httpcredentials.cpp @@ -25,7 +25,7 @@ #include "account.h" #include "accessmanager.h" -#include "utility.h" +#include "configfile.h" #include "theme.h" #include "syncengine.h" #include "creds/credentialscommon.h" @@ -94,7 +94,7 @@ private: static void addSettingsToJob(Account *account, QKeychain::Job *job) { Q_UNUSED(account); - auto settings = Utility::settingsWithGroup(Theme::instance()->appName()); + auto settings = ConfigFile::settingsWithGroup(Theme::instance()->appName()); settings->setParent(job); // make the job parent to make setting deleted properly job->setSettings(settings.release()); } diff --git a/src/libsync/creds/tokencredentials.cpp b/src/libsync/creds/tokencredentials.cpp index 2008542f5..c7e43bf8c 100644 --- a/src/libsync/creds/tokencredentials.cpp +++ b/src/libsync/creds/tokencredentials.cpp @@ -21,7 +21,7 @@ #include "account.h" #include "accessmanager.h" -#include "utility.h" +#include "common/utility.h" #include "theme.h" #include "creds/credentialscommon.h" #include "creds/tokencredentials.h" diff --git a/src/libsync/excludedfiles.cpp b/src/libsync/excludedfiles.cpp index 289164efb..62c4711ad 100644 --- a/src/libsync/excludedfiles.cpp +++ b/src/libsync/excludedfiles.cpp @@ -14,7 +14,7 @@ #include "config.h" #include "excludedfiles.h" -#include "utility.h" +#include "common/utility.h" #include diff --git a/src/libsync/filesystem.cpp b/src/libsync/filesystem.cpp index 8299fcc04..4625eed04 100644 --- a/src/libsync/filesystem.cpp +++ b/src/libsync/filesystem.cpp @@ -14,7 +14,7 @@ #include "filesystem.h" -#include "utility.h" +#include "common/utility.h" #include #include #include diff --git a/src/libsync/logger.h b/src/libsync/logger.h index 555abe52f..bf73009a9 100644 --- a/src/libsync/logger.h +++ b/src/libsync/logger.h @@ -22,7 +22,9 @@ #include #include -#include "utility.h" +#include "common/utility.h" +#include "logger.h" +#include "owncloudlib.h" namespace OCC { diff --git a/src/libsync/owncloudpropagator.cpp b/src/libsync/owncloudpropagator.cpp index 17ab9faca..2dcc7a26d 100644 --- a/src/libsync/owncloudpropagator.cpp +++ b/src/libsync/owncloudpropagator.cpp @@ -23,7 +23,7 @@ #include "propagateremotemkdir.h" #include "propagatorjobs.h" #include "configfile.h" -#include "utility.h" +#include "common/utility.h" #include "account.h" #include "asserts.h" diff --git a/src/libsync/owncloudtheme.cpp b/src/libsync/owncloudtheme.cpp index 4f30571b2..9a932eefc 100644 --- a/src/libsync/owncloudtheme.cpp +++ b/src/libsync/owncloudtheme.cpp @@ -24,9 +24,9 @@ #endif #include -#include "version.h" #include "config.h" -#include "utility.h" +#include "common/utility.h" +#include "version.h" namespace OCC { diff --git a/src/libsync/ownsql.cpp b/src/libsync/ownsql.cpp index 69dae7847..759f1981d 100644 --- a/src/libsync/ownsql.cpp +++ b/src/libsync/ownsql.cpp @@ -21,7 +21,7 @@ #include #include "ownsql.h" -#include "utility.h" +#include "common/utility.h" #include "asserts.h" #define SQLITE_SLEEP_TIME_USEC 100000 diff --git a/src/libsync/propagatedownload.cpp b/src/libsync/propagatedownload.cpp index 2a6ca1439..f5b199024 100644 --- a/src/libsync/propagatedownload.cpp +++ b/src/libsync/propagatedownload.cpp @@ -19,7 +19,7 @@ #include "account.h" #include "syncjournaldb.h" #include "syncjournalfilerecord.h" -#include "utility.h" +#include "common/utility.h" #include "filesystem.h" #include "propagatorjobs.h" #include "checksums.h" diff --git a/src/libsync/propagateupload.cpp b/src/libsync/propagateupload.cpp index 3032bb65f..ac6c68259 100644 --- a/src/libsync/propagateupload.cpp +++ b/src/libsync/propagateupload.cpp @@ -19,7 +19,7 @@ #include "account.h" #include "syncjournaldb.h" #include "syncjournalfilerecord.h" -#include "utility.h" +#include "common/utility.h" #include "filesystem.h" #include "propagatorjobs.h" #include "checksums.h" diff --git a/src/libsync/propagateuploadng.cpp b/src/libsync/propagateuploadng.cpp index 7717203a1..00e3d0524 100644 --- a/src/libsync/propagateuploadng.cpp +++ b/src/libsync/propagateuploadng.cpp @@ -19,7 +19,7 @@ #include "account.h" #include "syncjournaldb.h" #include "syncjournalfilerecord.h" -#include "utility.h" +#include "common/utility.h" #include "filesystem.h" #include "propagatorjobs.h" #include "syncengine.h" diff --git a/src/libsync/propagateuploadv1.cpp b/src/libsync/propagateuploadv1.cpp index 74a5f6e52..c1182bb70 100644 --- a/src/libsync/propagateuploadv1.cpp +++ b/src/libsync/propagateuploadv1.cpp @@ -19,7 +19,7 @@ #include "account.h" #include "syncjournaldb.h" #include "syncjournalfilerecord.h" -#include "utility.h" +#include "common/utility.h" #include "filesystem.h" #include "propagatorjobs.h" #include "checksums.h" diff --git a/src/libsync/propagatorjobs.cpp b/src/libsync/propagatorjobs.cpp index 65d7ef86a..1bdee68ae 100644 --- a/src/libsync/propagatorjobs.cpp +++ b/src/libsync/propagatorjobs.cpp @@ -16,7 +16,7 @@ #include "propagatorjobs.h" #include "owncloudpropagator_p.h" #include "propagateremotemove.h" -#include "utility.h" +#include "common/utility.h" #include "syncjournaldb.h" #include "syncjournalfilerecord.h" #include "filesystem.h" diff --git a/src/libsync/syncengine.h b/src/libsync/syncengine.h index a275618a4..50e52f6f4 100644 --- a/src/libsync/syncengine.h +++ b/src/libsync/syncengine.h @@ -34,7 +34,7 @@ #include "excludedfiles.h" #include "syncfileitem.h" #include "progressdispatcher.h" -#include "utility.h" +#include "common/utility.h" #include "syncfilestatustracker.h" #include "accountfwd.h" #include "discoveryphase.h" diff --git a/src/libsync/syncjournaldb.cpp b/src/libsync/syncjournaldb.cpp index e46d35db6..6706fb65e 100644 --- a/src/libsync/syncjournaldb.cpp +++ b/src/libsync/syncjournaldb.cpp @@ -23,7 +23,7 @@ #include "syncjournaldb.h" #include "syncjournalfilerecord.h" -#include "utility.h" +#include "common/utility.h" #include "version.h" #include "filesystem.h" #include "asserts.h" diff --git a/src/libsync/syncjournaldb.h b/src/libsync/syncjournaldb.h index 62295f62e..931588dfa 100644 --- a/src/libsync/syncjournaldb.h +++ b/src/libsync/syncjournaldb.h @@ -20,7 +20,7 @@ #include #include -#include "utility.h" +#include "common/utility.h" #include "ownsql.h" #include "syncjournalfilerecord.h" diff --git a/src/libsync/syncjournalfilerecord.cpp b/src/libsync/syncjournalfilerecord.cpp index 024c32746..9c68e646c 100644 --- a/src/libsync/syncjournalfilerecord.cpp +++ b/src/libsync/syncjournalfilerecord.cpp @@ -14,7 +14,7 @@ #include "syncjournalfilerecord.h" #include "syncfileitem.h" -#include "utility.h" +#include "common/utility.h" #include "filesystem.h" #include diff --git a/src/libsync/theme.cpp b/src/libsync/theme.cpp index 1d1391b1f..978efc9cb 100644 --- a/src/libsync/theme.cpp +++ b/src/libsync/theme.cpp @@ -13,9 +13,9 @@ */ #include "theme.h" -#include "version.h" #include "config.h" -#include "utility.h" +#include "common/utility.h" +#include "version.h" #include #ifndef TOKEN_AUTH_ONLY diff --git a/src/libsync/utility.cpp b/src/libsync/utility.cpp deleted file mode 100644 index c73b48d91..000000000 --- a/src/libsync/utility.cpp +++ /dev/null @@ -1,628 +0,0 @@ -/* - * Copyright (C) by Klaas Freitag - * Copyright (C) by Daniel Molkentin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - */ -#include "config.h" - -#include "utility.h" - -#include "version.h" -#include "configfile.h" - -// Note: This file must compile without QtGui -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) -#include -#else -#include -#endif -#if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) -#include -#endif -#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0) -#include -#endif - - -#ifdef Q_OS_UNIX -#include -#include -#include -#endif - -#include -#include - -#if defined(Q_OS_WIN) -#include "utility_win.cpp" -#elif defined(Q_OS_MAC) -#include "utility_mac.cpp" -#else -#include "utility_unix.cpp" -#endif - -namespace OCC { - -Q_LOGGING_CATEGORY(lcUtility, "sync.utility", QtInfoMsg) - -bool Utility::writeRandomFile(const QString &fname, int size) -{ - int maxSize = 10 * 10 * 1024; - qsrand(QDateTime::currentMSecsSinceEpoch()); - - if (size == -1) - size = qrand() % maxSize; - - QString randString; - for (int i = 0; i < size; i++) { - int r = qrand() % 128; - randString.append(QChar(r)); - } - - QFile file(fname); - if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { - QTextStream out(&file); - out << randString; - // optional, as QFile destructor will already do it: - file.close(); - return true; - } - return false; -} - -QString Utility::formatFingerprint(const QByteArray &fmhash, bool colonSeparated) -{ - QByteArray hash; - int steps = fmhash.length() / 2; - for (int i = 0; i < steps; i++) { - hash.append(fmhash[i * 2]); - hash.append(fmhash[i * 2 + 1]); - hash.append(' '); - } - - QString fp = QString::fromLatin1(hash.trimmed()); - if (colonSeparated) { - fp.replace(QChar(' '), QChar(':')); - } - - return fp; -} - -void Utility::setupFavLink(const QString &folder) -{ - setupFavLink_private(folder); -} - -QString Utility::octetsToString(qint64 octets) -{ -#define THE_FACTOR 1024 - static const qint64 kb = THE_FACTOR; - static const qint64 mb = THE_FACTOR * kb; - static const qint64 gb = THE_FACTOR * mb; - - QString s; - qreal value = octets; - - // Whether we care about decimals: only for GB/MB and only - // if it's less than 10 units. - bool round = true; - - // do not display terra byte with the current units, as when - // the MB, GB and KB units were made, there was no TB, - // see the JEDEC standard - // https://en.wikipedia.org/wiki/JEDEC_memory_standards - if (octets >= gb) { - s = QCoreApplication::translate("Utility", "%L1 GB"); - value /= gb; - round = false; - } else if (octets >= mb) { - s = QCoreApplication::translate("Utility", "%L1 MB"); - value /= mb; - round = false; - } else if (octets >= kb) { - s = QCoreApplication::translate("Utility", "%L1 KB"); - value /= kb; - } else { - s = QCoreApplication::translate("Utility", "%L1 B"); - } - - if (value > 9.95) - round = true; - - if (round) - return s.arg(qRound(value)); - - return s.arg(value, 0, 'g', 2); -} - -// Qtified version of get_platforms() in csync_owncloud.c -static QLatin1String platform() -{ -#if defined(Q_OS_WIN) - return QLatin1String("Windows"); -#elif defined(Q_OS_MAC) - return QLatin1String("Macintosh"); -#elif defined(Q_OS_LINUX) - return QLatin1String("Linux"); -#elif defined(__DragonFly__) // Q_OS_FREEBSD also defined - return QLatin1String("DragonFlyBSD"); -#elif defined(Q_OS_FREEBSD) || defined(Q_OS_FREEBSD_KERNEL) - return QLatin1String("FreeBSD"); -#elif defined(Q_OS_NETBSD) - return QLatin1String("NetBSD"); -#elif defined(Q_OS_OPENBSD) - return QLatin1String("OpenBSD"); -#elif defined(Q_OS_SOLARIS) - return QLatin1String("Solaris"); -#else - return QLatin1String("Unknown OS"); -#endif -} - -QByteArray Utility::userAgentString() -{ - QString re = QString::fromLatin1("Mozilla/5.0 (%1) mirall/%2") - .arg(platform(), QLatin1String(MIRALL_VERSION_STRING)); - - QLatin1String appName(APPLICATION_SHORTNAME); - - // this constant "ownCloud" is defined in the default OEM theming - // that is used for the standard client. If it is changed there, - // it needs to be adjusted here. - if (appName != QLatin1String("ownCloud")) { - re += QString(" (%1)").arg(appName); - } - return re.toLatin1(); -} - -bool Utility::hasLaunchOnStartup(const QString &appName) -{ - return hasLaunchOnStartup_private(appName); -} - -void Utility::setLaunchOnStartup(const QString &appName, const QString &guiName, bool enable) -{ - setLaunchOnStartup_private(appName, guiName, enable); -} - -qint64 Utility::freeDiskSpace(const QString &path) -{ -#if defined(Q_OS_MAC) || defined(Q_OS_FREEBSD) || defined(Q_OS_FREEBSD_KERNEL) || defined(Q_OS_NETBSD) || defined(Q_OS_OPENBSD) - struct statvfs stat; - if (statvfs(path.toLocal8Bit().data(), &stat) == 0) { - return (qint64)stat.f_bavail * stat.f_frsize; - } -#elif defined(Q_OS_UNIX) - struct statvfs64 stat; - if (statvfs64(path.toLocal8Bit().data(), &stat) == 0) { - return (qint64)stat.f_bavail * stat.f_frsize; - } -#elif defined(Q_OS_WIN) - ULARGE_INTEGER freeBytes; - freeBytes.QuadPart = 0L; - if (GetDiskFreeSpaceEx(reinterpret_cast(path.utf16()), &freeBytes, NULL, NULL)) { - return freeBytes.QuadPart; - } -#endif - return -1; -} - -QString Utility::compactFormatDouble(double value, int prec, const QString &unit) -{ - QLocale locale = QLocale::system(); - QChar decPoint = locale.decimalPoint(); - QString str = locale.toString(value, 'f', prec); - while (str.endsWith('0') || str.endsWith(decPoint)) { - if (str.endsWith(decPoint)) { - str.chop(1); - break; - } - str.chop(1); - } - if (!unit.isEmpty()) - str += (QLatin1Char(' ') + unit); - return str; -} - -QString Utility::escape(const QString &in) -{ -#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) - return Qt::escape(in); -#else - return in.toHtmlEscaped(); -#endif -} - -#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) -// In Qt 4, QThread::sleep functions are protected. -// This is a hack to make them visible in this namespace. -struct QThread : ::QThread -{ - using ::QThread::sleep; - using ::QThread::usleep; -}; -#endif - -void Utility::sleep(int sec) -{ - QThread::sleep(sec); -} - -void Utility::usleep(int usec) -{ - QThread::usleep(usec); -} - -bool Utility::fsCasePreserving() -{ -#ifdef WITH_TESTING - QByteArray env = qgetenv("OWNCLOUD_TEST_CASE_PRESERVING"); - if (!env.isEmpty()) - return env.toInt(); -#endif - - return isWindows() || isMac(); -} - -bool Utility::fileNamesEqual(const QString &fn1, const QString &fn2) -{ - const QDir fd1(fn1); - const QDir fd2(fn2); - - // Attention: If the path does not exist, canonicalPath returns "" - // ONLY use this function with existing pathes. - const QString a = fd1.canonicalPath(); - const QString b = fd2.canonicalPath(); - bool re = !a.isEmpty() && QString::compare(a, b, fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive) == 0; - return re; -} - -QDateTime Utility::qDateTimeFromTime_t(qint64 t) -{ - return QDateTime::fromMSecsSinceEpoch(t * 1000); -} - -qint64 Utility::qDateTimeToTime_t(const QDateTime &t) -{ - return t.toMSecsSinceEpoch() / 1000; -} - -namespace { - struct Period - { - const char *name; - quint64 msec; - - QString description(quint64 value) const - { - return QCoreApplication::translate( - "Utility", name, 0, QCoreApplication::UnicodeUTF8, - value); - } - }; -// QTBUG-3945 and issue #4855: QT_TRANSLATE_NOOP does not work with plural form because lupdate -// limitation unless we fake more arguments -// (it must be in the form ("context", "source", "comment", n) -#undef QT_TRANSLATE_NOOP -#define QT_TRANSLATE_NOOP(ctx, str, ...) str - Q_DECL_CONSTEXPR Period periods[] = { - { QT_TRANSLATE_NOOP("Utility", "%n year(s)", 0, _), 365 * 24 * 3600 * 1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n month(s)", 0, _), 30 * 24 * 3600 * 1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n day(s)", 0, _), 24 * 3600 * 1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n hour(s)", 0, _), 3600 * 1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n minute(s)", 0, _), 60 * 1000LL }, - { QT_TRANSLATE_NOOP("Utility", "%n second(s)", 0, _), 1000LL }, - { 0, 0 } - }; -} // anonymous namespace - -QString Utility::durationToDescriptiveString2(quint64 msecs) -{ - int p = 0; - while (periods[p + 1].name && msecs < periods[p].msec) { - p++; - } - - auto firstPart = periods[p].description(int(msecs / periods[p].msec)); - - if (!periods[p + 1].name) { - return firstPart; - } - - quint64 secondPartNum = qRound(double(msecs % periods[p].msec) / periods[p + 1].msec); - - if (secondPartNum == 0) { - return firstPart; - } - - return QCoreApplication::translate("Utility", "%1 %2").arg(firstPart, periods[p + 1].description(secondPartNum)); -} - -QString Utility::durationToDescriptiveString1(quint64 msecs) -{ - int p = 0; - while (periods[p + 1].name && msecs < periods[p].msec) { - p++; - } - - quint64 amount = qRound(double(msecs) / periods[p].msec); - return periods[p].description(amount); -} - -QString Utility::fileNameForGuiUse(const QString &fName) -{ - if (isMac()) { - QString n(fName); - return n.replace(QChar(':'), QChar('/')); - } - return fName; -} - -bool Utility::hasDarkSystray() -{ - return hasDarkSystray_private(); -} - - -bool Utility::isWindows() -{ -#ifdef Q_OS_WIN - return true; -#else - return false; -#endif -} - -bool Utility::isMac() -{ -#ifdef Q_OS_MAC - return true; -#else - return false; -#endif -} - -bool Utility::isUnix() -{ -#ifdef Q_OS_UNIX - return true; -#else - return false; -#endif -} - -bool Utility::isLinux() -{ -#if defined(Q_OS_LINUX) - return true; -#else - return false; -#endif -} - -bool Utility::isBSD() -{ -#if defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) || defined(Q_OS_OPENBSD) - return true; -#else - return false; -#endif -} - -QString Utility::platformName() -{ - QString re("Windows"); - -#if QT_VERSION < QT_VERSION_CHECK(5, 4, 0) - if (isMac()) { - re = QLatin1String("MacOSX"); - } else if (isLinux()) { - re = QLatin1String("Linux"); - } else if (isBSD()) { - re = QLatin1String("BSD"); - } else if (isUnix()) { - re = QLatin1String("Unix"); - } -#else - re = QSysInfo::prettyProductName(); -#endif - return re; -} - -void Utility::crash() -{ - volatile int *a = (int *)(NULL); - *a = 1; -} - -// read the output of the owncloud --version command from the owncloud -// version that is on disk. This works for most versions of the client, -// because clients that do not yet know the --version flag return the -// version in the first line of the help output :-) -// -// This version only delivers output on linux, as Mac and Win get their -// restarting from the installer. -QByteArray Utility::versionOfInstalledBinary(const QString &command) -{ - QByteArray re; - if (isLinux()) { - QString binary(command); - if (binary.isEmpty()) { - binary = qApp->arguments()[0]; - } - QStringList params; - params << QLatin1String("--version"); - QProcess process; - process.start(binary, params); - process.waitForFinished(); // sets current thread to sleep and waits for pingProcess end - re = process.readAllStandardOutput(); - int newline = re.indexOf(QChar('\n')); - if (newline > 0) { - re.truncate(newline); - } - } - return re; -} - -QString Utility::timeAgoInWords(const QDateTime &dt, const QDateTime &from) -{ - QDateTime now = QDateTime::currentDateTimeUtc(); - - if (from.isValid()) { - now = from; - } - - if (dt.daysTo(now) > 0) { - int dtn = dt.daysTo(now); - return QObject::tr("%n day(s) ago", "", dtn); - } else { - qint64 secs = dt.secsTo(now); - if (secs < 0) { - return QObject::tr("in the future"); - } - if (floor(secs / 3600.0) > 0) { - int hours = floor(secs / 3600.0); - return (QObject::tr("%n hour(s) ago", "", hours)); - } else { - int minutes = qRound(secs / 60.0); - if (minutes == 0) { - if (secs < 5) { - return QObject::tr("now"); - } else { - return QObject::tr("Less than a minute ago"); - } - } - return (QObject::tr("%n minute(s) ago", "", minutes)); - } - } - return QObject::tr("Some time ago"); -} - -/* --------------------------------------------------------------------------- */ - -static const char STOPWATCH_END_TAG[] = "_STOPWATCH_END"; - -void Utility::StopWatch::start() -{ - _startTime = QDateTime::currentDateTime(); - _timer.start(); -} - -quint64 Utility::StopWatch::stop() -{ - addLapTime(QLatin1String(STOPWATCH_END_TAG)); - quint64 duration = _timer.elapsed(); - _timer.invalidate(); - return duration; -} - -void Utility::StopWatch::reset() -{ - _timer.invalidate(); - _startTime.setMSecsSinceEpoch(0); - _lapTimes.clear(); -} - -quint64 Utility::StopWatch::addLapTime(const QString &lapName) -{ - if (!_timer.isValid()) { - start(); - } - quint64 re = _timer.elapsed(); - _lapTimes[lapName] = re; - return re; -} - -QDateTime Utility::StopWatch::startTime() const -{ - return _startTime; -} - -QDateTime Utility::StopWatch::timeOfLap(const QString &lapName) const -{ - quint64 t = durationOfLap(lapName); - if (t) { - QDateTime re(_startTime); - return re.addMSecs(t); - } - - return QDateTime(); -} - -quint64 Utility::StopWatch::durationOfLap(const QString &lapName) const -{ - return _lapTimes.value(lapName, 0); -} - -void Utility::sortFilenames(QStringList &fileNames) -{ -#if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0) - QCollator collator; - collator.setNumericMode(true); - collator.setCaseSensitivity(Qt::CaseInsensitive); - qSort(fileNames.begin(), fileNames.end(), collator); -#elif QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - fileNames.sort(Qt::CaseInsensitive); -#else - fileNames.sort(); -#endif -} - -QUrl Utility::concatUrlPath(const QUrl &url, const QString &concatPath, - const QList> &queryItems) -{ - QString path = url.path(); - if (!concatPath.isEmpty()) { - // avoid '//' - if (path.endsWith('/') && concatPath.startsWith('/')) { - path.chop(1); - } // avoid missing '/' - else if (!path.endsWith('/') && !concatPath.startsWith('/')) { - path += QLatin1Char('/'); - } - path += concatPath; // put the complete path together - } - - QUrl tmpUrl = url; - tmpUrl.setPath(path); - if (queryItems.size() > 0) { - tmpUrl.setQueryItems(queryItems); - } - return tmpUrl; -} - -Q_GLOBAL_STATIC(QString, g_configFileName) - -std::unique_ptr Utility::settingsWithGroup(const QString &group, QObject *parent) -{ - if (g_configFileName()->isEmpty()) { - // cache file name - ConfigFile cfg; - *g_configFileName() = cfg.configFile(); - } - std::unique_ptr settings(new QSettings(*g_configFileName(), QSettings::IniFormat, parent)); - settings->beginGroup(group); - return settings; -} - -} // namespace OCC diff --git a/src/libsync/utility.h b/src/libsync/utility.h deleted file mode 100644 index 7c26f2ab2..000000000 --- a/src/libsync/utility.h +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) by Klaas Freitag - * Copyright (C) by Daniel Molkentin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - */ - -#ifndef UTILITY_H -#define UTILITY_H - -#include "owncloudlib.h" -#include -#include -#include -#include -#include -#include -#include -#include - -class QSettings; - -namespace OCC { - -Q_DECLARE_LOGGING_CATEGORY(lcUtility) - -/** \addtogroup libsync - * @{ - */ -namespace Utility { - OWNCLOUDSYNC_EXPORT void sleep(int sec); - OWNCLOUDSYNC_EXPORT void usleep(int usec); - OWNCLOUDSYNC_EXPORT QString formatFingerprint(const QByteArray &, bool colonSeparated = true); - OWNCLOUDSYNC_EXPORT void setupFavLink(const QString &folder); - OWNCLOUDSYNC_EXPORT bool writeRandomFile(const QString &fname, int size = -1); - OWNCLOUDSYNC_EXPORT QString octetsToString(qint64 octets); - OWNCLOUDSYNC_EXPORT QByteArray userAgentString(); - OWNCLOUDSYNC_EXPORT bool hasLaunchOnStartup(const QString &appName); - OWNCLOUDSYNC_EXPORT void setLaunchOnStartup(const QString &appName, const QString &guiName, bool launch); - - /** - * Return the amount of free space available. - * - * \a path must point to a directory - */ - OWNCLOUDSYNC_EXPORT qint64 freeDiskSpace(const QString &path); - - /** - * @brief compactFormatDouble - formats a double value human readable. - * - * @param value the value to format. - * @param prec the precision. - * @param unit an optional unit that is appended if present. - * @return the formatted string. - */ - OWNCLOUDSYNC_EXPORT QString compactFormatDouble(double value, int prec, const QString &unit = QString::null); - - // porting methods - OWNCLOUDSYNC_EXPORT QString escape(const QString &); - - // conversion function QDateTime <-> time_t (because the ones builtin work on only unsigned 32bit) - OWNCLOUDSYNC_EXPORT QDateTime qDateTimeFromTime_t(qint64 t); - OWNCLOUDSYNC_EXPORT qint64 qDateTimeToTime_t(const QDateTime &t); - - /** - * @brief Convert milliseconds duration to human readable string. - * @param quint64 msecs the milliseconds to convert to string. - * @return an HMS representation of the milliseconds value. - * - * durationToDescriptiveString1 describes the duration in a single - * unit, like "5 minutes" or "2 days". - * - * durationToDescriptiveString2 uses two units where possible, so - * "5 minutes 43 seconds" or "1 month 3 days". - */ - OWNCLOUDSYNC_EXPORT QString durationToDescriptiveString1(quint64 msecs); - OWNCLOUDSYNC_EXPORT QString durationToDescriptiveString2(quint64 msecs); - - /** - * @brief hasDarkSystray - determines whether the systray is dark or light. - * - * Use this to check if the OS has a dark or a light systray. - * - * The value might change during the execution of the program - * (e.g. on OS X 10.10). - * - * @return bool which is true for systems with dark systray. - */ - OWNCLOUDSYNC_EXPORT bool hasDarkSystray(); - - // convenience OS detection methods - OWNCLOUDSYNC_EXPORT bool isWindows(); - OWNCLOUDSYNC_EXPORT bool isMac(); - OWNCLOUDSYNC_EXPORT bool isUnix(); - OWNCLOUDSYNC_EXPORT bool isLinux(); // use with care - OWNCLOUDSYNC_EXPORT bool isBSD(); // use with care, does not match OS X - - OWNCLOUDSYNC_EXPORT QString platformName(); - // crash helper for --debug - OWNCLOUDSYNC_EXPORT void crash(); - - // Case preserving file system underneath? - // if this function returns true, the file system is case preserving, - // that means "test" means the same as "TEST" for filenames. - // if false, the two cases are two different files. - OWNCLOUDSYNC_EXPORT bool fsCasePreserving(); - - // Check if two pathes that MUST exist are equal. This function - // uses QDir::canonicalPath() to judge and cares for the systems - // case sensitivity. - OWNCLOUDSYNC_EXPORT bool fileNamesEqual(const QString &fn1, const QString &fn2); - - // Call the given command with the switch --version and rerun the first line - // of the output. - // If command is empty, the function calls the running application which, on - // Linux, might have changed while this one is running. - // For Mac and Windows, it returns QString() - OWNCLOUDSYNC_EXPORT QByteArray versionOfInstalledBinary(const QString &command = QString()); - - OWNCLOUDSYNC_EXPORT QString fileNameForGuiUse(const QString &fName); - - /** - * @brief timeAgoInWords - human readable time span - * - * Use this to get a string that describes the timespan between the first and - * the second timestamp in a human readable and understandable form. - * - * If the second parameter is ommitted, the current time is used. - */ - OWNCLOUDSYNC_EXPORT QString timeAgoInWords(const QDateTime &dt, const QDateTime &from = QDateTime()); - - class OWNCLOUDSYNC_EXPORT StopWatch - { - private: - QMap _lapTimes; - QDateTime _startTime; - QElapsedTimer _timer; - - public: - void start(); - quint64 stop(); - quint64 addLapTime(const QString &lapName); - void reset(); - - // out helpers, return the measured times. - QDateTime startTime() const; - QDateTime timeOfLap(const QString &lapName) const; - quint64 durationOfLap(const QString &lapName) const; - }; - - /** - * @brief Sort a QStringList in a way that's appropriate for filenames - */ - OWNCLOUDSYNC_EXPORT void sortFilenames(QStringList &fileNames); - - /** Appends concatPath and queryItems to the url */ - OWNCLOUDSYNC_EXPORT QUrl concatUrlPath( - const QUrl &url, const QString &concatPath, - const QList> &queryItems = (QList>())); - - /** Returns a new settings pre-set in a specific group. The Settings will be created - with the given parent. If no parent is specified, the caller must destroy the settings */ - OWNCLOUDSYNC_EXPORT std::unique_ptr settingsWithGroup(const QString &group, QObject *parent = 0); -} -/** @} */ // \addtogroup -} -#endif // UTILITY_H diff --git a/src/libsync/utility_mac.cpp b/src/libsync/utility_mac.cpp deleted file mode 100644 index 5a71aa2af..000000000 --- a/src/libsync/utility_mac.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) by Daniel Molkentin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - */ - -#include -#include - -namespace OCC { - -static void setupFavLink_private(const QString &folder) -{ - // Finder: Place under "Places"/"Favorites" on the left sidebar - CFStringRef folderCFStr = CFStringCreateWithCString(0, folder.toUtf8().data(), kCFStringEncodingUTF8); - CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); - - LSSharedFileListRef placesItems = LSSharedFileListCreate(0, kLSSharedFileListFavoriteItems, 0); - if (placesItems) { - //Insert an item to the list. - LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(placesItems, - kLSSharedFileListItemLast, 0, 0, - urlRef, 0, 0); - if (item) - CFRelease(item); - } - CFRelease(placesItems); - CFRelease(folderCFStr); - CFRelease(urlRef); -} - -bool hasLaunchOnStartup_private(const QString &) -{ - // this is quite some duplicate code with setLaunchOnStartup, at some point we should fix this FIXME. - bool returnValue = false; - QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath(); - CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); - CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); - LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); - if (loginItems) { - // We need to iterate over the items and check which one is "ours". - UInt32 seedValue; - CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue); - CFStringRef appUrlRefString = CFURLGetString(urlRef); // no need for release - for (int i = 0; i < CFArrayGetCount(itemsArray); i++) { - LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); - CFURLRef itemUrlRef = NULL; - - if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { - CFStringRef itemUrlString = CFURLGetString(itemUrlRef); - if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { - returnValue = true; - } - CFRelease(itemUrlRef); - } - } - CFRelease(itemsArray); - } - CFRelease(loginItems); - CFRelease(folderCFStr); - CFRelease(urlRef); - return returnValue; -} - -void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) -{ - Q_UNUSED(appName) - Q_UNUSED(guiName) - QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath(); - CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8); - CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true); - LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0); - - if (loginItems && enable) { - //Insert an item to the list. - LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems, - kLSSharedFileListItemLast, 0, 0, - urlRef, 0, 0); - if (item) - CFRelease(item); - CFRelease(loginItems); - } else if (loginItems && !enable) { - // We need to iterate over the items and check which one is "ours". - UInt32 seedValue; - CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue); - CFStringRef appUrlRefString = CFURLGetString(urlRef); - for (int i = 0; i < CFArrayGetCount(itemsArray); i++) { - LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); - CFURLRef itemUrlRef = NULL; - - if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) { - CFStringRef itemUrlString = CFURLGetString(itemUrlRef); - if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { - LSSharedFileListItemRemove(loginItems, item); // remove it! - } - CFRelease(itemUrlRef); - } - } - CFRelease(itemsArray); - CFRelease(loginItems); - }; - - CFRelease(folderCFStr); - CFRelease(urlRef); -} - -static bool hasDarkSystray_private() -{ - bool returnValue = false; - CFStringRef interfaceStyleKey = CFSTR("AppleInterfaceStyle"); - CFStringRef interfaceStyle = NULL; - CFStringRef darkInterfaceStyle = CFSTR("Dark"); - interfaceStyle = (CFStringRef)CFPreferencesCopyAppValue(interfaceStyleKey, - kCFPreferencesCurrentApplication); - if (interfaceStyle != NULL) { - returnValue = (kCFCompareEqualTo == CFStringCompare(interfaceStyle, darkInterfaceStyle, 0)); - CFRelease(interfaceStyle); - } - return returnValue; -} - -} // namespace OCC diff --git a/src/libsync/utility_unix.cpp b/src/libsync/utility_unix.cpp deleted file mode 100644 index e21c1cc75..000000000 --- a/src/libsync/utility_unix.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) by Klaas Freitag - * Copyright (C) by Daniel Molkentin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - */ - -#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) -#include -#endif - -namespace OCC { - -static void setupFavLink_private(const QString &folder) -{ - // Nautilus: add to ~/.gtk-bookmarks - QFile gtkBookmarks(QDir::homePath() + QLatin1String("/.gtk-bookmarks")); - QByteArray folderUrl = "file://" + folder.toUtf8(); - if (gtkBookmarks.open(QFile::ReadWrite)) { - QByteArray places = gtkBookmarks.readAll(); - if (!places.contains(folderUrl)) { - places += folderUrl; - gtkBookmarks.reset(); - gtkBookmarks.write(places + '\n'); - } - } -} - -// returns the autostart directory the linux way -// and respects the XDG_CONFIG_HOME env variable -QString getUserAutostartDir_private() -{ -#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - QString config = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation); -#else - QString config = QFile::decodeName(qgetenv("XDG_CONFIG_HOME")); - - if (config.isEmpty()) { - config = QDir::homePath() + QLatin1String("/.config"); - } -#endif - config += QLatin1String("/autostart/"); - return config; -} - -bool hasLaunchOnStartup_private(const QString &appName) -{ - QString desktopFileLocation = getUserAutostartDir_private() + appName + QLatin1String(".desktop"); - return QFile::exists(desktopFileLocation); -} - -void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) -{ - QString userAutoStartPath = getUserAutostartDir_private(); - QString desktopFileLocation = userAutoStartPath + appName + QLatin1String(".desktop"); - if (enable) { - if (!QDir().exists(userAutoStartPath) && !QDir().mkpath(userAutoStartPath)) { - qCWarning(lcUtility) << "Could not create autostart folder"; - return; - } - QFile iniFile(desktopFileLocation); - if (!iniFile.open(QIODevice::WriteOnly)) { - qCWarning(lcUtility) << "Could not write auto start entry" << desktopFileLocation; - return; - } - QTextStream ts(&iniFile); - ts.setCodec("UTF-8"); - ts << QLatin1String("[Desktop Entry]") << endl - << QLatin1String("Name=") << guiName << endl - << QLatin1String("GenericName=") << QLatin1String("File Synchronizer") << endl - << QLatin1String("Exec=") << QCoreApplication::applicationFilePath() << endl - << QLatin1String("Terminal=") << "false" << endl - << QLatin1String("Icon=") << appName.toLower() << endl // always use lowercase for icons - << QLatin1String("Categories=") << QLatin1String("Network") << endl - << QLatin1String("Type=") << QLatin1String("Application") << endl - << QLatin1String("StartupNotify=") << "false" << endl - << QLatin1String("X-GNOME-Autostart-enabled=") << "true" << endl; - } else { - if (!QFile::remove(desktopFileLocation)) { - qCWarning(lcUtility) << "Could not remove autostart desktop file"; - } - } -} - -static inline bool hasDarkSystray_private() -{ - return true; -} - -} // namespace OCC diff --git a/src/libsync/utility_win.cpp b/src/libsync/utility_win.cpp deleted file mode 100644 index 3762808b7..000000000 --- a/src/libsync/utility_win.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) by Daniel Molkentin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - */ - -#define _WIN32_WINNT 0x0600 -#define WINVER 0x0600 -#include -#include -#include -#include -#include -#include -#include - -static const char runPathC[] = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"; - -namespace OCC { - -static void setupFavLink_private(const QString &folder) -{ - // First create a Desktop.ini so that the folder and favorite link show our application's icon. - QFile desktopIni(folder + QLatin1String("/Desktop.ini")); - if (desktopIni.exists()) { - qCWarning(lcUtility) << desktopIni.fileName() << "already exists, not overwriting it to set the folder icon."; - } else { - qCInfo(lcUtility) << "Creating" << desktopIni.fileName() << "to set a folder icon in Explorer."; - desktopIni.open(QFile::WriteOnly); - desktopIni.write("[.ShellClassInfo]\r\nIconResource="); - desktopIni.write(QDir::toNativeSeparators(qApp->applicationFilePath()).toUtf8()); - desktopIni.write(",0\r\n"); - desktopIni.close(); - } - - // Windows Explorer: Place under "Favorites" (Links) - QString linkName; - QDir folderDir(QDir::fromNativeSeparators(folder)); - - /* Use new WINAPI functions */ - PWSTR path; - - if (SHGetKnownFolderPath(FOLDERID_Links, 0, NULL, &path) == S_OK) { - QString links = QDir::fromNativeSeparators(QString::fromWCharArray(path)); - linkName = QDir(links).filePath(folderDir.dirName() + QLatin1String(".lnk")); - CoTaskMemFree(path); - } - qCInfo(lcUtility) << "Creating favorite link from" << folder << "to" << linkName; - if (!QFile::link(folder, linkName)) - qCWarning(lcUtility) << "linking" << folder << "to" << linkName << "failed!"; -} - - -bool hasLaunchOnStartup_private(const QString &appName) -{ - QString runPath = QLatin1String(runPathC); - QSettings settings(runPath, QSettings::NativeFormat); - return settings.contains(appName); -} - -void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable) -{ - Q_UNUSED(guiName); - QString runPath = QLatin1String(runPathC); - QSettings settings(runPath, QSettings::NativeFormat); - if (enable) { - settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/', '\\')); - } else { - settings.remove(appName); - } -} - -static inline bool hasDarkSystray_private() -{ - return true; -} - -} // namespace OCC diff --git a/src/libsync/version.h.in b/src/libsync/version.h.in deleted file mode 100644 index c05c224c1..000000000 --- a/src/libsync/version.h.in +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) by Klaas Freitag - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * for more details. - */ - -#ifndef VERSION_H -#define VERSION_H - -#cmakedefine GIT_SHA1 "@GIT_SHA1@" - -#define MIRALL_STRINGIFY(s) MIRALL_TOSTRING(s) -#define MIRALL_TOSTRING(s) #s - -/* MIRALL version */ -#define MIRALL_VERSION_MAJOR @MIRALL_VERSION_MAJOR@ -#define MIRALL_VERSION_MINOR @MIRALL_VERSION_MINOR@ -#define MIRALL_VERSION_PATCH @MIRALL_VERSION_PATCH@ -#define MIRALL_VERSION_BUILD @MIRALL_VERSION_BUILD@ - -#define MIRALL_VERSION @MIRALL_VERSION@ -#define MIRALL_VERSION_FULL @MIRALL_VERSION_FULL@ - -#define MIRALL_VERSION_STRING "@MIRALL_VERSION_STRING@" - -#endif // VERSION_H diff --git a/test/csync/csync_tests/check_csync_misc.cpp b/test/csync/csync_tests/check_csync_misc.cpp index 80736b825..64f95694b 100644 --- a/test/csync/csync_tests/check_csync_misc.cpp +++ b/test/csync/csync_tests/check_csync_misc.cpp @@ -17,10 +17,9 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#include "torture.h" - #include "csync_misc.h" #include +#include "torture.h" static void check_csync_normalize_etag(void **state) { diff --git a/test/testchecksumvalidator.cpp b/test/testchecksumvalidator.cpp index 88c3b1d34..fd1988eab 100644 --- a/test/testchecksumvalidator.cpp +++ b/test/testchecksumvalidator.cpp @@ -11,7 +11,7 @@ #include "checksums.h" #include "networkjobs.h" -#include "utility.h" +#include "common/utility.h" #include "filesystem.h" #include "propagatorjobs.h" diff --git a/test/testfilesystem.cpp b/test/testfilesystem.cpp index a9b3f2b9f..0b8b61246 100644 --- a/test/testfilesystem.cpp +++ b/test/testfilesystem.cpp @@ -8,7 +8,7 @@ #include #include "filesystem.h" -#include "utility.h" +#include "common/utility.h" using namespace OCC::Utility; using namespace OCC::FileSystem; diff --git a/test/testfolder.cpp b/test/testfolder.cpp index e8775ac06..986c588eb 100644 --- a/test/testfolder.cpp +++ b/test/testfolder.cpp @@ -7,7 +7,7 @@ #include -#include "utility.h" +#include "common/utility.h" #include "folder.h" using namespace OCC; diff --git a/test/testfolderman.cpp b/test/testfolderman.cpp index b6e6478f5..78a2dd71a 100644 --- a/test/testfolderman.cpp +++ b/test/testfolderman.cpp @@ -11,7 +11,7 @@ #endif #include -#include "utility.h" +#include "common/utility.h" #include "folderman.h" #include "account.h" #include "accountstate.h" diff --git a/test/testfolderwatcher.cpp b/test/testfolderwatcher.cpp index 1cb231cf6..0f8551db6 100644 --- a/test/testfolderwatcher.cpp +++ b/test/testfolderwatcher.cpp @@ -8,7 +8,7 @@ #include #include "folderwatcher.h" -#include "utility.h" +#include "common/utility.h" void touch(const QString &file) { diff --git a/test/testinotifywatcher.cpp b/test/testinotifywatcher.cpp index 799b09da9..2d8cf937d 100644 --- a/test/testinotifywatcher.cpp +++ b/test/testinotifywatcher.cpp @@ -7,7 +7,7 @@ #include #include "folderwatcher_linux.h" -#include "utility.h" +#include "common/utility.h" using namespace OCC; diff --git a/test/testutility.cpp b/test/testutility.cpp index 5093ce76d..5e86a336e 100644 --- a/test/testutility.cpp +++ b/test/testutility.cpp @@ -9,7 +9,7 @@ #include #endif -#include "utility.h" +#include "common/utility.h" using namespace OCC::Utility; diff --git a/version.h.in b/version.h.in new file mode 100644 index 000000000..064309f52 --- /dev/null +++ b/version.h.in @@ -0,0 +1,38 @@ +/* + * Copyright (C) by Klaas Freitag + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef VERSION_H +#define VERSION_H + +#cmakedefine GIT_SHA1 "@GIT_SHA1@" + +#define MIRALL_STRINGIFY(s) MIRALL_TOSTRING(s) +#define MIRALL_TOSTRING(s) #s + +/* MIRALL version */ +#define MIRALL_VERSION_MAJOR @MIRALL_VERSION_MAJOR@ +#define MIRALL_VERSION_MINOR @MIRALL_VERSION_MINOR@ +#define MIRALL_VERSION_PATCH @MIRALL_VERSION_PATCH@ +#define MIRALL_VERSION_BUILD @MIRALL_VERSION_BUILD@ + +#define MIRALL_VERSION @MIRALL_VERSION@ +#define MIRALL_VERSION_FULL @MIRALL_VERSION_FULL@ + +#define MIRALL_VERSION_STRING "@MIRALL_VERSION_STRING@" + +#endif // VERSION_H