Move utilities to core/utils folder.

Also move the names to Utils namespace.
This commit is contained in:
Vladimir Golovnev (Glassez) 2015-05-06 14:53:27 +03:00
parent 427688cb34
commit 191cdc2849
67 changed files with 1172 additions and 1135 deletions

View file

@ -60,7 +60,7 @@
#include "application.h" #include "application.h"
#include "core/logger.h" #include "core/logger.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/iconprovider.h" #include "core/iconprovider.h"
#include "core/scanfoldersmodel.h" #include "core/scanfoldersmodel.h"
#include "core/net/smtp.h" #include "core/net/smtp.h"
@ -74,7 +74,7 @@ Application::Application(const QString &id, int &argc, char **argv)
: BaseApplication(id, argc, argv) : BaseApplication(id, argc, argv)
, m_running(false) , m_running(false)
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
, m_shutdownAct(NO_SHUTDOWN) , m_shutdownAct(ShutdownAction::None)
#endif #endif
{ {
Logger::initInstance(); Logger::initInstance();
@ -118,11 +118,11 @@ void Application::sendNotificationEmail(BitTorrent::TorrentHandle *const torrent
{ {
// Prepare mail content // Prepare mail content
QString content = QObject::tr("Torrent name: %1").arg(torrent->name()) + "\n"; QString content = QObject::tr("Torrent name: %1").arg(torrent->name()) + "\n";
content += QObject::tr("Torrent size: %1").arg(misc::friendlyUnit(torrent->wantedSize())) + "\n"; content += QObject::tr("Torrent size: %1").arg(Utils::Misc::friendlyUnit(torrent->wantedSize())) + "\n";
content += QObject::tr("Save path: %1").arg(torrent->savePath()) + "\n\n"; content += QObject::tr("Save path: %1").arg(torrent->savePath()) + "\n\n";
content += QObject::tr("The torrent was downloaded in %1.", content += QObject::tr("The torrent was downloaded in %1.",
"The torrent was downloaded in 1 hour and 20 seconds") "The torrent was downloaded in 1 hour and 20 seconds")
.arg(misc::userFriendlyDuration(torrent->activeTime())) + "\n\n\n"; .arg(Utils::Misc::userFriendlyDuration(torrent->activeTime())) + "\n\n\n";
content += QObject::tr("Thank you for using qBittorrent.") + "\n"; content += QObject::tr("Thank you for using qBittorrent.") + "\n";
// Send the notification email // Send the notification email
@ -169,13 +169,13 @@ void Application::allTorrentsFinished()
bool shutdown = pref->shutdownWhenDownloadsComplete(); bool shutdown = pref->shutdownWhenDownloadsComplete();
// Confirm shutdown // Confirm shutdown
ShutDownAction action = NO_SHUTDOWN; ShutdownAction action = ShutdownAction::None;
if (suspend) if (suspend)
action = SUSPEND_COMPUTER; action = ShutdownAction::Suspend;
else if (hibernate) else if (hibernate)
action = HIBERNATE_COMPUTER; action = ShutdownAction::Hibernate;
else if (shutdown) else if (shutdown)
action = SHUTDOWN_COMPUTER; action = ShutdownAction::Shutdown;
if (!ShutdownConfirmDlg::askForConfirmation(action)) return; if (!ShutdownConfirmDlg::askForConfirmation(action)) return;
@ -458,9 +458,9 @@ void Application::cleanup()
shutdownBRDestroy((HWND)m_window->effectiveWinId()); shutdownBRDestroy((HWND)m_window->effectiveWinId());
#endif // Q_OS_WIN #endif // Q_OS_WIN
delete m_window; delete m_window;
if (m_shutdownAct != NO_SHUTDOWN) { if (m_shutdownAct != ShutdownAction::None) {
qDebug() << "Sending computer shutdown/suspend/hibernate signal..."; qDebug() << "Sending computer shutdown/suspend/hibernate signal...";
misc::shutdownComputer(m_shutdownAct); Utils::Misc::shutdownComputer(m_shutdownAct);
} }
#endif #endif
} }

View file

@ -50,7 +50,7 @@ QT_END_NAMESPACE
typedef QtSingleCoreApplication BaseApplication; typedef QtSingleCoreApplication BaseApplication;
#endif #endif
#include "core/misc.h" #include "core/utils/misc.h"
#ifndef DISABLE_WEBUI #ifndef DISABLE_WEBUI
class WebUI; class WebUI;
@ -96,7 +96,7 @@ private:
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
QPointer<MainWindow> m_window; QPointer<MainWindow> m_window;
ShutDownAction m_shutdownAct; ShutdownAction m_shutdownAct;
#endif #endif
#ifndef DISABLE_WEBUI #ifndef DISABLE_WEBUI

View file

@ -66,7 +66,7 @@ Q_IMPORT_PLUGIN(qico)
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <iostream>
#include "application.h" #include "application.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/preferences.h" #include "core/preferences.h"
// Signal handlers // Signal handlers
@ -123,7 +123,7 @@ int main(int argc, char *argv[])
bool isOneArg = (argc == 2); bool isOneArg = (argc == 2);
// Create Application // Create Application
QString appId = QLatin1String("qBittorrent-") + misc::getUserIDString(); QString appId = QLatin1String("qBittorrent-") + Utils::Misc::getUserIDString();
QScopedPointer<Application> app(new Application(appId, argc, argv)); QScopedPointer<Application> app(new Application(appId, argc, argv));
const QBtCommandLineParameters params = parseCommandLine(); const QBtCommandLineParameters params = parseCommandLine();
@ -188,7 +188,7 @@ int main(int argc, char *argv[])
#endif #endif
qDebug("qBittorrent is already running for this user."); qDebug("qBittorrent is already running for this user.");
misc::msleep(300); Utils::Misc::msleep(300);
app->sendParams(params.torrents); app->sendParams(params.torrents);
return EXIT_SUCCESS; return EXIT_SUCCESS;
@ -395,7 +395,7 @@ void displayUsage(const QString& prg_name)
#else #else
QMessageBox msgBox(QMessageBox::Information, QObject::tr("Help"), makeUsage(prg_name), QMessageBox::Ok); QMessageBox msgBox(QMessageBox::Information, QObject::tr("Help"), makeUsage(prg_name), QMessageBox::Ok);
msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.show(); // Need to be shown or to moveToCenter does not work
msgBox.move(misc::screenCenter(&msgBox)); msgBox.move(Utils::Misc::screenCenter(&msgBox));
msgBox.exec(); msgBox.exec();
#endif #endif
} }
@ -407,7 +407,7 @@ void displayBadArgMessage(const QString& message)
QMessageBox msgBox(QMessageBox::Critical, QObject::tr("Bad command line"), QMessageBox msgBox(QMessageBox::Critical, QObject::tr("Bad command line"),
message + QLatin1Char('\n') + help, QMessageBox::Ok); message + QLatin1Char('\n') + help, QMessageBox::Ok);
msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.show(); // Need to be shown or to moveToCenter does not work
msgBox.move(misc::screenCenter(&msgBox)); msgBox.move(Utils::Misc::screenCenter(&msgBox));
msgBox.exec(); msgBox.exec();
#else #else
std::cerr << qPrintable(QObject::tr("Bad command line: ")); std::cerr << qPrintable(QObject::tr("Bad command line: "));
@ -439,7 +439,7 @@ bool userAgreesWithLegalNotice()
msgBox.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole); msgBox.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole);
QAbstractButton *agree_button = msgBox.addButton(QObject::tr("I Agree"), QMessageBox::AcceptRole); QAbstractButton *agree_button = msgBox.addButton(QObject::tr("I Agree"), QMessageBox::AcceptRole);
msgBox.show(); // Need to be shown or to moveToCenter does not work msgBox.show(); // Need to be shown or to moveToCenter does not work
msgBox.move(misc::screenCenter(&msgBox)); msgBox.move(Utils::Misc::screenCenter(&msgBox));
msgBox.exec(); msgBox.exec();
if (msgBox.clickedButton() == agree_button) { if (msgBox.clickedButton() == agree_button) {
// Save the answer // Save the answer

View file

@ -48,10 +48,10 @@ MagnetUri::MagnetUri(const QString &url)
m_valid = true; m_valid = true;
m_hash = m_addTorrentParams.info_hash; m_hash = m_addTorrentParams.info_hash;
m_name = String::fromStdString(m_addTorrentParams.name); m_name = Utils::String::fromStdString(m_addTorrentParams.name);
foreach (const std::string &tracker, m_addTorrentParams.trackers) foreach (const std::string &tracker, m_addTorrentParams.trackers)
m_trackers.append(String::fromStdString(tracker)); m_trackers.append(Utils::String::fromStdString(tracker));
#if LIBTORRENT_VERSION_NUM >= 10000 #if LIBTORRENT_VERSION_NUM >= 10000
foreach (const std::string &urlSeed, m_addTorrentParams.url_seeds) foreach (const std::string &urlSeed, m_addTorrentParams.url_seeds)

View file

@ -202,7 +202,7 @@ PeerAddress PeerInfo::address() const
QString PeerInfo::client() const QString PeerInfo::client() const
{ {
return String::fromStdString(m_nativeInfo.client); return Utils::String::fromStdString(m_nativeInfo.client);
} }

View file

@ -66,8 +66,8 @@ using namespace BitTorrent;
#include "geoipmanager.h" #include "geoipmanager.h"
#endif #endif
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/utils/string.h" #include "core/utils/string.h"
#include "core/logger.h" #include "core/logger.h"
#include "core/preferences.h" #include "core/preferences.h"
@ -163,7 +163,7 @@ Session::Session(QObject *parent)
// Construct session // Construct session
libt::fingerprint fingerprint(PEER_ID, VERSION_MAJOR, VERSION_MINOR, VERSION_BUGFIX, VERSION_BUILD); libt::fingerprint fingerprint(PEER_ID, VERSION_MAJOR, VERSION_MINOR, VERSION_BUGFIX, VERSION_BUILD);
m_nativeSession = new libt::session(fingerprint, 0); m_nativeSession = new libt::session(fingerprint, 0);
Logger::instance()->addMessage("Peer ID: " + String::fromStdString(fingerprint.to_string())); Logger::instance()->addMessage("Peer ID: " + Utils::String::fromStdString(fingerprint.to_string()));
m_nativeSession->set_alert_dispatch(boost::bind(&Session::dispatchAlerts, this, _1)); m_nativeSession->set_alert_dispatch(boost::bind(&Session::dispatchAlerts, this, _1));
@ -318,12 +318,12 @@ Session *Session::instance()
void Session::loadState() void Session::loadState()
{ {
const QString statePath = fsutils::cacheLocation() + QLatin1String("/ses_state"); const QString statePath = Utils::Fs::cacheLocation() + QLatin1String("/ses_state");
if (!QFile::exists(statePath)) return; if (!QFile::exists(statePath)) return;
if (QFile(statePath).size() == 0) { if (QFile(statePath).size() == 0) {
// Remove empty invalid state file // Remove empty invalid state file
fsutils::forceRemove(statePath); Utils::Fs::forceRemove(statePath);
return; return;
} }
@ -343,7 +343,7 @@ void Session::saveState()
{ {
qDebug("Saving session state to disk..."); qDebug("Saving session state to disk...");
const QString state_path = fsutils::cacheLocation() + QLatin1String("/ses_state"); const QString state_path = Utils::Fs::cacheLocation() + QLatin1String("/ses_state");
libt::entry session_state; libt::entry session_state;
m_nativeSession->save_state(session_state); m_nativeSession->save_state(session_state);
std::vector<char> out; std::vector<char> out;
@ -364,7 +364,7 @@ void Session::setSessionSettings()
libt::session_settings sessionSettings = m_nativeSession->settings(); libt::session_settings sessionSettings = m_nativeSession->settings();
sessionSettings.user_agent = "qBittorrent " VERSION; sessionSettings.user_agent = "qBittorrent " VERSION;
//std::cout << "HTTP user agent is " << sessionSettings.user_agent << std::endl; //std::cout << "HTTP user agent is " << sessionSettings.user_agent << std::endl;
logger->addMessage(tr("HTTP user agent is %1").arg(String::fromStdString(sessionSettings.user_agent))); logger->addMessage(tr("HTTP user agent is %1").arg(Utils::String::fromStdString(sessionSettings.user_agent)));
sessionSettings.upnp_ignore_nonrouters = true; sessionSettings.upnp_ignore_nonrouters = true;
sessionSettings.use_dht_as_fallback = false; sessionSettings.use_dht_as_fallback = false;
@ -422,7 +422,7 @@ void Session::setSessionSettings()
// IP address to announce to trackers // IP address to announce to trackers
QString announce_ip = pref->getNetworkAddress(); QString announce_ip = pref->getNetworkAddress();
if (!announce_ip.isEmpty()) if (!announce_ip.isEmpty())
sessionSettings.announce_ip = String::toStdString(announce_ip); sessionSettings.announce_ip = Utils::String::toStdString(announce_ip);
// Super seeding // Super seeding
sessionSettings.strict_super_seeding = pref->isSuperSeedingEnabled(); sessionSettings.strict_super_seeding = pref->isSuperSeedingEnabled();
// * Max Half-open connections // * Max Half-open connections
@ -668,13 +668,13 @@ void Session::configure()
libt::proxy_settings proxySettings; libt::proxy_settings proxySettings;
if (pref->isProxyEnabled()) { if (pref->isProxyEnabled()) {
qDebug("Enabling P2P proxy"); qDebug("Enabling P2P proxy");
proxySettings.hostname = String::toStdString(pref->getProxyIp()); proxySettings.hostname = Utils::String::toStdString(pref->getProxyIp());
qDebug("hostname is %s", proxySettings.hostname.c_str()); qDebug("hostname is %s", proxySettings.hostname.c_str());
proxySettings.port = pref->getProxyPort(); proxySettings.port = pref->getProxyPort();
qDebug("port is %d", proxySettings.port); qDebug("port is %d", proxySettings.port);
if (pref->isProxyAuthEnabled()) { if (pref->isProxyAuthEnabled()) {
proxySettings.username = String::toStdString(pref->getProxyUsername()); proxySettings.username = Utils::String::toStdString(pref->getProxyUsername());
proxySettings.password = String::toStdString(pref->getProxyPassword()); proxySettings.password = Utils::String::toStdString(pref->getProxyPassword());
qDebug("username is %s", proxySettings.username.c_str()); qDebug("username is %s", proxySettings.username.c_str());
qDebug("password is %s", proxySettings.password.c_str()); qDebug("password is %s", proxySettings.password.c_str());
} }
@ -780,7 +780,7 @@ void Session::handleDownloadFinished(const QString &url, const QString &filePath
{ {
emit downloadFromUrlFinished(url); emit downloadFromUrlFinished(url);
addTorrent_impl(m_downloadedTorrents.take(url), MagnetUri(), TorrentInfo::loadFromFile(filePath)); addTorrent_impl(m_downloadedTorrents.take(url), MagnetUri(), TorrentInfo::loadFromFile(filePath));
fsutils::forceRemove(filePath); // remove temporary file Utils::Fs::forceRemove(filePath); // remove temporary file
} }
void Session::changeSpeedLimitMode(bool alternative) void Session::changeSpeedLimitMode(bool alternative)
@ -870,8 +870,8 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles)
// Remove unwanted and incomplete files // Remove unwanted and incomplete files
foreach (const QString &unwantedFile, unwantedFiles) { foreach (const QString &unwantedFile, unwantedFiles) {
qDebug("Removing unwanted file: %s", qPrintable(unwantedFile)); qDebug("Removing unwanted file: %s", qPrintable(unwantedFile));
fsutils::forceRemove(unwantedFile); Utils::Fs::forceRemove(unwantedFile);
const QString parentFolder = fsutils::branchPath(unwantedFile); const QString parentFolder = Utils::Fs::branchPath(unwantedFile);
qDebug("Attempt to remove parent folder (if empty): %s", qPrintable(parentFolder)); qDebug("Attempt to remove parent folder (if empty): %s", qPrintable(parentFolder));
QDir().rmpath(parentFolder); QDir().rmpath(parentFolder);
} }
@ -883,7 +883,7 @@ bool Session::deleteTorrent(const QString &hash, bool deleteLocalFiles)
filters << QString("%1.*").arg(torrent->hash()); filters << QString("%1.*").arg(torrent->hash());
const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted); const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted);
foreach (const QString &file, files) foreach (const QString &file, files)
fsutils::forceRemove(resumeDataDir.absoluteFilePath(file)); Utils::Fs::forceRemove(resumeDataDir.absoluteFilePath(file));
if (deleteLocalFiles) if (deleteLocalFiles)
Logger::instance()->addMessage(tr("'%1' was removed from transfer list and hard disk.", "'xxx.avi' was removed...").arg(torrent->name())); Logger::instance()->addMessage(tr("'%1' was removed from transfer list and hard disk.", "'xxx.avi' was removed...").arg(torrent->name()));
@ -1038,10 +1038,10 @@ bool Session::addTorrent(QString source, const AddTorrentParams &params)
if (source.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (source.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
source = misc::bcLinkToMagnet(source); source = Utils::Misc::bcLinkToMagnet(source);
} }
if (misc::isUrl(source)) { if (Utils::Misc::isUrl(source)) {
Logger::instance()->addMessage(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source)); Logger::instance()->addMessage(tr("Downloading '%1', please wait...", "e.g: Downloading 'xxx.torrent', please wait...").arg(source));
// Launch downloader // Launch downloader
Net::DownloadHandler *handler = Net::DownloadManager::instance()->downloadUrl(source, 10485760 /* 10MB */); Net::DownloadHandler *handler = Net::DownloadManager::instance()->downloadUrl(source, 10485760 /* 10MB */);
@ -1164,7 +1164,7 @@ bool Session::addTorrent_impl(const AddTorrentData &addData, const MagnetUri &ma
savePath += "/"; savePath += "/";
} }
p.save_path = String::toStdString(fsutils::toNativePath(savePath)); p.save_path = Utils::String::toStdString(Utils::Fs::toNativePath(savePath));
// Check if save path exists, creating it otherwise // Check if save path exists, creating it otherwise
if (!QDir(savePath).exists()) if (!QDir(savePath).exists())
QDir().mkpath(savePath); QDir().mkpath(savePath);
@ -1214,7 +1214,7 @@ bool Session::loadMetadata(const QString &magnetUri)
#endif #endif
QString savePath = QString("%1/%2").arg(QDir::tempPath()).arg(hash); QString savePath = QString("%1/%2").arg(QDir::tempPath()).arg(hash);
p.save_path = String::toStdString(fsutils::toNativePath(savePath)); p.save_path = Utils::String::toStdString(Utils::Fs::toNativePath(savePath));
// Check if save path exists, creating it otherwise // Check if save path exists, creating it otherwise
if (!QDir(savePath).exists()) if (!QDir(savePath).exists())
QDir().mkpath(savePath); QDir().mkpath(savePath);
@ -1253,7 +1253,7 @@ void Session::exportTorrentFile(TorrentHandle *const torrent, TorrentExportFolde
QDir exportPath(folder == TorrentExportFolder::Regular ? Preferences::instance()->getTorrentExportDir() : Preferences::instance()->getFinishedTorrentExportDir()); QDir exportPath(folder == TorrentExportFolder::Regular ? Preferences::instance()->getTorrentExportDir() : Preferences::instance()->getFinishedTorrentExportDir());
if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) {
QString newTorrentPath = exportPath.absoluteFilePath(torrentFilename); QString newTorrentPath = exportPath.absoluteFilePath(torrentFilename);
if (QFile::exists(newTorrentPath) && fsutils::sameFiles(torrentPath, newTorrentPath)) { if (QFile::exists(newTorrentPath) && Utils::Fs::sameFiles(torrentPath, newTorrentPath)) {
// Append hash to torrent name to make it unique // Append hash to torrent name to make it unique
newTorrentPath = exportPath.absoluteFilePath(torrent->name() + "-" + torrentFilename); newTorrentPath = exportPath.absoluteFilePath(torrent->name() + "-" + torrentFilename);
} }
@ -1285,7 +1285,7 @@ void Session::exportTorrentFiles(QString path)
if (QFile::exists(srcPath)) { if (QFile::exists(srcPath)) {
QString dstPath = exportDir.absoluteFilePath(QString("%1.torrent").arg(torrent->name())); QString dstPath = exportDir.absoluteFilePath(QString("%1.torrent").arg(torrent->name()));
if (QFile::exists(dstPath)) { if (QFile::exists(dstPath)) {
if (!fsutils::sameFiles(srcPath, dstPath)) { if (!Utils::Fs::sameFiles(srcPath, dstPath)) {
dstPath = exportDir.absoluteFilePath(QString("%1-%2.torrent").arg(torrent->name()).arg(torrent->hash())); dstPath = exportDir.absoluteFilePath(QString("%1-%2.torrent").arg(torrent->name()).arg(torrent->hash()));
} }
else { else {
@ -1375,7 +1375,7 @@ void Session::enableDHT(bool enable)
} }
catch(std::exception &e) { catch(std::exception &e) {
qDebug("Could not enable DHT, reason: %s", e.what()); qDebug("Could not enable DHT, reason: %s", e.what());
logger->addMessage(tr("DHT support [OFF]. Reason: %1").arg(String::fromStdString(e.what())), Log::CRITICAL); logger->addMessage(tr("DHT support [OFF]. Reason: %1").arg(Utils::String::fromStdString(e.what())), Log::CRITICAL);
} }
} }
} }
@ -1442,7 +1442,7 @@ void Session::setDefaultSavePath(const QString &path)
{ {
if (path.isEmpty()) return; if (path.isEmpty()) return;
QString defaultSavePath = fsutils::fromNativePath(path); QString defaultSavePath = Utils::Fs::fromNativePath(path);
if (!defaultSavePath.endsWith("/")) if (!defaultSavePath.endsWith("/"))
defaultSavePath += "/"; defaultSavePath += "/";
if (m_defaultSavePath != defaultSavePath) { if (m_defaultSavePath != defaultSavePath) {
@ -1457,7 +1457,7 @@ void Session::setDefaultTempPath(const QString &path)
QString tempPath; QString tempPath;
if (!path.isEmpty()) { if (!path.isEmpty()) {
tempPath = fsutils::fromNativePath(path); tempPath = Utils::Fs::fromNativePath(path);
if (!tempPath.endsWith("/")) if (!tempPath.endsWith("/"))
tempPath += "/"; tempPath += "/";
} }
@ -1506,7 +1506,7 @@ void Session::setListeningPort(int port)
m_nativeSession->listen_on(ports, ec, 0, libt::session::listen_no_system_port); m_nativeSession->listen_on(ports, ec, 0, libt::session::listen_no_system_port);
if (ec) if (ec)
logger->addMessage(tr("qBittorrent failed to listen on any interface port: %1. Reason: %2", "e.g: qBittorrent failed to listen on any interface port: TCP/6881. Reason: no such interface" ).arg(QString::number(port)).arg(String::fromStdString(ec.message())), Log::CRITICAL); logger->addMessage(tr("qBittorrent failed to listen on any interface port: %1. Reason: %2", "e.g: qBittorrent failed to listen on any interface port: TCP/6881. Reason: no such interface" ).arg(QString::number(port)).arg(Utils::String::fromStdString(ec.message())), Log::CRITICAL);
return; return;
} }
@ -1716,7 +1716,7 @@ void Session::handleTorrentFinished(TorrentHandle *const torrent)
} }
else { else {
qDebug("Caught error loading torrent"); qDebug("Caught error loading torrent");
Logger::instance()->addMessage(tr("Unable to decode %1 torrent file.").arg(fsutils::toNativePath(torrentFullpath)), Log::CRITICAL); Logger::instance()->addMessage(tr("Unable to decode %1 torrent file.").arg(Utils::Fs::toNativePath(torrentFullpath)), Log::CRITICAL);
} }
} }
} }
@ -1773,7 +1773,7 @@ bool Session::hasPerTorrentRatioLimit() const
void Session::initResumeFolder() void Session::initResumeFolder()
{ {
m_resumeFolderPath = fsutils::expandPathAbs(fsutils::QDesktopServicesDataLocation() + RESUME_FOLDER); m_resumeFolderPath = Utils::Fs::expandPathAbs(Utils::Fs::QDesktopServicesDataLocation() + RESUME_FOLDER);
QDir resumeFolderDir(m_resumeFolderPath); QDir resumeFolderDir(m_resumeFolderPath);
if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) { if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) {
m_resumeFolderLock.setFileName(resumeFolderDir.absoluteFilePath("session.lock")); m_resumeFolderLock.setFileName(resumeFolderDir.absoluteFilePath("session.lock"));
@ -1795,9 +1795,9 @@ void Session::enableIPFilter(const QString &filterPath, bool force)
connect(m_filterParser.data(), SIGNAL(IPFilterParsed(int)), SLOT(handleIPFilterParsed(int))); connect(m_filterParser.data(), SIGNAL(IPFilterParsed(int)), SLOT(handleIPFilterParsed(int)));
connect(m_filterParser.data(), SIGNAL(IPFilterError()), SLOT(handleIPFilterError())); connect(m_filterParser.data(), SIGNAL(IPFilterError()), SLOT(handleIPFilterError()));
} }
if (m_filterPath.isEmpty() || m_filterPath != fsutils::fromNativePath(filterPath) || force) { if (m_filterPath.isEmpty() || m_filterPath != Utils::Fs::fromNativePath(filterPath) || force) {
m_filterPath = fsutils::fromNativePath(filterPath); m_filterPath = Utils::Fs::fromNativePath(filterPath);
m_filterParser->processFilterFile(fsutils::fromNativePath(filterPath)); m_filterParser->processFilterFile(Utils::Fs::fromNativePath(filterPath));
} }
} }
@ -1824,7 +1824,7 @@ void Session::recursiveTorrentDownload(const InfoHash &hash)
Logger::instance()->addMessage( Logger::instance()->addMessage(
tr("Recursive download of file %1 embedded in torrent %2" tr("Recursive download of file %1 embedded in torrent %2"
, "Recursive download of test.torrent embedded in torrent test2") , "Recursive download of test.torrent embedded in torrent test2")
.arg(fsutils::toNativePath(torrentRelpath)).arg(torrent->name())); .arg(Utils::Fs::toNativePath(torrentRelpath)).arg(torrent->name()));
const QString torrentFullpath = torrent->savePath() + "/" + torrentRelpath; const QString torrentFullpath = torrent->savePath() + "/" + torrentRelpath;
AddTorrentParams params; AddTorrentParams params;
@ -1857,18 +1857,18 @@ void Session::setProxySettings(libt::proxy_settings proxySettings)
QString proxy_str; QString proxy_str;
switch(proxySettings.type) { switch(proxySettings.type) {
case libt::proxy_settings::http_pw: case libt::proxy_settings::http_pw:
proxy_str = QString("http://%1:%2@%3:%4").arg(String::fromStdString(proxySettings.username)).arg(String::fromStdString(proxySettings.password)) proxy_str = QString("http://%1:%2@%3:%4").arg(Utils::String::fromStdString(proxySettings.username)).arg(Utils::String::fromStdString(proxySettings.password))
.arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port); .arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break; break;
case libt::proxy_settings::http: case libt::proxy_settings::http:
proxy_str = QString("http://%1:%2").arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port); proxy_str = QString("http://%1:%2").arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break; break;
case libt::proxy_settings::socks5: case libt::proxy_settings::socks5:
proxy_str = QString("%1:%2").arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port); proxy_str = QString("%1:%2").arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break; break;
case libt::proxy_settings::socks5_pw: case libt::proxy_settings::socks5_pw:
proxy_str = QString("%1:%2@%3:%4").arg(String::fromStdString(proxySettings.username)).arg(String::fromStdString(proxySettings.password)) proxy_str = QString("%1:%2@%3:%4").arg(Utils::String::fromStdString(proxySettings.username)).arg(Utils::String::fromStdString(proxySettings.password))
.arg(String::fromStdString(proxySettings.hostname)).arg(proxySettings.port); .arg(Utils::String::fromStdString(proxySettings.hostname)).arg(proxySettings.port);
break; break;
default: default:
qDebug("Disabling HTTP communications proxy"); qDebug("Disabling HTTP communications proxy");
@ -1930,11 +1930,11 @@ void Session::startUpTorrents()
qDebug("Starting up torrent %s ...", qPrintable(hash)); qDebug("Starting up torrent %s ...", qPrintable(hash));
if (!addTorrent_impl(resumeData, MagnetUri(), TorrentInfo::loadFromFile(filePath), data)) if (!addTorrent_impl(resumeData, MagnetUri(), TorrentInfo::loadFromFile(filePath), data))
logger->addMessage(tr("Unable to resume torrent '%1'.", "e.g: Unable to resume torrent 'hash'.") logger->addMessage(tr("Unable to resume torrent '%1'.", "e.g: Unable to resume torrent 'hash'.")
.arg(fsutils::toNativePath(hash)), Log::CRITICAL); .arg(Utils::Fs::toNativePath(hash)), Log::CRITICAL);
} }
else { else {
logger->addMessage(tr("Unable to resume torrent '%1': torrent file not found.", "e.g: Unable to resume torrent 'hash': torrent file not found.") logger->addMessage(tr("Unable to resume torrent '%1': torrent file not found.", "e.g: Unable to resume torrent 'hash': torrent file not found.")
.arg(fsutils::toNativePath(hash)), Log::CRITICAL); .arg(Utils::Fs::toNativePath(hash)), Log::CRITICAL);
} }
} }
} }
@ -2074,7 +2074,7 @@ void Session::handleAlert(libt::alert *a)
} }
} }
catch (std::exception &exc) { catch (std::exception &exc) {
qWarning() << "Caught exception in readAlerts(): " << String::fromStdString(exc.what()); qWarning() << "Caught exception in readAlerts(): " << Utils::String::fromStdString(exc.what());
} }
} }
@ -2090,7 +2090,7 @@ void Session::handleAddTorrentAlert(libtorrent::add_torrent_alert *p)
Logger *const logger = Logger::instance(); Logger *const logger = Logger::instance();
if (p->error) { if (p->error) {
qDebug("/!\\ Error: Failed to add torrent!"); qDebug("/!\\ Error: Failed to add torrent!");
QString msg = String::fromStdString(p->message()); QString msg = Utils::String::fromStdString(p->message());
logger->addMessage(tr("Couldn't add torrent. Reason: %1").arg(msg), Log::WARNING); logger->addMessage(tr("Couldn't add torrent. Reason: %1").arg(msg), Log::WARNING);
emit addTorrentFailed(msg); emit addTorrentFailed(msg);
return; return;
@ -2166,7 +2166,7 @@ void Session::handleTorrentDeletedAlert(libt::torrent_deleted_alert *p)
qDebug("A torrent was deleted from the hard disk, attempting to remove the root folder too..."); qDebug("A torrent was deleted from the hard disk, attempting to remove the root folder too...");
const QString dirpath = m_savePathsToRemove.take(p->info_hash); const QString dirpath = m_savePathsToRemove.take(p->info_hash);
qDebug() << "Removing save path: " << dirpath << "..."; qDebug() << "Removing save path: " << dirpath << "...";
bool ok = fsutils::smartRemoveEmptyFolderTree(dirpath); bool ok = Utils::Fs::smartRemoveEmptyFolderTree(dirpath);
Q_UNUSED(ok); Q_UNUSED(ok);
qDebug() << "Folder was removed: " << ok; qDebug() << "Folder was removed: " << ok;
} }
@ -2194,7 +2194,7 @@ void Session::handleFileErrorAlert(libt::file_error_alert *p)
// NOTE: Check this function! // NOTE: Check this function!
TorrentHandle *const torrent = m_torrents.value(p->handle.info_hash()); TorrentHandle *const torrent = m_torrents.value(p->handle.info_hash());
if (torrent) { if (torrent) {
QString msg = String::fromStdString(p->message()); QString msg = Utils::String::fromStdString(p->message());
Logger::instance()->addMessage(tr("An I/O error occurred, '%1' paused. %2") Logger::instance()->addMessage(tr("An I/O error occurred, '%1' paused. %2")
.arg(torrent->name()).arg(msg)); .arg(torrent->name()).arg(msg));
emit fullDiskError(torrent, msg); emit fullDiskError(torrent, msg);
@ -2203,13 +2203,13 @@ void Session::handleFileErrorAlert(libt::file_error_alert *p)
void Session::handlePortmapWarningAlert(libt::portmap_error_alert *p) void Session::handlePortmapWarningAlert(libt::portmap_error_alert *p)
{ {
Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping failure, message: %1").arg(String::fromStdString(p->message())), Log::CRITICAL); Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping failure, message: %1").arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
} }
void Session::handlePortmapAlert(libt::portmap_alert *p) void Session::handlePortmapAlert(libt::portmap_alert *p)
{ {
qDebug("UPnP Success, msg: %s", p->message().c_str()); qDebug("UPnP Success, msg: %s", p->message().c_str());
Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping successful, message: %1").arg(String::fromStdString(p->message())), Log::INFO); Logger::instance()->addMessage(tr("UPnP/NAT-PMP: Port mapping successful, message: %1").arg(Utils::String::fromStdString(p->message())), Log::INFO);
} }
void Session::handlePeerBlockedAlert(libt::peer_blocked_alert *p) void Session::handlePeerBlockedAlert(libt::peer_blocked_alert *p)
@ -2257,7 +2257,7 @@ void Session::handlePeerBanAlert(libt::peer_ban_alert *p)
void Session::handleUrlSeedAlert(libt::url_seed_alert *p) void Session::handleUrlSeedAlert(libt::url_seed_alert *p)
{ {
Logger::instance()->addMessage(tr("Url seed lookup failed for url: %1, message: %2").arg(String::fromStdString(p->url)).arg(String::fromStdString(p->message())), Log::CRITICAL); Logger::instance()->addMessage(tr("Url seed lookup failed for url: %1, message: %2").arg(Utils::String::fromStdString(p->url)).arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
} }
void Session::handleListenSucceededAlert(libt::listen_succeeded_alert *p) void Session::handleListenSucceededAlert(libt::listen_succeeded_alert *p)
@ -2304,7 +2304,7 @@ void Session::handleListenFailedAlert(libt::listen_failed_alert *p)
tr("qBittorrent failed listening on interface %1 port: %2/%3. Reason: %4", tr("qBittorrent failed listening on interface %1 port: %2/%3. Reason: %4",
"e.g: qBittorrent failed listening on interface 192.168.0.1 port: TCP/6881. Reason: already in use") "e.g: qBittorrent failed listening on interface 192.168.0.1 port: TCP/6881. Reason: already in use")
.arg(p->endpoint.address().to_string(ec).c_str()).arg(proto).arg(QString::number(p->endpoint.port())) .arg(p->endpoint.address().to_string(ec).c_str()).arg(proto).arg(QString::number(p->endpoint.port()))
.arg(String::fromStdString(p->error.message())), Log::CRITICAL); .arg(Utils::String::fromStdString(p->error.message())), Log::CRITICAL);
} }
void Session::handleExternalIPAlert(libt::external_ip_alert *p) void Session::handleExternalIPAlert(libt::external_ip_alert *p)
@ -2367,10 +2367,10 @@ bool loadTorrentResumeData(const QByteArray &data, AddTorrentData &out)
if ((fast.type() != libt::lazy_entry::dict_t) && !ec) return false; if ((fast.type() != libt::lazy_entry::dict_t) && !ec) return false;
out.addedTime = QDateTime::fromTime_t(fast.dict_find_int_value("qBt-addedTime")); out.addedTime = QDateTime::fromTime_t(fast.dict_find_int_value("qBt-addedTime"));
out.savePath = fsutils::fromNativePath(QString::fromUtf8(fast.dict_find_string_value("qBt-savePath").c_str())); out.savePath = Utils::Fs::fromNativePath(Utils::String::fromStdString(fast.dict_find_string_value("qBt-savePath")));
out.ratioLimit = QString::fromUtf8(fast.dict_find_string_value("qBt-ratioLimit").c_str()).toDouble(); out.ratioLimit = Utils::String::fromStdString(fast.dict_find_string_value("qBt-ratioLimit")).toDouble();
out.label = QString::fromUtf8(fast.dict_find_string_value("qBt-label").c_str()); out.label = Utils::String::fromStdString(fast.dict_find_string_value("qBt-label"));
out.name = QString::fromUtf8(fast.dict_find_string_value("qBt-name").c_str()); out.name = Utils::String::fromStdString(fast.dict_find_string_value("qBt-name"));
out.hasSeedStatus = fast.dict_find_int_value("qBt-seedStatus"); out.hasSeedStatus = fast.dict_find_int_value("qBt-seedStatus");
out.disableTempPath = fast.dict_find_int_value("qBt-tempPathDisabled"); out.disableTempPath = fast.dict_find_int_value("qBt-tempPathDisabled");
@ -2384,7 +2384,7 @@ bool Session::writeResumeDataFile(TorrentHandle *const torrent, const libt::entr
QStringList filters(QString("%1.fastresume.*").arg(torrent->hash())); QStringList filters(QString("%1.fastresume.*").arg(torrent->hash()));
const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted); const QStringList files = resumeDataDir.entryList(filters, QDir::Files, QDir::Unsorted);
foreach (const QString &file, files) foreach (const QString &file, files)
fsutils::forceRemove(resumeDataDir.absoluteFilePath(file)); Utils::Fs::forceRemove(resumeDataDir.absoluteFilePath(file));
QString filename = QString("%1.fastresume.%2").arg(torrent->hash()).arg(torrent->queuePosition()); QString filename = QString("%1.fastresume.%2").arg(torrent->hash()).arg(torrent->queuePosition());
QString filepath = resumeDataDir.absoluteFilePath(filename); QString filepath = resumeDataDir.absoluteFilePath(filename);

View file

@ -44,8 +44,8 @@
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/utils/string.h" #include "core/utils/string.h"
#include "torrentcreatorthread.h" #include "torrentcreatorthread.h"
@ -73,10 +73,10 @@ TorrentCreatorThread::~TorrentCreatorThread()
void TorrentCreatorThread::create(const QString &inputPath, const QString &savePath, const QStringList &trackers, void TorrentCreatorThread::create(const QString &inputPath, const QString &savePath, const QStringList &trackers,
const QStringList &urlSeeds, const QString &comment, bool isPrivate, int pieceSize) const QStringList &urlSeeds, const QString &comment, bool isPrivate, int pieceSize)
{ {
m_inputPath = fsutils::fromNativePath(inputPath); m_inputPath = Utils::Fs::fromNativePath(inputPath);
m_savePath = fsutils::fromNativePath(savePath); m_savePath = Utils::Fs::fromNativePath(savePath);
if (QFile(m_savePath).exists()) if (QFile(m_savePath).exists())
fsutils::forceRemove(m_savePath); Utils::Fs::forceRemove(m_savePath);
m_trackers = trackers; m_trackers = trackers;
m_urlSeeds = urlSeeds; m_urlSeeds = urlSeeds;
m_comment = comment; m_comment = comment;
@ -105,14 +105,14 @@ void TorrentCreatorThread::run()
try { try {
libt::file_storage fs; libt::file_storage fs;
// Adding files to the torrent // Adding files to the torrent
libt::add_files(fs, String::toStdString(fsutils::toNativePath(m_inputPath)), fileFilter); libt::add_files(fs, Utils::String::toStdString(Utils::Fs::toNativePath(m_inputPath)), fileFilter);
if (m_abort) return; if (m_abort) return;
libt::create_torrent t(fs, m_pieceSize); libt::create_torrent t(fs, m_pieceSize);
// Add url seeds // Add url seeds
foreach (const QString &seed, m_urlSeeds) foreach (const QString &seed, m_urlSeeds)
t.add_url_seed(String::toStdString(seed.trimmed())); t.add_url_seed(Utils::String::toStdString(seed.trimmed()));
int tier = 0; int tier = 0;
bool newline = false; bool newline = false;
@ -124,14 +124,14 @@ void TorrentCreatorThread::run()
newline = true; newline = true;
continue; continue;
} }
t.add_tracker(String::toStdString(tracker.trimmed()), tier); t.add_tracker(Utils::String::toStdString(tracker.trimmed()), tier);
newline = false; newline = false;
} }
if (m_abort) return; if (m_abort) return;
// calculate the hash for all pieces // calculate the hash for all pieces
const QString parentPath = fsutils::branchPath(m_inputPath) + "/"; const QString parentPath = Utils::Fs::branchPath(m_inputPath) + "/";
libt::set_piece_hashes(t, String::toStdString(fsutils::toNativePath(parentPath)), boost::bind(&TorrentCreatorThread::sendProgressSignal, this, _1, t.num_pieces())); libt::set_piece_hashes(t, Utils::String::toStdString(Utils::Fs::toNativePath(parentPath)), boost::bind(&TorrentCreatorThread::sendProgressSignal, this, _1, t.num_pieces()));
// Set qBittorrent as creator and add user comment to // Set qBittorrent as creator and add user comment to
// torrent_info structure // torrent_info structure
t.set_creator(creator_str.toUtf8().constData()); t.set_creator(creator_str.toUtf8().constData());
@ -144,12 +144,12 @@ void TorrentCreatorThread::run()
qDebug("Saving to %s", qPrintable(m_savePath)); qDebug("Saving to %s", qPrintable(m_savePath));
#ifdef _MSC_VER #ifdef _MSC_VER
wchar_t *savePathW = new wchar_t[m_savePath.length() + 1]; wchar_t *savePathW = new wchar_t[m_savePath.length() + 1];
int len = fsutils::toNativePath(m_savePath).toWCharArray(savePathW); int len = Utils::Fs::toNativePath(m_savePath).toWCharArray(savePathW);
savePathW[len] = L'\0'; savePathW[len] = L'\0';
std::ofstream outfile(savePathW, std::ios_base::out | std::ios_base::binary); std::ofstream outfile(savePathW, std::ios_base::out | std::ios_base::binary);
delete[] savePathW; delete[] savePathW;
#else #else
std::ofstream outfile(fsutils::toNativePath(m_savePath).toLocal8Bit().constData(), std::ios_base::out | std::ios_base::binary); std::ofstream outfile(Utils::Fs::toNativePath(m_savePath).toLocal8Bit().constData(), std::ios_base::out | std::ios_base::binary);
#endif #endif
if (outfile.fail()) if (outfile.fail())
throw std::exception(); throw std::exception();
@ -161,6 +161,6 @@ void TorrentCreatorThread::run()
emit creationSuccess(m_savePath, parentPath); emit creationSuccess(m_savePath, parentPath);
} }
catch (std::exception& e) { catch (std::exception& e) {
emit creationFailure(String::fromStdString(e.what())); emit creationFailure(Utils::String::fromStdString(e.what()));
} }
} }

View file

@ -45,11 +45,11 @@
#include <Windows.h> #include <Windows.h>
#endif #endif
#include "core/fs_utils.h"
#include "core/misc.h"
#include "core/logger.h" #include "core/logger.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "core/utils/string.h" #include "core/utils/string.h"
#include "core/utils/fs.h"
#include "core/utils/misc.h"
#include "session.h" #include "session.h"
#include "peerinfo.h" #include "peerinfo.h"
#include "trackerentry.h" #include "trackerentry.h"
@ -186,7 +186,7 @@ TorrentHandle::TorrentHandle(Session *session, const libtorrent::torrent_handle
, m_state(TorrentState::Unknown) , m_state(TorrentState::Unknown)
, m_name(data.name) , m_name(data.name)
, m_addedTime(data.resumed ? data.addedTime : QDateTime::currentDateTime()) , m_addedTime(data.resumed ? data.addedTime : QDateTime::currentDateTime())
, m_savePath(fsutils::toNativePath(data.savePath)) , m_savePath(Utils::Fs::toNativePath(data.savePath))
, m_label(data.label) , m_label(data.label)
, m_hasSeedStatus(data.resumed ? data.hasSeedStatus : false) , m_hasSeedStatus(data.resumed ? data.hasSeedStatus : false)
, m_ratioLimit(data.resumed ? data.ratioLimit : (data.ignoreShareRatio ? NO_RATIO_LIMIT : USE_GLOBAL_RATIO)) , m_ratioLimit(data.resumed ? data.ratioLimit : (data.ignoreShareRatio ? NO_RATIO_LIMIT : USE_GLOBAL_RATIO))
@ -230,7 +230,7 @@ QString TorrentHandle::name() const
#if LIBTORRENT_VERSION_NUM < 10000 #if LIBTORRENT_VERSION_NUM < 10000
name = m_nativeName; name = m_nativeName;
#else #else
name = String::fromStdString(m_nativeStatus.name); name = Utils::String::fromStdString(m_nativeStatus.name);
#endif #endif
} }
@ -293,12 +293,12 @@ qlonglong TorrentHandle::wastedSize() const
QString TorrentHandle::currentTracker() const QString TorrentHandle::currentTracker() const
{ {
return String::fromStdString(m_nativeStatus.current_tracker); return Utils::String::fromStdString(m_nativeStatus.current_tracker);
} }
QString TorrentHandle::savePath() const QString TorrentHandle::savePath() const
{ {
return fsutils::fromNativePath(m_savePath); return Utils::Fs::fromNativePath(m_savePath);
} }
QString TorrentHandle::rootPath() const QString TorrentHandle::rootPath() const
@ -318,13 +318,13 @@ QString TorrentHandle::nativeActualSavePath() const
#if LIBTORRENT_VERSION_NUM < 10000 #if LIBTORRENT_VERSION_NUM < 10000
return m_nativeSavePath; return m_nativeSavePath;
#else #else
return String::fromStdString(m_nativeStatus.save_path); return Utils::String::fromStdString(m_nativeStatus.save_path);
#endif #endif
} }
QString TorrentHandle::actualSavePath() const QString TorrentHandle::actualSavePath() const
{ {
return fsutils::fromNativePath(nativeActualSavePath()); return Utils::Fs::fromNativePath(nativeActualSavePath());
} }
QList<TrackerEntry> TorrentHandle::trackers() const QList<TrackerEntry> TorrentHandle::trackers() const
@ -437,7 +437,7 @@ bool TorrentHandle::addUrlSeed(const QUrl &urlSeed)
QList<QUrl> seeds = urlSeeds(); QList<QUrl> seeds = urlSeeds();
if (seeds.contains(urlSeed)) return false; if (seeds.contains(urlSeed)) return false;
SAFE_CALL_BOOL(add_url_seed, String::toStdString(urlSeed.toString())); SAFE_CALL_BOOL(add_url_seed, Utils::String::toStdString(urlSeed.toString()));
} }
bool TorrentHandle::removeUrlSeed(const QUrl &urlSeed) bool TorrentHandle::removeUrlSeed(const QUrl &urlSeed)
@ -445,13 +445,13 @@ bool TorrentHandle::removeUrlSeed(const QUrl &urlSeed)
QList<QUrl> seeds = urlSeeds(); QList<QUrl> seeds = urlSeeds();
if (!seeds.contains(urlSeed)) return false; if (!seeds.contains(urlSeed)) return false;
SAFE_CALL_BOOL(remove_url_seed, String::toStdString(urlSeed.toString())); SAFE_CALL_BOOL(remove_url_seed, Utils::String::toStdString(urlSeed.toString()));
} }
bool TorrentHandle::connectPeer(const PeerAddress &peerAddress) bool TorrentHandle::connectPeer(const PeerAddress &peerAddress)
{ {
libt::error_code ec; libt::error_code ec;
libt::address addr = libt::address::from_string(String::toStdString(peerAddress.ip.toString()), ec); libt::address addr = libt::address::from_string(Utils::String::toStdString(peerAddress.ip.toString()), ec);
if (ec) return false; if (ec) return false;
libt::asio::ip::tcp::endpoint ep(addr, peerAddress.port); libt::asio::ip::tcp::endpoint ep(addr, peerAddress.port);
@ -479,7 +479,7 @@ QString TorrentHandle::savePathParsed() const
else else
p = savePath(); p = savePath();
return fsutils::toNativePath(p); return Utils::Fs::toNativePath(p);
} }
int TorrentHandle::filesCount() const int TorrentHandle::filesCount() const
@ -544,7 +544,7 @@ QString TorrentHandle::filePath(int index) const
QString TorrentHandle::fileName(int index) const QString TorrentHandle::fileName(int index) const
{ {
if (!hasMetadata()) return QString(); if (!hasMetadata()) return QString();
return fsutils::fileName(filePath(index)); return Utils::Fs::fileName(filePath(index));
} }
qlonglong TorrentHandle::fileSize(int index) const qlonglong TorrentHandle::fileSize(int index) const
@ -561,7 +561,7 @@ QStringList TorrentHandle::absoluteFilePaths() const
QDir saveDir(actualSavePath()); QDir saveDir(actualSavePath());
QStringList res; QStringList res;
for (int i = 0; i < filesCount(); ++i) for (int i = 0; i < filesCount(); ++i)
res << fsutils::expandPathAbs(saveDir.absoluteFilePath(filePath(i))); res << Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
return res; return res;
} }
@ -577,7 +577,7 @@ QStringList TorrentHandle::absoluteFilePathsUnwanted() const
int count = static_cast<int>(fp.size()); int count = static_cast<int>(fp.size());
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
if (fp[i] == 0) { if (fp[i] == 0) {
const QString path = fsutils::expandPathAbs(saveDir.absoluteFilePath(filePath(i))); const QString path = Utils::Fs::expandPathAbs(saveDir.absoluteFilePath(filePath(i)));
if (path.contains(".unwanted")) if (path.contains(".unwanted"))
res << path; res << path;
} }
@ -720,8 +720,8 @@ bool TorrentHandle::hasFirstLastPiecePriority() const
bool found = false; bool found = false;
int count = static_cast<int>(fp.size()); int count = static_cast<int>(fp.size());
for (int i = 0; i < count; ++i) { for (int i = 0; i < count; ++i) {
const QString ext = fsutils::fileExtension(filePath(i)); const QString ext = Utils::Fs::fileExtension(filePath(i));
if (misc::isPreviewable(ext) && (fp[i] > 0)) { if (Utils::Misc::isPreviewable(ext) && (fp[i] > 0)) {
extremities = fileExtremityPieces(i); extremities = fileExtremityPieces(i);
found = true; found = true;
break; break;
@ -824,7 +824,7 @@ int TorrentHandle::queuePosition() const
QString TorrentHandle::error() const QString TorrentHandle::error() const
{ {
return String::fromStdString(m_nativeStatus.error); return Utils::String::fromStdString(m_nativeStatus.error);
} }
qlonglong TorrentHandle::totalDownload() const qlonglong TorrentHandle::totalDownload() const
@ -1114,7 +1114,7 @@ void TorrentHandle::move(QString path)
// even if new path same as default. // even if new path same as default.
m_useDefaultSavePath = false; m_useDefaultSavePath = false;
path = fsutils::toNativePath(path); path = Utils::Fs::toNativePath(path);
if (path == savePath()) return; if (path == savePath()) return;
if (!useTempPath()) { if (!useTempPath()) {
@ -1183,8 +1183,8 @@ void TorrentHandle::setFirstLastPiecePriority(bool b)
int nbfiles = static_cast<int>(fp.size()); int nbfiles = static_cast<int>(fp.size());
for (int index = 0; index < nbfiles; ++index) { for (int index = 0; index < nbfiles; ++index) {
const QString path = filePath(index); const QString path = filePath(index);
const QString ext = fsutils::fileExtension(path); const QString ext = Utils::Fs::fileExtension(path);
if (misc::isPreviewable(ext) && (fp[index] > 0)) { if (Utils::Misc::isPreviewable(ext) && (fp[index] > 0)) {
qDebug() << "File" << path << "is previewable, toggle downloading of first/last pieces first"; qDebug() << "File" << path << "is previewable, toggle downloading of first/last pieces first";
// Determine the priority to set // Determine the priority to set
int prio = b ? 7 : fp[index]; int prio = b ? 7 : fp[index];
@ -1258,7 +1258,7 @@ void TorrentHandle::setTrackerLogin(const QString &username, const QString &pass
void TorrentHandle::renameFile(int index, const QString &name) void TorrentHandle::renameFile(int index, const QString &name)
{ {
qDebug() << Q_FUNC_INFO << index << name; qDebug() << Q_FUNC_INFO << index << name;
SAFE_CALL(rename_file, index, String::toStdString(fsutils::toNativePath(name))); SAFE_CALL(rename_file, index, Utils::String::toStdString(Utils::Fs::toNativePath(name)));
} }
bool TorrentHandle::saveTorrentFile(const QString &path) bool TorrentHandle::saveTorrentFile(const QString &path)
@ -1307,7 +1307,7 @@ void TorrentHandle::handleStorageMovedAlert(libtorrent::storage_moved_alert *p)
return; return;
} }
QString newPath = String::fromStdString(p->path); QString newPath = Utils::String::fromStdString(p->path);
if (newPath != m_newPath) { if (newPath != m_newPath) {
qWarning("TorrentHandleImpl::handleStorageMoved(): New path doesn't match a path in a queue."); qWarning("TorrentHandleImpl::handleStorageMoved(): New path doesn't match a path in a queue.");
return; return;
@ -1328,7 +1328,7 @@ void TorrentHandle::handleStorageMovedAlert(libtorrent::storage_moved_alert *p)
} }
// Attempt to remove old folder if empty // Attempt to remove old folder if empty
QDir oldSaveDir(fsutils::fromNativePath(m_oldPath)); QDir oldSaveDir(Utils::Fs::fromNativePath(m_oldPath));
if ((oldSaveDir != QDir(m_session->defaultSavePath())) && (oldSaveDir != QDir(m_session->tempPath()))) { if ((oldSaveDir != QDir(m_session->defaultSavePath())) && (oldSaveDir != QDir(m_session->tempPath()))) {
qDebug("Attempting to remove %s", qPrintable(m_oldPath)); qDebug("Attempting to remove %s", qPrintable(m_oldPath));
QDir().rmpath(m_oldPath); QDir().rmpath(m_oldPath);
@ -1348,7 +1348,7 @@ void TorrentHandle::handleStorageMovedFailedAlert(libtorrent::storage_moved_fail
} }
Logger::instance()->addMessage(tr("Could not move torrent: '%1'. Reason: %2") Logger::instance()->addMessage(tr("Could not move torrent: '%1'. Reason: %2")
.arg(name()).arg(String::fromStdString(p->message())), Log::CRITICAL); .arg(name()).arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
m_newPath.clear(); m_newPath.clear();
if (!m_queuedPath.isEmpty()) { if (!m_queuedPath.isEmpty()) {
@ -1364,7 +1364,7 @@ void TorrentHandle::handleStorageMovedFailedAlert(libtorrent::storage_moved_fail
void TorrentHandle::handleTrackerReplyAlert(libtorrent::tracker_reply_alert *p) void TorrentHandle::handleTrackerReplyAlert(libtorrent::tracker_reply_alert *p)
{ {
QString trackerUrl = String::fromStdString(p->url); QString trackerUrl = Utils::String::fromStdString(p->url);
qDebug("Received a tracker reply from %s (Num_peers = %d)", qPrintable(trackerUrl), p->num_peers); qDebug("Received a tracker reply from %s (Num_peers = %d)", qPrintable(trackerUrl), p->num_peers);
// Connection was successful now. Remove possible old errors // Connection was successful now. Remove possible old errors
m_trackerInfos[trackerUrl].lastMessage.clear(); // Reset error/warning message m_trackerInfos[trackerUrl].lastMessage.clear(); // Reset error/warning message
@ -1375,8 +1375,8 @@ void TorrentHandle::handleTrackerReplyAlert(libtorrent::tracker_reply_alert *p)
void TorrentHandle::handleTrackerWarningAlert(libtorrent::tracker_warning_alert *p) void TorrentHandle::handleTrackerWarningAlert(libtorrent::tracker_warning_alert *p)
{ {
QString trackerUrl = String::fromStdString(p->url); QString trackerUrl = Utils::String::fromStdString(p->url);
QString message = String::fromStdString(p->msg); QString message = Utils::String::fromStdString(p->msg);
qDebug("Received a tracker warning for %s: %s", qPrintable(trackerUrl), qPrintable(message)); qDebug("Received a tracker warning for %s: %s", qPrintable(trackerUrl), qPrintable(message));
// Connection was successful now but there is a warning message // Connection was successful now but there is a warning message
m_trackerInfos[trackerUrl].lastMessage = message; // Store warning message m_trackerInfos[trackerUrl].lastMessage = message; // Store warning message
@ -1386,8 +1386,8 @@ void TorrentHandle::handleTrackerWarningAlert(libtorrent::tracker_warning_alert
void TorrentHandle::handleTrackerErrorAlert(libtorrent::tracker_error_alert *p) void TorrentHandle::handleTrackerErrorAlert(libtorrent::tracker_error_alert *p)
{ {
QString trackerUrl = String::fromStdString(p->url); QString trackerUrl = Utils::String::fromStdString(p->url);
QString message = String::fromStdString(p->msg); QString message = Utils::String::fromStdString(p->msg);
qDebug("Received a tracker error for %s: %s", qPrintable(trackerUrl), qPrintable(message)); qDebug("Received a tracker error for %s: %s", qPrintable(trackerUrl), qPrintable(message));
m_trackerInfos[trackerUrl].lastMessage = message; m_trackerInfos[trackerUrl].lastMessage = message;
@ -1487,13 +1487,13 @@ void TorrentHandle::handleFastResumeRejectedAlert(libtorrent::fastresume_rejecte
} }
else { else {
logger->addMessage(tr("Fast resume data was rejected for torrent %1. Reason: %2. Checking again...") logger->addMessage(tr("Fast resume data was rejected for torrent %1. Reason: %2. Checking again...")
.arg(name()).arg(String::fromStdString(p->message())), Log::CRITICAL); .arg(name()).arg(Utils::String::fromStdString(p->message())), Log::CRITICAL);
} }
} }
void TorrentHandle::handleFileRenamedAlert(libtorrent::file_renamed_alert *p) void TorrentHandle::handleFileRenamedAlert(libtorrent::file_renamed_alert *p)
{ {
QString newName = fsutils::fromNativePath(String::fromStdString(p->name)); QString newName = Utils::Fs::fromNativePath(Utils::String::fromStdString(p->name));
// TODO: Check this! // TODO: Check this!
if (filesCount() > 1) { if (filesCount() > 1) {
@ -1573,7 +1573,7 @@ void TorrentHandle::adjustSavePath()
QString defaultSavePath = m_session->defaultSavePath(); QString defaultSavePath = m_session->defaultSavePath();
if (m_session->useAppendLabelToSavePath() && !m_label.isEmpty()) if (m_session->useAppendLabelToSavePath() && !m_label.isEmpty())
defaultSavePath += QString("%1/").arg(m_label); defaultSavePath += QString("%1/").arg(m_label);
defaultSavePath = fsutils::toNativePath(defaultSavePath); defaultSavePath = Utils::Fs::toNativePath(defaultSavePath);
if (m_savePath != defaultSavePath) { if (m_savePath != defaultSavePath) {
if (!useTempPath()) { if (!useTempPath()) {
moveStorage(defaultSavePath); moveStorage(defaultSavePath);
@ -1702,7 +1702,7 @@ void TorrentHandle::adjustActualSavePath()
qDebug("Moving torrent to its temp save path: %s", qPrintable(path)); qDebug("Moving torrent to its temp save path: %s", qPrintable(path));
} }
moveStorage(fsutils::toNativePath(path)); moveStorage(Utils::Fs::toNativePath(path));
} }
libtorrent::torrent_handle TorrentHandle::nativeHandle() const libtorrent::torrent_handle TorrentHandle::nativeHandle() const
@ -1764,8 +1764,8 @@ void TorrentHandle::updateStatus(const libtorrent::torrent_status &nativeStatus)
m_nativeStatus = nativeStatus; m_nativeStatus = nativeStatus;
#if LIBTORRENT_VERSION_NUM < 10000 #if LIBTORRENT_VERSION_NUM < 10000
try { try {
m_nativeName = String::fromStdString(m_nativeHandle.name()); m_nativeName = Utils::String::fromStdString(m_nativeHandle.name());
m_nativeSavePath = fsutils::fromNativePath(String::fromStdString(m_nativeHandle.save_path())); m_nativeSavePath = Utils::Fs::fromNativePath(Utils::String::fromStdString(m_nativeHandle.save_path()));
} }
catch (std::exception &exc) { catch (std::exception &exc) {
qDebug("torrent_handle method inside TorrentHandleImpl::updateStatus() throws exception: %s", exc.what()); qDebug("torrent_handle method inside TorrentHandleImpl::updateStatus() throws exception: %s", exc.what());
@ -1835,11 +1835,11 @@ void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
// Move unwanted files to a .unwanted subfolder // Move unwanted files to a .unwanted subfolder
if (priorities[i] == 0) { if (priorities[i] == 0) {
QString oldAbsPath = QDir(spath).absoluteFilePath(filepath); QString oldAbsPath = QDir(spath).absoluteFilePath(filepath);
QString parentAbsPath = fsutils::branchPath(oldAbsPath); QString parentAbsPath = Utils::Fs::branchPath(oldAbsPath);
// Make sure the file does not already exists // Make sure the file does not already exists
if (QDir(parentAbsPath).dirName() != ".unwanted") { if (QDir(parentAbsPath).dirName() != ".unwanted") {
QString unwantedAbsPath = parentAbsPath + "/.unwanted"; QString unwantedAbsPath = parentAbsPath + "/.unwanted";
QString newAbsPath = unwantedAbsPath + "/" + fsutils::fileName(filepath); QString newAbsPath = unwantedAbsPath + "/" + Utils::Fs::fileName(filepath);
qDebug() << "Unwanted path is" << unwantedAbsPath; qDebug() << "Unwanted path is" << unwantedAbsPath;
if (QFile::exists(newAbsPath)) { if (QFile::exists(newAbsPath)) {
qWarning() << "File" << newAbsPath << "already exists at destination."; qWarning() << "File" << newAbsPath << "already exists at destination.";
@ -1852,25 +1852,25 @@ void TorrentHandle::prioritizeFiles(const QVector<int> &priorities)
if (created) { if (created) {
// Hide the folder on Windows // Hide the folder on Windows
qDebug() << "Hiding folder (Windows)"; qDebug() << "Hiding folder (Windows)";
std::wstring winPath = fsutils::toNativePath(unwantedAbsPath).toStdWString(); std::wstring winPath = Utils::Fs::toNativePath(unwantedAbsPath).toStdWString();
DWORD dwAttrs = ::GetFileAttributesW(winPath.c_str()); DWORD dwAttrs = ::GetFileAttributesW(winPath.c_str());
bool ret = ::SetFileAttributesW(winPath.c_str(), dwAttrs | FILE_ATTRIBUTE_HIDDEN); bool ret = ::SetFileAttributesW(winPath.c_str(), dwAttrs | FILE_ATTRIBUTE_HIDDEN);
Q_ASSERT(ret != 0); Q_UNUSED(ret); Q_ASSERT(ret != 0); Q_UNUSED(ret);
} }
#endif #endif
QString parentPath = fsutils::branchPath(filepath); QString parentPath = Utils::Fs::branchPath(filepath);
if (!parentPath.isEmpty() && !parentPath.endsWith("/")) if (!parentPath.isEmpty() && !parentPath.endsWith("/"))
parentPath += "/"; parentPath += "/";
renameFile(i, parentPath + ".unwanted/" + fsutils::fileName(filepath)); renameFile(i, parentPath + ".unwanted/" + Utils::Fs::fileName(filepath));
} }
} }
// Move wanted files back to their original folder // Move wanted files back to their original folder
if (priorities[i] > 0) { if (priorities[i] > 0) {
QString parentRelPath = fsutils::branchPath(filepath); QString parentRelPath = Utils::Fs::branchPath(filepath);
if (QDir(parentRelPath).dirName() == ".unwanted") { if (QDir(parentRelPath).dirName() == ".unwanted") {
QString oldName = fsutils::fileName(filepath); QString oldName = Utils::Fs::fileName(filepath);
QString newRelPath = fsutils::branchPath(parentRelPath); QString newRelPath = Utils::Fs::branchPath(parentRelPath);
if (newRelPath.isEmpty()) if (newRelPath.isEmpty())
renameFile(i, oldName); renameFile(i, oldName);
else else

View file

@ -34,8 +34,8 @@
#include <libtorrent/error_code.hpp> #include <libtorrent/error_code.hpp>
#include <libtorrent/magnet_uri.hpp> #include <libtorrent/magnet_uri.hpp>
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/utils/string.h" #include "core/utils/string.h"
#include "infohash.h" #include "infohash.h"
#include "trackerentry.h" #include "trackerentry.h"
@ -64,7 +64,7 @@ TorrentInfo TorrentInfo::loadFromFile(const QString &path, QString &error)
{ {
error.clear(); error.clear();
libt::error_code ec; libt::error_code ec;
TorrentInfo info(new libt::torrent_info(String::toStdString(fsutils::toNativePath(path)), ec)); TorrentInfo info(new libt::torrent_info(Utils::String::toStdString(Utils::Fs::toNativePath(path)), ec));
if (ec) { if (ec) {
error = QString::fromUtf8(ec.message().c_str()); error = QString::fromUtf8(ec.message().c_str());
qDebug("Cannot load .torrent file: %s", qPrintable(error)); qDebug("Cannot load .torrent file: %s", qPrintable(error));
@ -93,7 +93,7 @@ InfoHash TorrentInfo::hash() const
QString TorrentInfo::name() const QString TorrentInfo::name() const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return String::fromStdString(m_nativeInfo->name()); return Utils::String::fromStdString(m_nativeInfo->name());
} }
QDateTime TorrentInfo::creationDate() const QDateTime TorrentInfo::creationDate() const
@ -106,13 +106,13 @@ QDateTime TorrentInfo::creationDate() const
QString TorrentInfo::creator() const QString TorrentInfo::creator() const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return String::fromStdString(m_nativeInfo->creator()); return Utils::String::fromStdString(m_nativeInfo->creator());
} }
QString TorrentInfo::comment() const QString TorrentInfo::comment() const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return String::fromStdString(m_nativeInfo->comment()); return Utils::String::fromStdString(m_nativeInfo->comment());
} }
bool TorrentInfo::isPrivate() const bool TorrentInfo::isPrivate() const
@ -148,7 +148,7 @@ int TorrentInfo::piecesCount() const
QString TorrentInfo::filePath(int index) const QString TorrentInfo::filePath(int index) const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return fsutils::fromNativePath(String::fromStdString(m_nativeInfo->files().file_path(index))); return Utils::Fs::fromNativePath(Utils::String::fromStdString(m_nativeInfo->files().file_path(index)));
} }
QStringList TorrentInfo::filePaths() const QStringList TorrentInfo::filePaths() const
@ -162,13 +162,13 @@ QStringList TorrentInfo::filePaths() const
QString TorrentInfo::fileName(int index) const QString TorrentInfo::fileName(int index) const
{ {
return fsutils::fileName(filePath(index)); return Utils::Fs::fileName(filePath(index));
} }
QString TorrentInfo::origFilePath(int index) const QString TorrentInfo::origFilePath(int index) const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return fsutils::fromNativePath(String::fromStdString(m_nativeInfo->orig_files().file_path(index))); return Utils::Fs::fromNativePath(Utils::String::fromStdString(m_nativeInfo->orig_files().file_path(index)));
} }
qlonglong TorrentInfo::fileSize(int index) const qlonglong TorrentInfo::fileSize(int index) const
@ -215,13 +215,13 @@ QByteArray TorrentInfo::metadata() const
QString TorrentInfo::toMagnetUri() const QString TorrentInfo::toMagnetUri() const
{ {
if (!isValid()) return QString(); if (!isValid()) return QString();
return String::fromStdString(libt::make_magnet_uri(*m_nativeInfo)); return Utils::String::fromStdString(libt::make_magnet_uri(*m_nativeInfo));
} }
void TorrentInfo::renameFile(uint index, const QString &newPath) void TorrentInfo::renameFile(uint index, const QString &newPath)
{ {
if (!isValid()) return; if (!isValid()) return;
m_nativeInfo->rename_file(index, String::toStdString(newPath)); m_nativeInfo->rename_file(index, Utils::String::toStdString(newPath));
} }
boost::intrusive_ptr<libtorrent::torrent_info> TorrentInfo::nativeInfo() const boost::intrusive_ptr<libtorrent::torrent_info> TorrentInfo::nativeInfo() const

View file

@ -65,8 +65,8 @@ libtorrent::entry Peer::toEntry(bool noPeerId) const
{ {
libtorrent::entry::dictionary_type peerMap; libtorrent::entry::dictionary_type peerMap;
if (!noPeerId) if (!noPeerId)
peerMap["id"] = libtorrent::entry(String::toStdString(peerId)); peerMap["id"] = libtorrent::entry(Utils::String::toStdString(peerId));
peerMap["ip"] = libtorrent::entry(String::toStdString(ip)); peerMap["ip"] = libtorrent::entry(Utils::String::toStdString(ip));
peerMap["port"] = libtorrent::entry(port); peerMap["port"] = libtorrent::entry(port);
return libtorrent::entry(peerMap); return libtorrent::entry(peerMap);

View file

@ -28,14 +28,14 @@
#include <QString> #include <QString>
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/utils/string.h" #include "core/utils/string.h"
#include "trackerentry.h" #include "trackerentry.h"
using namespace BitTorrent; using namespace BitTorrent;
TrackerEntry::TrackerEntry(const QString &url) TrackerEntry::TrackerEntry(const QString &url)
: m_nativeEntry(libtorrent::announce_entry(String::toStdString(url))) : m_nativeEntry(libtorrent::announce_entry(Utils::String::toStdString(url)))
{ {
} }
@ -51,7 +51,7 @@ TrackerEntry::TrackerEntry(const TrackerEntry &other)
QString TrackerEntry::url() const QString TrackerEntry::url() const
{ {
return String::fromStdString(m_nativeEntry.url); return Utils::String::fromStdString(m_nativeEntry.url);
} }
int TrackerEntry::tier() const int TrackerEntry::tier() const

View file

@ -1,7 +1,5 @@
HEADERS += \ HEADERS += \
$$PWD/types.h \ $$PWD/types.h \
$$PWD/misc.h \
$$PWD/fs_utils.h \
$$PWD/tristatebool.h \ $$PWD/tristatebool.h \
$$PWD/filesystemwatcher.h \ $$PWD/filesystemwatcher.h \
$$PWD/qinisettings.h \ $$PWD/qinisettings.h \
@ -38,13 +36,13 @@ HEADERS += \
$$PWD/bittorrent/private/bandwidthscheduler.h \ $$PWD/bittorrent/private/bandwidthscheduler.h \
$$PWD/bittorrent/private/filterparserthread.h \ $$PWD/bittorrent/private/filterparserthread.h \
$$PWD/bittorrent/private/statistics.h \ $$PWD/bittorrent/private/statistics.h \
$$PWD/utils/fs.h \
$$PWD/utils/misc.h \
$$PWD/utils/string.h \ $$PWD/utils/string.h \
$$PWD/torrentfilter.h \ $$PWD/torrentfilter.h \
$$PWD/scanfoldersmodel.h $$PWD/scanfoldersmodel.h
SOURCES += \ SOURCES += \
$$PWD/misc.cpp \
$$PWD/fs_utils.cpp \
$$PWD/tristatebool.cpp \ $$PWD/tristatebool.cpp \
$$PWD/filesystemwatcher.cpp \ $$PWD/filesystemwatcher.cpp \
$$PWD/logger.cpp \ $$PWD/logger.cpp \
@ -76,6 +74,8 @@ SOURCES += \
$$PWD/bittorrent/private/bandwidthscheduler.cpp \ $$PWD/bittorrent/private/bandwidthscheduler.cpp \
$$PWD/bittorrent/private/filterparserthread.cpp \ $$PWD/bittorrent/private/filterparserthread.cpp \
$$PWD/bittorrent/private/statistics.cpp \ $$PWD/bittorrent/private/statistics.cpp \
$$PWD/utils/fs.cpp \
$$PWD/utils/misc.cpp \
$$PWD/utils/string.cpp \ $$PWD/utils/string.cpp \
$$PWD/torrentfilter.cpp \ $$PWD/torrentfilter.cpp \
$$PWD/scanfoldersmodel.cpp $$PWD/scanfoldersmodel.cpp

View file

@ -1,475 +0,0 @@
/*
* Bittorrent Client using Qt4 and libtorrent.
* Copyright (C) 2012 Christophe Dumez
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*
* Contact : chris@qbittorrent.org
*/
#include "fs_utils.h"
#include "misc.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QCoreApplication>
#include <libtorrent/torrent_info.hpp>
#ifdef Q_OS_MAC
#include <CoreServices/CoreServices.h>
#include <Carbon/Carbon.h>
#endif
#ifndef Q_OS_WIN
#if defined(Q_OS_MAC) || defined(Q_OS_FREEBSD)
#include <sys/param.h>
#include <sys/mount.h>
#elif defined(Q_OS_HAIKU)
#include <kernel/fs_info.h>
#else
#include <sys/vfs.h>
#endif
#else
#include <shlobj.h>
#include <winbase.h>
#endif
#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QDesktopServices>
#else
#include <QStandardPaths>
#endif
#endif
using namespace libtorrent;
/**
* Converts a path to a string suitable for display.
* This function makes sure the directory separator used is consistent
* with the OS being run.
*/
QString fsutils::toNativePath(const QString& path) {
return QDir::toNativeSeparators(path);
}
QString fsutils::fromNativePath(const QString &path) {
return QDir::fromNativeSeparators(path);
}
/**
* Returns the file extension part of a file name.
*/
QString fsutils::fileExtension(const QString &filename) {
QString ext = QString(filename).remove(".!qB");
const int point_index = ext.lastIndexOf(".");
return (point_index >= 0) ? ext.mid(point_index + 1) : QString();
}
QString fsutils::fileName(const QString& file_path) {
QString path = fsutils::fromNativePath(file_path);
const int slash_index = path.lastIndexOf("/");
if (slash_index == -1)
return path;
return path.mid(slash_index + 1);
}
QString fsutils::folderName(const QString& file_path) {
QString path = fsutils::fromNativePath(file_path);
const int slash_index = path.lastIndexOf("/");
if (slash_index == -1)
return path;
return path.left(slash_index);
}
/**
* Remove an empty folder tree.
*
* This function will also remove .DS_Store files on Mac OS and
* Thumbs.db on Windows.
*/
bool fsutils::smartRemoveEmptyFolderTree(const QString& dir_path) {
qDebug() << Q_FUNC_INFO << dir_path;
if (dir_path.isEmpty())
return false;
QDir dir(dir_path);
if (!dir.exists())
return true;
// Remove Files created by the OS
#if defined Q_OS_MAC
fsutils::forceRemove(dir_path + QLatin1String("/.DS_Store"));
#elif defined Q_OS_WIN
fsutils::forceRemove(dir_path + QLatin1String("/Thumbs.db"));
#endif
QFileInfoList sub_files = dir.entryInfoList();
foreach (const QFileInfo& info, sub_files) {
QString sub_name = info.fileName();
if (sub_name == "." || sub_name == "..")
continue;
QString sub_path = info.absoluteFilePath();
qDebug() << Q_FUNC_INFO << "sub file: " << sub_path;
if (info.isDir()) {
if (!smartRemoveEmptyFolderTree(sub_path)) {
qWarning() << Q_FUNC_INFO << "Failed to remove folder: " << sub_path;
return false;
}
} else {
if (info.isHidden()) {
qDebug() << Q_FUNC_INFO << "Removing hidden file: " << sub_path;
if (!fsutils::forceRemove(sub_path)) {
qWarning() << Q_FUNC_INFO << "Failed to remove " << sub_path;
return false;
}
} else {
qWarning() << Q_FUNC_INFO << "Folder is not empty, aborting. Found: " << sub_path;
}
}
}
qDebug() << Q_FUNC_INFO << "Calling rmdir on " << dir_path;
return QDir().rmdir(dir_path);
}
/**
* Removes the file with the given file_path.
*
* This function will try to fix the file permissions before removing it.
*/
bool fsutils::forceRemove(const QString& file_path) {
QFile f(file_path);
if (!f.exists())
return true;
// Make sure we have read/write permissions
f.setPermissions(f.permissions()|QFile::ReadOwner|QFile::WriteOwner|QFile::ReadUser|QFile::WriteUser);
// Remove the file
return f.remove();
}
/**
* Returns the size of a file.
* If the file is a folder, it will compute its size based on its content.
*
* Returns -1 in case of error.
*/
qint64 fsutils::computePathSize(const QString& path) {
// Check if it is a file
QFileInfo fi(path);
if (!fi.exists()) return -1;
if (fi.isFile()) return fi.size();
// Compute folder size based on its content
qint64 size = 0;
foreach (const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) {
if (subfi.fileName().startsWith(".")) continue;
if (subfi.isDir())
size += fsutils::computePathSize(subfi.absoluteFilePath());
else
size += subfi.size();
}
return size;
}
/**
* Makes deep comparison of two files to make sure they are identical.
*/
bool fsutils::sameFiles(const QString& path1, const QString& path2) {
QFile f1(path1), f2(path2);
if (!f1.exists() || !f2.exists()) return false;
if (f1.size() != f2.size()) return false;
if (!f1.open(QIODevice::ReadOnly)) return false;
if (!f2.open(QIODevice::ReadOnly)) {
f1.close();
return false;
}
bool same = true;
while(!f1.atEnd() && !f2.atEnd()) {
if (f1.read(1024) != f2.read(1024)) {
same = false;
break;
}
}
f1.close(); f2.close();
return same;
}
QString fsutils::toValidFileSystemName(QString filename) {
qDebug("toValidFSName: %s", qPrintable(filename));
const QRegExp regex("[\\\\/:?\"*<>|]");
filename.replace(regex, " ");
qDebug("toValidFSName, result: %s", qPrintable(filename));
return filename.trimmed();
}
bool fsutils::isValidFileSystemName(const QString& filename) {
if (filename.isEmpty()) return false;
const QRegExp regex("[\\\\/:?\"*<>|]");
return !filename.contains(regex);
}
long long fsutils::freeDiskSpaceOnPath(QString path) {
if (path.isEmpty()) return -1;
QDir dir_path(path);
if (!dir_path.exists()) {
QStringList parts = path.split("/");
while (parts.size() > 1 && !QDir(parts.join("/")).exists()) {
parts.removeLast();
}
dir_path = QDir(parts.join("/"));
if (!dir_path.exists()) return -1;
}
Q_ASSERT(dir_path.exists());
#ifndef Q_OS_WIN
unsigned long long available;
#ifdef Q_OS_HAIKU
const QString statfs_path = dir_path.path()+"/.";
dev_t device = dev_for_path (qPrintable(statfs_path));
if (device >= 0) {
fs_info info;
if(fs_stat_dev(device, &info)==B_OK){
available = ((unsigned long long)(info.free_blocks*info.block_size));
return available;
}
}
return -1;
#else
struct statfs stats;
const QString statfs_path = dir_path.path()+"/.";
const int ret = statfs (qPrintable(statfs_path), &stats) ;
if (ret == 0) {
available = ((unsigned long long)stats.f_bavail) *
((unsigned long long)stats.f_bsize) ;
return available;
} else {
return -1;
}
#endif
#else
typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
PULARGE_INTEGER,
PULARGE_INTEGER,
PULARGE_INTEGER);
GetDiskFreeSpaceEx_t
pGetDiskFreeSpaceEx = (GetDiskFreeSpaceEx_t)::GetProcAddress
(
::GetModuleHandle(TEXT("kernel32.dll")),
"GetDiskFreeSpaceExW"
);
if ( pGetDiskFreeSpaceEx )
{
ULARGE_INTEGER bytesFree, bytesTotal;
unsigned long long *ret;
if (pGetDiskFreeSpaceEx((LPCTSTR)(fsutils::toNativePath(dir_path.path())).utf16(), &bytesFree, &bytesTotal, NULL)) {
ret = (unsigned long long*)&bytesFree;
return *ret;
} else {
return -1;
}
} else {
return -1;
}
#endif
}
QString fsutils::branchPath(const QString& file_path, QString* removed) {
QString ret = fsutils::fromNativePath(file_path);
if (ret.endsWith("/"))
ret.chop(1);
const int slashIndex = ret.lastIndexOf("/");
if (slashIndex >= 0) {
if (removed)
*removed = ret.mid(slashIndex + 1);
ret = ret.left(slashIndex);
}
return ret;
}
bool fsutils::sameFileNames(const QString &first, const QString &second) {
#if defined(Q_OS_UNIX) || defined(Q_WS_QWS)
return QString::compare(first, second, Qt::CaseSensitive) == 0;
#else
return QString::compare(first, second, Qt::CaseInsensitive) == 0;
#endif
}
QString fsutils::expandPath(const QString &path) {
QString ret = fsutils::fromNativePath(path.trimmed());
if (ret.isEmpty())
return ret;
return QDir::cleanPath(ret);
}
QString fsutils::expandPathAbs(const QString& path) {
QString ret = fsutils::expandPath(path);
if (!QDir::isAbsolutePath(ret))
ret = QDir(ret).absolutePath();
return ret;
}
QString fsutils::QDesktopServicesDataLocation() {
QString result;
#ifdef Q_OS_WIN
LPWSTR path=new WCHAR[256];
if (SHGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, FALSE))
result = fsutils::fromNativePath(QString::fromWCharArray(path));
if (!QCoreApplication::applicationName().isEmpty())
result += QLatin1String("/") + qApp->applicationName();
#else
#ifdef Q_OS_MAC
FSRef ref;
OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
if (err)
return QString();
QString path;
QByteArray ba(2048, 0);
if (FSRefMakePath(&ref, reinterpret_cast<UInt8 *>(ba.data()), ba.size()) == noErr)
result = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C);
result += QLatin1Char('/') + qApp->applicationName();
#else
QString xdgDataHome = QLatin1String(qgetenv("XDG_DATA_HOME"));
if (xdgDataHome.isEmpty())
xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
xdgDataHome += QLatin1String("/data/")
+ qApp->applicationName();
result = xdgDataHome;
#endif
#endif
if (!result.endsWith("/"))
result += "/";
return result;
}
QString fsutils::QDesktopServicesCacheLocation() {
QString result;
#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
result = QDesktopServicesDataLocation() + QLatin1String("cache");
#else
#ifdef Q_OS_MAC
// http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/Reference/reference.html
FSRef ref;
OSErr err = FSFindFolder(kUserDomain, kCachedDataFolderType, false, &ref);
if (err)
return QString();
QByteArray ba(2048, 0);
if (FSRefMakePath(&ref, reinterpret_cast<UInt8 *>(ba.data()), ba.size()) == noErr)
result = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C);
result += QLatin1Char('/') + qApp->applicationName();
#else
QString xdgCacheHome = QLatin1String(qgetenv("XDG_CACHE_HOME"));
if (xdgCacheHome.isEmpty())
xdgCacheHome = QDir::homePath() + QLatin1String("/.cache");
xdgCacheHome += QLatin1Char('/') + QCoreApplication::applicationName();
result = xdgCacheHome;
#endif
#endif
if (!result.endsWith("/"))
result += "/";
return result;
}
QString fsutils::QDesktopServicesDownloadLocation() {
#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
// as long as it stays WinXP like we do the same on OS/2
// TODO: Use IKnownFolderManager to get path of FOLDERID_Downloads
// instead of hardcoding "Downloads"
// Unfortunately, this would break compatibility with WinXP
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
return QDir(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)).absoluteFilePath(
QCoreApplication::translate("fsutils", "Downloads"));
#else
return QDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).absoluteFilePath(
QCoreApplication::translate("fsutils", "Downloads"));
#endif
#endif
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
QString save_path;
// Default save path on Linux
QString config_path = QString::fromLocal8Bit(qgetenv("XDG_CONFIG_HOME").constData());
if (config_path.isEmpty())
config_path = QDir::home().absoluteFilePath(".config");
QString user_dirs_file = config_path + "/user-dirs.dirs";
if (QFile::exists(user_dirs_file)) {
QSettings settings(user_dirs_file, QSettings::IniFormat);
// We need to force UTF-8 encoding here since this is not
// the default for Ini files.
settings.setIniCodec("UTF-8");
QString xdg_download_dir = settings.value("XDG_DOWNLOAD_DIR").toString();
if (!xdg_download_dir.isEmpty()) {
// Resolve $HOME environment variables
xdg_download_dir.replace("$HOME", QDir::homePath());
save_path = xdg_download_dir;
qDebug() << Q_FUNC_INFO << "SUCCESS: Using XDG path for downloads: " << save_path;
}
}
// Fallback
if (!save_path.isEmpty() && !QFile::exists(save_path)) {
QDir().mkpath(save_path);
}
if (save_path.isEmpty() || !QFile::exists(save_path)) {
save_path = QDir::home().absoluteFilePath(QCoreApplication::translate("fsutils", "Downloads"));
qDebug() << Q_FUNC_INFO << "using" << save_path << "as fallback since the XDG detection did not work";
}
return save_path;
#endif
#ifdef Q_OS_MAC
// TODO: How to support this on Mac OS X?
#endif
// Fallback
return QDir::home().absoluteFilePath(QCoreApplication::translate("fsutils", "Downloads"));
}
QString fsutils::searchEngineLocation() {
QString folder = "nova";
if (misc::pythonVersion() >= 3)
folder = "nova3";
const QString location = fsutils::expandPathAbs(QDesktopServicesDataLocation()
+ folder);
QDir locationDir(location);
if (!locationDir.exists())
locationDir.mkpath(locationDir.absolutePath());
return location;
}
QString fsutils::cacheLocation() {
QString location = fsutils::expandPathAbs(QDesktopServicesCacheLocation());
QDir locationDir(location);
if (!locationDir.exists())
locationDir.mkpath(locationDir.absolutePath());
return location;
}

View file

@ -38,8 +38,8 @@
#include <zlib.h> #include <zlib.h>
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "downloadmanager.h" #include "downloadmanager.h"
#include "downloadhandler.h" #include "downloadhandler.h"
@ -108,7 +108,7 @@ void DownloadHandler::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal)
// Total number of bytes is available // Total number of bytes is available
if (bytesTotal > m_sizeLimit) { if (bytesTotal > m_sizeLimit) {
m_reply->abort(); m_reply->abort();
emit downloadFailed(m_url, msg.arg(misc::friendlyUnit(bytesTotal)).arg(misc::friendlyUnit(m_sizeLimit))); emit downloadFailed(m_url, msg.arg(Utils::Misc::friendlyUnit(bytesTotal)).arg(Utils::Misc::friendlyUnit(m_sizeLimit)));
} }
else { else {
disconnect(m_reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(checkDownloadSize(qint64, qint64))); disconnect(m_reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(checkDownloadSize(qint64, qint64)));
@ -116,7 +116,7 @@ void DownloadHandler::checkDownloadSize(qint64 bytesReceived, qint64 bytesTotal)
} }
else if (bytesReceived > m_sizeLimit) { else if (bytesReceived > m_sizeLimit) {
m_reply->abort(); m_reply->abort();
emit downloadFailed(m_url, msg.arg(misc::friendlyUnit(bytesReceived)).arg(misc::friendlyUnit(m_sizeLimit))); emit downloadFailed(m_url, msg.arg(Utils::Misc::friendlyUnit(bytesReceived)).arg(Utils::Misc::friendlyUnit(m_sizeLimit)));
} }
} }
@ -154,7 +154,7 @@ bool DownloadHandler::saveToFile(QString &filePath)
} }
else { else {
delete tmpfile; delete tmpfile;
fsutils::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
} }
return false; return false;

View file

@ -50,8 +50,8 @@
#include <winreg.h> #include <winreg.h>
#endif #endif
#include "misc.h" #include "core/utils/fs.h"
#include "fs_utils.h" #include "core/utils/misc.h"
Preferences* Preferences::m_instance = 0; Preferences* Preferences::m_instance = 0;
@ -169,7 +169,7 @@ bool Preferences::save()
QString final_path = new_path; QString final_path = new_path;
int index = final_path.lastIndexOf("_new", -1, Qt::CaseInsensitive); int index = final_path.lastIndexOf("_new", -1, Qt::CaseInsensitive);
final_path.remove(index, 4); final_path.remove(index, 4);
fsutils::forceRemove(final_path); Utils::Fs::forceRemove(final_path);
QFile::rename(new_path, final_path); QFile::rename(new_path, final_path);
#else #else
delete settings; delete settings;
@ -347,7 +347,7 @@ void Preferences::setWinStartup(bool b)
{ {
QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat); QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat);
if (b) { if (b) {
const QString bin_path = "\"" + fsutils::toNativePath(qApp->applicationFilePath()) + "\""; const QString bin_path = "\"" + Utils::Fs::toNativePath(qApp->applicationFilePath()) + "\"";
settings.setValue("qBittorrent", bin_path); settings.setValue("qBittorrent", bin_path);
} }
else { else {
@ -361,13 +361,13 @@ QString Preferences::getSavePath() const
{ {
QString save_path = value("Preferences/Downloads/SavePath").toString(); QString save_path = value("Preferences/Downloads/SavePath").toString();
if (!save_path.isEmpty()) if (!save_path.isEmpty())
return fsutils::fromNativePath(save_path); return Utils::Fs::fromNativePath(save_path);
return fsutils::QDesktopServicesDownloadLocation(); return Utils::Fs::QDesktopServicesDownloadLocation();
} }
void Preferences::setSavePath(const QString &save_path) void Preferences::setSavePath(const QString &save_path)
{ {
setValue("Preferences/Downloads/SavePath", fsutils::fromNativePath(save_path)); setValue("Preferences/Downloads/SavePath", Utils::Fs::fromNativePath(save_path));
} }
bool Preferences::isTempPathEnabled() const bool Preferences::isTempPathEnabled() const
@ -383,12 +383,12 @@ void Preferences::setTempPathEnabled(bool enabled)
QString Preferences::getTempPath() const QString Preferences::getTempPath() const
{ {
const QString temp = QDir(getSavePath()).absoluteFilePath("temp"); const QString temp = QDir(getSavePath()).absoluteFilePath("temp");
return fsutils::fromNativePath(value("Preferences/Downloads/TempPath", temp).toString()); return Utils::Fs::fromNativePath(value("Preferences/Downloads/TempPath", temp).toString());
} }
void Preferences::setTempPath(const QString &path) void Preferences::setTempPath(const QString &path)
{ {
setValue("Preferences/Downloads/TempPath", fsutils::fromNativePath(path)); setValue("Preferences/Downloads/TempPath", Utils::Fs::fromNativePath(path));
} }
bool Preferences::useIncompleteFilesExtension() const bool Preferences::useIncompleteFilesExtension() const
@ -413,12 +413,12 @@ void Preferences::setAppendTorrentLabel(bool b)
QString Preferences::lastLocationPath() const QString Preferences::lastLocationPath() const
{ {
return fsutils::fromNativePath(value("Preferences/Downloads/LastLocationPath").toString()); return Utils::Fs::fromNativePath(value("Preferences/Downloads/LastLocationPath").toString());
} }
void Preferences::setLastLocationPath(const QString &path) void Preferences::setLastLocationPath(const QString &path)
{ {
setValue("Preferences/Downloads/LastLocationPath", fsutils::fromNativePath(path)); setValue("Preferences/Downloads/LastLocationPath", Utils::Fs::fromNativePath(path));
} }
bool Preferences::preAllocateAllFiles() const bool Preferences::preAllocateAllFiles() const
@ -469,7 +469,7 @@ QStringList Preferences::getScanDirs() const
QStringList newList; QStringList newList;
foreach (const QString& s, originalList) foreach (const QString& s, originalList)
newList << fsutils::fromNativePath(s); newList << Utils::Fs::fromNativePath(s);
return newList; return newList;
} }
@ -479,28 +479,28 @@ void Preferences::setScanDirs(const QStringList &dirs)
QStringList newList; QStringList newList;
if (!dirs.isEmpty()) if (!dirs.isEmpty())
foreach (const QString& s, dirs) foreach (const QString& s, dirs)
newList << fsutils::fromNativePath(s); newList << Utils::Fs::fromNativePath(s);
setValue("Preferences/Downloads/ScanDirs", newList); setValue("Preferences/Downloads/ScanDirs", newList);
} }
QList<bool> Preferences::getDownloadInScanDirs() const QList<bool> Preferences::getDownloadInScanDirs() const
{ {
return misc::boolListfromStringList(value("Preferences/Downloads/DownloadInScanDirs").toStringList()); return Utils::Misc::boolListfromStringList(value("Preferences/Downloads/DownloadInScanDirs").toStringList());
} }
void Preferences::setDownloadInScanDirs(const QList<bool> &list) void Preferences::setDownloadInScanDirs(const QList<bool> &list)
{ {
setValue("Preferences/Downloads/DownloadInScanDirs", misc::toStringList(list)); setValue("Preferences/Downloads/DownloadInScanDirs", Utils::Misc::toStringList(list));
} }
QString Preferences::getScanDirsLastPath() const QString Preferences::getScanDirsLastPath() const
{ {
return fsutils::fromNativePath(value("Preferences/Downloads/ScanDirsLastPath").toString()); return Utils::Fs::fromNativePath(value("Preferences/Downloads/ScanDirsLastPath").toString());
} }
void Preferences::setScanDirsLastPath(const QString &path) void Preferences::setScanDirsLastPath(const QString &path)
{ {
setValue("Preferences/Downloads/ScanDirsLastPath", fsutils::fromNativePath(path)); setValue("Preferences/Downloads/ScanDirsLastPath", Utils::Fs::fromNativePath(path));
} }
bool Preferences::isTorrentExportEnabled() const bool Preferences::isTorrentExportEnabled() const
@ -510,12 +510,12 @@ bool Preferences::isTorrentExportEnabled() const
QString Preferences::getTorrentExportDir() const QString Preferences::getTorrentExportDir() const
{ {
return fsutils::fromNativePath(value("Preferences/Downloads/TorrentExportDir").toString()); return Utils::Fs::fromNativePath(value("Preferences/Downloads/TorrentExportDir").toString());
} }
void Preferences::setTorrentExportDir(QString path) void Preferences::setTorrentExportDir(QString path)
{ {
setValue("Preferences/Downloads/TorrentExportDir", fsutils::fromNativePath(path.trimmed())); setValue("Preferences/Downloads/TorrentExportDir", Utils::Fs::fromNativePath(path.trimmed()));
} }
bool Preferences::isFinishedTorrentExportEnabled() const bool Preferences::isFinishedTorrentExportEnabled() const
@ -525,12 +525,12 @@ bool Preferences::isFinishedTorrentExportEnabled() const
QString Preferences::getFinishedTorrentExportDir() const QString Preferences::getFinishedTorrentExportDir() const
{ {
return fsutils::fromNativePath(value("Preferences/Downloads/FinishedTorrentExportDir").toString()); return Utils::Fs::fromNativePath(value("Preferences/Downloads/FinishedTorrentExportDir").toString());
} }
void Preferences::setFinishedTorrentExportDir(QString path) void Preferences::setFinishedTorrentExportDir(QString path)
{ {
setValue("Preferences/Downloads/FinishedTorrentExportDir", fsutils::fromNativePath(path.trimmed())); setValue("Preferences/Downloads/FinishedTorrentExportDir", Utils::Fs::fromNativePath(path.trimmed()));
} }
bool Preferences::isMailNotificationEnabled() const bool Preferences::isMailNotificationEnabled() const
@ -975,12 +975,12 @@ void Preferences::setFilteringEnabled(bool enabled)
QString Preferences::getFilter() const QString Preferences::getFilter() const
{ {
return fsutils::fromNativePath(value("Preferences/IPFilter/File").toString()); return Utils::Fs::fromNativePath(value("Preferences/IPFilter/File").toString());
} }
void Preferences::setFilter(const QString &path) void Preferences::setFilter(const QString &path)
{ {
setValue("Preferences/IPFilter/File", fsutils::fromNativePath(path)); setValue("Preferences/IPFilter/File", Utils::Fs::fromNativePath(path));
} }
QStringList Preferences::bannedIPs() const QStringList Preferences::bannedIPs() const
@ -1275,12 +1275,12 @@ void Preferences::setAutoRunEnabled(bool enabled)
QString Preferences::getAutoRunProgram() const QString Preferences::getAutoRunProgram() const
{ {
return fsutils::fromNativePath(value("AutoRun/program").toString()); return Utils::Fs::fromNativePath(value("AutoRun/program").toString());
} }
void Preferences::setAutoRunProgram(const QString &program) void Preferences::setAutoRunProgram(const QString &program)
{ {
setValue("AutoRun/program", fsutils::fromNativePath(program)); setValue("AutoRun/program", Utils::Fs::fromNativePath(program));
} }
bool Preferences::shutdownWhenDownloadsComplete() const bool Preferences::shutdownWhenDownloadsComplete() const
@ -1788,12 +1788,12 @@ bool Preferences::isMagnetLinkAssocSet()
// Check magnet link assoc // Check magnet link assoc
QRegExp exe_reg("\"([^\"]+)\".*"); QRegExp exe_reg("\"([^\"]+)\".*");
QString shell_command = fsutils::toNativePath(settings.value("magnet/shell/open/command/Default", "").toString()); QString shell_command = Utils::Fs::toNativePath(settings.value("magnet/shell/open/command/Default", "").toString());
if (exe_reg.indexIn(shell_command) < 0) if (exe_reg.indexIn(shell_command) < 0)
return false; return false;
QString assoc_exe = exe_reg.cap(1); QString assoc_exe = exe_reg.cap(1);
qDebug("exe: %s", qPrintable(assoc_exe)); qDebug("exe: %s", qPrintable(assoc_exe));
if (assoc_exe.compare(fsutils::toNativePath(qApp->applicationFilePath()), Qt::CaseInsensitive) != 0) if (assoc_exe.compare(Utils::Fs::toNativePath(qApp->applicationFilePath()), Qt::CaseInsensitive) != 0)
return false; return false;
return true; return true;
@ -1829,9 +1829,9 @@ void Preferences::setMagnetLinkAssoc(bool set)
settings.setValue("magnet/Default", "URL:Magnet link"); settings.setValue("magnet/Default", "URL:Magnet link");
settings.setValue("magnet/Content Type", "application/x-magnet"); settings.setValue("magnet/Content Type", "application/x-magnet");
settings.setValue("magnet/URL Protocol", ""); settings.setValue("magnet/URL Protocol", "");
settings.setValue("magnet/DefaultIcon/Default", fsutils::toNativePath(icon_str)); settings.setValue("magnet/DefaultIcon/Default", Utils::Fs::toNativePath(icon_str));
settings.setValue("magnet/shell/Default", "open"); settings.setValue("magnet/shell/Default", "open");
settings.setValue("magnet/shell/open/command/Default", fsutils::toNativePath(command_str)); settings.setValue("magnet/shell/open/command/Default", Utils::Fs::toNativePath(command_str));
} }
else if (isMagnetLinkAssocSet()) { else if (isMagnetLinkAssocSet()) {
settings.remove("magnet"); settings.remove("magnet");

View file

@ -34,8 +34,8 @@
#include <QStringList> #include <QStringList>
#include <QTemporaryFile> #include <QTemporaryFile>
#include "misc.h" #include "utils/misc.h"
#include "fs_utils.h" #include "utils/fs.h"
#include "preferences.h" #include "preferences.h"
#include "filesystemwatcher.h" #include "filesystemwatcher.h"
#include "bittorrent/session.h" #include "bittorrent/session.h"
@ -122,7 +122,7 @@ QVariant ScanFoldersModel::data(const QModelIndex &index, int role) const
const PathData *pathData = m_pathList.at(index.row()); const PathData *pathData = m_pathList.at(index.row());
if ((index.column() == PathColumn) && (role == Qt::DisplayRole)) if ((index.column() == PathColumn) && (role == Qt::DisplayRole))
return fsutils::toNativePath(pathData->path); return Utils::Fs::toNativePath(pathData->path);
if ((index.column() == DownloadAtTorrentColumn) && (role == Qt::CheckStateRole)) if ((index.column() == DownloadAtTorrentColumn) && (role == Qt::CheckStateRole))
return (pathData->downloadAtPath ? Qt::Checked : Qt::Unchecked); return (pathData->downloadAtPath ? Qt::Checked : Qt::Unchecked);
@ -230,7 +230,7 @@ bool ScanFoldersModel::downloadInTorrentFolder(const QString &filePath) const
int ScanFoldersModel::findPathData(const QString &path) const int ScanFoldersModel::findPathData(const QString &path) const
{ {
for (int i = 0; i < m_pathList.count(); ++i) for (int i = 0; i < m_pathList.count(); ++i)
if (m_pathList.at(i)->path == fsutils::fromNativePath(path)) if (m_pathList.at(i)->path == Utils::Fs::fromNativePath(path))
return i; return i;
return -1; return -1;
@ -285,7 +285,7 @@ void ScanFoldersModel::addTorrentsToSession(const QStringList &pathList)
BitTorrent::TorrentInfo torrentInfo = BitTorrent::TorrentInfo::loadFromFile(file); BitTorrent::TorrentInfo torrentInfo = BitTorrent::TorrentInfo::loadFromFile(file);
if (torrentInfo.isValid()) { if (torrentInfo.isValid()) {
BitTorrent::Session::instance()->addTorrent(torrentInfo, params); BitTorrent::Session::instance()->addTorrent(torrentInfo, params);
fsutils::forceRemove(file); Utils::Fs::forceRemove(file);
} }
else { else {
qDebug("Ignoring incomplete torrent file: %s", qPrintable(file)); qDebug("Ignoring incomplete torrent file: %s", qPrintable(file));

View file

@ -45,6 +45,7 @@ public:\
#define END_SCOPED_ENUM ; }; #define END_SCOPED_ENUM ; };
const qlonglong MAX_ETA = 8640000;
BEGIN_SCOPED_ENUM(MaxRatioAction) BEGIN_SCOPED_ENUM(MaxRatioAction)
{ {
@ -60,4 +61,13 @@ BEGIN_SCOPED_ENUM(TorrentExportFolder)
} }
END_SCOPED_ENUM END_SCOPED_ENUM
BEGIN_SCOPED_ENUM(ShutdownAction)
{
None,
Shutdown,
Suspend,
Hibernate
}
END_SCOPED_ENUM
#endif // TYPES_H #endif // TYPES_H

492
src/core/utils/fs.cpp Normal file
View file

@ -0,0 +1,492 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2012 Christophe Dumez
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*
* Contact : chris@qbittorrent.org
*/
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QCoreApplication>
#ifdef Q_OS_MAC
#include <CoreServices/CoreServices.h>
#include <Carbon/Carbon.h>
#endif
#ifndef Q_OS_WIN
#if defined(Q_OS_MAC) || defined(Q_OS_FREEBSD)
#include <sys/param.h>
#include <sys/mount.h>
#elif defined(Q_OS_HAIKU)
#include <kernel/fs_info.h>
#else
#include <sys/vfs.h>
#endif
#else
#include <shlobj.h>
#include <winbase.h>
#endif
#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QDesktopServices>
#else
#include <QStandardPaths>
#endif
#endif
#include "misc.h"
#include "fs.h"
/**
* Converts a path to a string suitable for display.
* This function makes sure the directory separator used is consistent
* with the OS being run.
*/
QString Utils::Fs::toNativePath(const QString& path)
{
return QDir::toNativeSeparators(path);
}
QString Utils::Fs::fromNativePath(const QString &path)
{
return QDir::fromNativeSeparators(path);
}
/**
* Returns the file extension part of a file name.
*/
QString Utils::Fs::fileExtension(const QString &filename)
{
QString ext = QString(filename).remove(".!qB");
const int point_index = ext.lastIndexOf(".");
return (point_index >= 0) ? ext.mid(point_index + 1) : QString();
}
QString Utils::Fs::fileName(const QString& file_path)
{
QString path = fromNativePath(file_path);
const int slash_index = path.lastIndexOf("/");
if (slash_index == -1)
return path;
return path.mid(slash_index + 1);
}
QString Utils::Fs::folderName(const QString& file_path)
{
QString path = fromNativePath(file_path);
const int slash_index = path.lastIndexOf("/");
if (slash_index == -1)
return path;
return path.left(slash_index);
}
/**
* Remove an empty folder tree.
*
* This function will also remove .DS_Store files on Mac OS and
* Thumbs.db on Windows.
*/
bool Utils::Fs::smartRemoveEmptyFolderTree(const QString& dir_path)
{
qDebug() << Q_FUNC_INFO << dir_path;
if (dir_path.isEmpty())
return false;
QDir dir(dir_path);
if (!dir.exists())
return true;
// Remove Files created by the OS
#if defined Q_OS_MAC
forceRemove(dir_path + QLatin1String("/.DS_Store"));
#elif defined Q_OS_WIN
forceRemove(dir_path + QLatin1String("/Thumbs.db"));
#endif
QFileInfoList sub_files = dir.entryInfoList();
foreach (const QFileInfo& info, sub_files) {
QString sub_name = info.fileName();
if (sub_name == "." || sub_name == "..")
continue;
QString sub_path = info.absoluteFilePath();
qDebug() << Q_FUNC_INFO << "sub file: " << sub_path;
if (info.isDir()) {
if (!smartRemoveEmptyFolderTree(sub_path)) {
qWarning() << Q_FUNC_INFO << "Failed to remove folder: " << sub_path;
return false;
}
}
else {
if (info.isHidden()) {
qDebug() << Q_FUNC_INFO << "Removing hidden file: " << sub_path;
if (!forceRemove(sub_path)) {
qWarning() << Q_FUNC_INFO << "Failed to remove " << sub_path;
return false;
}
}
else {
qWarning() << Q_FUNC_INFO << "Folder is not empty, aborting. Found: " << sub_path;
}
}
}
qDebug() << Q_FUNC_INFO << "Calling rmdir on " << dir_path;
return QDir().rmdir(dir_path);
}
/**
* Removes the file with the given file_path.
*
* This function will try to fix the file permissions before removing it.
*/
bool Utils::Fs::forceRemove(const QString& file_path)
{
QFile f(file_path);
if (!f.exists())
return true;
// Make sure we have read/write permissions
f.setPermissions(f.permissions() | QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::WriteUser);
// Remove the file
return f.remove();
}
/**
* Returns the size of a file.
* If the file is a folder, it will compute its size based on its content.
*
* Returns -1 in case of error.
*/
qint64 Utils::Fs::computePathSize(const QString& path)
{
// Check if it is a file
QFileInfo fi(path);
if (!fi.exists()) return -1;
if (fi.isFile()) return fi.size();
// Compute folder size based on its content
qint64 size = 0;
foreach (const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) {
if (subfi.fileName().startsWith(".")) continue;
if (subfi.isDir())
size += computePathSize(subfi.absoluteFilePath());
else
size += subfi.size();
}
return size;
}
/**
* Makes deep comparison of two files to make sure they are identical.
*/
bool Utils::Fs::sameFiles(const QString& path1, const QString& path2)
{
QFile f1(path1), f2(path2);
if (!f1.exists() || !f2.exists()) return false;
if (f1.size() != f2.size()) return false;
if (!f1.open(QIODevice::ReadOnly)) return false;
if (!f2.open(QIODevice::ReadOnly)) {
f1.close();
return false;
}
bool same = true;
while(!f1.atEnd() && !f2.atEnd()) {
if (f1.read(1024) != f2.read(1024)) {
same = false;
break;
}
}
f1.close(); f2.close();
return same;
}
QString Utils::Fs::toValidFileSystemName(QString filename)
{
qDebug("toValidFSName: %s", qPrintable(filename));
const QRegExp regex("[\\\\/:?\"*<>|]");
filename.replace(regex, " ");
qDebug("toValidFSName, result: %s", qPrintable(filename));
return filename.trimmed();
}
bool Utils::Fs::isValidFileSystemName(const QString& filename)
{
if (filename.isEmpty()) return false;
const QRegExp regex("[\\\\/:?\"*<>|]");
return !filename.contains(regex);
}
qlonglong Utils::Fs::freeDiskSpaceOnPath(QString path)
{
if (path.isEmpty()) return -1;
QDir dir_path(path);
if (!dir_path.exists()) {
QStringList parts = path.split("/");
while (parts.size() > 1 && !QDir(parts.join("/")).exists()) {
parts.removeLast();
}
dir_path = QDir(parts.join("/"));
if (!dir_path.exists()) return -1;
}
Q_ASSERT(dir_path.exists());
#ifndef Q_OS_WIN
unsigned long long available;
#ifdef Q_OS_HAIKU
const QString statfs_path = dir_path.path() + "/.";
dev_t device = dev_for_path (qPrintable(statfs_path));
if (device >= 0) {
fs_info info;
if (fs_stat_dev(device, &info) == B_OK) {
available = ((unsigned long long)(info.free_blocks * info.block_size));
return available;
}
}
return -1;
#else
struct statfs stats;
const QString statfs_path = dir_path.path() + "/.";
const int ret = statfs(qPrintable(statfs_path), &stats);
if (ret == 0) {
available = ((unsigned long long)stats.f_bavail)
* ((unsigned long long)stats.f_bsize);
return available;
}
else {
return -1;
}
#endif
#else
typedef BOOL (WINAPI *GetDiskFreeSpaceEx_t)(LPCTSTR,
PULARGE_INTEGER,
PULARGE_INTEGER,
PULARGE_INTEGER);
GetDiskFreeSpaceEx_t pGetDiskFreeSpaceEx =
(GetDiskFreeSpaceEx_t)::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "GetDiskFreeSpaceExW");
if (pGetDiskFreeSpaceEx) {
ULARGE_INTEGER bytesFree, bytesTotal;
unsigned long long *ret;
if (pGetDiskFreeSpaceEx((LPCTSTR)(toNativePath(dir_path.path())).utf16(), &bytesFree, &bytesTotal, NULL)) {
ret = (unsigned long long*)&bytesFree;
return *ret;
}
else {
return -1;
}
}
else {
return -1;
}
#endif
}
QString Utils::Fs::branchPath(const QString& file_path, QString* removed)
{
QString ret = fromNativePath(file_path);
if (ret.endsWith("/"))
ret.chop(1);
const int slashIndex = ret.lastIndexOf("/");
if (slashIndex >= 0) {
if (removed)
*removed = ret.mid(slashIndex + 1);
ret = ret.left(slashIndex);
}
return ret;
}
bool Utils::Fs::sameFileNames(const QString &first, const QString &second)
{
#if defined(Q_OS_UNIX) || defined(Q_WS_QWS)
return QString::compare(first, second, Qt::CaseSensitive) == 0;
#else
return QString::compare(first, second, Qt::CaseInsensitive) == 0;
#endif
}
QString Utils::Fs::expandPath(const QString &path)
{
QString ret = fromNativePath(path.trimmed());
if (ret.isEmpty())
return ret;
return QDir::cleanPath(ret);
}
QString Utils::Fs::expandPathAbs(const QString& path)
{
QString ret = expandPath(path);
if (!QDir::isAbsolutePath(ret))
ret = QDir(ret).absolutePath();
return ret;
}
QString Utils::Fs::QDesktopServicesDataLocation()
{
QString result;
#ifdef Q_OS_WIN
LPWSTR path=new WCHAR[256];
if (SHGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, FALSE))
result = fromNativePath(QString::fromWCharArray(path));
if (!QCoreApplication::applicationName().isEmpty())
result += QLatin1String("/") + qApp->applicationName();
#else
#ifdef Q_OS_MAC
FSRef ref;
OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
if (err)
return QString();
QString path;
QByteArray ba(2048, 0);
if (FSRefMakePath(&ref, reinterpret_cast<UInt8 *>(ba.data()), ba.size()) == noErr)
result = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C);
result += QLatin1Char('/') + qApp->applicationName();
#else
QString xdgDataHome = QLatin1String(qgetenv("XDG_DATA_HOME"));
if (xdgDataHome.isEmpty())
xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
xdgDataHome += QLatin1String("/data/")
+ qApp->applicationName();
result = xdgDataHome;
#endif
#endif
if (!result.endsWith("/"))
result += "/";
return result;
}
QString Utils::Fs::QDesktopServicesCacheLocation()
{
QString result;
#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
result = QDesktopServicesDataLocation() + QLatin1String("cache");
#else
#ifdef Q_OS_MAC
// http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/Reference/reference.html
FSRef ref;
OSErr err = FSFindFolder(kUserDomain, kCachedDataFolderType, false, &ref);
if (err)
return QString();
QByteArray ba(2048, 0);
if (FSRefMakePath(&ref, reinterpret_cast<UInt8 *>(ba.data()), ba.size()) == noErr)
result = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C);
result += QLatin1Char('/') + qApp->applicationName();
#else
QString xdgCacheHome = QLatin1String(qgetenv("XDG_CACHE_HOME"));
if (xdgCacheHome.isEmpty())
xdgCacheHome = QDir::homePath() + QLatin1String("/.cache");
xdgCacheHome += QLatin1Char('/') + QCoreApplication::applicationName();
result = xdgCacheHome;
#endif
#endif
if (!result.endsWith("/"))
result += "/";
return result;
}
QString Utils::Fs::QDesktopServicesDownloadLocation()
{
#if defined(Q_OS_WIN) || defined(Q_OS_OS2)
// as long as it stays WinXP like we do the same on OS/2
// TODO: Use IKnownFolderManager to get path of FOLDERID_Downloads
// instead of hardcoding "Downloads"
// Unfortunately, this would break compatibility with WinXP
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
return QDir(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)).absoluteFilePath(
QCoreApplication::translate("fsutils", "Downloads"));
#else
return QDir(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)).absoluteFilePath(
QCoreApplication::translate("fsutils", "Downloads"));
#endif
#endif
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))
QString save_path;
// Default save path on Linux
QString config_path = QString::fromLocal8Bit(qgetenv("XDG_CONFIG_HOME").constData());
if (config_path.isEmpty())
config_path = QDir::home().absoluteFilePath(".config");
QString user_dirs_file = config_path + "/user-dirs.dirs";
if (QFile::exists(user_dirs_file)) {
QSettings settings(user_dirs_file, QSettings::IniFormat);
// We need to force UTF-8 encoding here since this is not
// the default for Ini files.
settings.setIniCodec("UTF-8");
QString xdg_download_dir = settings.value("XDG_DOWNLOAD_DIR").toString();
if (!xdg_download_dir.isEmpty()) {
// Resolve $HOME environment variables
xdg_download_dir.replace("$HOME", QDir::homePath());
save_path = xdg_download_dir;
qDebug() << Q_FUNC_INFO << "SUCCESS: Using XDG path for downloads: " << save_path;
}
}
// Fallback
if (!save_path.isEmpty() && !QFile::exists(save_path)) {
QDir().mkpath(save_path);
}
if (save_path.isEmpty() || !QFile::exists(save_path)) {
save_path = QDir::home().absoluteFilePath(QCoreApplication::translate("fsutils", "Downloads"));
qDebug() << Q_FUNC_INFO << "using" << save_path << "as fallback since the XDG detection did not work";
}
return save_path;
#endif
#ifdef Q_OS_MAC
// TODO: How to support this on Mac OS X?
#endif
// Fallback
return QDir::home().absoluteFilePath(QCoreApplication::translate("fsutils", "Downloads"));
}
QString Utils::Fs::searchEngineLocation()
{
QString folder = "nova";
if (Utils::Misc::pythonVersion() >= 3)
folder = "nova3";
const QString location = expandPathAbs(QDesktopServicesDataLocation() + folder);
QDir locationDir(location);
if (!locationDir.exists())
locationDir.mkpath(locationDir.absolutePath());
return location;
}
QString Utils::Fs::cacheLocation()
{
QString location = expandPathAbs(QDesktopServicesCacheLocation());
QDir locationDir(location);
if (!locationDir.exists())
locationDir.mkpath(locationDir.absolutePath());
return location;
}

View file

@ -1,5 +1,5 @@
/* /*
* Bittorrent Client using Qt4 and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2012 Christophe Dumez * Copyright (C) 2012 Christophe Dumez
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -28,43 +28,44 @@
* Contact : chris@qbittorrent.org * Contact : chris@qbittorrent.org
*/ */
#ifndef FS_UTILS_H #ifndef UTILS_FS_H
#define FS_UTILS_H #define UTILS_FS_H
#include <QString>
/** /**
* Utility functions related to file system. * Utility functions related to file system.
*/ */
namespace fsutils
#include <QString>
namespace Utils
{ {
namespace Fs
{
QString toNativePath(const QString& path);
QString fromNativePath(const QString& path);
QString fileExtension(const QString& filename);
QString fileName(const QString& file_path);
QString folderName(const QString& file_path);
qint64 computePathSize(const QString& path);
bool sameFiles(const QString& path1, const QString& path2);
QString toValidFileSystemName(QString filename);
bool isValidFileSystemName(const QString& filename);
qlonglong freeDiskSpaceOnPath(QString path);
QString branchPath(const QString& file_path, QString* removed = 0);
bool sameFileNames(const QString& first, const QString& second);
QString expandPath(const QString& path);
QString expandPathAbs(const QString& path);
bool smartRemoveEmptyFolderTree(const QString& dir_path);
bool forceRemove(const QString& file_path);
QString toNativePath(const QString& path); /* Ported from Qt4 to drop dependency on QtGui */
QString fromNativePath(const QString& path); QString QDesktopServicesDataLocation();
QString fileExtension(const QString& filename); QString QDesktopServicesCacheLocation();
QString fileName(const QString& file_path); QString QDesktopServicesDownloadLocation();
QString folderName(const QString& file_path); /* End of Qt4 code */
qint64 computePathSize(const QString& path); QString searchEngineLocation();
bool sameFiles(const QString& path1, const QString& path2); QString cacheLocation();
QString toValidFileSystemName(QString filename); }
bool isValidFileSystemName(const QString& filename);
long long freeDiskSpaceOnPath(QString path);
QString branchPath(const QString& file_path, QString* removed = 0);
bool sameFileNames(const QString& first, const QString& second);
QString expandPath(const QString& path);
QString expandPathAbs(const QString& path);
bool smartRemoveEmptyFolderTree(const QString& dir_path);
bool forceRemove(const QString& file_path);
/* Ported from Qt4 to drop dependency on QtGui */
QString QDesktopServicesDataLocation();
QString QDesktopServicesCacheLocation();
QString QDesktopServicesDownloadLocation();
/* End of Qt4 code */
QString searchEngineLocation();
QString cacheLocation();
} }
#endif // FS_UTILS_H #endif // UTILS_FS_H

View file

@ -28,8 +28,6 @@
* Contact : chris@qbittorrent.org * Contact : chris@qbittorrent.org
*/ */
#include <cmath>
#include <QUrl> #include <QUrl>
#include <QDir> #include <QDir>
#include <QFileInfo> #include <QFileInfo>
@ -38,7 +36,6 @@
#include <QDebug> #include <QDebug>
#include <QProcess> #include <QProcess>
#include <QSettings> #include <QSettings>
#include <QLocale>
#include <QThread> #include <QThread>
#ifdef DISABLE_GUI #ifdef DISABLE_GUI
@ -69,6 +66,7 @@ const int UNLEN = 256;
#endif #endif
#endif // DISABLE_GUI #endif // DISABLE_GUI
#include "core/utils/string.h"
#include "misc.h" #include "misc.h"
static struct { const char *source; const char *comment; } units[] = { static struct { const char *source; const char *comment; } units[] = {
@ -80,16 +78,16 @@ static struct { const char *source; const char *comment; } units[] = {
}; };
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
void misc::shutdownComputer(ShutDownAction action) void Utils::Misc::shutdownComputer(ShutdownAction action)
{ {
#if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) && defined(QT_DBUS_LIB) #if (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)) && defined(QT_DBUS_LIB)
// Use dbus to power off / suspend the system // Use dbus to power off / suspend the system
if (action != SHUTDOWN_COMPUTER) { if (action != ShutdownAction::Shutdown) {
// Some recent systems use systemd's logind // Some recent systems use systemd's logind
QDBusInterface login1Iface("org.freedesktop.login1", "/org/freedesktop/login1", QDBusInterface login1Iface("org.freedesktop.login1", "/org/freedesktop/login1",
"org.freedesktop.login1.Manager", QDBusConnection::systemBus()); "org.freedesktop.login1.Manager", QDBusConnection::systemBus());
if (login1Iface.isValid()) { if (login1Iface.isValid()) {
if (action == SUSPEND_COMPUTER) if (action == ShutdownAction::Suspend)
login1Iface.call("Suspend", false); login1Iface.call("Suspend", false);
else else
login1Iface.call("Hibernate", false); login1Iface.call("Hibernate", false);
@ -99,7 +97,7 @@ void misc::shutdownComputer(ShutDownAction action)
QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower", QDBusInterface upowerIface("org.freedesktop.UPower", "/org/freedesktop/UPower",
"org.freedesktop.UPower", QDBusConnection::systemBus()); "org.freedesktop.UPower", QDBusConnection::systemBus());
if (upowerIface.isValid()) { if (upowerIface.isValid()) {
if (action == SUSPEND_COMPUTER) if (action == ShutdownAction::Suspend)
upowerIface.call("Suspend"); upowerIface.call("Suspend");
else else
upowerIface.call("Hibernate"); upowerIface.call("Hibernate");
@ -109,7 +107,7 @@ void misc::shutdownComputer(ShutDownAction action)
QDBusInterface halIface("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer", QDBusInterface halIface("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer",
"org.freedesktop.Hal.Device.SystemPowerManagement", "org.freedesktop.Hal.Device.SystemPowerManagement",
QDBusConnection::systemBus()); QDBusConnection::systemBus());
if (action == SUSPEND_COMPUTER) if (action == ShutdownAction::Suspend)
halIface.call("Suspend", 5); halIface.call("Suspend", 5);
else else
halIface.call("Hibernate"); halIface.call("Hibernate");
@ -138,7 +136,7 @@ void misc::shutdownComputer(ShutDownAction action)
#endif #endif
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
AEEventID EventToSend; AEEventID EventToSend;
if (action != SHUTDOWN_COMPUTER) if (action != ShutdownAction::Shutdown)
EventToSend = kAESleep; EventToSend = kAESleep;
else else
EventToSend = kAEShutDown; EventToSend = kAEShutDown;
@ -193,9 +191,9 @@ void misc::shutdownComputer(ShutDownAction action)
if (GetLastError() != ERROR_SUCCESS) if (GetLastError() != ERROR_SUCCESS)
return; return;
if (action == SUSPEND_COMPUTER) if (action == ShutdownAction::Suspend)
SetSuspendState(false, false, false); SetSuspendState(false, false, false);
else if (action == HIBERNATE_COMPUTER) else if (action == ShutdownAction::Hibernate)
SetSuspendState(true, false, false); SetSuspendState(true, false, false);
else else
InitiateSystemShutdownA(0, QCoreApplication::translate("misc", "qBittorrent will shutdown the computer now because all downloads are complete.").toLocal8Bit().data(), 10, true, false); InitiateSystemShutdownA(0, QCoreApplication::translate("misc", "qBittorrent will shutdown the computer now because all downloads are complete.").toLocal8Bit().data(), 10, true, false);
@ -210,7 +208,7 @@ void misc::shutdownComputer(ShutDownAction action)
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
// Get screen center // Get screen center
QPoint misc::screenCenter(QWidget *win) QPoint Utils::Misc::screenCenter(QWidget *win)
{ {
int scrn = 0; int scrn = 0;
const QWidget *w = win->window(); const QWidget *w = win->window();
@ -231,7 +229,7 @@ QPoint misc::screenCenter(QWidget *win)
* Detects the version of python by calling * Detects the version of python by calling
* "python --version" and parsing the output. * "python --version" and parsing the output.
*/ */
int misc::pythonVersion() int Utils::Misc::pythonVersion()
{ {
static int version = -1; static int version = -1;
if (version < 0) { if (version < 0) {
@ -257,7 +255,7 @@ int misc::pythonVersion()
// see http://en.wikipedia.org/wiki/Kilobyte // see http://en.wikipedia.org/wiki/Kilobyte
// value must be given in bytes // value must be given in bytes
// to send numbers instead of strings with suffixes // to send numbers instead of strings with suffixes
QString misc::friendlyUnit(qreal val, bool is_speed) QString Utils::Misc::friendlyUnit(qreal val, bool is_speed)
{ {
if (val < 0) if (val < 0)
return QCoreApplication::translate("misc", "Unknown", "Unknown (size)"); return QCoreApplication::translate("misc", "Unknown", "Unknown (size)");
@ -268,13 +266,13 @@ QString misc::friendlyUnit(qreal val, bool is_speed)
if (i == 0) if (i == 0)
ret = QString::number((long)val) + " " + QCoreApplication::translate("misc", units[0].source, units[0].comment); ret = QString::number((long)val) + " " + QCoreApplication::translate("misc", units[0].source, units[0].comment);
else else
ret = accurateDoubleToString(val, 1) + " " + QCoreApplication::translate("misc", units[i].source, units[i].comment); ret = Utils::String::fromDouble(val, 1) + " " + QCoreApplication::translate("misc", units[i].source, units[i].comment);
if (is_speed) if (is_speed)
ret += QCoreApplication::translate("misc", "/s", "per second"); ret += QCoreApplication::translate("misc", "/s", "per second");
return ret; return ret;
} }
bool misc::isPreviewable(const QString& extension) bool Utils::Misc::isPreviewable(const QString& extension)
{ {
static QSet<QString> multimedia_extensions; static QSet<QString> multimedia_extensions;
if (multimedia_extensions.empty()) { if (multimedia_extensions.empty()) {
@ -327,7 +325,7 @@ bool misc::isPreviewable(const QString& extension)
return multimedia_extensions.contains(extension.toUpper()); return multimedia_extensions.contains(extension.toUpper());
} }
QString misc::bcLinkToMagnet(QString bc_link) QString Utils::Misc::bcLinkToMagnet(QString bc_link)
{ {
QByteArray raw_bc = bc_link.toUtf8(); QByteArray raw_bc = bc_link.toUtf8();
raw_bc = raw_bc.mid(8); // skip bc://bt/ raw_bc = raw_bc.mid(8); // skip bc://bt/
@ -344,7 +342,7 @@ QString misc::bcLinkToMagnet(QString bc_link)
// Take a number of seconds and return an user-friendly // Take a number of seconds and return an user-friendly
// time duration like "1d 2h 10m". // time duration like "1d 2h 10m".
QString misc::userFriendlyDuration(qlonglong seconds) QString Utils::Misc::userFriendlyDuration(qlonglong seconds)
{ {
if (seconds < 0 || seconds >= MAX_ETA) if (seconds < 0 || seconds >= MAX_ETA)
return QString::fromUtf8(""); return QString::fromUtf8("");
@ -366,7 +364,7 @@ QString misc::userFriendlyDuration(qlonglong seconds)
return QString::fromUtf8(""); return QString::fromUtf8("");
} }
QString misc::getUserIDString() QString Utils::Misc::getUserIDString()
{ {
QString uid = "0"; QString uid = "0";
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@ -380,7 +378,7 @@ QString misc::getUserIDString()
return uid; return uid;
} }
QStringList misc::toStringList(const QList<bool> &l) QStringList Utils::Misc::toStringList(const QList<bool> &l)
{ {
QStringList ret; QStringList ret;
foreach (const bool &b, l) foreach (const bool &b, l)
@ -388,7 +386,7 @@ QStringList misc::toStringList(const QList<bool> &l)
return ret; return ret;
} }
QList<int> misc::intListfromStringList(const QStringList &l) QList<int> Utils::Misc::intListfromStringList(const QStringList &l)
{ {
QList<int> ret; QList<int> ret;
foreach (const QString &s, l) foreach (const QString &s, l)
@ -396,7 +394,7 @@ QList<int> misc::intListfromStringList(const QStringList &l)
return ret; return ret;
} }
QList<bool> misc::boolListfromStringList(const QStringList &l) QList<bool> Utils::Misc::boolListfromStringList(const QStringList &l)
{ {
QList<bool> ret; QList<bool> ret;
foreach (const QString &s, l) foreach (const QString &s, l)
@ -404,14 +402,14 @@ QList<bool> misc::boolListfromStringList(const QStringList &l)
return ret; return ret;
} }
bool misc::isUrl(const QString &s) bool Utils::Misc::isUrl(const QString &s)
{ {
const QString scheme = QUrl(s).scheme(); const QString scheme = QUrl(s).scheme();
QRegExp is_url("http[s]?|ftp", Qt::CaseInsensitive); QRegExp is_url("http[s]?|ftp", Qt::CaseInsensitive);
return is_url.exactMatch(scheme); return is_url.exactMatch(scheme);
} }
QString misc::parseHtmlLinks(const QString &raw_text) QString Utils::Misc::parseHtmlLinks(const QString &raw_text)
{ {
QString result = raw_text; QString result = raw_text;
static QRegExp reURL( static QRegExp reURL(
@ -472,107 +470,20 @@ QString misc::parseHtmlLinks(const QString &raw_text)
return result; return result;
} }
#ifndef DISABLE_GUI namespace
bool misc::naturalSort(QString left, QString right, bool &result) // uses lessThan comparison
{ // Return value indicates if functions was successful
// result argument will contain actual comparison result if function was successful
int posL = 0;
int posR = 0;
do {
for (;; ) {
if (posL == left.size() || posR == right.size())
return false; // No data
QChar leftChar = left.at(posL);
QChar rightChar = right.at(posR);
bool leftCharIsDigit = leftChar.isDigit();
bool rightCharIsDigit = rightChar.isDigit();
if (leftCharIsDigit != rightCharIsDigit)
return false; // Digit positions mismatch
if (leftCharIsDigit)
break; // Both are digit, break this loop and compare numbers
if (leftChar != rightChar)
return false; // Strings' subsets before digit do not match
++posL;
++posR;
}
QString temp;
while (posL < left.size()) {
if (left.at(posL).isDigit())
temp += left.at(posL);
else
break;
posL++;
}
int numL = temp.toInt();
temp.clear();
while (posR < right.size()) {
if (right.at(posR).isDigit())
temp += right.at(posR);
else
break;
posR++;
}
int numR = temp.toInt();
if (numL != numR) {
result = (numL < numR);
return true;
}
// Strings + digits do match and we haven't hit string end
// Do another round
} while (true);
return false;
}
#endif
// to send numbers instead of strings with suffixes
QString misc::accurateDoubleToString(const double &n, const int &precision)
{ {
/* HACK because QString rounds up. Eg QString::number(0.999*100.0, 'f' ,1) == 99.9 // Trick to get a portable sleep() function
** but QString::number(0.9999*100.0, 'f' ,1) == 100.0 The problem manifests when class SleeperThread : public QThread
** the number has more digits after the decimal than we want AND the digit after
** our 'wanted' is >= 5. In this case our last digit gets rounded up. So for each
** precision we add an extra 0 behind 1 in the below algorithm. */
double prec = std::pow(10.0, precision);
return QLocale::system().toString(std::floor(n * prec) / prec, 'f', precision);
}
// Implements constant-time comparison to protect against timing attacks
// Taken from https://crackstation.net/hashing-security.htm
bool misc::slowEquals(const QByteArray &a, const QByteArray &b)
{
int lengthA = a.length();
int lengthB = b.length();
int diff = lengthA ^ lengthB;
for(int i = 0; i < lengthA && i < lengthB; i++)
diff |= a[i] ^ b[i];
return (diff == 0);
}
namespace {
// Trick to get a portable sleep() function
class SleeperThread: public QThread {
public:
static void msleep(unsigned long msecs)
{ {
QThread::msleep(msecs); public:
} static void msleep(unsigned long msecs)
}; {
QThread::msleep(msecs);
}
};
} }
void misc::msleep(unsigned long msecs) void Utils::Misc::msleep(unsigned long msecs)
{ {
SleeperThread::msleep(msecs); SleeperThread::msleep(msecs);
} }

View file

@ -28,8 +28,8 @@
* Contact : chris@qbittorrent.org * Contact : chris@qbittorrent.org
*/ */
#ifndef MISC_H #ifndef UTILS_MISC_H
#define MISC_H #define UTILS_MISC_H
#include <vector> #include <vector>
#include <QString> #include <QString>
@ -39,57 +39,43 @@
#include <QFile> #include <QFile>
#include <QDir> #include <QDir>
#include <QUrl> #include <QUrl>
#include "core/types.h"
namespace BitTorrent { class TorrentHandle; }
const qlonglong MAX_ETA = 8640000;
enum ShutDownAction { NO_SHUTDOWN, SHUTDOWN_COMPUTER, SUSPEND_COMPUTER, HIBERNATE_COMPUTER };
/* Miscellaneaous functions that can be useful */ /* Miscellaneaous functions that can be useful */
namespace misc
namespace Utils
{ {
namespace Misc
{
QString parseHtmlLinks(const QString &raw_text);
bool isUrl(const QString &s);
#ifndef DISABLE_GUI #ifndef DISABLE_GUI
void shutdownComputer(ShutDownAction action = SHUTDOWN_COMPUTER); void shutdownComputer(ShutdownAction action);
// Get screen center
QPoint screenCenter(QWidget *win);
#endif #endif
int pythonVersion();
// return best userfriendly storage unit (B, KiB, MiB, GiB, TiB)
// use Binary prefix standards from IEC 60027-2
// see http://en.wikipedia.org/wiki/Kilobyte
// value must be given in bytes
QString friendlyUnit(qreal val, bool is_speed = false);
bool isPreviewable(const QString& extension);
QString parseHtmlLinks(const QString &raw_text); QString bcLinkToMagnet(QString bc_link);
// Take a number of seconds and return an user-friendly
// time duration like "1d 2h 10m".
QString userFriendlyDuration(qlonglong seconds);
QString getUserIDString();
bool isUrl(const QString &s); // Convert functions
QStringList toStringList(const QList<bool> &l);
QList<int> intListfromStringList(const QStringList &l);
QList<bool> boolListfromStringList(const QStringList &l);
#ifndef DISABLE_GUI void msleep(unsigned long msecs);
// Get screen center }
QPoint screenCenter(QWidget *win);
#endif
int pythonVersion();
// return best userfriendly storage unit (B, KiB, MiB, GiB, TiB)
// use Binary prefix standards from IEC 60027-2
// see http://en.wikipedia.org/wiki/Kilobyte
// value must be given in bytes
QString friendlyUnit(qreal val, bool is_speed = false);
bool isPreviewable(const QString& extension);
QString bcLinkToMagnet(QString bc_link);
// Take a number of seconds and return an user-friendly
// time duration like "1d 2h 10m".
QString userFriendlyDuration(qlonglong seconds);
QString getUserIDString();
// Convert functions
QStringList toStringList(const QList<bool> &l);
QList<int> intListfromStringList(const QStringList &l);
QList<bool> boolListfromStringList(const QStringList &l);
QString accurateDoubleToString(const double &n, const int &precision);
#ifndef DISABLE_GUI
bool naturalSort(QString left, QString right, bool& result);
#endif
// Implements constant-time comparison to protect against timing attacks
// Taken from https://crackstation.net/hashing-security.htm
bool slowEquals(const QByteArray &a, const QByteArray &b);
void msleep(unsigned long msecs);
} }
#endif #endif

View file

@ -29,15 +29,106 @@
#include <QByteArray> #include <QByteArray>
#include <QString> #include <QString>
#include <QLocale>
#include <cmath>
#include "string.h" #include "string.h"
QString String::fromStdString(const std::string &str) QString Utils::String::fromStdString(const std::string &str)
{ {
return QString::fromUtf8(str.c_str()); return QString::fromUtf8(str.c_str());
} }
std::string String::toStdString(const QString &str) std::string Utils::String::toStdString(const QString &str)
{ {
QByteArray utf8 = str.toUtf8(); QByteArray utf8 = str.toUtf8();
return std::string(utf8.constData(), utf8.length()); return std::string(utf8.constData(), utf8.length());
} }
// uses lessThan comparison
bool Utils::String::naturalSort(QString left, QString right, bool &result)
{
// Return value indicates if functions was successful
// result argument will contain actual comparison result if function was successful
int posL = 0;
int posR = 0;
do {
forever {
if (posL == left.size() || posR == right.size())
return false; // No data
QChar leftChar = left.at(posL);
QChar rightChar = right.at(posR);
bool leftCharIsDigit = leftChar.isDigit();
bool rightCharIsDigit = rightChar.isDigit();
if (leftCharIsDigit != rightCharIsDigit)
return false; // Digit positions mismatch
if (leftCharIsDigit)
break; // Both are digit, break this loop and compare numbers
if (leftChar != rightChar)
return false; // Strings' subsets before digit do not match
++posL;
++posR;
}
QString temp;
while (posL < left.size()) {
if (left.at(posL).isDigit())
temp += left.at(posL);
else
break;
posL++;
}
int numL = temp.toInt();
temp.clear();
while (posR < right.size()) {
if (right.at(posR).isDigit())
temp += right.at(posR);
else
break;
posR++;
}
int numR = temp.toInt();
if (numL != numR) {
result = (numL < numR);
return true;
}
// Strings + digits do match and we haven't hit string end
// Do another round
} while (true);
return false;
}
// to send numbers instead of strings with suffixes
QString Utils::String::fromDouble(double n, int precision)
{
/* HACK because QString rounds up. Eg QString::number(0.999*100.0, 'f' ,1) == 99.9
** but QString::number(0.9999*100.0, 'f' ,1) == 100.0 The problem manifests when
** the number has more digits after the decimal than we want AND the digit after
** our 'wanted' is >= 5. In this case our last digit gets rounded up. So for each
** precision we add an extra 0 behind 1 in the below algorithm. */
double prec = std::pow(10.0, precision);
return QLocale::system().toString(std::floor(n * prec) / prec, 'f', precision);
}
// Implements constant-time comparison to protect against timing attacks
// Taken from https://crackstation.net/hashing-security.htm
bool Utils::String::slowEquals(const QByteArray &a, const QByteArray &b)
{
int lengthA = a.length();
int lengthB = b.length();
int diff = lengthA ^ lengthB;
for (int i = 0; (i < lengthA) && (i < lengthB); i++)
diff |= a[i] ^ b[i];
return (diff == 0);
}

View file

@ -33,11 +33,21 @@
#include <string> #include <string>
class QString; class QString;
class QByteArray;
namespace String namespace Utils
{ {
QString fromStdString(const std::string &str); namespace String
std::string toStdString(const QString &str); {
QString fromStdString(const std::string &str);
std::string toStdString(const QString &str);
bool naturalSort(QString left, QString right, bool &result);
QString fromDouble(double n, int precision);
// Implements constant-time comparison to protect against timing attacks
// Taken from https://crackstation.net/hashing-security.htm
bool slowEquals(const QByteArray &a, const QByteArray &b);
}
} }
#endif // UTILS_STRING_H #endif // UTILS_STRING_H

View file

@ -40,7 +40,7 @@
#include "core/bittorrent/magneturi.h" #include "core/bittorrent/magneturi.h"
#include "core/bittorrent/torrentinfo.h" #include "core/bittorrent/torrentinfo.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
#include "messageboxraised.h" #include "messageboxraised.h"
@ -66,7 +66,7 @@ AddNewTorrentDialog::AddNewTorrentDialog(QWidget *parent)
Preferences* const pref = Preferences::instance(); Preferences* const pref = Preferences::instance();
ui->start_torrent_cb->setChecked(!pref->addTorrentsInPause()); ui->start_torrent_cb->setChecked(!pref->addTorrentsInPause());
ui->save_path_combo->addItem(fsutils::toNativePath(pref->getSavePath()), pref->getSavePath()); ui->save_path_combo->addItem(Utils::Fs::toNativePath(pref->getSavePath()), pref->getSavePath());
loadSavePathHistory(); loadSavePathHistory();
connect(ui->save_path_combo, SIGNAL(currentIndexChanged(int)), SLOT(onSavePathChanged(int))); connect(ui->save_path_combo, SIGNAL(currentIndexChanged(int)), SLOT(onSavePathChanged(int)));
connect(ui->browse_button, SIGNAL(clicked()), SLOT(browseButton_clicked())); connect(ui->browse_button, SIGNAL(clicked()), SLOT(browseButton_clicked()));
@ -125,12 +125,12 @@ void AddNewTorrentDialog::show(QString source, QWidget *parent)
{ {
if (source.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (source.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
source = misc::bcLinkToMagnet(source); source = Utils::Misc::bcLinkToMagnet(source);
} }
AddNewTorrentDialog *dlg = new AddNewTorrentDialog(parent); AddNewTorrentDialog *dlg = new AddNewTorrentDialog(parent);
if (misc::isUrl(source)) { if (Utils::Misc::isUrl(source)) {
// Launch downloader // Launch downloader
Net::DownloadHandler *handler = Net::DownloadManager::instance()->downloadUrl(source, 10485760 /* 10MB */); Net::DownloadHandler *handler = Net::DownloadManager::instance()->downloadUrl(source, 10485760 /* 10MB */);
connect(handler, SIGNAL(downloadFinished(QString, QString)), dlg, SLOT(handleDownloadFinished(QString, QString))); connect(handler, SIGNAL(downloadFinished(QString, QString)), dlg, SLOT(handleDownloadFinished(QString, QString)));
@ -303,7 +303,7 @@ void AddNewTorrentDialog::updateFileNameInSavePaths(const QString &new_filename)
{ {
for(int i = 0; i < ui->save_path_combo->count(); ++i) { for(int i = 0; i < ui->save_path_combo->count(); ++i) {
const QDir folder(ui->save_path_combo->itemData(i).toString()); const QDir folder(ui->save_path_combo->itemData(i).toString());
ui->save_path_combo->setItemText(i, fsutils::toNativePath(folder.absoluteFilePath(new_filename))); ui->save_path_combo->setItemText(i, Utils::Fs::toNativePath(folder.absoluteFilePath(new_filename)));
} }
} }
@ -325,9 +325,9 @@ void AddNewTorrentDialog::updateDiskSpaceLabel()
} }
} }
QString size_string = torrent_size ? misc::friendlyUnit(torrent_size) : QString(tr("Not Available", "This size is unavailable.")); QString size_string = torrent_size ? Utils::Misc::friendlyUnit(torrent_size) : QString(tr("Not Available", "This size is unavailable."));
size_string += " ("; size_string += " (";
size_string += tr("Disk space: %1").arg(misc::friendlyUnit(fsutils::freeDiskSpaceOnPath( size_string += tr("Disk space: %1").arg(Utils::Misc::friendlyUnit(Utils::Fs::freeDiskSpaceOnPath(
ui->save_path_combo->itemData( ui->save_path_combo->itemData(
ui->save_path_combo->currentIndex()).toString()))); ui->save_path_combo->currentIndex()).toString())));
size_string += ")"; size_string += ")";
@ -353,10 +353,10 @@ void AddNewTorrentDialog::browseButton_clicked()
QString new_path, old_filename, new_filename; QString new_path, old_filename, new_filename;
if (m_torrentInfo.isValid() && (m_torrentInfo.filesCount() == 1)) { if (m_torrentInfo.isValid() && (m_torrentInfo.filesCount() == 1)) {
old_filename = fsutils::fileName(cur_save_path); old_filename = Utils::Fs::fileName(cur_save_path);
new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), cur_save_path, QString(), 0, QFileDialog::DontConfirmOverwrite); new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), cur_save_path, QString(), 0, QFileDialog::DontConfirmOverwrite);
if (!new_path.isEmpty()) if (!new_path.isEmpty())
new_path = fsutils::branchPath(new_path, &new_filename); new_path = Utils::Fs::branchPath(new_path, &new_filename);
qDebug() << "new_path: " << new_path; qDebug() << "new_path: " << new_path;
qDebug() << "new_filename: " << new_filename; qDebug() << "new_filename: " << new_filename;
} }
@ -374,13 +374,13 @@ void AddNewTorrentDialog::browseButton_clicked()
else { else {
// New path, prepend to combo box // New path, prepend to combo box
if (!new_filename.isEmpty()) if (!new_filename.isEmpty())
ui->save_path_combo->insertItem(0, fsutils::toNativePath(QDir(new_path).absoluteFilePath(new_filename)), new_path); ui->save_path_combo->insertItem(0, Utils::Fs::toNativePath(QDir(new_path).absoluteFilePath(new_filename)), new_path);
else else
ui->save_path_combo->insertItem(0, fsutils::toNativePath(new_path), new_path); ui->save_path_combo->insertItem(0, Utils::Fs::toNativePath(new_path), new_path);
ui->save_path_combo->setCurrentIndex(0); ui->save_path_combo->setCurrentIndex(0);
} }
// Update file name in all save_paths // Update file name in all save_paths
if (!new_filename.isEmpty() && !fsutils::sameFileNames(old_filename, new_filename)) { if (!new_filename.isEmpty() && !Utils::Fs::sameFileNames(old_filename, new_filename)) {
m_torrentInfo.renameFile(0, new_filename); m_torrentInfo.renameFile(0, new_filename);
updateFileNameInSavePaths(new_filename); updateFileNameInSavePaths(new_filename);
} }
@ -419,7 +419,7 @@ void AddNewTorrentDialog::renameSelectedFile()
tr("New name:"), QLineEdit::Normal, tr("New name:"), QLineEdit::Normal,
index.data().toString(), &ok).trimmed(); index.data().toString(), &ok).trimmed();
if (ok && !new_name_last.isEmpty()) { if (ok && !new_name_last.isEmpty()) {
if (!fsutils::isValidFileSystemName(new_name_last)) { if (!Utils::Fs::isValidFileSystemName(new_name_last)) {
MessageBoxRaised::warning(this, tr("The file could not be renamed"), MessageBoxRaised::warning(this, tr("The file could not be renamed"),
tr("This file name contains forbidden characters, please choose a different one."), tr("This file name contains forbidden characters, please choose a different one."),
QMessageBox::Ok); QMessageBox::Ok);
@ -428,22 +428,22 @@ void AddNewTorrentDialog::renameSelectedFile()
if (m_contentModel->itemType(index) == TorrentContentModelItem::FileType) { if (m_contentModel->itemType(index) == TorrentContentModelItem::FileType) {
// File renaming // File renaming
const int file_index = m_contentModel->getFileIndex(index); const int file_index = m_contentModel->getFileIndex(index);
QString old_name = fsutils::fromNativePath(m_torrentInfo.filePath(file_index)); QString old_name = Utils::Fs::fromNativePath(m_torrentInfo.filePath(file_index));
qDebug("Old name: %s", qPrintable(old_name)); qDebug("Old name: %s", qPrintable(old_name));
QStringList path_items = old_name.split("/"); QStringList path_items = old_name.split("/");
path_items.removeLast(); path_items.removeLast();
path_items << new_name_last; path_items << new_name_last;
QString new_name = path_items.join("/"); QString new_name = path_items.join("/");
if (fsutils::sameFileNames(old_name, new_name)) { if (Utils::Fs::sameFileNames(old_name, new_name)) {
qDebug("Name did not change"); qDebug("Name did not change");
return; return;
} }
new_name = fsutils::expandPath(new_name); new_name = Utils::Fs::expandPath(new_name);
qDebug("New name: %s", qPrintable(new_name)); qDebug("New name: %s", qPrintable(new_name));
// Check if that name is already used // Check if that name is already used
for (int i = 0; i < m_torrentInfo.filesCount(); ++i) { for (int i = 0; i < m_torrentInfo.filesCount(); ++i) {
if (i == file_index) continue; if (i == file_index) continue;
if (fsutils::sameFileNames(m_torrentInfo.filePath(i), new_name)) { if (Utils::Fs::sameFileNames(m_torrentInfo.filePath(i), new_name)) {
// Display error message // Display error message
MessageBoxRaised::warning(this, tr("The file could not be renamed"), MessageBoxRaised::warning(this, tr("The file could not be renamed"),
tr("This name is already in use in this folder. Please use a different name."), tr("This name is already in use in this folder. Please use a different name."),
@ -490,7 +490,7 @@ void AddNewTorrentDialog::renameSelectedFile()
if (current_name.startsWith(old_path)) { if (current_name.startsWith(old_path)) {
QString new_name = current_name; QString new_name = current_name;
new_name.replace(0, old_path.length(), new_path); new_name.replace(0, old_path.length(), new_path);
new_name = fsutils::expandPath(new_name); new_name = Utils::Fs::expandPath(new_name);
qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name)); qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name));
m_torrentInfo.renameFile(i, new_name); m_torrentInfo.renameFile(i, new_name);
} }
@ -505,7 +505,7 @@ void AddNewTorrentDialog::renameSelectedFile()
void AddNewTorrentDialog::setdialogPosition() void AddNewTorrentDialog::setdialogPosition()
{ {
qApp->processEvents(); qApp->processEvents();
QPoint center(misc::screenCenter(this)); QPoint center(Utils::Misc::screenCenter(this));
// Adjust y // Adjust y
int y = Preferences::instance()->getAddNewTorrentDialogPos(); int y = Preferences::instance()->getAddNewTorrentDialogPos();
if (y >= 0) { if (y >= 0) {
@ -526,7 +526,7 @@ void AddNewTorrentDialog::loadSavePathHistory()
QStringList raw_path_history = Preferences::instance()->getAddNewTorrentDialogPathHistory(); QStringList raw_path_history = Preferences::instance()->getAddNewTorrentDialogPathHistory();
foreach (const QString &sp, raw_path_history) foreach (const QString &sp, raw_path_history)
if (QDir(sp) != default_save_path) if (QDir(sp) != default_save_path)
ui->save_path_combo->addItem(fsutils::toNativePath(sp), sp); ui->save_path_combo->addItem(Utils::Fs::toNativePath(sp), sp);
} }
void AddNewTorrentDialog::displayContentTreeMenu(const QPoint&) void AddNewTorrentDialog::displayContentTreeMenu(const QPoint&)
@ -694,7 +694,7 @@ void AddNewTorrentDialog::setupTreeview()
// Update save paths (append file name to them) // Update save paths (append file name to them)
QString single_file_relpath = m_torrentInfo.filePath(0); QString single_file_relpath = m_torrentInfo.filePath(0);
for (int i = 0; i < ui->save_path_combo->count(); ++i) for (int i = 0; i < ui->save_path_combo->count(); ++i)
ui->save_path_combo->setItemText(i, fsutils::toNativePath(QDir(ui->save_path_combo->itemText(i)).absoluteFilePath(single_file_relpath))); ui->save_path_combo->setItemText(i, Utils::Fs::toNativePath(QDir(ui->save_path_combo->itemText(i)).absoluteFilePath(single_file_relpath)));
} }
} }

View file

@ -36,7 +36,7 @@
#include "ui_confirmdeletiondlg.h" #include "ui_confirmdeletiondlg.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/misc.h" #include "core/utils/misc.h"
class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg { class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
Q_OBJECT Q_OBJECT
@ -53,7 +53,7 @@ class DeletionConfirmationDlg : public QDialog, private Ui::confirmDeletionDlg {
lbl_warn->setFixedWidth(lbl_warn->height()); lbl_warn->setFixedWidth(lbl_warn->height());
rememberBtn->setIcon(GuiIconProvider::instance()->getIcon("object-locked")); rememberBtn->setIcon(GuiIconProvider::instance()->getIcon("object-locked"));
move(misc::screenCenter(this)); move(Utils::Misc::screenCenter(this));
checkPermDelete->setChecked(Preferences::instance()->deleteTorrentFilesAsDefault()); checkPermDelete->setChecked(Preferences::instance()->deleteTorrentFilesAsDefault());
connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState())); connect(checkPermDelete, SIGNAL(clicked()), this, SLOT(updateRememberButtonState()));
buttonBox->button(QDialogButtonBox::Cancel)->setFocus(); buttonBox->button(QDialogButtonBox::Cancel)->setFocus();

View file

@ -64,7 +64,7 @@
#include <QFile> #include <QFile>
#include <QChar> #include <QChar>
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include <libtorrent/session.hpp> #include <libtorrent/session.hpp>
using namespace libtorrent; using namespace libtorrent;
@ -73,7 +73,7 @@ QString GeoIPManager::geoipFolder(bool embedded) {
#ifdef WITH_GEOIP_EMBEDDED #ifdef WITH_GEOIP_EMBEDDED
if (embedded) if (embedded)
return ":/geoip/"; return ":/geoip/";
return fsutils::QDesktopServicesDataLocation()+"geoip"+"/"; return Utils::Fs::QDesktopServicesDataLocation()+"geoip"+"/";
#else #else
Q_UNUSED(embedded); Q_UNUSED(embedded);
if (QFile::exists("/usr/local/share/GeoIP/GeoIP.dat")) if (QFile::exists("/usr/local/share/GeoIP/GeoIP.dat"))
@ -102,7 +102,7 @@ void GeoIPManager::exportEmbeddedDb() {
} }
// Remove destination files // Remove destination files
if (QFile::exists(geoipDBpath(false))) if (QFile::exists(geoipDBpath(false)))
fsutils::forceRemove(geoipDBpath(false)); Utils::Fs::forceRemove(geoipDBpath(false));
// Copy from executable to hard disk // Copy from executable to hard disk
qDebug("%s -> %s", qPrintable(geoipDBpath(true)), qPrintable(geoipDBpath(false))); qDebug("%s -> %s", qPrintable(geoipDBpath(true)), qPrintable(geoipDBpath(false)));
if (!QFile::copy(geoipDBpath(true), geoipDBpath(false))) { if (!QFile::copy(geoipDBpath(true), geoipDBpath(false))) {

View file

@ -49,7 +49,7 @@
#include "mainwindow.h" #include "mainwindow.h"
#include "transferlistwidget.h" #include "transferlistwidget.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "torrentcreatordlg.h" #include "torrentcreatordlg.h"
#include "downloadfromurldlg.h" #include "downloadfromurldlg.h"
#include "addnewtorrentdialog.h" #include "addnewtorrentdialog.h"
@ -874,7 +874,7 @@ void MainWindow::showEvent(QShowEvent *e)
// Make sure the window is initially centered // Make sure the window is initially centered
if (!m_posInitialized) { if (!m_posInitialized) {
move(misc::screenCenter(this)); move(Utils::Misc::screenCenter(this));
m_posInitialized = true; m_posInitialized = true;
} }
} }
@ -1045,9 +1045,9 @@ void MainWindow::on_actionOpen_triggered()
} }
// Save last dir to remember it // Save last dir to remember it
QStringList top_dir = fsutils::fromNativePath(pathsList.at(0)).split("/"); QStringList top_dir = Utils::Fs::fromNativePath(pathsList.at(0)).split("/");
top_dir.removeLast(); top_dir.removeLast();
pref->setMainLastDir(fsutils::fromNativePath(top_dir.join("/"))); pref->setMainLastDir(Utils::Fs::fromNativePath(top_dir.join("/")));
} }
void MainWindow::activate() void MainWindow::activate()
@ -1186,21 +1186,21 @@ void MainWindow::updateGUI()
html += "qBittorrent"; html += "qBittorrent";
html += "</div>"; html += "</div>";
html += "<div style='vertical-align: baseline; height: 18px;'>"; html += "<div style='vertical-align: baseline; height: 18px;'>";
html += "<img src=':/icons/skin/download.png'/>&nbsp;" + tr("DL speed: %1", "e.g: Download speed: 10 KiB/s").arg(misc::friendlyUnit(status.payloadDownloadRate(), true)); html += "<img src=':/icons/skin/download.png'/>&nbsp;" + tr("DL speed: %1", "e.g: Download speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate(), true));
html += "</div>"; html += "</div>";
html += "<div style='vertical-align: baseline; height: 18px;'>"; html += "<div style='vertical-align: baseline; height: 18px;'>";
html += "<img src=':/icons/skin/seeding.png'/>&nbsp;" + tr("UP speed: %1", "e.g: Upload speed: 10 KiB/s").arg(misc::friendlyUnit(status.payloadUploadRate(), true)); html += "<img src=':/icons/skin/seeding.png'/>&nbsp;" + tr("UP speed: %1", "e.g: Upload speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadUploadRate(), true));
html += "</div>"; html += "</div>";
#else #else
// OSes such as Windows do not support html here // OSes such as Windows do not support html here
QString html = tr("DL speed: %1", "e.g: Download speed: 10 KiB/s").arg(misc::friendlyUnit(status.payloadDownloadRate(), true)); QString html = tr("DL speed: %1", "e.g: Download speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate(), true));
html += "\n"; html += "\n";
html += tr("UP speed: %1", "e.g: Upload speed: 10 KiB/s").arg(misc::friendlyUnit(status.payloadUploadRate(), true)); html += tr("UP speed: %1", "e.g: Upload speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadUploadRate(), true));
#endif #endif
systrayIcon->setToolTip(html); // tray icon systrayIcon->setToolTip(html); // tray icon
} }
if (displaySpeedInTitle) if (displaySpeedInTitle)
setWindowTitle(tr("[D: %1, U: %2] qBittorrent %3", "D = Download; U = Upload; %3 is qBittorrent version").arg(misc::friendlyUnit(status.payloadDownloadRate(), true)).arg(misc::friendlyUnit(status.payloadUploadRate(), true)).arg(QString::fromUtf8(VERSION))); setWindowTitle(tr("[D: %1, U: %2] qBittorrent %3", "D = Download; U = Upload; %3 is qBittorrent version").arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate(), true)).arg(Utils::Misc::friendlyUnit(status.payloadUploadRate(), true)).arg(QString::fromUtf8(VERSION)));
} }
void MainWindow::showNotificationBaloon(QString title, QString msg) const void MainWindow::showNotificationBaloon(QString title, QString msg) const
@ -1377,7 +1377,7 @@ void MainWindow::on_actionSearch_engine_triggered()
bool res = false; bool res = false;
// Check if python is already in PATH // Check if python is already in PATH
if (misc::pythonVersion() > 0) if (Utils::Misc::pythonVersion() > 0)
res = true; res = true;
else else
res = addPythonPathToEnv(); res = addPythonPathToEnv();
@ -1567,7 +1567,7 @@ bool MainWindow::addPythonPathToEnv()
path_envar = ""; path_envar = "";
path_envar = python_path + ";" + path_envar; path_envar = python_path + ";" + path_envar;
qDebug("New PATH envvar is: %s", qPrintable(path_envar)); qDebug("New PATH envvar is: %s", qPrintable(path_envar));
qputenv("PATH", fsutils::toNativePath(path_envar).toLocal8Bit()); qputenv("PATH", Utils::Fs::toNativePath(path_envar).toLocal8Bit());
return true; return true;
} }
return false; return false;
@ -1590,7 +1590,7 @@ void MainWindow::pythonDownloadSuccess(const QString &url, const QString &filePa
QProcess installer; QProcess installer;
qDebug("Launching Python installer in passive mode..."); qDebug("Launching Python installer in passive mode...");
installer.start("msiexec.exe /passive /i " + fsutils::toNativePath(filePath) + ".msi"); installer.start("msiexec.exe /passive /i " + Utils::Fs::toNativePath(filePath) + ".msi");
// Wait for setup to complete // Wait for setup to complete
installer.waitForFinished(); installer.waitForFinished();
@ -1598,7 +1598,7 @@ void MainWindow::pythonDownloadSuccess(const QString &url, const QString &filePa
qDebug("Installer stderr: %s", installer.readAllStandardError().data()); qDebug("Installer stderr: %s", installer.readAllStandardError().data());
qDebug("Setup should be complete!"); qDebug("Setup should be complete!");
// Delete temp file // Delete temp file
fsutils::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
// Reload search engine // Reload search engine
has_python = addPythonPathToEnv(); has_python = addPythonPathToEnv();
if (has_python) { if (has_python) {

View file

@ -43,7 +43,7 @@
#include "options_imp.h" #include "options_imp.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "advancedsettings.h" #include "advancedsettings.h"
#include "core/scanfoldersmodel.h" #include "core/scanfoldersmodel.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
@ -545,14 +545,14 @@ void options_imp::loadOptions() {
#endif #endif
// End General preferences // End General preferences
// Downloads preferences // Downloads preferences
textSavePath->setText(fsutils::toNativePath(pref->getSavePath())); textSavePath->setText(Utils::Fs::toNativePath(pref->getSavePath()));
if (pref->isTempPathEnabled()) { if (pref->isTempPathEnabled()) {
// enable // enable
checkTempFolder->setChecked(true); checkTempFolder->setChecked(true);
} else { } else {
checkTempFolder->setChecked(false); checkTempFolder->setChecked(false);
} }
textTempPath->setText(fsutils::toNativePath(pref->getTempPath())); textTempPath->setText(Utils::Fs::toNativePath(pref->getTempPath()));
checkAppendLabel->setChecked(pref->appendTorrentLabel()); checkAppendLabel->setChecked(pref->appendTorrentLabel());
checkAppendqB->setChecked(pref->useIncompleteFilesExtension()); checkAppendqB->setChecked(pref->useIncompleteFilesExtension());
checkPreallocateAll->setChecked(pref->preAllocateAllFiles()); checkPreallocateAll->setChecked(pref->preAllocateAllFiles());
@ -560,7 +560,7 @@ void options_imp::loadOptions() {
checkAdditionDialogFront->setChecked(pref->additionDialogFront()); checkAdditionDialogFront->setChecked(pref->additionDialogFront());
checkStartPaused->setChecked(pref->addTorrentsInPause()); checkStartPaused->setChecked(pref->addTorrentsInPause());
strValue = fsutils::toNativePath(pref->getTorrentExportDir()); strValue = Utils::Fs::toNativePath(pref->getTorrentExportDir());
if (strValue.isEmpty()) { if (strValue.isEmpty()) {
// Disable // Disable
checkExportDir->setChecked(false); checkExportDir->setChecked(false);
@ -570,7 +570,7 @@ void options_imp::loadOptions() {
textExportDir->setText(strValue); textExportDir->setText(strValue);
} }
strValue = fsutils::toNativePath(pref->getFinishedTorrentExportDir()); strValue = Utils::Fs::toNativePath(pref->getFinishedTorrentExportDir());
if (strValue.isEmpty()) { if (strValue.isEmpty()) {
// Disable // Disable
checkExportDirFin->setChecked(false); checkExportDirFin->setChecked(false);
@ -735,7 +735,7 @@ void options_imp::loadOptions() {
// Misc preferences // Misc preferences
// * IP Filter // * IP Filter
checkIPFilter->setChecked(pref->isFilteringEnabled()); checkIPFilter->setChecked(pref->isFilteringEnabled());
textFilterPath->setText(fsutils::toNativePath(pref->getFilter())); textFilterPath->setText(Utils::Fs::toNativePath(pref->getFilter()));
// End IP Filter // End IP Filter
// Queueing system preferences // Queueing system preferences
checkEnableQueueing->setChecked(pref->isQueueingSystemEnabled()); checkEnableQueueing->setChecked(pref->isQueueingSystemEnabled());
@ -850,13 +850,13 @@ qreal options_imp::getMaxRatio() const {
QString options_imp::getSavePath() const { QString options_imp::getSavePath() const {
if (textSavePath->text().trimmed().isEmpty()) { if (textSavePath->text().trimmed().isEmpty()) {
QString save_path = Preferences::instance()->getSavePath(); QString save_path = Preferences::instance()->getSavePath();
textSavePath->setText(fsutils::toNativePath(save_path)); textSavePath->setText(Utils::Fs::toNativePath(save_path));
} }
return fsutils::expandPathAbs(textSavePath->text()); return Utils::Fs::expandPathAbs(textSavePath->text());
} }
QString options_imp::getTempPath() const { QString options_imp::getTempPath() const {
return fsutils::expandPathAbs(textTempPath->text()); return Utils::Fs::expandPathAbs(textTempPath->text());
} }
bool options_imp::isTempPathEnabled() const { bool options_imp::isTempPathEnabled() const {
@ -1051,13 +1051,13 @@ void options_imp::setLocale(const QString &localeStr) {
QString options_imp::getTorrentExportDir() const { QString options_imp::getTorrentExportDir() const {
if (checkExportDir->isChecked()) if (checkExportDir->isChecked())
return fsutils::expandPathAbs(textExportDir->text()); return Utils::Fs::expandPathAbs(textExportDir->text());
return QString(); return QString();
} }
QString options_imp::getFinishedTorrentExportDir() const { QString options_imp::getFinishedTorrentExportDir() const {
if (checkExportDirFin->isChecked()) if (checkExportDirFin->isChecked())
return fsutils::expandPathAbs(textExportDirFin->text()); return Utils::Fs::expandPathAbs(textExportDirFin->text());
return QString(); return QString();
} }
@ -1078,7 +1078,7 @@ int options_imp::getActionOnDblClOnTorrentFn() const {
void options_imp::on_addScanFolderButton_clicked() { void options_imp::on_addScanFolderButton_clicked() {
Preferences* const pref = Preferences::instance(); Preferences* const pref = Preferences::instance();
const QString dir = QFileDialog::getExistingDirectory(this, tr("Add directory to scan"), const QString dir = QFileDialog::getExistingDirectory(this, tr("Add directory to scan"),
fsutils::toNativePath(fsutils::folderName(pref->getScanDirsLastPath()))); Utils::Fs::toNativePath(Utils::Fs::folderName(pref->getScanDirsLastPath())));
if (!dir.isEmpty()) { if (!dir.isEmpty()) {
const ScanFoldersModel::PathStatus status = ScanFoldersModel::instance()->addPath(dir, false); const ScanFoldersModel::PathStatus status = ScanFoldersModel::instance()->addPath(dir, false);
QString error; QString error;
@ -1120,7 +1120,7 @@ void options_imp::handleScanFolderViewSelectionChanged() {
QString options_imp::askForExportDir(const QString& currentExportPath) QString options_imp::askForExportDir(const QString& currentExportPath)
{ {
QDir currentExportDir(fsutils::expandPathAbs(currentExportPath)); QDir currentExportDir(Utils::Fs::expandPathAbs(currentExportPath));
QString dir; QString dir;
if (!currentExportPath.isEmpty() && currentExportDir.exists()) { if (!currentExportPath.isEmpty() && currentExportDir.exists()) {
dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), currentExportDir.absolutePath()); dir = QFileDialog::getExistingDirectory(this, tr("Choose export directory"), currentExportDir.absolutePath());
@ -1133,17 +1133,17 @@ QString options_imp::askForExportDir(const QString& currentExportPath)
void options_imp::on_browseExportDirButton_clicked() { void options_imp::on_browseExportDirButton_clicked() {
const QString newExportDir = askForExportDir(textExportDir->text()); const QString newExportDir = askForExportDir(textExportDir->text());
if (!newExportDir.isNull()) if (!newExportDir.isNull())
textExportDir->setText(fsutils::toNativePath(newExportDir)); textExportDir->setText(Utils::Fs::toNativePath(newExportDir));
} }
void options_imp::on_browseExportDirFinButton_clicked() { void options_imp::on_browseExportDirFinButton_clicked() {
const QString newExportDir = askForExportDir(textExportDirFin->text()); const QString newExportDir = askForExportDir(textExportDirFin->text());
if (!newExportDir.isNull()) if (!newExportDir.isNull())
textExportDirFin->setText(fsutils::toNativePath(newExportDir)); textExportDirFin->setText(Utils::Fs::toNativePath(newExportDir));
} }
void options_imp::on_browseFilterButton_clicked() { void options_imp::on_browseFilterButton_clicked() {
const QString filter_path = fsutils::expandPathAbs(textFilterPath->text()); const QString filter_path = Utils::Fs::expandPathAbs(textFilterPath->text());
QDir filterDir(filter_path); QDir filterDir(filter_path);
QString ipfilter; QString ipfilter;
if (!filter_path.isEmpty() && filterDir.exists()) { if (!filter_path.isEmpty() && filterDir.exists()) {
@ -1152,12 +1152,12 @@ void options_imp::on_browseFilterButton_clicked() {
ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), QDir::homePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)")); ipfilter = QFileDialog::getOpenFileName(this, tr("Choose an ip filter file"), QDir::homePath(), tr("Filters")+QString(" (*.dat *.p2p *.p2b)"));
} }
if (!ipfilter.isNull()) if (!ipfilter.isNull())
textFilterPath->setText(fsutils::toNativePath(ipfilter)); textFilterPath->setText(Utils::Fs::toNativePath(ipfilter));
} }
// Display dialog to choose save dir // Display dialog to choose save dir
void options_imp::on_browseSaveDirButton_clicked() { void options_imp::on_browseSaveDirButton_clicked() {
const QString save_path = fsutils::expandPathAbs(textSavePath->text()); const QString save_path = Utils::Fs::expandPathAbs(textSavePath->text());
QDir saveDir(save_path); QDir saveDir(save_path);
QString dir; QString dir;
if (!save_path.isEmpty() && saveDir.exists()) { if (!save_path.isEmpty() && saveDir.exists()) {
@ -1166,11 +1166,11 @@ void options_imp::on_browseSaveDirButton_clicked() {
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath()); dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath());
} }
if (!dir.isNull()) if (!dir.isNull())
textSavePath->setText(fsutils::toNativePath(dir)); textSavePath->setText(Utils::Fs::toNativePath(dir));
} }
void options_imp::on_browseTempDirButton_clicked() { void options_imp::on_browseTempDirButton_clicked() {
const QString temp_path = fsutils::expandPathAbs(textTempPath->text()); const QString temp_path = Utils::Fs::expandPathAbs(textTempPath->text());
QDir tempDir(temp_path); QDir tempDir(temp_path);
QString dir; QString dir;
if (!temp_path.isEmpty() && tempDir.exists()) { if (!temp_path.isEmpty() && tempDir.exists()) {
@ -1179,12 +1179,12 @@ void options_imp::on_browseTempDirButton_clicked() {
dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath()); dir = QFileDialog::getExistingDirectory(this, tr("Choose a save directory"), QDir::homePath());
} }
if (!dir.isNull()) if (!dir.isNull())
textTempPath->setText(fsutils::toNativePath(dir)); textTempPath->setText(Utils::Fs::toNativePath(dir));
} }
// Return Filter object to apply to BT session // Return Filter object to apply to BT session
QString options_imp::getFilter() const { QString options_imp::getFilter() const {
return fsutils::fromNativePath(textFilterPath->text()); return Utils::Fs::fromNativePath(textFilterPath->text());
} }
// Web UI // Web UI

View file

@ -37,7 +37,8 @@
#include <QModelIndex> #include <QModelIndex>
#include <QPainter> #include <QPainter>
#include <QApplication> #include <QApplication>
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/utils/string.h"
#include "previewselect.h" #include "previewselect.h"
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@ -63,13 +64,13 @@ class PreviewListDelegate: public QItemDelegate {
switch(index.column()) { switch(index.column()) {
case PreviewSelect::SIZE: case PreviewSelect::SIZE:
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong())); QItemDelegate::drawDisplay(painter, opt, option.rect, Utils::Misc::friendlyUnit(index.data().toLongLong()));
break; break;
case PreviewSelect::PROGRESS:{ case PreviewSelect::PROGRESS:{
QStyleOptionProgressBarV2 newopt; QStyleOptionProgressBarV2 newopt;
qreal progress = index.data().toDouble()*100.; qreal progress = index.data().toDouble()*100.;
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = ((progress == 100.0) ? QString("100%") : misc::accurateDoubleToString(progress, 1) + "%"); newopt.text = ((progress == 100.0) ? QString("100%") : Utils::String::fromDouble(progress, 1) + "%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
newopt.maximum = 100; newopt.maximum = 100;
newopt.minimum = 0; newopt.minimum = 0;

View file

@ -33,10 +33,10 @@
#include <QMessageBox> #include <QMessageBox>
#include <QFile> #include <QFile>
#include "core/misc.h" #include "core/utils/misc.h"
#include "previewlistdelegate.h" #include "previewlistdelegate.h"
#include "previewselect.h" #include "previewselect.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/preferences.h" #include "core/preferences.h"
PreviewSelect::PreviewSelect(QWidget* parent, BitTorrent::TorrentHandle *const torrent) PreviewSelect::PreviewSelect(QWidget* parent, BitTorrent::TorrentHandle *const torrent)
@ -64,8 +64,8 @@ PreviewSelect::PreviewSelect(QWidget* parent, BitTorrent::TorrentHandle *const t
QString fileName = torrent->fileName(i); QString fileName = torrent->fileName(i);
if (fileName.endsWith(".!qB")) if (fileName.endsWith(".!qB"))
fileName.chop(4); fileName.chop(4);
QString extension = fsutils::fileExtension(fileName).toUpper(); QString extension = Utils::Fs::fileExtension(fileName).toUpper();
if (misc::isPreviewable(extension)) { if (Utils::Misc::isPreviewable(extension)) {
int row = previewListModel->rowCount(); int row = previewListModel->rowCount();
previewListModel->insertRow(row); previewListModel->insertRow(row);
previewListModel->setData(previewListModel->index(row, NAME), QVariant(fileName)); previewListModel->setData(previewListModel->index(row, NAME), QVariant(fileName));

View file

@ -39,7 +39,7 @@
#include <QStringList> #include <QStringList>
#include "programupdater.h" #include "programupdater.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/preferences.h" #include "core/preferences.h"
#ifdef Q_OS_MAC #ifdef Q_OS_MAC
@ -122,7 +122,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply)
} else if (xml.isEndElement()) { } else if (xml.isEndElement()) {
if (in_item && xml.name() == "title") { if (in_item && xml.name() == "title") {
in_title = false; in_title = false;
const QString ext = fsutils::fileExtension(item_title).toUpper(); const QString ext = Utils::Fs::fileExtension(item_title).toUpper();
qDebug("Found an update with file extension: %s", qPrintable(ext)); qDebug("Found an update with file extension: %s", qPrintable(ext));
if (ext == FILE_EXT) { if (ext == FILE_EXT) {
qDebug("The last update available is %s", qPrintable(item_title)); qDebug("The last update available is %s", qPrintable(item_title));

View file

@ -33,7 +33,8 @@
#include <QItemDelegate> #include <QItemDelegate>
#include <QPainter> #include <QPainter>
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/utils/string.h"
class PeerListDelegate: public QItemDelegate { class PeerListDelegate: public QItemDelegate {
Q_OBJECT Q_OBJECT
@ -54,21 +55,21 @@ public:
case TOT_DOWN: case TOT_DOWN:
case TOT_UP: case TOT_UP:
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong())); QItemDelegate::drawDisplay(painter, opt, option.rect, Utils::Misc::friendlyUnit(index.data().toLongLong()));
break; break;
case DOWN_SPEED: case DOWN_SPEED:
case UP_SPEED:{ case UP_SPEED:{
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
qreal speed = index.data().toDouble(); qreal speed = index.data().toDouble();
if (speed > 0.0) if (speed > 0.0)
QItemDelegate::drawDisplay(painter, opt, opt.rect, misc::friendlyUnit(speed)+tr("/s", "/second (i.e. per second)")); QItemDelegate::drawDisplay(painter, opt, opt.rect, Utils::Misc::friendlyUnit(speed)+tr("/s", "/second (i.e. per second)"));
break; break;
} }
case PROGRESS: case PROGRESS:
case RELEVANCE:{ case RELEVANCE:{
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
qreal progress = index.data().toDouble(); qreal progress = index.data().toDouble();
QItemDelegate::drawDisplay(painter, opt, opt.rect, misc::accurateDoubleToString(progress*100.0, 1)+"%"); QItemDelegate::drawDisplay(painter, opt, opt.rect, Utils::String::fromDouble(progress*100.0, 1)+"%");
break; break;
} }
default: default:

View file

@ -52,7 +52,7 @@ protected:
Q_ASSERT(vR.isValid()); Q_ASSERT(vR.isValid());
bool res = false; bool res = false;
if (misc::naturalSort(vL.toString(), vR.toString(), res)) if (Utils::String::naturalSort(vL.toString(), vR.toString(), res))
return res; return res;
return QSortFilterProxyModel::lessThan(left, right); return QSortFilterProxyModel::lessThan(left, right);

View file

@ -57,7 +57,8 @@
#include "proptabbar.h" #include "proptabbar.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "lineedit.h" #include "lineedit.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/utils/string.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
PropertiesWidget::PropertiesWidget(QWidget *parent, MainWindow* main_window, TransferListWidget *transferList): PropertiesWidget::PropertiesWidget(QWidget *parent, MainWindow* main_window, TransferListWidget *transferList):
@ -264,9 +265,9 @@ void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent
// Creation date // Creation date
lbl_creationDate->setText(m_torrent->creationDate().toString()); lbl_creationDate->setText(m_torrent->creationDate().toString());
// Piece size // Piece size
pieceSize_lbl->setText(misc::friendlyUnit(m_torrent->pieceLength())); pieceSize_lbl->setText(Utils::Misc::friendlyUnit(m_torrent->pieceLength()));
// Comment // Comment
comment_text->setHtml(misc::parseHtmlLinks(m_torrent->comment())); comment_text->setHtml(Utils::Misc::parseHtmlLinks(m_torrent->comment()));
// URL seeds // URL seeds
loadUrlSeeds(); loadUrlSeeds();
// List files in torrent // List files in torrent
@ -333,14 +334,14 @@ void PropertiesWidget::loadDynamicData() {
// Transfer infos // Transfer infos
if (stackedProperties->currentIndex() == PropTabBar::MAIN_TAB) { if (stackedProperties->currentIndex() == PropTabBar::MAIN_TAB) {
wasted->setText(misc::friendlyUnit(m_torrent->wastedSize())); wasted->setText(Utils::Misc::friendlyUnit(m_torrent->wastedSize()));
upTotal->setText(misc::friendlyUnit(m_torrent->totalUpload()) + " ("+misc::friendlyUnit(m_torrent->totalPayloadUpload())+" "+tr("this session")+")"); upTotal->setText(Utils::Misc::friendlyUnit(m_torrent->totalUpload()) + " ("+Utils::Misc::friendlyUnit(m_torrent->totalPayloadUpload())+" "+tr("this session")+")");
dlTotal->setText(misc::friendlyUnit(m_torrent->totalDownload()) + " ("+misc::friendlyUnit(m_torrent->totalPayloadDownload())+" "+tr("this session")+")"); dlTotal->setText(Utils::Misc::friendlyUnit(m_torrent->totalDownload()) + " ("+Utils::Misc::friendlyUnit(m_torrent->totalPayloadDownload())+" "+tr("this session")+")");
lbl_uplimit->setText(m_torrent->uploadLimit() <= 0 ? QString::fromUtf8("") : misc::friendlyUnit(m_torrent->uploadLimit())+tr("/s", "/second (i.e. per second)")); lbl_uplimit->setText(m_torrent->uploadLimit() <= 0 ? QString::fromUtf8("") : Utils::Misc::friendlyUnit(m_torrent->uploadLimit())+tr("/s", "/second (i.e. per second)"));
lbl_dllimit->setText(m_torrent->downloadLimit() <= 0 ? QString::fromUtf8("") : misc::friendlyUnit(m_torrent->downloadLimit())+tr("/s", "/second (i.e. per second)")); lbl_dllimit->setText(m_torrent->downloadLimit() <= 0 ? QString::fromUtf8("") : Utils::Misc::friendlyUnit(m_torrent->downloadLimit())+tr("/s", "/second (i.e. per second)"));
QString elapsed_txt = misc::userFriendlyDuration(m_torrent->activeTime()); QString elapsed_txt = Utils::Misc::userFriendlyDuration(m_torrent->activeTime());
if (m_torrent->isSeed()) { if (m_torrent->isSeed()) {
elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(m_torrent->seedingTime()))+")"; elapsed_txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(Utils::Misc::userFriendlyDuration(m_torrent->seedingTime()))+")";
} }
lbl_elapsed->setText(elapsed_txt); lbl_elapsed->setText(elapsed_txt);
if (m_torrent->connectionsLimit() > 0) if (m_torrent->connectionsLimit() > 0)
@ -348,10 +349,10 @@ void PropertiesWidget::loadDynamicData() {
else else
lbl_connections->setText(QString::number(m_torrent->connectionsLimit())); lbl_connections->setText(QString::number(m_torrent->connectionsLimit()));
// Update next announce time // Update next announce time
reannounce_lbl->setText(misc::userFriendlyDuration(m_torrent->nextAnnounce())); reannounce_lbl->setText(Utils::Misc::userFriendlyDuration(m_torrent->nextAnnounce()));
// Update ratio info // Update ratio info
const qreal ratio = m_torrent->realRatio(); const qreal ratio = m_torrent->realRatio();
shareRatio->setText(ratio > BitTorrent::TorrentHandle::MAX_RATIO ? QString::fromUtf8("") : misc::accurateDoubleToString(ratio, 2)); shareRatio->setText(ratio > BitTorrent::TorrentHandle::MAX_RATIO ? QString::fromUtf8("") : Utils::String::fromDouble(ratio, 2));
if (!m_torrent->isSeed() && m_torrent->hasMetadata()) { if (!m_torrent->isSeed() && m_torrent->hasMetadata()) {
showPiecesDownloaded(true); showPiecesDownloaded(true);
// Downloaded pieces // Downloaded pieces
@ -360,13 +361,13 @@ void PropertiesWidget::loadDynamicData() {
if (!m_torrent->isPaused() && !m_torrent->isQueued() && !m_torrent->isChecking()) { if (!m_torrent->isPaused() && !m_torrent->isQueued() && !m_torrent->isChecking()) {
showPiecesAvailability(true); showPiecesAvailability(true);
pieces_availability->setAvailability(m_torrent->pieceAvailability()); pieces_availability->setAvailability(m_torrent->pieceAvailability());
avail_average_lbl->setText(misc::accurateDoubleToString(m_torrent->distributedCopies(), 3)); avail_average_lbl->setText(Utils::String::fromDouble(m_torrent->distributedCopies(), 3));
} else { } else {
showPiecesAvailability(false); showPiecesAvailability(false);
} }
// Progress // Progress
qreal progress = m_torrent->progress() * 100.; qreal progress = m_torrent->progress() * 100.;
progress_lbl->setText(misc::accurateDoubleToString(progress, 1)+"%"); progress_lbl->setText(Utils::String::fromDouble(progress, 1)+"%");
} else { } else {
showPiecesAvailability(false); showPiecesAvailability(false);
showPiecesDownloaded(false); showPiecesDownloaded(false);
@ -422,13 +423,13 @@ void PropertiesWidget::openFile(const QModelIndex &index) {
int i = PropListModel->getFileIndex(index); int i = PropListModel->getFileIndex(index);
const QDir saveDir(m_torrent->actualSavePath()); const QDir saveDir(m_torrent->actualSavePath());
const QString filename = m_torrent->filePath(i); const QString filename = m_torrent->filePath(i);
const QString file_path = fsutils::expandPath(saveDir.absoluteFilePath(filename)); const QString file_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(filename));
qDebug("Trying to open file at %s", qPrintable(file_path)); qDebug("Trying to open file at %s", qPrintable(file_path));
// Flush data // Flush data
m_torrent->flushCache(); m_torrent->flushCache();
if (QFile::exists(file_path)) { if (QFile::exists(file_path)) {
if (file_path.startsWith("//")) if (file_path.startsWith("//"))
QDesktopServices::openUrl(fsutils::toNativePath("file:" + file_path)); QDesktopServices::openUrl(Utils::Fs::toNativePath("file:" + file_path));
else else
QDesktopServices::openUrl(QUrl::fromLocalFile(file_path)); QDesktopServices::openUrl(QUrl::fromLocalFile(file_path));
} }
@ -457,17 +458,17 @@ void PropertiesWidget::openFolder(const QModelIndex &index, bool containing_fold
#endif #endif
const QDir saveDir(m_torrent->actualSavePath()); const QDir saveDir(m_torrent->actualSavePath());
const QString relative_path = path_items.join("/"); const QString relative_path = path_items.join("/");
absolute_path = fsutils::expandPath(saveDir.absoluteFilePath(relative_path)); absolute_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(relative_path));
} }
else { else {
int i = PropListModel->getFileIndex(index); int i = PropListModel->getFileIndex(index);
const QDir saveDir(m_torrent->actualSavePath()); const QDir saveDir(m_torrent->actualSavePath());
const QString relative_path = m_torrent->filePath(i); const QString relative_path = m_torrent->filePath(i);
absolute_path = fsutils::expandPath(saveDir.absoluteFilePath(relative_path)); absolute_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(relative_path));
#if !(defined(Q_OS_WIN) || (defined(Q_OS_UNIX) && !defined(Q_OS_MAC))) #if !(defined(Q_OS_WIN) || (defined(Q_OS_UNIX) && !defined(Q_OS_MAC)))
if (containing_folder) if (containing_folder)
absolute_path = fsutils::folderName(absolute_path); absolute_path = Utils::Fs::folderName(absolute_path);
#endif #endif
} }
@ -481,7 +482,7 @@ void PropertiesWidget::openFolder(const QModelIndex &index, bool containing_fold
if (containing_folder) { if (containing_folder) {
// Syntax is: explorer /select, "C:\Folder1\Folder2\file_to_select" // Syntax is: explorer /select, "C:\Folder1\Folder2\file_to_select"
// Dir separators MUST be win-style slashes // Dir separators MUST be win-style slashes
QProcess::startDetached("explorer.exe", QStringList() << "/select," << fsutils::toNativePath(absolute_path)); QProcess::startDetached("explorer.exe", QStringList() << "/select," << Utils::Fs::toNativePath(absolute_path));
} else { } else {
#elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC) #elif defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
if (containing_folder) { if (containing_folder) {
@ -491,11 +492,11 @@ void PropertiesWidget::openFolder(const QModelIndex &index, bool containing_fold
proc.waitForFinished(); proc.waitForFinished();
output = proc.readLine().simplified(); output = proc.readLine().simplified();
if (output == "dolphin.desktop") if (output == "dolphin.desktop")
proc.startDetached("dolphin", QStringList() << "--select" << fsutils::toNativePath(absolute_path)); proc.startDetached("dolphin", QStringList() << "--select" << Utils::Fs::toNativePath(absolute_path));
else if (output == "nautilus-folder-handler.desktop") else if (output == "nautilus-folder-handler.desktop")
proc.startDetached("nautilus", QStringList() << "--no-desktop" << fsutils::toNativePath(absolute_path)); proc.startDetached("nautilus", QStringList() << "--no-desktop" << Utils::Fs::toNativePath(absolute_path));
else if (output == "kfmclient_dir.desktop") else if (output == "kfmclient_dir.desktop")
proc.startDetached("konqueror", QStringList() << "--select" << fsutils::toNativePath(absolute_path)); proc.startDetached("konqueror", QStringList() << "--select" << Utils::Fs::toNativePath(absolute_path));
else else
QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(absolute_path).absolutePath())); QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(absolute_path).absolutePath()));
} else { } else {
@ -503,7 +504,7 @@ void PropertiesWidget::openFolder(const QModelIndex &index, bool containing_fold
if (QFile::exists(absolute_path)) { if (QFile::exists(absolute_path)) {
// Hack to access samba shares with QDesktopServices::openUrl // Hack to access samba shares with QDesktopServices::openUrl
if (absolute_path.startsWith("//")) if (absolute_path.startsWith("//"))
QDesktopServices::openUrl(fsutils::toNativePath("file:" + absolute_path)); QDesktopServices::openUrl(Utils::Fs::toNativePath("file:" + absolute_path));
else else
QDesktopServices::openUrl(QUrl::fromLocalFile(absolute_path)); QDesktopServices::openUrl(QUrl::fromLocalFile(absolute_path));
} else { } else {
@ -616,7 +617,7 @@ void PropertiesWidget::renameSelectedFile() {
tr("New name:"), QLineEdit::Normal, tr("New name:"), QLineEdit::Normal,
index.data().toString(), &ok).trimmed(); index.data().toString(), &ok).trimmed();
if (ok && !new_name_last.isEmpty()) { if (ok && !new_name_last.isEmpty()) {
if (!fsutils::isValidFileSystemName(new_name_last)) { if (!Utils::Fs::isValidFileSystemName(new_name_last)) {
QMessageBox::warning(this, tr("The file could not be renamed"), QMessageBox::warning(this, tr("The file could not be renamed"),
tr("This file name contains forbidden characters, please choose a different one."), tr("This file name contains forbidden characters, please choose a different one."),
QMessageBox::Ok); QMessageBox::Ok);
@ -638,7 +639,7 @@ void PropertiesWidget::renameSelectedFile() {
qDebug("Name did not change"); qDebug("Name did not change");
return; return;
} }
new_name = fsutils::expandPath(new_name); new_name = Utils::Fs::expandPath(new_name);
// Check if that name is already used // Check if that name is already used
for (int i = 0; i < m_torrent->filesCount(); ++i) { for (int i = 0; i < m_torrent->filesCount(); ++i) {
if (i == file_index) continue; if (i == file_index) continue;
@ -701,7 +702,7 @@ void PropertiesWidget::renameSelectedFile() {
new_name.replace(0, old_path.length(), new_path); new_name.replace(0, old_path.length(), new_path);
if (!force_recheck && QDir(m_torrent->actualSavePath()).exists(new_name)) if (!force_recheck && QDir(m_torrent->actualSavePath()).exists(new_name))
force_recheck = true; force_recheck = true;
new_name = fsutils::expandPath(new_name); new_name = Utils::Fs::expandPath(new_name);
qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name)); qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name));
m_torrent->renameFile(i, new_name); m_torrent->renameFile(i, new_name);
} }
@ -714,8 +715,8 @@ void PropertiesWidget::renameSelectedFile() {
const QDir old_folder(m_torrent->actualSavePath() + "/" + old_path); const QDir old_folder(m_torrent->actualSavePath() + "/" + old_path);
int timeout = 10; int timeout = 10;
while(!QDir().rmpath(old_folder.absolutePath()) && timeout > 0) { while(!QDir().rmpath(old_folder.absolutePath()) && timeout > 0) {
// XXX: We should not sleep here (freezes the UI for 1 second) // FIXME: We should not sleep here (freezes the UI for 1 second)
misc::msleep(100); Utils::Misc::msleep(100);
--timeout; --timeout;
} }
} }

View file

@ -40,7 +40,8 @@
#include <QPainter> #include <QPainter>
#include <QProgressBar> #include <QProgressBar>
#include <QApplication> #include <QApplication>
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/utils/string.h"
#include "propertieswidget.h" #include "propertieswidget.h"
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@ -75,14 +76,14 @@ public:
switch(index.column()) { switch(index.column()) {
case PCSIZE: case PCSIZE:
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong())); QItemDelegate::drawDisplay(painter, opt, option.rect, Utils::Misc::friendlyUnit(index.data().toLongLong()));
break; break;
case PROGRESS:{ case PROGRESS:{
if (index.data().toDouble() >= 0) { if (index.data().toDouble() >= 0) {
QStyleOptionProgressBarV2 newopt; QStyleOptionProgressBarV2 newopt;
qreal progress = index.data().toDouble()*100.; qreal progress = index.data().toDouble()*100.;
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = ((progress == 100.0) ? QString("100%") : misc::accurateDoubleToString(progress, 1) + "%"); newopt.text = ((progress == 100.0) ? QString("100%") : Utils::String::fromDouble(progress, 1) + "%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
newopt.maximum = 100; newopt.maximum = 100;
newopt.minimum = 0; newopt.minimum = 0;

View file

@ -45,7 +45,7 @@
#include "core/bittorrent/peerinfo.h" #include "core/bittorrent/peerinfo.h"
#include "core/bittorrent/trackerentry.h" #include "core/bittorrent/trackerentry.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
TrackerList::TrackerList(PropertiesWidget *properties): QTreeWidget(), properties(properties) { TrackerList::TrackerList(PropertiesWidget *properties): QTreeWidget(), properties(properties) {

View file

@ -37,13 +37,13 @@
#include <QFile> #include <QFile>
#include <QUrl> #include <QUrl>
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "ui_trackersadditiondlg.h" #include "ui_trackersadditiondlg.h"
#include "core/net/downloadmanager.h" #include "core/net/downloadmanager.h"
#include "core/net/downloadhandler.h" #include "core/net/downloadhandler.h"
#include "core/bittorrent/trackerentry.h" #include "core/bittorrent/trackerentry.h"
#include "core/bittorrent/torrenthandle.h" #include "core/bittorrent/torrenthandle.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
class TrackersAdditionDlg : public QDialog, private Ui::TrackersAdditionDlg{ class TrackersAdditionDlg : public QDialog, private Ui::TrackersAdditionDlg{
Q_OBJECT Q_OBJECT
@ -80,7 +80,7 @@ public slots:
QMessageBox::warning(this, tr("I/O Error"), tr("Error while trying to open the downloaded file."), QMessageBox::Ok); QMessageBox::warning(this, tr("I/O Error"), tr("Error while trying to open the downloaded file."), QMessageBox::Ok);
setCursor(Qt::ArrowCursor); setCursor(Qt::ArrowCursor);
uTorrentListButton->setEnabled(true); uTorrentListButton->setEnabled(true);
fsutils::forceRemove(path); Utils::Fs::forceRemove(path);
return; return;
} }
@ -109,7 +109,7 @@ public slots:
} }
// Clean up // Clean up
list_file.close(); list_file.close();
fsutils::forceRemove(path); Utils::Fs::forceRemove(path);
//To restore the cursor ... //To restore the cursor ...
setCursor(Qt::ArrowCursor); setCursor(Qt::ArrowCursor);
uTorrentListButton->setEnabled(true); uTorrentListButton->setEnabled(true);

View file

@ -42,7 +42,7 @@
#include "rssfeed.h" #include "rssfeed.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
AutomatedRssDownloader::AutomatedRssDownloader(const QWeakPointer<RssManager>& manager, QWidget *parent) : AutomatedRssDownloader::AutomatedRssDownloader(const QWeakPointer<RssManager>& manager, QWidget *parent) :
QDialog(parent), QDialog(parent),
@ -247,7 +247,7 @@ void AutomatedRssDownloader::updateRuleDefinitionBox()
else else
ui->lineEFilter->clear(); ui->lineEFilter->clear();
ui->saveDiffDir_check->setChecked(!rule->savePath().isEmpty()); ui->saveDiffDir_check->setChecked(!rule->savePath().isEmpty());
ui->lineSavePath->setText(fsutils::toNativePath(rule->savePath())); ui->lineSavePath->setText(Utils::Fs::toNativePath(rule->savePath()));
ui->checkRegex->setChecked(rule->useRegex()); ui->checkRegex->setChecked(rule->useRegex());
if (rule->label().isEmpty()) { if (rule->label().isEmpty()) {
ui->comboLabel->setCurrentIndex(-1); ui->comboLabel->setCurrentIndex(-1);
@ -398,7 +398,7 @@ void AutomatedRssDownloader::on_browseSP_clicked()
{ {
QString save_path = QFileDialog::getExistingDirectory(this, tr("Destination directory"), QDir::homePath()); QString save_path = QFileDialog::getExistingDirectory(this, tr("Destination directory"), QDir::homePath());
if (!save_path.isEmpty()) if (!save_path.isEmpty())
ui->lineSavePath->setText(fsutils::toNativePath(save_path)); ui->lineSavePath->setText(Utils::Fs::toNativePath(save_path));
} }
void AutomatedRssDownloader::on_exportBtn_clicked() void AutomatedRssDownloader::on_exportBtn_clicked()

View file

@ -10,14 +10,14 @@
#include <QDateTime> #include <QDateTime>
#include <QScrollBar> #include <QScrollBar>
#include "core/fs_utils.h" #include "core/utils/fs.h"
HtmlBrowser::HtmlBrowser(QWidget* parent) HtmlBrowser::HtmlBrowser(QWidget* parent)
: QTextBrowser(parent) : QTextBrowser(parent)
{ {
m_netManager = new QNetworkAccessManager(this); m_netManager = new QNetworkAccessManager(this);
m_diskCache = new QNetworkDiskCache(this); m_diskCache = new QNetworkDiskCache(this);
m_diskCache->setCacheDirectory(QDir::cleanPath(fsutils::cacheLocation() + "/rss")); m_diskCache->setCacheDirectory(QDir::cleanPath(Utils::Fs::cacheLocation() + "/rss"));
m_diskCache->setMaximumCacheSize(50 * 1024 * 1024); m_diskCache->setMaximumCacheSize(50 * 1024 * 1024);
qDebug() << "HtmlBrowser cache path:" << m_diskCache->cacheDirectory() << " max size:" << m_diskCache->maximumCacheSize() / 1024 / 1024 << "MB"; qDebug() << "HtmlBrowser cache path:" << m_diskCache->cacheDirectory() << " max size:" << m_diskCache->maximumCacheSize() / 1024 / 1024 << "MB";
m_netManager->setCache(m_diskCache); m_netManager->setCache(m_diskCache);

View file

@ -36,7 +36,7 @@
#include "core/preferences.h" #include "core/preferences.h"
#include "rssfeed.h" #include "rssfeed.h"
#include "rssarticle.h" #include "rssarticle.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
RssDownloadRule::RssDownloadRule(): m_enabled(false), m_useRegex(false), m_apstate(USE_GLOBAL) RssDownloadRule::RssDownloadRule(): m_enabled(false), m_useRegex(false), m_apstate(USE_GLOBAL)
{ {
@ -179,7 +179,7 @@ bool RssDownloadRule::operator==(const RssDownloadRule &other) const {
void RssDownloadRule::setSavePath(const QString &save_path) void RssDownloadRule::setSavePath(const QString &save_path)
{ {
if (!save_path.isEmpty() && QDir(save_path) != QDir(Preferences::instance()->getSavePath())) if (!save_path.isEmpty() && QDir(save_path) != QDir(Preferences::instance()->getSavePath()))
m_savePath = fsutils::fromNativePath(save_path); m_savePath = Utils::Fs::fromNativePath(save_path);
else else
m_savePath = QString(); m_savePath = QString();
} }

View file

@ -37,11 +37,11 @@
#include "core/qinisettings.h" #include "core/qinisettings.h"
#include "rssarticle.h" #include "rssarticle.h"
#include "rssparser.h" #include "rssparser.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "rssdownloadrulelist.h" #include "rssdownloadrulelist.h"
#include "core/net/downloadmanager.h" #include "core/net/downloadmanager.h"
#include "core/net/downloadhandler.h" #include "core/net/downloadhandler.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/logger.h" #include "core/logger.h"
bool rssArticleDateRecentThan(const RssArticlePtr& left, const RssArticlePtr& right) bool rssArticleDateRecentThan(const RssArticlePtr& left, const RssArticlePtr& right)
@ -78,7 +78,7 @@ RssFeed::RssFeed(RssManager* manager, RssFolder* parent, const QString& url):
RssFeed::~RssFeed() RssFeed::~RssFeed()
{ {
if (!m_icon.startsWith(":/") && QFile::exists(m_icon)) if (!m_icon.startsWith(":/") && QFile::exists(m_icon))
fsutils::forceRemove(m_icon); Utils::Fs::forceRemove(m_icon);
} }
void RssFeed::saveItemsToDisk() void RssFeed::saveItemsToDisk()

View file

@ -29,7 +29,7 @@
*/ */
#include "rssparser.h" #include "rssparser.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include <QDebug> #include <QDebug>
#include <QFile> #include <QFile>
@ -214,7 +214,7 @@ void RssParser::parseRssFile(const QString& feedUrl, const QString& filePath)
{ {
qDebug() << Q_FUNC_INFO << feedUrl << filePath; qDebug() << Q_FUNC_INFO << feedUrl << filePath;
m_mutex.lock(); m_mutex.lock();
ParsingJob job = { feedUrl, fsutils::fromNativePath(filePath) }; ParsingJob job = { feedUrl, Utils::Fs::fromNativePath(filePath) };
m_queue.enqueue(job); m_queue.enqueue(job);
// Wake up thread. // Wake up thread.
if (m_queue.count() == 1) { if (m_queue.count() == 1) {
@ -499,11 +499,11 @@ void RssParser::parseFeed(const ParsingJob& job)
// Clean up // Clean up
fileRss.close(); fileRss.close();
emit feedParsingFinished(job.feedUrl, QString()); emit feedParsingFinished(job.feedUrl, QString());
fsutils::forceRemove(job.filePath); Utils::Fs::forceRemove(job.filePath);
} }
void RssParser::reportFailure(const ParsingJob& job, const QString& error) void RssParser::reportFailure(const ParsingJob& job, const QString& error)
{ {
emit feedParsingFinished(job.feedUrl, error); emit feedParsingFinished(job.feedUrl, error);
fsutils::forceRemove(job.filePath); Utils::Fs::forceRemove(job.filePath);
} }

View file

@ -30,17 +30,18 @@
* Contact : hammered999@gmail.com * Contact : hammered999@gmail.com
*/ */
#include "core/types.h"
#include "shutdownconfirm.h" #include "shutdownconfirm.h"
#include <QPushButton> #include <QPushButton>
ShutdownConfirmDlg::ShutdownConfirmDlg(const ShutDownAction &action) ShutdownConfirmDlg::ShutdownConfirmDlg(const ShutdownAction &action)
: m_exitNow(0) : m_exitNow(0)
, m_timeout(15) , m_timeout(15)
, m_action(action) , m_action(action)
{ {
// Title and button // Title and button
if (m_action == NO_SHUTDOWN) { if (m_action == ShutdownAction::None) {
setWindowTitle(tr("Exit confirmation")); setWindowTitle(tr("Exit confirmation"));
m_exitNow = addButton(tr("Exit now"), QMessageBox::AcceptRole); m_exitNow = addButton(tr("Exit now"), QMessageBox::AcceptRole);
} }
@ -62,7 +63,7 @@ ShutdownConfirmDlg::ShutdownConfirmDlg(const ShutDownAction &action)
connect(&m_timer, SIGNAL(m_timeout()), this, SLOT(updateSeconds())); connect(&m_timer, SIGNAL(m_timeout()), this, SLOT(updateSeconds()));
show(); show();
// Move to center // Move to center
move(misc::screenCenter(this)); move(Utils::Misc::screenCenter(this));
} }
void ShutdownConfirmDlg::showEvent(QShowEvent *event) void ShutdownConfirmDlg::showEvent(QShowEvent *event)
@ -71,7 +72,7 @@ void ShutdownConfirmDlg::showEvent(QShowEvent *event)
m_timer.start(); m_timer.start();
} }
bool ShutdownConfirmDlg::askForConfirmation(const ShutDownAction &action) bool ShutdownConfirmDlg::askForConfirmation(const ShutdownAction &action)
{ {
ShutdownConfirmDlg dlg(action); ShutdownConfirmDlg dlg(action);
dlg.exec(); dlg.exec();
@ -104,16 +105,16 @@ void ShutdownConfirmDlg::updateText()
QString text; QString text;
switch (m_action) { switch (m_action) {
case NO_SHUTDOWN: case ShutdownAction::None:
text = tr("qBittorrent will now exit unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout)); text = tr("qBittorrent will now exit unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout));
break; break;
case SHUTDOWN_COMPUTER: case ShutdownAction::Shutdown:
text = tr("The computer will now be switched off unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout)); text = tr("The computer will now be switched off unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout));
break; break;
case SUSPEND_COMPUTER: case ShutdownAction::Suspend:
text = tr("The computer will now go to sleep mode unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout)); text = tr("The computer will now go to sleep mode unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout));
break; break;
case HIBERNATE_COMPUTER: case ShutdownAction::Hibernate:
text = tr("The computer will now go to hibernation mode unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout)); text = tr("The computer will now go to hibernation mode unless you cancel within the next %1 seconds.").arg(QString::number(m_timeout));
break; break;
} }

View file

@ -33,17 +33,17 @@
#include <QMessageBox> #include <QMessageBox>
#include <QTimer> #include <QTimer>
#include "core/misc.h" #include "core/utils/misc.h"
class ShutdownConfirmDlg : public QMessageBox class ShutdownConfirmDlg : public QMessageBox
{ {
Q_OBJECT Q_OBJECT
public: public:
ShutdownConfirmDlg(const ShutDownAction &action); ShutdownConfirmDlg(const ShutdownAction &action);
bool shutdown() const; bool shutdown() const;
static bool askForConfirmation(const ShutDownAction &action); static bool askForConfirmation(const ShutdownAction &action);
QAbstractButton *getExit_now() const; QAbstractButton *getExit_now() const;
void setExit_now(QAbstractButton *value); void setExit_now(QAbstractButton *value);
@ -62,7 +62,7 @@ private:
QAbstractButton *m_exitNow; QAbstractButton *m_exitNow;
QTimer m_timer; QTimer m_timer;
int m_timeout; int m_timeout;
ShutDownAction m_action; ShutdownAction m_action;
}; };
#endif // SHUTDOWNCONFIRM_H #endif // SHUTDOWNCONFIRM_H

View file

@ -37,7 +37,7 @@ SpeedLimitDialog::SpeedLimitDialog(QWidget *parent): QDialog(parent)
// Connect to slots // Connect to slots
connect(bandwidthSlider, SIGNAL(valueChanged(int)), this, SLOT(updateSpinValue(int))); connect(bandwidthSlider, SIGNAL(valueChanged(int)), this, SLOT(updateSpinValue(int)));
connect(spinBandwidth, SIGNAL(valueChanged(int)), this, SLOT(updateSliderValue(int))); connect(spinBandwidth, SIGNAL(valueChanged(int)), this, SLOT(updateSliderValue(int)));
move(misc::screenCenter(this)); move(Utils::Misc::screenCenter(this));
} }
SpeedLimitDialog::~SpeedLimitDialog() SpeedLimitDialog::~SpeedLimitDialog()

View file

@ -34,7 +34,7 @@
#include <QDialog> #include <QDialog>
#include <QList> #include <QList>
#include "ui_bandwidth_limit.h" #include "ui_bandwidth_limit.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg { class SpeedLimitDialog : public QDialog, private Ui_bandwidth_dlg {

View file

@ -31,7 +31,8 @@
#include "statsdialog.h" #include "statsdialog.h"
#include "ui_statsdialog.h" #include "ui_statsdialog.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/utils/string.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
#include "core/bittorrent/sessionstatus.h" #include "core/bittorrent/sessionstatus.h"
#include "core/bittorrent/cachestatus.h" #include "core/bittorrent/cachestatus.h"
@ -65,21 +66,21 @@ void StatsDialog::updateUI() {
// Alltime DL/UL // Alltime DL/UL
quint64 atd = BitTorrent::Session::instance()->getAlltimeDL(); quint64 atd = BitTorrent::Session::instance()->getAlltimeDL();
quint64 atu = BitTorrent::Session::instance()->getAlltimeUL(); quint64 atu = BitTorrent::Session::instance()->getAlltimeUL();
ui->labelAlltimeDL->setText(misc::friendlyUnit(atd)); ui->labelAlltimeDL->setText(Utils::Misc::friendlyUnit(atd));
ui->labelAlltimeUL->setText(misc::friendlyUnit(atu)); ui->labelAlltimeUL->setText(Utils::Misc::friendlyUnit(atu));
// Total waste (this session) // Total waste (this session)
ui->labelWaste->setText(misc::friendlyUnit(ss.totalWasted())); ui->labelWaste->setText(Utils::Misc::friendlyUnit(ss.totalWasted()));
// Global ratio // Global ratio
ui->labelGlobalRatio->setText( ui->labelGlobalRatio->setText(
( atd > 0 && atu > 0 ) ? ( atd > 0 && atu > 0 ) ?
misc::accurateDoubleToString((qreal)atu / (qreal)atd, 2) : Utils::String::fromDouble((qreal)atu / (qreal)atd, 2) :
"-" "-"
); );
// Cache hits // Cache hits
qreal readRatio = cs.readRatio(); qreal readRatio = cs.readRatio();
ui->labelCacheHits->setText((readRatio >= 0) ? misc::accurateDoubleToString(100 * readRatio, 2) : "-"); ui->labelCacheHits->setText((readRatio >= 0) ? Utils::String::fromDouble(100 * readRatio, 2) : "-");
// Buffers size // Buffers size
ui->labelTotalBuf->setText(misc::friendlyUnit(cs.totalUsedBuffers() * 16 * 1024)); ui->labelTotalBuf->setText(Utils::Misc::friendlyUnit(cs.totalUsedBuffers() * 16 * 1024));
// Disk overload (100%) equivalent // Disk overload (100%) equivalent
// From lt manual: disk_write_queue and disk_read_queue are the number of peers currently waiting on a disk write or disk read // From lt manual: disk_write_queue and disk_read_queue are the number of peers currently waiting on a disk write or disk read
// to complete before it receives or sends any more data on the socket. It'a a metric of how disk bound you are. // to complete before it receives or sends any more data on the socket. It'a a metric of how disk bound you are.
@ -90,15 +91,15 @@ void StatsDialog::updateUI() {
peers += torrent->peersCount(); peers += torrent->peersCount();
ui->labelWriteStarve->setText(QString("%1%").arg(((ss.diskWriteQueue() > 0) && (peers > 0)) ui->labelWriteStarve->setText(QString("%1%").arg(((ss.diskWriteQueue() > 0) && (peers > 0))
? misc::accurateDoubleToString((100. * ss.diskWriteQueue()) / peers, 2) ? Utils::String::fromDouble((100. * ss.diskWriteQueue()) / peers, 2)
: "0")); : "0"));
ui->labelReadStarve->setText(QString("%1%").arg(((ss.diskReadQueue() > 0) && (peers > 0)) ui->labelReadStarve->setText(QString("%1%").arg(((ss.diskReadQueue() > 0) && (peers > 0))
? misc::accurateDoubleToString((100. * ss.diskReadQueue()) / peers, 2) ? Utils::String::fromDouble((100. * ss.diskReadQueue()) / peers, 2)
: "0")); : "0"));
// Disk queues // Disk queues
ui->labelQueuedJobs->setText(QString::number(cs.jobQueueLength())); ui->labelQueuedJobs->setText(QString::number(cs.jobQueueLength()));
ui->labelJobsTime->setText(QString::number(cs.averageJobTime())); ui->labelJobsTime->setText(QString::number(cs.averageJobTime()));
ui->labelQueuedBytes->setText(misc::friendlyUnit(cs.queuedBytes())); ui->labelQueuedBytes->setText(Utils::Misc::friendlyUnit(cs.queuedBytes()));
// Total connected peers // Total connected peers
ui->labelPeers->setText(QString::number(ss.peersCount())); ui->labelPeers->setText(QString::number(ss.peersCount()));

View file

@ -38,7 +38,7 @@
#include "speedlimitdlg.h" #include "speedlimitdlg.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/logger.h" #include "core/logger.h"
StatusBar::StatusBar(QStatusBar *bar) StatusBar::StatusBar(QStatusBar *bar)
@ -181,15 +181,15 @@ void StatusBar::refreshStatusBar() {
//statusSep1->setVisible(false); //statusSep1->setVisible(false);
} }
// Update speed labels // Update speed labels
QString speedLbl = misc::friendlyUnit(sessionStatus.payloadDownloadRate(), true)+" ("+misc::friendlyUnit(sessionStatus.totalPayloadDownload())+")"; QString speedLbl = Utils::Misc::friendlyUnit(sessionStatus.payloadDownloadRate(), true)+" ("+Utils::Misc::friendlyUnit(sessionStatus.totalPayloadDownload())+")";
int speedLimit = BitTorrent::Session::instance()->downloadRateLimit(); int speedLimit = BitTorrent::Session::instance()->downloadRateLimit();
if (speedLimit) if (speedLimit)
speedLbl = "["+misc::friendlyUnit(speedLimit, true)+"] " + speedLbl; speedLbl = "["+Utils::Misc::friendlyUnit(speedLimit, true)+"] " + speedLbl;
dlSpeedLbl->setText(speedLbl); dlSpeedLbl->setText(speedLbl);
speedLimit = BitTorrent::Session::instance()->uploadRateLimit(); speedLimit = BitTorrent::Session::instance()->uploadRateLimit();
speedLbl = misc::friendlyUnit(sessionStatus.payloadUploadRate(), true)+" ("+misc::friendlyUnit(sessionStatus.totalPayloadUpload())+")"; speedLbl = Utils::Misc::friendlyUnit(sessionStatus.payloadUploadRate(), true)+" ("+Utils::Misc::friendlyUnit(sessionStatus.totalPayloadUpload())+")";
if (speedLimit) if (speedLimit)
speedLbl = "["+misc::friendlyUnit(speedLimit, true)+"] " + speedLbl; speedLbl = "["+Utils::Misc::friendlyUnit(speedLimit, true)+"] " + speedLbl;
upSpeedLbl->setText(speedLbl); upSpeedLbl->setText(speedLbl);
} }

View file

@ -28,6 +28,7 @@
* Contact : chris@qbittorrent.org * Contact : chris@qbittorrent.org
*/ */
#include "core/utils/string.h"
#include "torrentcontentfiltermodel.h" #include "torrentcontentfiltermodel.h"
#include "torrentcontentmodel.h" #include "torrentcontentmodel.h"
@ -95,7 +96,7 @@ bool TorrentContentFilterModel::lessThan(const QModelIndex &left, const QModelIn
rightType = m_model->itemType(m_model->index(right.row(), 0, right.parent())); rightType = m_model->itemType(m_model->index(right.row(), 0, right.parent()));
if (leftType == rightType) { if (leftType == rightType) {
bool res = false; bool res = false;
if (misc::naturalSort(vL.toString(), vR.toString(), res)) if (Utils::String::naturalSort(vL.toString(), vR.toString(), res))
return res; return res;
return QSortFilterProxyModel::lessThan(left, right); return QSortFilterProxyModel::lessThan(left, right);
} }

View file

@ -32,8 +32,8 @@
#include <QIcon> #include <QIcon>
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "torrentcontentmodel.h" #include "torrentcontentmodel.h"
#include "torrentcontentmodelitem.h" #include "torrentcontentmodelitem.h"
#include "torrentcontentmodelfolder.h" #include "torrentcontentmodelfolder.h"
@ -296,7 +296,7 @@ void TorrentContentModel::setupModelData(const BitTorrent::TorrentInfo &info)
// Iterate over files // Iterate over files
for (int i = 0; i < info.filesCount(); ++i) { for (int i = 0; i < info.filesCount(); ++i) {
current_parent = m_rootItem; current_parent = m_rootItem;
QString path = fsutils::fromNativePath(info.filePath(i)); QString path = Utils::Fs::fromNativePath(info.filePath(i));
// Iterate of parts of the path to create necessary folders // Iterate of parts of the path to create necessary folders
QStringList pathFolders = path.split("/", QString::SkipEmptyParts); QStringList pathFolders = path.split("/", QString::SkipEmptyParts);
pathFolders.removeLast(); pathFolders.removeLast();

View file

@ -28,8 +28,8 @@
* Contact : chris@qbittorrent.org * Contact : chris@qbittorrent.org
*/ */
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "torrentcontentmodelitem.h" #include "torrentcontentmodelitem.h"
#include "torrentcontentmodelfolder.h" #include "torrentcontentmodelfolder.h"
#include <QDebug> #include <QDebug>

View file

@ -33,8 +33,8 @@
#include <QMessageBox> #include <QMessageBox>
#include "torrentcreatordlg.h" #include "torrentcreatordlg.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
@ -73,7 +73,7 @@ void TorrentCreatorDlg::on_addFolder_button_clicked() {
QString dir = QFileDialog::getExistingDirectory(this, tr("Select a folder to add to the torrent"), last_path, QFileDialog::ShowDirsOnly); QString dir = QFileDialog::getExistingDirectory(this, tr("Select a folder to add to the torrent"), last_path, QFileDialog::ShowDirsOnly);
if (!dir.isEmpty()) { if (!dir.isEmpty()) {
pref->setCreateTorLastAddPath(dir); pref->setCreateTorLastAddPath(dir);
textInputPath->setText(fsutils::toNativePath(dir)); textInputPath->setText(Utils::Fs::toNativePath(dir));
// Update piece size // Update piece size
if (checkAutoPieceSize->isChecked()) if (checkAutoPieceSize->isChecked())
updateOptimalPieceSize(); updateOptimalPieceSize();
@ -85,8 +85,8 @@ void TorrentCreatorDlg::on_addFile_button_clicked() {
QString last_path = pref->getCreateTorLastAddPath(); QString last_path = pref->getCreateTorLastAddPath();
QString file = QFileDialog::getOpenFileName(this, tr("Select a file to add to the torrent"), last_path); QString file = QFileDialog::getOpenFileName(this, tr("Select a file to add to the torrent"), last_path);
if (!file.isEmpty()) { if (!file.isEmpty()) {
pref->setCreateTorLastAddPath(fsutils::branchPath(file)); pref->setCreateTorLastAddPath(Utils::Fs::branchPath(file));
textInputPath->setText(fsutils::toNativePath(file)); textInputPath->setText(Utils::Fs::toNativePath(file));
// Update piece size // Update piece size
if (checkAutoPieceSize->isChecked()) if (checkAutoPieceSize->isChecked())
updateOptimalPieceSize(); updateOptimalPieceSize();
@ -99,7 +99,7 @@ int TorrentCreatorDlg::getPieceSize() const {
// Main function that create a .torrent file // Main function that create a .torrent file
void TorrentCreatorDlg::on_createButton_clicked() { void TorrentCreatorDlg::on_createButton_clicked() {
QString input = fsutils::fromNativePath(textInputPath->text()).trimmed(); QString input = Utils::Fs::fromNativePath(textInputPath->text()).trimmed();
if (input.endsWith("/")) if (input.endsWith("/"))
input.chop(1); input.chop(1);
if (input.isEmpty()) { if (input.isEmpty()) {
@ -115,7 +115,7 @@ void TorrentCreatorDlg::on_createButton_clicked() {
QString destination = QFileDialog::getSaveFileName(this, tr("Select destination torrent file"), last_path, tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); QString destination = QFileDialog::getSaveFileName(this, tr("Select destination torrent file"), last_path, tr("Torrent Files")+QString::fromUtf8(" (*.torrent)"));
if (!destination.isEmpty()) { if (!destination.isEmpty()) {
pref->setCreateTorLastSavePath(fsutils::branchPath(destination)); pref->setCreateTorLastSavePath(Utils::Fs::branchPath(destination));
if (!destination.toUpper().endsWith(".TORRENT")) if (!destination.toUpper().endsWith(".TORRENT"))
destination += QString::fromUtf8(".torrent"); destination += QString::fromUtf8(".torrent");
} else { } else {
@ -150,7 +150,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path)
setCursor(QCursor(Qt::ArrowCursor)); setCursor(QCursor(Qt::ArrowCursor));
if (checkStartSeeding->isChecked()) { if (checkStartSeeding->isChecked()) {
// Create save path temp data // Create save path temp data
BitTorrent::TorrentInfo t = BitTorrent::TorrentInfo::loadFromFile(fsutils::toNativePath(path)); BitTorrent::TorrentInfo t = BitTorrent::TorrentInfo::loadFromFile(Utils::Fs::toNativePath(path));
if (!t.isValid()) { if (!t.isValid()) {
QMessageBox::critical(0, tr("Torrent creation"), tr("Created torrent file is invalid. It won't be added to download list.")); QMessageBox::critical(0, tr("Torrent creation"), tr("Created torrent file is invalid. It won't be added to download list."));
return; return;
@ -164,7 +164,7 @@ void TorrentCreatorDlg::handleCreationSuccess(QString path, QString branch_path)
BitTorrent::Session::instance()->addTorrent(t, params); BitTorrent::Session::instance()->addTorrent(t, params);
} }
QMessageBox::information(0, tr("Torrent creation"), tr("Torrent was created successfully:")+" "+fsutils::toNativePath(path)); QMessageBox::information(0, tr("Torrent creation"), tr("Torrent was created successfully:")+" "+Utils::Fs::toNativePath(path));
close(); close();
} }
@ -217,7 +217,7 @@ void TorrentCreatorDlg::on_checkAutoPieceSize_clicked(bool checked)
void TorrentCreatorDlg::updateOptimalPieceSize() void TorrentCreatorDlg::updateOptimalPieceSize()
{ {
qint64 torrent_size = fsutils::computePathSize(textInputPath->text()); qint64 torrent_size = Utils::Fs::computePathSize(textInputPath->text());
qDebug("Torrent size is %lld", torrent_size); qDebug("Torrent size is %lld", torrent_size);
if (torrent_size < 0) return; if (torrent_size < 0) return;
int i = 0; int i = 0;

View file

@ -38,7 +38,7 @@
#include "core/bittorrent/infohash.h" #include "core/bittorrent/infohash.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
TorrentImportDlg::TorrentImportDlg(QWidget *parent): TorrentImportDlg::TorrentImportDlg(QWidget *parent):
QDialog(parent), QDialog(parent),
@ -73,15 +73,15 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
{ {
const QString default_dir = Preferences::instance()->getTorImportLastContentDir(); const QString default_dir = Preferences::instance()->getTorImportLastContentDir();
bool multifile = (m_torrentInfo.filesCount() > 1); bool multifile = (m_torrentInfo.filesCount() > 1);
QString filePath = fsutils::fromNativePath(m_torrentInfo.filePath(0)); QString filePath = Utils::Fs::fromNativePath(m_torrentInfo.filePath(0));
if (!multifile && (filePath.indexOf('/') != -1)) if (!multifile && (filePath.indexOf('/') != -1))
multifile = true; multifile = true;
if (!multifile) { if (!multifile) {
// Single file torrent // Single file torrent
const QString file_name = fsutils::fileName(filePath); const QString file_name = Utils::Fs::fileName(filePath);
qDebug("Torrent has only one file: %s", qPrintable(file_name)); qDebug("Torrent has only one file: %s", qPrintable(file_name));
QString extension = fsutils::fileExtension(file_name); QString extension = Utils::Fs::fileExtension(file_name);
qDebug("File extension is : %s", qPrintable(extension)); qDebug("File extension is : %s", qPrintable(extension));
QString filter; QString filter;
if (!extension.isEmpty()) { if (!extension.isEmpty()) {
@ -96,7 +96,7 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
return; return;
} }
// Update display // Update display
ui->lineContent->setText(fsutils::toNativePath(m_contentPath)); ui->lineContent->setText(Utils::Fs::toNativePath(m_contentPath));
// Check file size // Check file size
const qint64 file_size = QFile(m_contentPath).size(); const qint64 file_size = QFile(m_contentPath).size();
if (m_torrentInfo.fileSize(0) == file_size) { if (m_torrentInfo.fileSize(0) == file_size) {
@ -130,16 +130,16 @@ void TorrentImportDlg::on_browseContentBtn_clicked()
return; return;
} }
// Update the display // Update the display
ui->lineContent->setText(fsutils::toNativePath(m_contentPath)); ui->lineContent->setText(Utils::Fs::toNativePath(m_contentPath));
bool size_mismatch = false; bool size_mismatch = false;
QDir content_dir(m_contentPath); QDir content_dir(m_contentPath);
content_dir.cdUp(); content_dir.cdUp();
// Check file sizes // Check file sizes
for (int i = 0; i < m_torrentInfo.filesCount(); ++i) { for (int i = 0; i < m_torrentInfo.filesCount(); ++i) {
const QString rel_path = m_torrentInfo.filePath(i); const QString rel_path = m_torrentInfo.filePath(i);
if (QFile(fsutils::expandPath(content_dir.absoluteFilePath(rel_path))).size() != m_torrentInfo.fileSize(i)) { if (QFile(Utils::Fs::expandPath(content_dir.absoluteFilePath(rel_path))).size() != m_torrentInfo.fileSize(i)) {
qDebug("%s is %lld", qDebug("%s is %lld",
qPrintable(fsutils::expandPath(content_dir.absoluteFilePath(rel_path))), (long long int) QFile(fsutils::expandPath(content_dir.absoluteFilePath(rel_path))).size()); qPrintable(Utils::Fs::expandPath(content_dir.absoluteFilePath(rel_path))), (long long int) QFile(Utils::Fs::expandPath(content_dir.absoluteFilePath(rel_path))).size());
qDebug("%s is %lld", qDebug("%s is %lld",
qPrintable(rel_path), (long long int)m_torrentInfo.fileSize(i)); qPrintable(rel_path), (long long int)m_torrentInfo.fileSize(i));
size_mismatch = true; size_mismatch = true;
@ -204,8 +204,8 @@ void TorrentImportDlg::importTorrent()
BitTorrent::Session::instance()->addTorrent(torrentInfo, params); BitTorrent::Session::instance()->addTorrent(torrentInfo, params);
// Remember the last opened folder // Remember the last opened folder
Preferences* const pref = Preferences::instance(); Preferences* const pref = Preferences::instance();
pref->setMainLastDir(fsutils::fromNativePath(torrentPath)); pref->setMainLastDir(Utils::Fs::fromNativePath(torrentPath));
pref->setTorImportLastContentDir(fsutils::fromNativePath(contentPath)); pref->setTorImportLastContentDir(Utils::Fs::fromNativePath(contentPath));
return; return;
} }
qDebug() << Q_FUNC_INFO << "EXIT"; qDebug() << Q_FUNC_INFO << "EXIT";
@ -223,7 +223,7 @@ void TorrentImportDlg::loadTorrent(const QString &torrentPath)
} }
else { else {
// Update display // Update display
ui->lineTorrent->setText(fsutils::toNativePath(torrentPath)); ui->lineTorrent->setText(Utils::Fs::toNativePath(torrentPath));
ui->browseContentBtn->setEnabled(true); ui->browseContentBtn->setEnabled(true);
// Load the file names // Load the file names
initializeFilesPath(); initializeFilesPath();

View file

@ -35,7 +35,7 @@
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
#include "core/torrentfilter.h" #include "core/torrentfilter.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "torrentmodel.h" #include "torrentmodel.h"
namespace { namespace {

View file

@ -34,7 +34,8 @@
#include <QStyleOptionViewItemV2> #include <QStyleOptionViewItemV2>
#include <QApplication> #include <QApplication>
#include <QPainter> #include <QPainter>
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/utils/string.h"
#include "torrentmodel.h" #include "torrentmodel.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
#include "core/bittorrent/torrenthandle.h" #include "core/bittorrent/torrenthandle.h"
@ -65,13 +66,13 @@ void TransferListDelegate::paint(QPainter * painter, const QStyleOptionViewItem
case TorrentModelItem::TR_TOTAL_SIZE: { case TorrentModelItem::TR_TOTAL_SIZE: {
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;
QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong())); QItemDelegate::drawDisplay(painter, opt, option.rect, Utils::Misc::friendlyUnit(index.data().toLongLong()));
break; break;
} }
case TorrentModelItem::TR_ETA: { case TorrentModelItem::TR_ETA: {
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;
QItemDelegate::drawDisplay(painter, opt, option.rect, misc::userFriendlyDuration(index.data().toLongLong())); QItemDelegate::drawDisplay(painter, opt, option.rect, Utils::Misc::userFriendlyDuration(index.data().toLongLong()));
break; break;
} }
case TorrentModelItem::TR_SEEDS: case TorrentModelItem::TR_SEEDS:
@ -142,7 +143,7 @@ void TransferListDelegate::paint(QPainter * painter, const QStyleOptionViewItem
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
const qulonglong speed = index.data().toULongLong(); const qulonglong speed = index.data().toULongLong();
opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;
QItemDelegate::drawDisplay(painter, opt, opt.rect, misc::friendlyUnit(speed)+tr("/s", "/second (.i.e per second)")); QItemDelegate::drawDisplay(painter, opt, opt.rect, Utils::Misc::friendlyUnit(speed)+tr("/s", "/second (.i.e per second)"));
break; break;
} }
case TorrentModelItem::TR_UPLIMIT: case TorrentModelItem::TR_UPLIMIT:
@ -150,15 +151,15 @@ void TransferListDelegate::paint(QPainter * painter, const QStyleOptionViewItem
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
const qlonglong limit = index.data().toLongLong(); const qlonglong limit = index.data().toLongLong();
opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;
QItemDelegate::drawDisplay(painter, opt, opt.rect, limit > 0 ? misc::accurateDoubleToString(limit/1024., 1) + " " + tr("KiB/s", "KiB/second (.i.e per second)") : QString::fromUtf8("")); QItemDelegate::drawDisplay(painter, opt, opt.rect, limit > 0 ? Utils::String::fromDouble(limit/1024., 1) + " " + tr("KiB/s", "KiB/second (.i.e per second)") : QString::fromUtf8(""));
break; break;
} }
case TorrentModelItem::TR_TIME_ELAPSED: { case TorrentModelItem::TR_TIME_ELAPSED: {
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
QString txt = misc::userFriendlyDuration(index.data().toLongLong()); QString txt = Utils::Misc::userFriendlyDuration(index.data().toLongLong());
qlonglong seeding_time = index.data(Qt::UserRole).toLongLong(); qlonglong seeding_time = index.data(Qt::UserRole).toLongLong();
if (seeding_time > 0) if (seeding_time > 0)
txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(misc::userFriendlyDuration(seeding_time))+")"; txt += " ("+tr("Seeded for %1", "e.g. Seeded for 3m10s").arg(Utils::Misc::userFriendlyDuration(seeding_time))+")";
QItemDelegate::drawDisplay(painter, opt, opt.rect, txt); QItemDelegate::drawDisplay(painter, opt, opt.rect, txt);
break; break;
} }
@ -173,7 +174,7 @@ void TransferListDelegate::paint(QPainter * painter, const QStyleOptionViewItem
opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter; opt.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;
const qreal ratio = index.data().toDouble(); const qreal ratio = index.data().toDouble();
QItemDelegate::drawDisplay(painter, opt, opt.rect, QItemDelegate::drawDisplay(painter, opt, opt.rect,
((ratio == -1) || (ratio > BitTorrent::TorrentHandle::MAX_RATIO)) ? QString::fromUtf8("") : misc::accurateDoubleToString(ratio, 2)); ((ratio == -1) || (ratio > BitTorrent::TorrentHandle::MAX_RATIO)) ? QString::fromUtf8("") : Utils::String::fromDouble(ratio, 2));
break; break;
} }
case TorrentModelItem::TR_PRIORITY: { case TorrentModelItem::TR_PRIORITY: {
@ -191,7 +192,7 @@ void TransferListDelegate::paint(QPainter * painter, const QStyleOptionViewItem
QStyleOptionProgressBarV2 newopt; QStyleOptionProgressBarV2 newopt;
qreal progress = index.data().toDouble()*100.; qreal progress = index.data().toDouble()*100.;
newopt.rect = opt.rect; newopt.rect = opt.rect;
newopt.text = ((progress == 100.0) ? QString("100%") : misc::accurateDoubleToString(progress, 1) + "%"); newopt.text = ((progress == 100.0) ? QString("100%") : Utils::String::fromDouble(progress, 1) + "%");
newopt.progress = (int)progress; newopt.progress = (int)progress;
newopt.maximum = 100; newopt.maximum = 100;
newopt.minimum = 0; newopt.minimum = 0;
@ -219,9 +220,9 @@ void TransferListDelegate::paint(QPainter * painter, const QStyleOptionViewItem
// Show '< 1m ago' when elapsed time is 0 // Show '< 1m ago' when elapsed time is 0
elapsed = 1; elapsed = 1;
if (elapsed < 0) if (elapsed < 0)
elapsedString = misc::userFriendlyDuration(elapsed); elapsedString = Utils::Misc::userFriendlyDuration(elapsed);
else else
elapsedString = tr("%1 ago", "e.g.: 1h 20m ago").arg(misc::userFriendlyDuration(elapsed)); elapsedString = tr("%1 ago", "e.g.: 1h 20m ago").arg(Utils::Misc::userFriendlyDuration(elapsed));
QItemDelegate::drawDisplay(painter, opt, option.rect, elapsedString); QItemDelegate::drawDisplay(painter, opt, option.rect, elapsedString);
break; break;
} }

View file

@ -44,14 +44,15 @@
#include "core/preferences.h" #include "core/preferences.h"
#include "torrentmodel.h" #include "torrentmodel.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/utils/string.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
#include "core/torrentfilter.h" #include "core/torrentfilter.h"
#include "core/bittorrent/trackerentry.h" #include "core/bittorrent/trackerentry.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
#include "core/net/downloadmanager.h" #include "core/net/downloadmanager.h"
#include "core/net/downloadhandler.h" #include "core/net/downloadhandler.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/logger.h" #include "core/logger.h"
FiltersBase::FiltersBase(QWidget *parent, TransferListWidget *transferList) FiltersBase::FiltersBase(QWidget *parent, TransferListWidget *transferList)
@ -202,7 +203,7 @@ void LabelFiltersList::addItem(QString &label, bool hasTorrent)
{ {
int labelCount = 0; int labelCount = 0;
QListWidgetItem *labelItem = 0; QListWidgetItem *labelItem = 0;
label = fsutils::toValidFileSystemName(label.trimmed()); label = Utils::Fs::toValidFileSystemName(label.trimmed());
item(0)->setText(tr("All (%1)", "this is for the label filter").arg(m_totalTorrents)); item(0)->setText(tr("All (%1)", "this is for the label filter").arg(m_totalTorrents));
if (label.isEmpty()) { if (label.isEmpty()) {
@ -235,7 +236,7 @@ void LabelFiltersList::addItem(QString &label, bool hasTorrent)
Q_ASSERT(count() >= 2); Q_ASSERT(count() >= 2);
for (int i = 2; i<count(); ++i) { for (int i = 2; i<count(); ++i) {
bool less = false; bool less = false;
if (!(misc::naturalSort(label, item(i)->text(), less))) if (!(Utils::String::naturalSort(label, item(i)->text(), less)))
less = (label.localeAwareCompare(item(i)->text()) < 0); less = (label.localeAwareCompare(item(i)->text()) < 0);
if (less) { if (less) {
insertItem(i, labelItem); insertItem(i, labelItem);
@ -357,7 +358,7 @@ void LabelFiltersList::showMenu(QPoint)
invalid = false; invalid = false;
label = AutoExpandableDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, label, &ok); label = AutoExpandableDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, label, &ok);
if (ok && !label.isEmpty()) { if (ok && !label.isEmpty()) {
if (fsutils::isValidFileSystemName(label)) { if (Utils::Fs::isValidFileSystemName(label)) {
addItem(label, false); addItem(label, false);
} }
else { else {
@ -445,7 +446,7 @@ TrackerFiltersList::TrackerFiltersList(QWidget *parent, TransferListWidget *tran
TrackerFiltersList::~TrackerFiltersList() TrackerFiltersList::~TrackerFiltersList()
{ {
foreach (const QString &iconPath, m_iconPaths) foreach (const QString &iconPath, m_iconPaths)
fsutils::forceRemove(iconPath); Utils::Fs::forceRemove(iconPath);
} }
void TrackerFiltersList::addItem(const QString &tracker, const QString &hash) void TrackerFiltersList::addItem(const QString &tracker, const QString &hash)
@ -493,7 +494,7 @@ void TrackerFiltersList::addItem(const QString &tracker, const QString &hash)
Q_ASSERT(count() >= 4); Q_ASSERT(count() >= 4);
for (int i = 4; i<count(); ++i) { for (int i = 4; i<count(); ++i) {
bool less = false; bool less = false;
if (!(misc::naturalSort(host, item(i)->text(), less))) if (!(Utils::String::naturalSort(host, item(i)->text(), less)))
less = (host.localeAwareCompare(item(i)->text()) < 0); less = (host.localeAwareCompare(item(i)->text()) < 0);
if (less) { if (less) {
insertItem(i, trackerItem); insertItem(i, trackerItem);
@ -633,7 +634,7 @@ void TrackerFiltersList::handleFavicoDownload(const QString& url, const QString&
else { else {
Logger::instance()->addMessage(tr("Couldn't decode favico for url `%1`.").arg(url), Log::WARNING); Logger::instance()->addMessage(tr("Couldn't decode favico for url `%1`.").arg(url), Log::WARNING);
} }
fsutils::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
} }
else { else {
trackerItem->setData(Qt::DecorationRole, QVariant(QIcon(filePath))); trackerItem->setData(Qt::DecorationRole, QVariant(QIcon(filePath)));

View file

@ -30,7 +30,8 @@
#include <QStringList> #include <QStringList>
#include "core/misc.h" #include "core/types.h"
#include "core/utils/string.h"
#include "core/bittorrent/torrenthandle.h" #include "core/bittorrent/torrenthandle.h"
#include "torrentmodel.h" #include "torrentmodel.h"
#include "transferlistsortmodel.h" #include "transferlistsortmodel.h"
@ -81,7 +82,7 @@ bool TransferListSortModel::lessThan(const QModelIndex &left, const QModelIndex
return lowerPositionThan(left, right); return lowerPositionThan(left, right);
bool res = false; bool res = false;
if (misc::naturalSort(vL.toString(), vR.toString(), res)) if (Utils::String::naturalSort(vL.toString(), vR.toString(), res))
return res; return res;
return QSortFilterProxyModel::lessThan(left, right); return QSortFilterProxyModel::lessThan(left, right);

View file

@ -57,7 +57,7 @@
#include "deletionconfirmationdlg.h" #include "deletionconfirmationdlg.h"
#include "propertieswidget.h" #include "propertieswidget.h"
#include "guiiconprovider.h" #include "guiiconprovider.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "autoexpandabledialog.h" #include "autoexpandabledialog.h"
#include "transferlistsortmodel.h" #include "transferlistsortmodel.h"
@ -255,7 +255,7 @@ void TransferListWidget::setSelectedTorrentsLocation()
BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash); BitTorrent::TorrentHandle *const torrent = BitTorrent::Session::instance()->findTorrent(hash);
if (!torrent) continue; if (!torrent) continue;
torrent->move(fsutils::expandPathAbs(dir)); torrent->move(Utils::Fs::expandPathAbs(dir));
main_window->getProperties()->updateSavePath(torrent); main_window->getProperties()->updateSavePath(torrent);
} }
} }
@ -622,7 +622,7 @@ void TransferListWidget::askNewLabelForSelection()
invalid = false; invalid = false;
const QString label = AutoExpandableDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, "", &ok).trimmed(); const QString label = AutoExpandableDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, "", &ok).trimmed();
if (ok && !label.isEmpty()) { if (ok && !label.isEmpty()) {
if (fsutils::isValidFileSystemName(label)) { if (Utils::Fs::isValidFileSystemName(label)) {
setSelectionLabel(label); setSelectionLabel(label);
} }
else { else {
@ -635,10 +635,10 @@ void TransferListWidget::askNewLabelForSelection()
bool TransferListWidget::openUrl(const QString &_path) const bool TransferListWidget::openUrl(const QString &_path) const
{ {
const QString path = fsutils::fromNativePath(_path); const QString path = Utils::Fs::fromNativePath(_path);
// Hack to access samba shares with QDesktopServices::openUrl // Hack to access samba shares with QDesktopServices::openUrl
if (path.startsWith("//")) if (path.startsWith("//"))
return QDesktopServices::openUrl(fsutils::toNativePath("file:" + path)); return QDesktopServices::openUrl(Utils::Fs::toNativePath("file:" + path));
else else
return QDesktopServices::openUrl(QUrl::fromLocalFile(path)); return QDesktopServices::openUrl(QUrl::fromLocalFile(path));
} }

View file

@ -31,8 +31,8 @@
#include "engineselectdlg.h" #include "engineselectdlg.h"
#include "core/net/downloadmanager.h" #include "core/net/downloadmanager.h"
#include "core/net/downloadhandler.h" #include "core/net/downloadhandler.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "ico.h" #include "ico.h"
#include "searchengine.h" #include "searchengine.h"
#include "pluginsource.h" #include "pluginsource.h"
@ -48,7 +48,7 @@
#include <QMimeData> #include <QMimeData>
enum EngineColumns {ENGINE_NAME, ENGINE_URL, ENGINE_STATE, ENGINE_ID}; enum EngineColumns {ENGINE_NAME, ENGINE_URL, ENGINE_STATE, ENGINE_ID};
const QString UPDATE_URL = QString("https://raw.github.com/qbittorrent/qBittorrent/master/src/searchengine/") + (misc::pythonVersion() >= 3 ? "nova3" : "nova") + "/engines/"; const QString UPDATE_URL = QString("https://raw.github.com/qbittorrent/qBittorrent/master/src/searchengine/") + (Utils::Misc::pythonVersion() >= 3 ? "nova3" : "nova") + "/engines/";
engineSelectDlg::engineSelectDlg(QWidget *parent, SupportedEngines *supported_engines) : QDialog(parent), supported_engines(supported_engines) { engineSelectDlg::engineSelectDlg(QWidget *parent, SupportedEngines *supported_engines) : QDialog(parent), supported_engines(supported_engines) {
setupUi(this); setupUi(this);
@ -76,7 +76,7 @@ void engineSelectDlg::dropEvent(QDropEvent *event) {
QStringList files = event->mimeData()->text().split(QString::fromUtf8("\n")); QStringList files = event->mimeData()->text().split(QString::fromUtf8("\n"));
foreach (QString file, files) { foreach (QString file, files) {
qDebug("dropped %s", qPrintable(file)); qDebug("dropped %s", qPrintable(file));
if (misc::isUrl(file)) { if (Utils::Misc::isUrl(file)) {
setCursor(QCursor(Qt::WaitCursor)); setCursor(QCursor(Qt::WaitCursor));
downloadFromUrl(file); downloadFromUrl(file);
continue; continue;
@ -84,7 +84,7 @@ void engineSelectDlg::dropEvent(QDropEvent *event) {
if (file.endsWith(".py", Qt::CaseInsensitive)) { if (file.endsWith(".py", Qt::CaseInsensitive)) {
if (file.startsWith("file:", Qt::CaseInsensitive)) if (file.startsWith("file:", Qt::CaseInsensitive))
file = QUrl(file).toLocalFile(); file = QUrl(file).toLocalFile();
QString plugin_name = fsutils::fileName(file); QString plugin_name = Utils::Fs::fileName(file);
plugin_name.chop(3); // Remove extension plugin_name.chop(3); // Remove extension
installPlugin(file, plugin_name); installPlugin(file, plugin_name);
} }
@ -155,7 +155,7 @@ void engineSelectDlg::on_actionUninstall_triggered() {
}else { }else {
// Proceed with uninstall // Proceed with uninstall
// remove it from hard drive // remove it from hard drive
QDir enginesFolder(fsutils::searchEngineLocation() + "/engines"); QDir enginesFolder(Utils::Fs::searchEngineLocation() + "/engines");
QStringList filters; QStringList filters;
filters << id+".*"; filters << id+".*";
QStringList files = enginesFolder.entryList(filters, QDir::Files, QDir::Unsorted); QStringList files = enginesFolder.entryList(filters, QDir::Files, QDir::Unsorted);
@ -221,7 +221,7 @@ QTreeWidgetItem* engineSelectDlg::findItemWithID(QString id) {
} }
bool engineSelectDlg::isUpdateNeeded(QString plugin_name, qreal new_version) const { bool engineSelectDlg::isUpdateNeeded(QString plugin_name, qreal new_version) const {
qreal old_version = SearchEngine::getPluginVersion(fsutils::searchEngineLocation() + "/engines/" + plugin_name + ".py"); qreal old_version = SearchEngine::getPluginVersion(Utils::Fs::searchEngineLocation() + "/engines/" + plugin_name + ".py");
qDebug("IsUpdate needed? tobeinstalled: %.2f, alreadyinstalled: %.2f", new_version, old_version); qDebug("IsUpdate needed? tobeinstalled: %.2f, alreadyinstalled: %.2f", new_version, old_version);
return (new_version > old_version); return (new_version > old_version);
} }
@ -236,13 +236,13 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
return; return;
} }
// Process with install // Process with install
QString dest_path = fsutils::searchEngineLocation() + "/engines/" + plugin_name + ".py"; QString dest_path = Utils::Fs::searchEngineLocation() + "/engines/" + plugin_name + ".py";
bool update = false; bool update = false;
if (QFile::exists(dest_path)) { if (QFile::exists(dest_path)) {
// Backup in case install fails // Backup in case install fails
QFile::copy(dest_path, dest_path+".bak"); QFile::copy(dest_path, dest_path+".bak");
fsutils::forceRemove(dest_path); Utils::Fs::forceRemove(dest_path);
fsutils::forceRemove(dest_path+"c"); Utils::Fs::forceRemove(dest_path+"c");
update = true; update = true;
} }
// Copy the plugin // Copy the plugin
@ -253,22 +253,22 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) {
if (!supported_engines->contains(plugin_name)) { if (!supported_engines->contains(plugin_name)) {
if (update) { if (update) {
// Remove broken file // Remove broken file
fsutils::forceRemove(dest_path); Utils::Fs::forceRemove(dest_path);
// restore backup // restore backup
QFile::copy(dest_path+".bak", dest_path); QFile::copy(dest_path+".bak", dest_path);
fsutils::forceRemove(dest_path+".bak"); Utils::Fs::forceRemove(dest_path+".bak");
QMessageBox::warning(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin could not be updated, keeping old version.", "%1 is the name of the search engine").arg(plugin_name)); QMessageBox::warning(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin could not be updated, keeping old version.", "%1 is the name of the search engine").arg(plugin_name));
return; return;
} else { } else {
// Remove broken file // Remove broken file
fsutils::forceRemove(dest_path); Utils::Fs::forceRemove(dest_path);
QMessageBox::warning(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin could not be installed.", "%1 is the name of the search engine").arg(plugin_name)); QMessageBox::warning(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin could not be installed.", "%1 is the name of the search engine").arg(plugin_name));
return; return;
} }
} }
// Install was successful, remove backup // Install was successful, remove backup
if (update) { if (update) {
fsutils::forceRemove(dest_path+".bak"); Utils::Fs::forceRemove(dest_path+".bak");
} }
if (update) { if (update) {
QMessageBox::information(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin was successfully updated.", "%1 is the name of the search engine").arg(plugin_name)); QMessageBox::information(this, tr("Search plugin install")+" -- "+tr("qBittorrent"), tr("%1 search engine plugin was successfully updated.", "%1 is the name of the search engine").arg(plugin_name));
@ -301,12 +301,12 @@ void engineSelectDlg::addNewEngine(QString engine_name) {
setRowColor(pluginsTree->indexOfTopLevelItem(item), "red"); setRowColor(pluginsTree->indexOfTopLevelItem(item), "red");
} }
// Handle icon // Handle icon
QString iconPath = fsutils::searchEngineLocation() + "/engines/" + engine->getName() + ".png"; QString iconPath = Utils::Fs::searchEngineLocation() + "/engines/" + engine->getName() + ".png";
if (QFile::exists(iconPath)) { if (QFile::exists(iconPath)) {
// Good, we already have the icon // Good, we already have the icon
item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath)));
} else { } else {
iconPath = fsutils::searchEngineLocation() + "/engines/" + engine->getName() + ".ico"; iconPath = Utils::Fs::searchEngineLocation() + "/engines/" + engine->getName() + ".ico";
if (QFile::exists(iconPath)) { // ICO support if (QFile::exists(iconPath)) { // ICO support
item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath)));
} else { } else {
@ -398,7 +398,7 @@ bool engineSelectDlg::parseVersionsFile(QString versions_file) {
// Close file // Close file
versions.close(); versions.close();
// Clean up tmp file // Clean up tmp file
fsutils::forceRemove(versions_file); Utils::Fs::forceRemove(versions_file);
if (file_correct && !updated) { if (file_correct && !updated) {
QMessageBox::information(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("All your plugins are already up to date.")); QMessageBox::information(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("All your plugins are already up to date."));
} }
@ -413,7 +413,7 @@ void engineSelectDlg::downloadFromUrl(const QString &url)
} }
void engineSelectDlg::processDownloadedFile(const QString &url, QString filePath) { void engineSelectDlg::processDownloadedFile(const QString &url, QString filePath) {
filePath = fsutils::fromNativePath(filePath); filePath = Utils::Fs::fromNativePath(filePath);
setCursor(QCursor(Qt::ArrowCursor)); setCursor(QCursor(Qt::ArrowCursor));
qDebug("engineSelectDlg received %s", qPrintable(url)); qDebug("engineSelectDlg received %s", qPrintable(url));
if (url.endsWith("favicon.ico", Qt::CaseInsensitive)) { if (url.endsWith("favicon.ico", Qt::CaseInsensitive)) {
@ -428,29 +428,29 @@ void engineSelectDlg::processDownloadedFile(const QString &url, QString filePath
QFile icon(filePath); QFile icon(filePath);
icon.open(QIODevice::ReadOnly); icon.open(QIODevice::ReadOnly);
if (ICOHandler::canRead(&icon)) if (ICOHandler::canRead(&icon))
iconPath = fsutils::searchEngineLocation() + "/engines/" + id + ".ico"; iconPath = Utils::Fs::searchEngineLocation() + "/engines/" + id + ".ico";
else else
iconPath = fsutils::searchEngineLocation() + "/engines/" + id + ".png"; iconPath = Utils::Fs::searchEngineLocation() + "/engines/" + id + ".png";
QFile::copy(filePath, iconPath); QFile::copy(filePath, iconPath);
item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath)));
} }
} }
// Delete tmp file // Delete tmp file
fsutils::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
return; return;
} }
if (url.endsWith("versions.txt")) { if (url.endsWith("versions.txt")) {
if (!parseVersionsFile(filePath)) { if (!parseVersionsFile(filePath)) {
QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable.")); QMessageBox::warning(this, tr("Search plugin update")+" -- "+tr("qBittorrent"), tr("Sorry, update server is temporarily unavailable."));
} }
fsutils::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
return; return;
} }
if (url.endsWith(".py", Qt::CaseInsensitive)) { if (url.endsWith(".py", Qt::CaseInsensitive)) {
QString plugin_name = fsutils::fileName(url); QString plugin_name = Utils::Fs::fileName(url);
plugin_name.chop(3); // Remove extension plugin_name.chop(3); // Remove extension
installPlugin(filePath, plugin_name); installPlugin(filePath, plugin_name);
fsutils::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
return; return;
} }
} }

View file

@ -49,8 +49,8 @@
#include "searchengine.h" #include "searchengine.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "searchlistdelegate.h" #include "searchlistdelegate.h"
#include "mainwindow.h" #include "mainwindow.h"
@ -217,7 +217,7 @@ void SearchEngine::on_search_button_clicked() {
// Getting checked search engines // Getting checked search engines
QStringList params; QStringList params;
search_stopped = false; search_stopped = false;
params << fsutils::toNativePath(fsutils::searchEngineLocation() + "/nova2.py"); params << Utils::Fs::toNativePath(Utils::Fs::searchEngineLocation() + "/nova2.py");
if (selectedEngine() == "all") params << supported_engines->enginesAll().join(","); if (selectedEngine() == "all") params << supported_engines->enginesAll().join(",");
else if (selectedEngine() == "enabled") params << supported_engines->enginesEnabled().join(","); else if (selectedEngine() == "enabled") params << supported_engines->enginesEnabled().join(",");
else if (selectedEngine() == "multi") params << supported_engines->enginesEnabled().join(","); else if (selectedEngine() == "multi") params << supported_engines->enginesEnabled().join(",");
@ -255,7 +255,7 @@ void SearchEngine::saveResultsColumnsWidth() {
void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) { void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) {
if (torrent_url.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (torrent_url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
torrent_url = misc::bcLinkToMagnet(torrent_url); torrent_url = Utils::Misc::bcLinkToMagnet(torrent_url);
} }
qDebug() << Q_FUNC_INFO << torrent_url; qDebug() << Q_FUNC_INFO << torrent_url;
if (torrent_url.startsWith("magnet:")) { if (torrent_url.startsWith("magnet:")) {
@ -268,7 +268,7 @@ void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) {
connect(downloadProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(downloadFinished(int,QProcess::ExitStatus))); connect(downloadProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(downloadFinished(int,QProcess::ExitStatus)));
downloaders << downloadProcess; downloaders << downloadProcess;
QStringList params; QStringList params;
params << fsutils::toNativePath(fsutils::searchEngineLocation() + "/nova2dl.py"); params << Utils::Fs::toNativePath(Utils::Fs::searchEngineLocation() + "/nova2dl.py");
params << engine_url; params << engine_url;
params << torrent_url; params << torrent_url;
// Launch search // Launch search
@ -323,16 +323,16 @@ void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) {
static void removePythonScriptIfExists(const QString& script_path) static void removePythonScriptIfExists(const QString& script_path)
{ {
fsutils::forceRemove(script_path); Utils::Fs::forceRemove(script_path);
fsutils::forceRemove(script_path + "c"); Utils::Fs::forceRemove(script_path + "c");
} }
// Update nova.py search plugin if necessary // Update nova.py search plugin if necessary
void SearchEngine::updateNova() { void SearchEngine::updateNova() {
qDebug("Updating nova"); qDebug("Updating nova");
// create nova directory if necessary // create nova directory if necessary
QDir search_dir(fsutils::searchEngineLocation()); QDir search_dir(Utils::Fs::searchEngineLocation());
QString nova_folder = misc::pythonVersion() >= 3 ? "nova3" : "nova"; QString nova_folder = Utils::Misc::pythonVersion() >= 3 ? "nova3" : "nova";
QFile package_file(search_dir.absoluteFilePath("__init__.py")); QFile package_file(search_dir.absoluteFilePath("__init__.py"));
package_file.open(QIODevice::WriteOnly | QIODevice::Text); package_file.open(QIODevice::WriteOnly | QIODevice::Text);
package_file.close(); package_file.close();
@ -382,7 +382,7 @@ void SearchEngine::updateNova() {
removePythonScriptIfExists(filePath); removePythonScriptIfExists(filePath);
QFile::copy(":/"+nova_folder+"/sgmllib3.py", filePath); QFile::copy(":/"+nova_folder+"/sgmllib3.py", filePath);
} }
QDir destDir(QDir(fsutils::searchEngineLocation()).absoluteFilePath("engines")); QDir destDir(QDir(Utils::Fs::searchEngineLocation()).absoluteFilePath("engines"));
QDir shipped_subDir(":/"+nova_folder+"/engines/"); QDir shipped_subDir(":/"+nova_folder+"/engines/");
QStringList files = shipped_subDir.entryList(); QStringList files = shipped_subDir.entryList();
foreach (const QString &file, files) { foreach (const QString &file, files) {

View file

@ -36,7 +36,7 @@
#include <QModelIndex> #include <QModelIndex>
#include <QPainter> #include <QPainter>
#include <QProgressBar> #include <QProgressBar>
#include "core/misc.h" #include "core/utils/misc.h"
#include "searchengine.h" #include "searchengine.h"
class SearchListDelegate: public QItemDelegate { class SearchListDelegate: public QItemDelegate {
@ -53,7 +53,7 @@ class SearchListDelegate: public QItemDelegate {
switch(index.column()) { switch(index.column()) {
case SearchSortModel::SIZE: case SearchSortModel::SIZE:
QItemDelegate::drawBackground(painter, opt, index); QItemDelegate::drawBackground(painter, opt, index);
QItemDelegate::drawDisplay(painter, opt, option.rect, misc::friendlyUnit(index.data().toLongLong())); QItemDelegate::drawDisplay(painter, opt, option.rect, Utils::Misc::friendlyUnit(index.data().toLongLong()));
break; break;
default: default:
QItemDelegate::paint(painter, option, index); QItemDelegate::paint(painter, option, index);

View file

@ -2,7 +2,7 @@
#define SEARCHSORTMODEL_H #define SEARCHSORTMODEL_H
#include <QSortFilterProxyModel> #include <QSortFilterProxyModel>
#include "core/misc.h" #include "core/utils/string.h"
class SearchSortModel : public QSortFilterProxyModel { class SearchSortModel : public QSortFilterProxyModel {
Q_OBJECT Q_OBJECT
@ -23,7 +23,7 @@ protected:
Q_ASSERT(vR.isValid()); Q_ASSERT(vR.isValid());
bool res = false; bool res = false;
if (misc::naturalSort(vL.toString(), vR.toString(), res)) if (Utils::String::naturalSort(vL.toString(), vR.toString(), res))
return res; return res;
return QSortFilterProxyModel::lessThan(left, right); return QSortFilterProxyModel::lessThan(left, right);

View file

@ -36,7 +36,7 @@
#include "searchtab.h" #include "searchtab.h"
#include "searchlistdelegate.h" #include "searchlistdelegate.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "searchengine.h" #include "searchengine.h"
#include "core/preferences.h" #include "core/preferences.h"

View file

@ -41,7 +41,7 @@
#include <QApplication> #include <QApplication>
#include <QDebug> #include <QDebug>
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/preferences.h" #include "core/preferences.h"
class SearchCategories: public QObject, public QHash<QString, QString> { class SearchCategories: public QObject, public QHash<QString, QString> {
@ -148,7 +148,7 @@ public slots:
QProcess nova; QProcess nova;
nova.setEnvironment(QProcess::systemEnvironment()); nova.setEnvironment(QProcess::systemEnvironment());
QStringList params; QStringList params;
params << fsutils::toNativePath(fsutils::searchEngineLocation()+"/nova2.py"); params << Utils::Fs::toNativePath(Utils::Fs::searchEngineLocation()+"/nova2.py");
params << "--capabilities"; params << "--capabilities";
nova.start("python", params, QIODevice::ReadOnly); nova.start("python", params, QIODevice::ReadOnly);
nova.waitForStarted(); nova.waitForStarted();

View file

@ -29,8 +29,8 @@
*/ */
#include "btjson.h" #include "btjson.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "core/bittorrent/session.h" #include "core/bittorrent/session.h"
#include "core/bittorrent/sessionstatus.h" #include "core/bittorrent/sessionstatus.h"
@ -411,7 +411,7 @@ QByteArray btjson::getPropertiesForTorrent(const QString& hash)
if (!torrent->hasMetadata()) if (!torrent->hasMetadata())
return QByteArray(); return QByteArray();
data[KEY_PROP_SAVE_PATH] = fsutils::toNativePath(torrent->savePath()); data[KEY_PROP_SAVE_PATH] = Utils::Fs::toNativePath(torrent->savePath());
data[KEY_PROP_CREATION_DATE] = torrent->creationDate().toTime_t(); data[KEY_PROP_CREATION_DATE] = torrent->creationDate().toTime_t();
data[KEY_PROP_PIECE_SIZE] = torrent->pieceLength(); data[KEY_PROP_PIECE_SIZE] = torrent->pieceLength();
data[KEY_PROP_COMMENT] = torrent->comment(); data[KEY_PROP_COMMENT] = torrent->comment();
@ -462,7 +462,7 @@ QByteArray btjson::getFilesForTorrent(const QString& hash)
QString fileName = torrent->filePath(i); QString fileName = torrent->filePath(i);
if (fileName.endsWith(".!qB", Qt::CaseInsensitive)) if (fileName.endsWith(".!qB", Qt::CaseInsensitive))
fileName.chop(4); fileName.chop(4);
file_dict[KEY_FILE_NAME] = fsutils::toNativePath(fileName); file_dict[KEY_FILE_NAME] = Utils::Fs::toNativePath(fileName);
const qlonglong size = torrent->fileSize(i); const qlonglong size = torrent->fileSize(i);
file_dict[KEY_FILE_SIZE] = size; file_dict[KEY_FILE_SIZE] = size;
file_dict[KEY_FILE_PROGRESS] = fp[i]; file_dict[KEY_FILE_PROGRESS] = fp[i];

View file

@ -31,7 +31,7 @@
#include "prefjson.h" #include "prefjson.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "core/scanfoldersmodel.h" #include "core/scanfoldersmodel.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#ifndef QT_NO_OPENSSL #ifndef QT_NO_OPENSSL
#include <QSslCertificate> #include <QSslCertificate>
@ -53,12 +53,12 @@ QByteArray prefjson::getPreferences()
// UI // UI
data["locale"] = pref->getLocale(); data["locale"] = pref->getLocale();
// Downloads // Downloads
data["save_path"] = fsutils::toNativePath(pref->getSavePath()); data["save_path"] = Utils::Fs::toNativePath(pref->getSavePath());
data["temp_path_enabled"] = pref->isTempPathEnabled(); data["temp_path_enabled"] = pref->isTempPathEnabled();
data["temp_path"] = fsutils::toNativePath(pref->getTempPath()); data["temp_path"] = Utils::Fs::toNativePath(pref->getTempPath());
QVariantList l; QVariantList l;
foreach (const QString& s, pref->getScanDirs()) { foreach (const QString& s, pref->getScanDirs()) {
l << fsutils::toNativePath(s); l << Utils::Fs::toNativePath(s);
} }
data["scan_dirs"] = l; data["scan_dirs"] = l;
QVariantList var_list; QVariantList var_list;
@ -67,7 +67,7 @@ QByteArray prefjson::getPreferences()
} }
data["download_in_scan_dirs"] = var_list; data["download_in_scan_dirs"] = var_list;
data["export_dir_enabled"] = pref->isTorrentExportEnabled(); data["export_dir_enabled"] = pref->isTorrentExportEnabled();
data["export_dir"] = fsutils::toNativePath(pref->getTorrentExportDir()); data["export_dir"] = Utils::Fs::toNativePath(pref->getTorrentExportDir());
data["mail_notification_enabled"] = pref->isMailNotificationEnabled(); data["mail_notification_enabled"] = pref->isMailNotificationEnabled();
data["mail_notification_email"] = pref->getMailNotificationEmail(); data["mail_notification_email"] = pref->getMailNotificationEmail();
data["mail_notification_smtp"] = pref->getMailNotificationSMTP(); data["mail_notification_smtp"] = pref->getMailNotificationSMTP();
@ -76,7 +76,7 @@ QByteArray prefjson::getPreferences()
data["mail_notification_username"] = pref->getMailNotificationSMTPUsername(); data["mail_notification_username"] = pref->getMailNotificationSMTPUsername();
data["mail_notification_password"] = pref->getMailNotificationSMTPPassword(); data["mail_notification_password"] = pref->getMailNotificationSMTPPassword();
data["autorun_enabled"] = pref->isAutoRunEnabled(); data["autorun_enabled"] = pref->isAutoRunEnabled();
data["autorun_program"] = fsutils::toNativePath(pref->getAutoRunProgram()); data["autorun_program"] = Utils::Fs::toNativePath(pref->getAutoRunProgram());
data["preallocate_all"] = pref->preAllocateAllFiles(); data["preallocate_all"] = pref->preAllocateAllFiles();
data["queueing_enabled"] = pref->isQueueingSystemEnabled(); data["queueing_enabled"] = pref->isQueueingSystemEnabled();
data["max_active_downloads"] = pref->getMaxActiveDownloads(); data["max_active_downloads"] = pref->getMaxActiveDownloads();
@ -122,7 +122,7 @@ QByteArray prefjson::getPreferences()
data["proxy_password"] = pref->getProxyPassword(); data["proxy_password"] = pref->getProxyPassword();
// IP Filter // IP Filter
data["ip_filter_enabled"] = pref->isFilteringEnabled(); data["ip_filter_enabled"] = pref->isFilteringEnabled();
data["ip_filter_path"] = fsutils::toNativePath(pref->getFilter()); data["ip_filter_path"] = Utils::Fs::toNativePath(pref->getFilter());
// Web UI // Web UI
data["web_ui_port"] = pref->getWebUiPort(); data["web_ui_port"] = pref->getWebUiPort();
data["web_ui_username"] = pref->getWebUiUsername(); data["web_ui_username"] = pref->getWebUiUsername();
@ -189,7 +189,7 @@ void prefjson::setPreferences(const QString& json)
foreach (const QString &new_folder, new_folders) { foreach (const QString &new_folder, new_folders) {
qDebug("New watched folder: %s", qPrintable(new_folder)); qDebug("New watched folder: %s", qPrintable(new_folder));
// Update new folders // Update new folders
if (!old_folders.contains(fsutils::fromNativePath(new_folder))) { if (!old_folders.contains(Utils::Fs::fromNativePath(new_folder))) {
ScanFoldersModel::instance()->addPath(new_folder, download_at_path.at(i)); ScanFoldersModel::instance()->addPath(new_folder, download_at_path.at(i));
} }
++i; ++i;

View file

@ -33,8 +33,9 @@
#include <queue> #include <queue>
#include <vector> #include <vector>
#include "core/iconprovider.h" #include "core/iconprovider.h"
#include "core/misc.h" #include "core/utils/misc.h"
#include "core/fs_utils.h" #include "core/utils/fs.h"
#include "core/utils/string.h"
#include "core/preferences.h" #include "core/preferences.h"
#include "btjson.h" #include "btjson.h"
#include "prefjson.h" #include "prefjson.h"
@ -164,8 +165,8 @@ void WebApplication::action_public_login()
md5.addData(request().posts["password"].toLocal8Bit()); md5.addData(request().posts["password"].toLocal8Bit());
QString pass = md5.result().toHex(); QString pass = md5.result().toHex();
bool equalUser = misc::slowEquals(request().posts["username"].toUtf8(), pref->getWebUiUsername().toUtf8()); bool equalUser = Utils::String::slowEquals(request().posts["username"].toUtf8(), pref->getWebUiUsername().toUtf8());
bool equalPass = misc::slowEquals(pass.toUtf8(), pref->getWebUiPassword().toUtf8()); bool equalPass = Utils::String::slowEquals(pass.toUtf8(), pref->getWebUiPassword().toUtf8());
if (equalUser && equalPass) { if (equalUser && equalPass) {
sessionStart(); sessionStart();
@ -303,7 +304,7 @@ void WebApplication::action_command_download()
if (!url.isEmpty()) { if (!url.isEmpty()) {
if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) { if (url.startsWith("bc://bt/", Qt::CaseInsensitive)) {
qDebug("Converting bc link to magnet link"); qDebug("Converting bc link to magnet link");
url = misc::bcLinkToMagnet(url); url = Utils::Misc::bcLinkToMagnet(url);
} }
BitTorrent::Session::instance()->addTorrent(url); BitTorrent::Session::instance()->addTorrent(url);
@ -332,7 +333,7 @@ void WebApplication::action_command_upload()
} }
} }
// Clean up // Clean up
fsutils::forceRemove(filePath); Utils::Fs::forceRemove(filePath);
} }
else { else {
qWarning() << "I/O Error: Could not create temporary file"; qWarning() << "I/O Error: Could not create temporary file";