diff --git a/src/addnewtorrentdialog.cpp b/src/addnewtorrentdialog.cpp index 5e73b8e51..2b2e55278 100644 --- a/src/addnewtorrentdialog.cpp +++ b/src/addnewtorrentdialog.cpp @@ -37,6 +37,7 @@ #include "torrentpersistentdata.h" #include "qbtsession.h" #include "iconprovider.h" +#include "fs_utils.h" #include #include @@ -62,7 +63,7 @@ AddNewTorrentDialog::AddNewTorrentDialog(QWidget *parent) : Preferences pref; ui->start_torrent_cb->setChecked(!pref.addTorrentsInPause()); - ui->save_path_combo->addItem(misc::toDisplayPath(pref.getSavePath())); + ui->save_path_combo->addItem(fsutils::toDisplayPath(pref.getSavePath())); loadSavePathHistory(); ui->save_path_combo->insertSeparator(ui->save_path_combo->count()); ui->save_path_combo->addItem(tr("Other...", "Other save path...")); @@ -257,7 +258,7 @@ void AddNewTorrentDialog::updateFileNameInSavePaths(const QString &new_filename) { for(int i=0; isave_path_combo->count()-1; ++i) { const QDir folder(ui->save_path_combo->itemData(i).toString()); - ui->save_path_combo->setItemText(i, misc::toDisplayPath(folder.absoluteFilePath(new_filename))); + ui->save_path_combo->setItemText(i, fsutils::toDisplayPath(folder.absoluteFilePath(new_filename))); } } @@ -278,7 +279,7 @@ void AddNewTorrentDialog::updateDiskSpaceLabel() } QString size_string = misc::friendlyUnit(torrent_size); size_string += " ("; - size_string += tr("Disk space: %1").arg(misc::friendlyUnit(misc::freeDiskSpaceOnPath(ui->save_path_combo->currentText()))); + size_string += tr("Disk space: %1").arg(misc::friendlyUnit(fsutils::freeDiskSpaceOnPath(ui->save_path_combo->currentText()))); size_string += ")"; ui->size_lbl->setText(size_string); } @@ -295,10 +296,10 @@ void AddNewTorrentDialog::onSavePathChanged(int index) QString new_path, old_filename, new_filename; if (m_torrentInfo && m_torrentInfo->num_files() == 1) { - misc::branchPath(cur_save_path, &old_filename); + old_filename = fsutils::fileName(cur_save_path); new_path = QFileDialog::getSaveFileName(this, tr("Choose save path"), cur_save_path, QString(), 0, QFileDialog::DontConfirmOverwrite); if (!new_path.isEmpty()) - new_path = misc::branchPath(new_path, &new_filename); + new_path = fsutils::branchPath(new_path, &new_filename); qDebug() << "new_path: " << new_path; qDebug() << "new_filename: " << new_filename; } else { @@ -314,13 +315,13 @@ void AddNewTorrentDialog::onSavePathChanged(int index) else { // New path, prepend to combo box if (!new_filename.isEmpty()) - ui->save_path_combo->insertItem(0, misc::toDisplayPath(QDir(new_path).absoluteFilePath(new_filename)), new_path); + ui->save_path_combo->insertItem(0, fsutils::toDisplayPath(QDir(new_path).absoluteFilePath(new_filename)), new_path); else - ui->save_path_combo->insertItem(0, misc::toDisplayPath(new_path), new_path); + ui->save_path_combo->insertItem(0, fsutils::toDisplayPath(new_path), new_path); ui->save_path_combo->setCurrentIndex(0); } // Update file name in all save_paths - if (!new_filename.isEmpty() && !misc::sameFileNames(old_filename, new_filename)) { + if (!new_filename.isEmpty() && !fsutils::sameFileNames(old_filename, new_filename)) { m_hasRenamedFile = true; m_filesPath[0] = new_filename; updateFileNameInSavePaths(new_filename); @@ -357,7 +358,7 @@ void AddNewTorrentDialog::renameSelectedFile() tr("New name:"), QLineEdit::Normal, index.data().toString(), &ok); if (ok && !new_name_last.isEmpty()) { - if (!misc::isValidFileSystemName(new_name_last)) { + if (!fsutils::isValidFileSystemName(new_name_last)) { QMessageBox::warning(this, tr("The file could not be renamed"), tr("This file name contains forbidden characters, please choose a different one."), QMessageBox::Ok); @@ -373,7 +374,7 @@ void AddNewTorrentDialog::renameSelectedFile() path_items.removeLast(); path_items << new_name_last; QString new_name = path_items.join("/"); - if (misc::sameFileNames(old_name, new_name)) { + if (fsutils::sameFileNames(old_name, new_name)) { qDebug("Name did not change"); return; } @@ -382,7 +383,7 @@ void AddNewTorrentDialog::renameSelectedFile() // Check if that name is already used for (int i=0; inum_files(); ++i) { if (i == file_index) continue; - if (misc::sameFileNames(m_filesPath.at(i), new_name)) { + if (fsutils::sameFileNames(m_filesPath.at(i), new_name)) { // Display error message QMessageBox::warning(this, tr("The file could not be renamed"), tr("This name is already in use in this folder. Please use a different name."), @@ -457,7 +458,7 @@ void AddNewTorrentDialog::loadSavePathHistory() QStringList raw_path_history = settings.value("TorrentAdditionDlg/save_path_history").toStringList(); foreach (const QString &sp, raw_path_history) { if (QDir(sp) != default_save_path) - ui->save_path_combo->addItem(misc::toDisplayPath(sp), sp); + ui->save_path_combo->addItem(fsutils::toDisplayPath(sp), sp); } } diff --git a/src/filesystemwatcher.h b/src/filesystemwatcher.h index 827f8ad8c..2522946ab 100644 --- a/src/filesystemwatcher.h +++ b/src/filesystemwatcher.h @@ -21,7 +21,7 @@ #endif #endif -#include "misc.h" +#include "fs_utils.h" #ifndef CIFS_MAGIC_NUMBER #define CIFS_MAGIC_NUMBER 0xFF534D42 @@ -226,7 +226,7 @@ protected slots: m_partialTorrents.remove(torrent_path); continue; } - if (misc::isValidTorrentFile(torrent_path)) { + if (fsutils::isValidTorrentFile(torrent_path)) { no_longer_partial << torrent_path; m_partialTorrents.remove(torrent_path); } else { @@ -271,7 +271,7 @@ private: const QStringList files = dir.entryList(m_filters, QDir::Files, QDir::Unsorted); foreach (const QString &file, files) { const QString file_abspath = dir.absoluteFilePath(file); - if (misc::isValidTorrentFile(file_abspath)) { + if (fsutils::isValidTorrentFile(file_abspath)) { torrents << file_abspath; } else { if (!m_partialTorrents.contains(file_abspath)) { diff --git a/src/fs_utils.cpp b/src/fs_utils.cpp new file mode 100644 index 000000000..2d0ccda0c --- /dev/null +++ b/src/fs_utils.cpp @@ -0,0 +1,481 @@ +/* + * 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 +#include +#include +#include +#include +#ifdef DISABLE_GUI +#include +#else +#include +#endif +#include + +#ifdef Q_WS_MAC +#include +#include +#endif + +#ifndef Q_WS_WIN +#if defined(Q_WS_MAC) || defined(Q_OS_FREEBSD) +#include +#include +#else +#include +#endif +#else +#include +#endif + +using namespace libtorrent; + +// EXT2/3/4 file systems support a maximum of 255 bytes for filenames. +const int MAX_FILENAME_BYTES = 255; + +/** + * 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::toDisplayPath(const QString& path) +{ +#if defined(Q_WS_WIN) || defined(Q_OS_OS2) + QString ret = path; + return ret.replace("/", "\\"); +#else + return path; +#endif +} + +/** + * Returns the file extension part of a file name. + */ +QString fsutils::fileExtension(const QString &filename) +{ + const int point_index = filename.lastIndexOf("."); + return (point_index >= 0) ? filename.mid(point_index + 1) : QString(); +} + +QString fsutils::fileName(const QString& file_path) +{ + const int slash_index = file_path.lastIndexOf(QRegExp("[/\\\\]")); + if (slash_index == -1) + return file_path; + return file_path.mid(slash_index + 1); +} + +bool fsutils::isValidTorrentFile(const QString& torrent_path) { + try { + boost::intrusive_ptr t = new torrent_info(torrent_path.toUtf8().constData()); + if (!t->is_valid() || t->num_files() == 0) + return false; + } catch(std::exception&) { + return false; + } + return true; +} + +/** + * 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; +} + +/** + * Fixes the given file path by shortening the file names if too long. + */ +QString fsutils::fixFileNames(const QString& path) +{ + QByteArray raw_path = path.toLocal8Bit(); + raw_path.replace("\\", "/"); + QList parts = raw_path.split('/'); + if (parts.isEmpty()) return path; + QByteArray last_part = parts.takeLast(); + QList::iterator it; + for (it = parts.begin(); it != parts.end(); it++) { + // Make sure the filename is not too long + if (it->size() > MAX_FILENAME_BYTES) { + qWarning() << "Folder" << *it << "was cut because it was too long"; + it->resize(MAX_FILENAME_BYTES); + qWarning() << "New folder name is" << *it; + Q_ASSERT(it->length() == MAX_FILENAME_BYTES); + } + } + // Fix the last part (file name) + qDebug() << "Last part length:" << last_part.length(); + if (last_part.length() > MAX_FILENAME_BYTES) { + qWarning() << "Filename" << last_part << "was cut because it was too long"; + // Shorten the name, keep the file extension + const int point_index = last_part.lastIndexOf("."); + QByteArray extension = ""; + if (point_index >= 0) { + extension = last_part.mid(point_index); + last_part = last_part.left(point_index); + } + last_part.resize(MAX_FILENAME_BYTES - extension.length()); + last_part += extension; + Q_ASSERT(last_part.length() == MAX_FILENAME_BYTES); + qWarning() << "New file name is" << last_part; + } + + QString ret; + foreach(const QByteArray& part, parts) { + ret += QString::fromLocal8Bit(part.constData()) + "/"; + } + ret += QString::fromLocal8Bit(last_part.constData()); + + return ret; +} + +/** + * 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::updateLabelInSavePath(QString defaultSavePath,QString save_path, const QString& old_label, const QString& new_label) { + if (old_label == new_label) return save_path; + defaultSavePath.replace("\\", "/"); + save_path.replace("\\", "/"); + qDebug("UpdateLabelInSavePath(%s, %s, %s)", qPrintable(save_path), qPrintable(old_label), qPrintable(new_label)); + if (!save_path.startsWith(defaultSavePath)) return save_path; + QString new_save_path = save_path; + new_save_path.replace(defaultSavePath, ""); + QStringList path_parts = new_save_path.split("/", QString::SkipEmptyParts); + if (path_parts.empty()) { + if (!new_label.isEmpty()) + path_parts << new_label; + } else { + if (old_label.isEmpty() || path_parts.first() != old_label) { + if (path_parts.first() != new_label) + path_parts.prepend(new_label); + } else { + if (new_label.isEmpty()) { + path_parts.removeAt(0); + } else { + if (path_parts.first() != new_label) + path_parts.replace(0, new_label); + } + } + } + new_save_path = defaultSavePath; + if (!new_save_path.endsWith(QDir::separator())) new_save_path += QDir::separator(); + new_save_path += path_parts.join(QDir::separator()); + qDebug("New save path is %s", qPrintable(new_save_path)); + return new_save_path; +} + +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; + path.replace("\\", "/"); + 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_WS_WIN + unsigned long long available; + 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; + } +#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)(QDir::toNativeSeparators(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 = file_path; + if (ret.endsWith("/") || ret.endsWith("\\")) + ret.chop(1); + const int slashIndex = ret.lastIndexOf(QRegExp("[/\\\\]")); + 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_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) + return QString::compare(first, second, Qt::CaseSensitive) == 0; +#else + return QString::compare(first, second, Qt::CaseInsensitive) == 0; +#endif +} + +// Replace ~ in path +QString fsutils::expandPath(const QString& path) { + QString ret = path.trimmed(); + if (ret.isEmpty()) return ret; + if (ret == "~") + return QDir::homePath(); + if (ret[0] == '~' && (ret[1] == '/' || ret[1] == '\\')) { + ret.replace(0, 1, QDir::homePath()); + } else { + if (!QDir::isAbsolutePath(ret)) + ret = QDir(ret).absolutePath(); + } + return QDir::cleanPath(path); +} + +QString fsutils::QDesktopServicesDataLocation() { +#ifdef Q_WS_WIN + LPWSTR path=new WCHAR[256]; + QString result; +#if defined Q_WS_WINCE + if (SHGetSpecialFolderPath(0, path, CSIDL_APPDATA, FALSE)) +#else + if (SHGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, FALSE)) +#endif + result = QString::fromWCharArray(path); + if (!QCoreApplication::applicationName().isEmpty()) + result = result + QLatin1String("\\") + qApp->applicationName(); + if (!result.endsWith("\\")) + result += "\\"; + return result; +#else +#ifdef Q_WS_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(ba.data()), ba.size()) == noErr) + path = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C); + path += QLatin1Char('/') + qApp->applicationName(); + return path; +#else + QString xdgDataHome = QLatin1String(qgetenv("XDG_DATA_HOME")); + if (xdgDataHome.isEmpty()) + xdgDataHome = QDir::homePath() + QLatin1String("/.local/share"); + xdgDataHome += QLatin1String("/data/") + + qApp->applicationName(); + return xdgDataHome; +#endif +#endif +} + +QString fsutils::QDesktopServicesCacheLocation() { +#ifdef Q_WS_WIN + return QDesktopServicesDataLocation() + QLatin1String("\\cache"); +#else +#ifdef Q_WS_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(); + QString path; + QByteArray ba(2048, 0); + if (FSRefMakePath(&ref, reinterpret_cast(ba.data()), ba.size()) == noErr) + path = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C); + path += QLatin1Char('/') + qApp->applicationName(); + return path; +#else + QString xdgCacheHome = QLatin1String(qgetenv("XDG_CACHE_HOME")); + if (xdgCacheHome.isEmpty()) + xdgCacheHome = QDir::homePath() + QLatin1String("/.cache"); + xdgCacheHome += QLatin1Char('/') + QCoreApplication::applicationName(); + return xdgCacheHome; +#endif +#endif +} + +QString fsutils::QDesktopServicesDownloadLocation() { +#if defined(Q_WS_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 + return QDir(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)).absoluteFilePath(tr("Downloads")); +#endif + +#ifdef Q_WS_X11 + 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); + 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(tr("Downloads")); + qDebug() << Q_FUNC_INFO << "using" << save_path << "as fallback since the XDG detection did not work"; + } + + return save_path; +#endif + +#ifdef Q_WS_MAC + // TODO: How to support this on Mac OS X? +#endif + + // Fallback + return QDir::home().absoluteFilePath(tr("Downloads")); +} + +QString fsutils::searchEngineLocation() { + QString folder = "nova"; + if (misc::pythonVersion() >= 3) + folder = "nova3"; + const QString location = QDir::cleanPath(QDesktopServicesDataLocation() + + QDir::separator() + folder); + QDir locationDir(location); + if (!locationDir.exists()) + locationDir.mkpath(locationDir.absolutePath()); + return location; +} + +QString fsutils::BTBackupLocation() { + const QString location = QDir::cleanPath(QDesktopServicesDataLocation() + + QDir::separator() + "BT_backup"); + QDir locationDir(location); + if (!locationDir.exists()) + locationDir.mkpath(locationDir.absolutePath()); + return location; +} + +QString fsutils::cacheLocation() { + QString location = QDir::cleanPath(QDesktopServicesCacheLocation()); + QDir locationDir(location); + if (!locationDir.exists()) + locationDir.mkpath(locationDir.absolutePath()); + return location; +} diff --git a/src/fs_utils.h b/src/fs_utils.h new file mode 100644 index 000000000..e46c5a331 --- /dev/null +++ b/src/fs_utils.h @@ -0,0 +1,72 @@ +/* + * 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 + */ + +#ifndef FS_UTILS_H +#define FS_UTILS_H + +#include +#include + +/** + * Utility functions related to file system. + */ +class fsutils +{ + Q_DECLARE_TR_FUNCTIONS(fsutils) + +public: +static QString toDisplayPath(const QString& path); +static QString fileExtension(const QString& filename); +static QString fileName(const QString& file_path); +static qint64 computePathSize(const QString& path); +static QString fixFileNames(const QString& path); +static bool sameFiles(const QString& path1, const QString& path2); +static QString updateLabelInSavePath(QString defaultSavePath, QString save_path, const QString& old_label, const QString& new_label); +static QString toValidFileSystemName(QString filename); +static bool isValidFileSystemName(const QString& filename); +static long long freeDiskSpaceOnPath(QString path); +static QString branchPath(const QString& file_path, QString* removed = 0); +static bool sameFileNames(const QString& first, const QString& second); +static QString expandPath(const QString& path); +static bool isValidTorrentFile(const QString& path); + +/* Ported from Qt4 to drop dependency on QtGui */ +static QString QDesktopServicesDataLocation(); +static QString QDesktopServicesCacheLocation(); +static QString QDesktopServicesDownloadLocation(); +/* End of Qt4 code */ +static QString searchEngineLocation(); +static QString BTBackupLocation(); +static QString cacheLocation(); + +}; + +#endif // FS_UTILS_H + diff --git a/src/geoip/geoipmanager.cpp b/src/geoip/geoipmanager.cpp index d934e66de..dbe6ee017 100644 --- a/src/geoip/geoipmanager.cpp +++ b/src/geoip/geoipmanager.cpp @@ -64,7 +64,7 @@ #include #include -#include "misc.h" +#include "fs_utils.h" using namespace libtorrent; @@ -72,7 +72,7 @@ QString GeoIPManager::geoipFolder(bool embedded) { #ifdef WITH_GEOIP_EMBEDDED if (embedded) return ":/geoip/"; - return misc::QDesktopServicesDataLocation()+"geoip"+QDir::separator(); + return fsutils::QDesktopServicesDataLocation()+"geoip"+QDir::separator(); #else Q_UNUSED(embedded); if (QFile::exists("/usr/local/share/GeoIP/GeoIP.dat")) diff --git a/src/misc.cpp b/src/misc.cpp index 643916886..9fef8f92f 100644 --- a/src/misc.cpp +++ b/src/misc.cpp @@ -61,17 +61,6 @@ const int UNLEN = 256; #include #endif -#ifndef Q_WS_WIN -#if defined(Q_WS_MAC) || defined(Q_OS_FREEBSD) -#include -#include -#else -#include -#endif -#else -#include -#endif - #ifndef DISABLE_GUI #if defined(Q_WS_X11) && defined(QT_DBUS_LIB) #include @@ -85,8 +74,6 @@ const int UNLEN = 256; using namespace libtorrent; -const int MAX_FILENAME_LENGTH = 255; - static struct { const char *source; const char *comment; } units[] = { QT_TRANSLATE_NOOP3("misc", "B", "bytes"), QT_TRANSLATE_NOOP3("misc", "KiB", "kibibytes (1024 bytes)"), @@ -95,172 +82,6 @@ static struct { const char *source; const char *comment; } units[] = { QT_TRANSLATE_NOOP3("misc", "TiB", "tebibytes (1024 gibibytes)") }; -QString misc::QDesktopServicesDataLocation() { -#ifdef Q_WS_WIN - LPWSTR path=new WCHAR[256]; - QString result; -#if defined Q_WS_WINCE - if (SHGetSpecialFolderPath(0, path, CSIDL_APPDATA, FALSE)) -#else - if (SHGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, FALSE)) -#endif - result = QString::fromWCharArray(path); - if (!QCoreApplication::applicationName().isEmpty()) - result = result + QLatin1String("\\") + qApp->applicationName(); - if (!result.endsWith("\\")) - result += "\\"; - return result; -#else -#ifdef Q_WS_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(ba.data()), ba.size()) == noErr) - path = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C); - path += QLatin1Char('/') + qApp->applicationName(); - return path; -#else - QString xdgDataHome = QLatin1String(qgetenv("XDG_DATA_HOME")); - if (xdgDataHome.isEmpty()) - xdgDataHome = QDir::homePath() + QLatin1String("/.local/share"); - xdgDataHome += QLatin1String("/data/") - + qApp->applicationName(); - return xdgDataHome; -#endif -#endif -} - -QString misc::QDesktopServicesCacheLocation() { -#ifdef Q_WS_WIN - return QDesktopServicesDataLocation() + QLatin1String("\\cache"); -#else -#ifdef Q_WS_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(); - QString path; - QByteArray ba(2048, 0); - if (FSRefMakePath(&ref, reinterpret_cast(ba.data()), ba.size()) == noErr) - path = QString::fromUtf8(ba).normalized(QString::NormalizationForm_C); - path += QLatin1Char('/') + qApp->applicationName(); - return path; -#else - QString xdgCacheHome = QLatin1String(qgetenv("XDG_CACHE_HOME")); - if (xdgCacheHome.isEmpty()) - xdgCacheHome = QDir::homePath() + QLatin1String("/.cache"); - xdgCacheHome += QLatin1Char('/') + QCoreApplication::applicationName(); - return xdgCacheHome; -#endif -#endif -} - -QString misc::QDesktopServicesDownloadLocation() { -#if defined(Q_WS_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 - return QDir(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation)).absoluteFilePath(tr("Downloads")); -#endif - -#ifdef Q_WS_X11 - 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); - 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(tr("Downloads")); - qDebug() << Q_FUNC_INFO << "using" << save_path << "as fallback since the XDG detection did not work"; - } - - return save_path; -#endif - -#ifdef Q_WS_MAC - // TODO: How to support this on Mac OS X? -#endif - - // Fallback - return QDir::home().absoluteFilePath(tr("Downloads")); -} - -long long misc::freeDiskSpaceOnPath(QString path) { - if (path.isEmpty()) return -1; - path.replace("\\", "/"); - 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_WS_WIN - unsigned long long available; - 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; - } -#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)(QDir::toNativeSeparators(dir_path.path())).utf16(), &bytesFree, &bytesTotal, NULL)) { - ret = (unsigned long long*)&bytesFree; - return *ret; - } else { - return -1; - } - } else { - return -1; - } -#endif -} - #ifndef DISABLE_GUI void misc::shutdownComputer(bool sleep) { #if defined(Q_WS_X11) && defined(QT_DBUS_LIB) @@ -369,113 +190,6 @@ void misc::shutdownComputer(bool sleep) { } #endif // DISABLE_GUI -QString misc::fixFileNames(QString path) { - //qDebug() << Q_FUNC_INFO << path; - path.replace("\\", "/"); - QStringList parts = path.split("/", QString::SkipEmptyParts); - if (parts.isEmpty()) return path; - QString last_part = parts.takeLast(); - QList::iterator it; - for (it = parts.begin(); it != parts.end(); it++) { - QByteArray raw_filename = it->toLocal8Bit(); - // Make sure the filename is not too long - if (raw_filename.size() > MAX_FILENAME_LENGTH) { - qDebug() << "Folder" << *it << "was cut because it was too long"; - raw_filename.resize(MAX_FILENAME_LENGTH); - *it = QString::fromLocal8Bit(raw_filename.constData()); - qDebug() << "New folder name is" << *it; - Q_ASSERT(it->length() == MAX_FILENAME_LENGTH); - } - } - // Fix the last part (file name) - QByteArray raw_lastPart = last_part.toLocal8Bit(); - qDebug() << "Last part length:" << raw_lastPart.length(); - if (raw_lastPart.length() > MAX_FILENAME_LENGTH) { - qDebug() << "Filename" << last_part << "was cut because it was too long"; - // Shorten the name, keep the file extension - int point_index = raw_lastPart.lastIndexOf("."); - QByteArray extension = ""; - if (point_index >= 0) { - extension = raw_lastPart.mid(point_index); - raw_lastPart = raw_lastPart.left(point_index); - } - raw_lastPart = raw_lastPart.left(MAX_FILENAME_LENGTH-extension.length()) + extension; - Q_ASSERT(raw_lastPart.length() == MAX_FILENAME_LENGTH); - last_part = QString::fromLocal8Bit(raw_lastPart.constData()); - qDebug() << "New file name is" << last_part; - } - parts << last_part; - return parts.join("/"); -} - -bool misc::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(5) != f2.read(5)) { - same = false; - break; - } - } - f1.close(); f2.close(); - return same; -} - -QString misc::updateLabelInSavePath(QString defaultSavePath, QString save_path, const QString &old_label, const QString &new_label) { - if (old_label == new_label) return save_path; -#if defined(Q_WS_WIN) || defined(Q_OS_OS2) - defaultSavePath.replace("\\", "/"); - save_path.replace("\\", "/"); -#endif - qDebug("UpdateLabelInSavePath(%s, %s, %s)", qPrintable(save_path), qPrintable(old_label), qPrintable(new_label)); - if (!save_path.startsWith(defaultSavePath)) return save_path; - QString new_save_path = save_path; - new_save_path.replace(defaultSavePath, ""); - QStringList path_parts = new_save_path.split("/", QString::SkipEmptyParts); - if (path_parts.empty()) { - if (!new_label.isEmpty()) - path_parts << new_label; - } else { - if (old_label.isEmpty() || path_parts.first() != old_label) { - if (path_parts.first() != new_label) - path_parts.prepend(new_label); - } else { - if (new_label.isEmpty()) { - path_parts.removeAt(0); - } else { - if (path_parts.first() != new_label) - path_parts.replace(0, new_label); - } - } - } - new_save_path = defaultSavePath; - if (!new_save_path.endsWith(QDir::separator())) new_save_path += QDir::separator(); - new_save_path += path_parts.join(QDir::separator()); - qDebug("New save path is %s", qPrintable(new_save_path)); - return new_save_path; -} - -QString misc::toValidFileSystemName(QString filename) { - qDebug("toValidFSName: %s", qPrintable(filename)); - const QRegExp regex("[\\\\/:?\"*<>|]"); - filename.replace(regex, " "); - qDebug("toValidFSName, result: %s", qPrintable(filename)); - return filename.trimmed(); -} - -bool misc::isValidFileSystemName(const QString& filename) { - if (filename.isEmpty()) return false; - const QRegExp regex("[\\\\/:?\"*<>|]"); - return !filename.contains(regex); -} - #ifndef DISABLE_GUI // Get screen center QPoint misc::screenCenter(QWidget *win) { @@ -518,35 +232,6 @@ int misc::pythonVersion() { return version; } -QString misc::searchEngineLocation() { - QString folder = "nova"; - if (pythonVersion() >= 3) - folder = "nova3"; - const QString location = QDir::cleanPath(QDesktopServicesDataLocation() - + QDir::separator() + folder); - QDir locationDir(location); - if (!locationDir.exists()) - locationDir.mkpath(locationDir.absolutePath()); - return location; -} - -QString misc::BTBackupLocation() { - const QString location = QDir::cleanPath(QDesktopServicesDataLocation() - + QDir::separator() + "BT_backup"); - QDir locationDir(location); - if (!locationDir.exists()) - locationDir.mkpath(locationDir.absolutePath()); - return location; -} - -QString misc::cacheLocation() { - QString location = QDir::cleanPath(QDesktopServicesCacheLocation()); - QDir locationDir(location); - if (!locationDir.exists()) - locationDir.mkpath(locationDir.absolutePath()); - return location; -} - // 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 @@ -664,23 +349,6 @@ QString misc::magnetUriToHash(QString magnet_uri) { return hash; } -// Replace ~ in path -QString misc::expandPath(QString path) { - path = path.trimmed(); - if (path.isEmpty()) return path; - if (path.length() == 1) { - if (path[0] == '~' ) return QDir::homePath(); - } - if (path[0] == '~' && path[1] == QDir::separator()) { - path.replace(0, 1, QDir::homePath()); - } else { - if (QDir::isAbsolutePath(path)) { - path = QDir(path).absolutePath(); - } - } - return QDir::cleanPath(path); -} - // Take a number of seconds and return an user-friendly // time duration like "1d 2h 10m". QString misc::userFriendlyDuration(qlonglong seconds) { @@ -747,58 +415,6 @@ QList misc::boolListfromStringList(const QStringList &l) { return ret; } -quint64 misc::computePathSize(QString path) -{ - // Check if it is a file - QFileInfo fi(path); - if (!fi.exists()) return 0; - if (fi.isFile()) return fi.size(); - // Compute folder size - quint64 size = 0; - foreach (const QFileInfo &subfi, QDir(path).entryInfoList(QDir::Dirs|QDir::Files)) { - if (subfi.fileName().startsWith(".")) continue; - if (subfi.isDir()) - size += misc::computePathSize(subfi.absoluteFilePath()); - else - size += subfi.size(); - } - return size; -} - -bool misc::isValidTorrentFile(const QString &torrent_path) { - try { - boost::intrusive_ptr t = new torrent_info(torrent_path.toUtf8().constData()); - if (!t->is_valid() || t->num_files() == 0) - throw std::exception(); - } catch(std::exception&) { - return false; - } - return true; -} - -QString misc::branchPath(const QString& file_path, QString* removed) -{ - QString ret = file_path; - if (ret.endsWith("/") || ret.endsWith("\\")) - ret.chop(1); - const int slashIndex = ret.lastIndexOf(QRegExp("[/\\\\]")); - if (slashIndex >= 0) { - if (removed) - *removed = ret.mid(slashIndex + 1); - ret = ret.left(slashIndex); - } - return ret; -} - -bool misc::sameFileNames(const QString &first, const QString &second) -{ -#if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) - return QString::compare(first, second, Qt::CaseSensitive) == 0; -#else - return QString::compare(first, second, Qt::CaseInsensitive) == 0; -#endif -} - bool misc::isUrl(const QString &s) { const QString scheme = QUrl(s).scheme(); @@ -806,15 +422,6 @@ bool misc::isUrl(const QString &s) return is_url.exactMatch(scheme); } -QString misc::fileName(QString file_path) -{ - file_path.replace("\\", "/"); - const int slash_index = file_path.lastIndexOf('/'); - if (slash_index == -1) - return file_path; - return file_path.mid(slash_index+1); -} - QString misc::parseHtmlLinks(const QString &raw_text) { QString result = raw_text; diff --git a/src/misc.h b/src/misc.h index c88c494da..82b98be0b 100644 --- a/src/misc.h +++ b/src/misc.h @@ -78,70 +78,28 @@ public: return QString(out); } - static inline QString toDisplayPath(const QString& path) { -#if defined(Q_WS_WIN) || defined(Q_OS_OS2) - QString ret = path; - return ret.replace("/", "\\"); -#else - return path; -#endif - } - - static inline QString file_extension(const QString &filename) { - QString extension; - int point_index = filename.lastIndexOf("."); - if (point_index >= 0) { - extension = filename.mid(point_index+1); - } - return extension; - } - #ifndef DISABLE_GUI static void shutdownComputer(bool sleep=false); #endif static QString parseHtmlLinks(const QString &raw_text); - static quint64 computePathSize(QString path); - - static QString fixFileNames(QString path); - - static QString updateLabelInSavePath(QString defaultSavePath, QString save_path, const QString &old_label, const QString &new_label); - - static bool sameFiles(const QString &path1, const QString &path2); static bool isUrl(const QString &s); - static QString toValidFileSystemName(QString filename); - static bool isValidFileSystemName(const QString& filename); - - /* Ported from Qt4 to drop dependency on QtGui */ - static QString QDesktopServicesDataLocation(); - static QString QDesktopServicesCacheLocation(); - static QString QDesktopServicesDownloadLocation(); - /* End of Qt4 code */ #ifndef DISABLE_GUI // Get screen center static QPoint screenCenter(QWidget *win); #endif static int pythonVersion(); - static QString searchEngineLocation(); - static QString BTBackupLocation(); - static QString cacheLocation(); - static long long freeDiskSpaceOnPath(QString path); // 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 static QString friendlyUnit(qreal val); static bool isPreviewable(QString extension); - static QString branchPath(const QString& file_path, QString* removed = 0); - static bool sameFileNames(const QString& first, const QString& second); - static QString fileName(QString file_path); static QString magnetUriToName(QString magnet_uri); static QString magnetUriToHash(QString magnet_uri); static QString bcLinkToMagnet(QString bc_link); - // Replace ~ in path - static QString expandPath(QString path); // Take a number of seconds and return an user-friendly // time duration like "1d 2h 10m". static QString userFriendlyDuration(qlonglong seconds); @@ -152,8 +110,6 @@ public: static QList intListfromStringList(const QStringList &l); static QList boolListfromStringList(const QStringList &l); - static bool isValidTorrentFile(const QString &path); - #if LIBTORRENT_VERSION_MINOR < 16 static QString toQString(const boost::posix_time::ptime& boostDate); #else diff --git a/src/preferences/options_imp.cpp b/src/preferences/options_imp.cpp index f9c41778d..e53151122 100644 --- a/src/preferences/options_imp.cpp +++ b/src/preferences/options_imp.cpp @@ -45,7 +45,7 @@ #include "options_imp.h" #include "preferences.h" -#include "misc.h" +#include "fs_utils.h" #include "advancedsettings.h" #include "scannedfoldersmodel.h" #include "qinisettings.h" @@ -852,11 +852,11 @@ QString options_imp::getSavePath() const { #endif textSavePath->setText(save_path); } - return misc::expandPath(textSavePath->text()); + return fsutils::expandPath(textSavePath->text()); } QString options_imp::getTempPath() const { - return misc::expandPath(textTempPath->text()); + return fsutils::expandPath(textTempPath->text()); } bool options_imp::isTempPathEnabled() const { @@ -1018,7 +1018,7 @@ void options_imp::setLocale(const QString &localeStr) { QString options_imp::getExportDir() const { if (checkExportDir->isChecked()) - return misc::expandPath(textExportDir->text()); + return fsutils::expandPath(textExportDir->text()); return QString(); } @@ -1076,7 +1076,7 @@ void options_imp::handleScanFolderViewSelectionChanged() { } void options_imp::on_browseExportDirButton_clicked() { - const QString export_path = misc::expandPath(textExportDir->text()); + const QString export_path = fsutils::expandPath(textExportDir->text()); QDir exportDir(export_path); QString dir; if (!export_path.isEmpty() && exportDir.exists()) { @@ -1093,7 +1093,7 @@ void options_imp::on_browseExportDirButton_clicked() { } void options_imp::on_browseFilterButton_clicked() { - const QString filter_path = misc::expandPath(textFilterPath->text()); + const QString filter_path = fsutils::expandPath(textFilterPath->text()); QDir filterDir(filter_path); QString ipfilter; if (!filter_path.isEmpty() && filterDir.exists()) { @@ -1111,7 +1111,7 @@ void options_imp::on_browseFilterButton_clicked() { // Display dialog to choose save dir void options_imp::on_browseSaveDirButton_clicked() { - const QString save_path = misc::expandPath(textSavePath->text()); + const QString save_path = fsutils::expandPath(textSavePath->text()); QDir saveDir(save_path); QString dir; if (!save_path.isEmpty() && saveDir.exists()) { @@ -1128,7 +1128,7 @@ void options_imp::on_browseSaveDirButton_clicked() { } void options_imp::on_browseTempDirButton_clicked() { - const QString temp_path = misc::expandPath(textTempPath->text()); + const QString temp_path = fsutils::expandPath(textTempPath->text()); QDir tempDir(temp_path); QString dir; if (!temp_path.isEmpty() && tempDir.exists()) { diff --git a/src/preferences/preferences.h b/src/preferences/preferences.h index cd14e57a0..584314927 100644 --- a/src/preferences/preferences.h +++ b/src/preferences/preferences.h @@ -46,6 +46,7 @@ #endif #include "misc.h" +#include "fs_utils.h" #include "qinisettings.h" #define QBT_REALM "Web UI Access" @@ -185,7 +186,7 @@ public: QString save_path = value(QString::fromUtf8("Preferences/Downloads/SavePath")).toString(); if (!save_path.isEmpty()) return save_path; - return misc::QDesktopServicesDownloadLocation(); + return fsutils::QDesktopServicesDownloadLocation(); } void setSavePath(const QString &save_path) { diff --git a/src/programupdater.cpp b/src/programupdater.cpp index 5023a26bd..ce3f59895 100644 --- a/src/programupdater.cpp +++ b/src/programupdater.cpp @@ -36,7 +36,7 @@ #include #include "programupdater.h" -#include "misc.h" +#include "fs_utils.h" #include "preferences.h" #ifdef Q_WS_MAC @@ -119,7 +119,7 @@ void ProgramUpdater::rssDownloadFinished(QNetworkReply *reply) } else if (xml.isEndElement()) { if (in_item && xml.name() == "title") { in_title = false; - const QString ext = misc::file_extension(item_title).toUpper(); + const QString ext = fsutils::fileExtension(item_title).toUpper(); qDebug("Found an update with file extension: %s", qPrintable(ext)); if (ext == FILE_EXT) { qDebug("The last update available is %s", qPrintable(item_title)); diff --git a/src/properties/propertieswidget.cpp b/src/properties/propertieswidget.cpp index 390eeb98f..96478791e 100644 --- a/src/properties/propertieswidget.cpp +++ b/src/properties/propertieswidget.cpp @@ -57,6 +57,7 @@ #include "proptabbar.h" #include "iconprovider.h" #include "lineedit.h" +#include "fs_utils.h" using namespace libtorrent; @@ -511,7 +512,7 @@ void PropertiesWidget::renameSelectedFile() { tr("New name:"), QLineEdit::Normal, index.data().toString(), &ok); if (ok && !new_name_last.isEmpty()) { - if (!misc::isValidFileSystemName(new_name_last)) { + if (!fsutils::isValidFileSystemName(new_name_last)) { QMessageBox::warning(this, tr("The file could not be renamed"), tr("This file name contains forbidden characters, please choose a different one."), QMessageBox::Ok); @@ -680,9 +681,9 @@ void PropertiesWidget::on_changeSavePathButton_clicked() { QString save_path_dir = new_path.replace("\\", "/"); QString new_file_name; if (h.has_metadata() && h.num_files() == 1) { - save_path_dir = misc::branchPath(save_path_dir, &new_file_name); // Skip file name + save_path_dir = fsutils::branchPath(save_path_dir, &new_file_name); // Skip file name } - QDir savePath(misc::expandPath(save_path_dir)); + QDir savePath(fsutils::expandPath(save_path_dir)); // Actually move storage if (!QBtSession::instance()->useTemporaryFolder() || h.is_seed()) { if (!savePath.exists()) savePath.mkpath(savePath.absolutePath()); diff --git a/src/qtlibtorrent/qbtsession.cpp b/src/qtlibtorrent/qbtsession.cpp index eb65b4670..e96245a66 100644 --- a/src/qtlibtorrent/qbtsession.cpp +++ b/src/qtlibtorrent/qbtsession.cpp @@ -42,6 +42,7 @@ #include "torrentspeedmonitor.h" #include "qbtsession.h" #include "misc.h" +#include "fs_utils.h" #include "downloadthread.h" #include "filterparserthread.h" #include "preferences.h" @@ -826,13 +827,13 @@ void QBtSession::deleteTorrent(const QString &hash, bool delete_local_files) { foreach (const QString &uneeded_file, uneeded_files) { qDebug("Removing uneeded file: %s", qPrintable(uneeded_file)); QFile::remove(uneeded_file); - const QString parent_folder = misc::branchPath(uneeded_file); + const QString parent_folder = fsutils::branchPath(uneeded_file); qDebug("Attempt to remove parent folder (if empty): %s", qPrintable(parent_folder)); QDir().rmpath(parent_folder); } } // Remove it from torrent backup directory - QDir torrentBackup(misc::BTBackupLocation()); + QDir torrentBackup(fsutils::BTBackupLocation()); QStringList filters; filters << hash+".*"; const QStringList files = torrentBackup.entryList(filters, QDir::Files, QDir::Unsorted); @@ -900,7 +901,7 @@ void QBtSession::resumeTorrent(const QString &hash) { } bool QBtSession::loadFastResumeData(const QString &hash, std::vector &buf) { - const QString fastresume_path = QDir(misc::BTBackupLocation()).absoluteFilePath(hash+QString(".fastresume")); + const QString fastresume_path = QDir(fsutils::BTBackupLocation()).absoluteFilePath(hash+QString(".fastresume")); qDebug("Trying to load fastresume data: %s", qPrintable(fastresume_path)); QFile fastresume_file(fastresume_path); if (!fastresume_file.open(QIODevice::ReadOnly)) return false; @@ -931,7 +932,7 @@ QTorrentHandle QBtSession::addMagnetUri(QString magnet_uri, bool resumed) { addConsoleMessage(tr("'%1' is not a valid magnet URI.").arg(magnet_uri)); return h; } - const QDir torrentBackup(misc::BTBackupLocation()); + const QDir torrentBackup(fsutils::BTBackupLocation()); if (resumed) { // Load metadata const QString torrent_path = torrentBackup.absoluteFilePath(hash+".torrent"); @@ -1011,7 +1012,7 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr Preferences pref; // Check if BT_backup directory exists - const QDir torrentBackup(misc::BTBackupLocation()); + const QDir torrentBackup(fsutils::BTBackupLocation()); if (!torrentBackup.exists()) return h; // Fix the input path if necessary @@ -1218,9 +1219,9 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr addConsoleMessage(tr("'%1' added to download list.", "'/home/y/xxx.torrent' was added to download list.").arg(from_url)); }else{ if (fastResume) - addConsoleMessage(tr("'%1' resumed. (fast resume)", "'/home/y/xxx.torrent' was resumed. (fast resume)").arg(misc::toDisplayPath(path))); + addConsoleMessage(tr("'%1' resumed. (fast resume)", "'/home/y/xxx.torrent' was resumed. (fast resume)").arg(fsutils::toDisplayPath(path))); else - addConsoleMessage(tr("'%1' added to download list.", "'/home/y/xxx.torrent' was added to download list.").arg(misc::toDisplayPath(path))); + addConsoleMessage(tr("'%1' added to download list.", "'/home/y/xxx.torrent' was added to download list.").arg(fsutils::toDisplayPath(path))); } // Send torrent addition signal @@ -1230,11 +1231,11 @@ QTorrentHandle QBtSession::addTorrent(QString path, bool fromScanDir, QString fr void QBtSession::exportTorrentFile(const QTorrentHandle &h) { Q_ASSERT(torrentExport); - QString torrent_path = QDir(misc::BTBackupLocation()).absoluteFilePath(h.hash()+".torrent"); + QString torrent_path = QDir(fsutils::BTBackupLocation()).absoluteFilePath(h.hash()+".torrent"); QDir exportPath(Preferences().getExportDir()); if (exportPath.exists() || exportPath.mkpath(exportPath.absolutePath())) { QString new_torrent_path = exportPath.absoluteFilePath(h.name()+".torrent"); - if (QFile::exists(new_torrent_path) && misc::sameFiles(torrent_path, new_torrent_path)) { + if (QFile::exists(new_torrent_path) && fsutils::sameFiles(torrent_path, new_torrent_path)) { // Append hash to torrent name to make it unique new_torrent_path = exportPath.absoluteFilePath(h.name()+"-"+h.hash()+".torrent"); } @@ -1399,7 +1400,7 @@ void QBtSession::exportTorrentFiles(QString path) { return; } } - QDir torrentBackup(misc::BTBackupLocation()); + QDir torrentBackup(fsutils::BTBackupLocation()); std::vector handles = s->get_torrents(); std::vector::iterator itr; for (itr=handles.begin(); itr != handles.end(); itr++) { @@ -1412,7 +1413,7 @@ void QBtSession::exportTorrentFiles(QString path) { if (QFile::exists(src_path)) { QString dst_path = exportDir.absoluteFilePath(h.name()+".torrent"); if (QFile::exists(dst_path)) { - if (!misc::sameFiles(src_path, dst_path)) { + if (!fsutils::sameFiles(src_path, dst_path)) { dst_path = exportDir.absoluteFilePath(h.name()+"-"+h.hash()+".torrent"); } else { qDebug("Torrent Export: Destination file exists, skipping..."); @@ -1508,7 +1509,7 @@ void QBtSession::enableLSD(bool b) { } void QBtSession::loadSessionState() { - const QString state_path = misc::cacheLocation()+QDir::separator()+QString::fromUtf8("ses_state"); + const QString state_path = fsutils::cacheLocation()+QDir::separator()+QString::fromUtf8("ses_state"); if (!QFile::exists(state_path)) return; if (QFile(state_path).size() == 0) { // Remove empty invalid state file @@ -1537,7 +1538,7 @@ void QBtSession::loadSessionState() { void QBtSession::saveSessionState() { qDebug("Saving session state to disk..."); - const QString state_path = misc::cacheLocation()+QDir::separator()+QString::fromUtf8("ses_state"); + const QString state_path = fsutils::cacheLocation()+QDir::separator()+QString::fromUtf8("ses_state"); entry session_state; s->save_state(session_state); vector out; @@ -1674,7 +1675,7 @@ void QBtSession::saveFastResumeData() { // Saving fast resume data was successful --num_resume_data; if (!rd->resume_data) continue; - QDir torrentBackup(misc::BTBackupLocation()); + QDir torrentBackup(fsutils::BTBackupLocation()); const QTorrentHandle h(rd->handle); if (!h.is_valid()) continue; try { @@ -1731,7 +1732,7 @@ bool QBtSession::isFilePreviewPossible(const QString &hash) const { } const unsigned int nbFiles = h.num_files(); for (unsigned int i=0; i(a.get())) { - const QDir torrentBackup(misc::BTBackupLocation()); + const QDir torrentBackup(fsutils::BTBackupLocation()); const QTorrentHandle h(p->handle); if (h.is_valid() && p->resume_data) { const QString filepath = torrentBackup.absoluteFilePath(h.hash()+".fastresume"); @@ -2356,7 +2357,7 @@ void QBtSession::readAlerts() { if (h.is_valid()) { qDebug("Received metadata for %s", qPrintable(h.hash())); // Save metadata - const QDir torrentBackup(misc::BTBackupLocation()); + const QDir torrentBackup(fsutils::BTBackupLocation()); if (!QFile::exists(torrentBackup.absoluteFilePath(h.hash()+QString(".torrent")))) h.save_torrent_file(torrentBackup.absoluteFilePath(h.hash()+QString(".torrent"))); // Copy the torrent file to the export folder @@ -2578,7 +2579,7 @@ QString QBtSession::getSavePath(const QString &hash, bool fromScanDir, QString f qDebug("appendLabelToSavePath is true"); const QString label = TorrentTempData::getLabel(hash); if (!label.isEmpty()) { - savePath = misc::updateLabelInSavePath(defaultSavePath, savePath, "", label); + savePath = fsutils::updateLabelInSavePath(defaultSavePath, savePath, "", label); } } qDebug("getSavePath, got save_path from temp data: %s", qPrintable(savePath)); @@ -2596,14 +2597,14 @@ QString QBtSession::getSavePath(const QString &hash, bool fromScanDir, QString f const QString label = TorrentPersistentData::getLabel(hash); if (!label.isEmpty()) { qDebug("Torrent label is %s", qPrintable(label)); - savePath = misc::updateLabelInSavePath(defaultSavePath, savePath, "", label); + savePath = fsutils::updateLabelInSavePath(defaultSavePath, savePath, "", label); } } qDebug("getSavePath, got save_path from persistent data: %s", qPrintable(savePath)); } // Clean path savePath.replace("\\", "/"); - savePath = misc::expandPath(savePath); + savePath = fsutils::expandPath(savePath); if (!savePath.endsWith("/")) savePath += "/"; return savePath; @@ -2694,7 +2695,7 @@ void QBtSession::applyEncryptionSettings(pe_settings se) { // backup directory void QBtSession::startUpTorrents() { qDebug("Resuming unfinished torrents"); - const QDir torrentBackup(misc::BTBackupLocation()); + const QDir torrentBackup(fsutils::BTBackupLocation()); const QStringList known_torrents = TorrentPersistentData::knownTorrents(); // Safety measure because some people reported torrent loss since diff --git a/src/qtlibtorrent/qtorrenthandle.cpp b/src/qtlibtorrent/qtorrenthandle.cpp index ed5786a8e..82368e49f 100644 --- a/src/qtlibtorrent/qtorrenthandle.cpp +++ b/src/qtlibtorrent/qtorrenthandle.cpp @@ -34,6 +34,7 @@ #include #include #include +#include "fs_utils.h" #include "misc.h" #include "preferences.h" #include "qtorrenthandle.h" @@ -189,7 +190,7 @@ bool QTorrentHandle::first_last_piece_first() const { #else QString path = misc::toQStringU(t.file_at(index).path.string()); #endif - const QString ext = misc::file_extension(path); + const QString ext = fsutils::fileExtension(path); if (misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) break; } @@ -316,7 +317,7 @@ int QTorrentHandle::num_files() const { QString QTorrentHandle::filename_at(unsigned int index) const { Q_ASSERT(index < (unsigned int)torrent_handle::get_torrent_info().num_files()); #if LIBTORRENT_VERSION_MINOR > 15 - return misc::fileName(filepath_at(index)); + return fsutils::fileName(filepath_at(index)); #else return misc::toQStringU(torrent_handle::get_torrent_info().file_at(index).path.leaf()); #endif @@ -708,7 +709,7 @@ void QTorrentHandle::prioritize_files(const vector &files) const { continue; } QString old_name = filename_at(i); - QString parent_path = misc::branchPath(old_path); + QString parent_path = fsutils::branchPath(old_path); if (parent_path.isEmpty() || QDir(parent_path).dirName() != ".unwanted") { QString unwanted_abspath = QDir::cleanPath(save_path()+"/"+parent_path+"/.unwanted"); qDebug() << "Unwanted path is" << unwanted_abspath; @@ -734,10 +735,10 @@ void QTorrentHandle::prioritize_files(const vector &files) const { // Move wanted files back to their original folder qDebug() << Q_FUNC_INFO << "Moving wanted files back from .unwanted folder"; if (files[i] > 0) { - QString parent_relpath = misc::branchPath(filepath_at(i)); + QString parent_relpath = fsutils::branchPath(filepath_at(i)); if (QDir(parent_relpath).dirName() == ".unwanted") { QString old_name = filename_at(i); - QString new_relpath = misc::branchPath(parent_relpath); + QString new_relpath = fsutils::branchPath(parent_relpath); if (new_relpath.isEmpty()) rename_file(i, old_name); else @@ -778,7 +779,7 @@ void QTorrentHandle::prioritize_first_last_piece(bool b) const { const uint nbfiles = num_files(); for (uint index = 0; index < nbfiles; ++index) { const QString path = filepath_at(index); - const QString ext = misc::file_extension(path); + const QString ext = fsutils::fileExtension(path); if (misc::isPreviewable(ext) && torrent_handle::file_priority(index) > 0) { qDebug() << "File" << path << "is previewable, toggle downloading of first/last pieces first"; prioritize_first_last_piece(index, b); diff --git a/src/searchengine/engineselectdlg.cpp b/src/searchengine/engineselectdlg.cpp index f105dcf86..c19662c02 100644 --- a/src/searchengine/engineselectdlg.cpp +++ b/src/searchengine/engineselectdlg.cpp @@ -30,6 +30,7 @@ #include "engineselectdlg.h" #include "downloadthread.h" +#include "fs_utils.h" #include "misc.h" #include "ico.h" #include "searchengine.h" @@ -86,7 +87,7 @@ void engineSelectDlg::dropEvent(QDropEvent *event) { if (file.endsWith(".py", Qt::CaseInsensitive)) { if (file.startsWith("file:", Qt::CaseInsensitive)) file = QUrl(file).toLocalFile(); - QString plugin_name = misc::fileName(file); + QString plugin_name = fsutils::fileName(file); plugin_name.chop(3); // Remove extension installPlugin(file, plugin_name); } @@ -157,7 +158,7 @@ void engineSelectDlg::on_actionUninstall_triggered() { }else { // Proceed with uninstall // remove it from hard drive - QDir enginesFolder(misc::searchEngineLocation()+QDir::separator()+"engines"); + QDir enginesFolder(fsutils::searchEngineLocation()+QDir::separator()+"engines"); QStringList filters; filters << id+".*"; QStringList files = enginesFolder.entryList(filters, QDir::Files, QDir::Unsorted); @@ -223,7 +224,7 @@ QTreeWidgetItem* engineSelectDlg::findItemWithID(QString id) { } bool engineSelectDlg::isUpdateNeeded(QString plugin_name, qreal new_version) const { - qreal old_version = SearchEngine::getPluginVersion(misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py"); + qreal old_version = SearchEngine::getPluginVersion(fsutils::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py"); qDebug("IsUpdate needed? tobeinstalled: %.2f, alreadyinstalled: %.2f", new_version, old_version); return (new_version > old_version); } @@ -238,7 +239,7 @@ void engineSelectDlg::installPlugin(QString path, QString plugin_name) { return; } // Process with install - QString dest_path = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py"; + QString dest_path = fsutils::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+plugin_name+".py"; bool update = false; if (QFile::exists(dest_path)) { // Backup in case install fails @@ -303,12 +304,12 @@ void engineSelectDlg::addNewEngine(QString engine_name) { setRowColor(pluginsTree->indexOfTopLevelItem(item), "red"); } // Handle icon - QString iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".png"; + QString iconPath = fsutils::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".png"; if (QFile::exists(iconPath)) { // Good, we already have the icon item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); } else { - iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".ico"; + iconPath = fsutils::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+engine->getName()+".ico"; if (QFile::exists(iconPath)) { // ICO support item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); } else { @@ -410,9 +411,9 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) { QFile icon(filePath); icon.open(QIODevice::ReadOnly); if (ICOHandler::canRead(&icon)) - iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".ico"; + iconPath = fsutils::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".ico"; else - iconPath = misc::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".png"; + iconPath = fsutils::searchEngineLocation()+QDir::separator()+"engines"+QDir::separator()+id+".png"; QFile::copy(filePath, iconPath); item->setData(ENGINE_NAME, Qt::DecorationRole, QVariant(QIcon(iconPath))); } @@ -429,7 +430,7 @@ void engineSelectDlg::processDownloadedFile(QString url, QString filePath) { return; } if (url.endsWith(".py", Qt::CaseInsensitive)) { - QString plugin_name = misc::fileName(url); + QString plugin_name = fsutils::fileName(url); plugin_name.chop(3); // Remove extension installPlugin(filePath, plugin_name); QFile::remove(filePath); diff --git a/src/searchengine/searchengine.cpp b/src/searchengine/searchengine.cpp index 39954a997..0ffb0d96c 100644 --- a/src/searchengine/searchengine.cpp +++ b/src/searchengine/searchengine.cpp @@ -51,6 +51,7 @@ #include "searchengine.h" #include "qbtsession.h" #include "downloadthread.h" +#include "fs_utils.h" #include "misc.h" #include "preferences.h" #include "searchlistdelegate.h" @@ -341,7 +342,7 @@ void SearchEngine::on_search_button_clicked() { // Getting checked search engines QStringList params; search_stopped = false; - params << misc::searchEngineLocation()+QDir::separator()+"nova2.py"; + params << fsutils::searchEngineLocation()+QDir::separator()+"nova2.py"; params << supported_engines->enginesEnabled().join(","); qDebug("Search with category: %s", qPrintable(selectedCategory())); params << selectedCategory(); @@ -416,7 +417,7 @@ void SearchEngine::downloadTorrent(QString engine_url, QString torrent_url) { connect(downloadProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(downloadFinished(int,QProcess::ExitStatus))); downloaders << downloadProcess; QStringList params; - params << misc::searchEngineLocation()+QDir::separator()+"nova2dl.py"; + params << fsutils::searchEngineLocation()+QDir::separator()+"nova2dl.py"; params << engine_url; params << torrent_url; // Launch search @@ -470,7 +471,7 @@ void SearchEngine::downloadFinished(int exitcode, QProcess::ExitStatus) { void SearchEngine::updateNova() { qDebug("Updating nova"); // create nova directory if necessary - QDir search_dir(misc::searchEngineLocation()); + QDir search_dir(fsutils::searchEngineLocation()); QString nova_folder = misc::pythonVersion() >= 3 ? "nova3" : "nova"; QFile package_file(search_dir.absoluteFilePath("__init__.py")); package_file.open(QIODevice::WriteOnly | QIODevice::Text); @@ -533,7 +534,7 @@ void SearchEngine::updateNova() { } QFile::copy(":/"+nova_folder+"/sgmllib3.py", filePath); } - QDir destDir(QDir(misc::searchEngineLocation()).absoluteFilePath("engines")); + QDir destDir(QDir(fsutils::searchEngineLocation()).absoluteFilePath("engines")); QDir shipped_subDir(":/"+nova_folder+"/engines/"); QStringList files = shipped_subDir.entryList(); foreach (const QString &file, files) { diff --git a/src/searchengine/supportedengines.h b/src/searchengine/supportedengines.h index 78f5bf39d..b3131b4d7 100644 --- a/src/searchengine/supportedengines.h +++ b/src/searchengine/supportedengines.h @@ -39,8 +39,9 @@ #include #include #include +#include -#include "misc.h" +#include "fs_utils.h" #include "qinisettings.h" class SearchCategories: public QObject, public QHash { @@ -143,7 +144,7 @@ public slots: QProcess nova; nova.setEnvironment(QProcess::systemEnvironment()); QStringList params; - params << misc::searchEngineLocation()+QDir::separator()+"nova2.py"; + params << fsutils::searchEngineLocation()+QDir::separator()+"nova2.py"; params << "--capabilities"; nova.start("python", params, QIODevice::ReadOnly); nova.waitForStarted(); @@ -151,13 +152,13 @@ public slots: QString capabilities = QString(nova.readAll()); QDomDocument xml_doc; if (!xml_doc.setContent(capabilities)) { - std::cerr << "Could not parse Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl; - std::cerr << "Error: " << nova.readAllStandardError().constData() << std::endl; + qWarning() << "Could not parse Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data(); + qWarning() << "Error: " << nova.readAllStandardError().constData(); return; } QDomElement root = xml_doc.documentElement(); if (root.tagName() != "capabilities") { - std::cout << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data() << std::endl; + qWarning() << "Invalid XML file for Nova search engine capabilities, msg: " << capabilities.toLocal8Bit().data(); return; } for (QDomNode engine_node = root.firstChild(); !engine_node.isNull(); engine_node = engine_node.nextSibling()) { diff --git a/src/src.pro b/src/src.pro index 6a08024ef..879f3841d 100644 --- a/src/src.pro +++ b/src/src.pro @@ -95,6 +95,7 @@ include (preferences/preferences.pri) } HEADERS += misc.h \ + fs_utils.h \ downloadthread.h \ stacktrace.h \ torrentpersistentdata.h \ @@ -109,6 +110,7 @@ SOURCES += main.cpp \ downloadthread.cpp \ scannedfoldersmodel.cpp \ misc.cpp \ + fs_utils.cpp \ smtp.cpp \ dnsupdater.cpp diff --git a/src/torrentcontentmodelitem.cpp b/src/torrentcontentmodelitem.cpp index 1b88f6867..934320aa1 100644 --- a/src/torrentcontentmodelitem.cpp +++ b/src/torrentcontentmodelitem.cpp @@ -29,6 +29,7 @@ */ #include "misc.h" +#include "fs_utils.h" #include "torrentcontentmodelitem.h" #include @@ -41,7 +42,7 @@ TorrentContentModelItem::TorrentContentModelItem(const libtorrent::torrent_info Q_ASSERT(parent); #if LIBTORRENT_VERSION_MINOR >= 16 - QString name = misc::fileName(misc::toQStringU(t.files().file_path(f))); + QString name = fsutils::fileName(misc::toQStringU(t.files().file_path(f))); #else Q_UNUSED(t); QString name = misc::toQStringU(f.path.filename()); diff --git a/src/torrentcreator/torrentcreatordlg.cpp b/src/torrentcreator/torrentcreatordlg.cpp index 8f92ed901..f5d642bb5 100644 --- a/src/torrentcreator/torrentcreatordlg.cpp +++ b/src/torrentcreator/torrentcreatordlg.cpp @@ -34,6 +34,7 @@ #include "torrentpersistentdata.h" #include "torrentcreatordlg.h" +#include "fs_utils.h" #include "misc.h" #include "qinisettings.h" #include "torrentcreatorthread.h" @@ -88,7 +89,7 @@ void TorrentCreatorDlg::on_addFile_button_clicked() { QString last_path = settings.value("CreateTorrent/last_add_path", QDir::homePath()).toString(); QString file = QFileDialog::getOpenFileName(this, tr("Select a file to add to the torrent"), last_path); if (!file.isEmpty()) { - settings.setValue("CreateTorrent/last_add_path", misc::branchPath(file)); + settings.setValue("CreateTorrent/last_add_path", fsutils::branchPath(file)); #if defined(Q_WS_WIN) || defined(Q_OS_OS2) file.replace("/", "\\"); #endif @@ -121,7 +122,7 @@ void TorrentCreatorDlg::on_createButton_clicked() { QString destination = QFileDialog::getSaveFileName(this, tr("Select destination torrent file"), last_path, tr("Torrent Files")+QString::fromUtf8(" (*.torrent)")); if (!destination.isEmpty()) { - settings.setValue("CreateTorrent/last_save_path", misc::branchPath(destination)); + settings.setValue("CreateTorrent/last_save_path", fsutils::branchPath(destination)); if (!destination.toUpper().endsWith(".TORRENT")) destination += QString::fromUtf8(".torrent"); } else { @@ -221,7 +222,7 @@ void TorrentCreatorDlg::on_checkAutoPieceSize_clicked(bool checked) void TorrentCreatorDlg::updateOptimalPieceSize() { - quint64 torrent_size = misc::computePathSize(textInputPath->text()); + quint64 torrent_size = fsutils::computePathSize(textInputPath->text()); qDebug("Torrent size is %lld", torrent_size); if (torrent_size == 0) return; int i = 0; diff --git a/src/torrentcreator/torrentcreatorthread.cpp b/src/torrentcreator/torrentcreatorthread.cpp index dbd9d7a98..85e378483 100644 --- a/src/torrentcreator/torrentcreatorthread.cpp +++ b/src/torrentcreator/torrentcreatorthread.cpp @@ -40,7 +40,7 @@ #include #include "torrentcreatorthread.h" -#include "misc.h" +#include "fs_utils.h" #if LIBTORRENT_VERSION_MINOR < 16 #include @@ -116,7 +116,7 @@ void TorrentCreatorThread::run() { } if (abort) return; // calculate the hash for all pieces - const QString parent_path = misc::branchPath(input_path); + const QString parent_path = fsutils::branchPath(input_path); set_piece_hashes(t, parent_path.toUtf8().constData(), boost::bind(&sendProgressUpdateSignal, _1, t.num_pieces(), this)); // Set qBittorrent as creator and add user comment to // torrent_info structure diff --git a/src/torrentimportdlg.cpp b/src/torrentimportdlg.cpp index 1c6aca906..3bfe20eae 100644 --- a/src/torrentimportdlg.cpp +++ b/src/torrentimportdlg.cpp @@ -38,6 +38,7 @@ #include "qbtsession.h" #include "torrentpersistentdata.h" #include "iconprovider.h" +#include "fs_utils.h" using namespace libtorrent; @@ -79,12 +80,12 @@ void TorrentImportDlg::on_browseContentBtn_clicked() if (t->num_files() == 1) { // Single file torrent #if LIBTORRENT_VERSION_MINOR > 15 - const QString file_name = misc::fileName(misc::toQStringU(t->file_at(0).path)); + const QString file_name = fsutils::fileName(misc::toQStringU(t->file_at(0).path)); #else const QString file_name = misc::toQStringU(t->file_at(0).path.filename()); #endif qDebug("Torrent has only one file: %s", qPrintable(file_name)); - QString extension = misc::file_extension(file_name); + QString extension = fsutils::fileExtension(file_name); qDebug("File extension is : %s", qPrintable(extension)); QString filter; if (!extension.isEmpty()) { diff --git a/src/transferlistfilterswidget.h b/src/transferlistfilterswidget.h index 79e542959..7f2f6a5b6 100644 --- a/src/transferlistfilterswidget.h +++ b/src/transferlistfilterswidget.h @@ -49,6 +49,7 @@ #include "qinisettings.h" #include "torrentmodel.h" #include "iconprovider.h" +#include "fs_utils.h" class LabelFiltersList: public QListWidget { Q_OBJECT @@ -302,7 +303,7 @@ protected slots: } void addLabel(QString label) { - label = misc::toValidFileSystemName(label.trimmed()); + label = fsutils::toValidFileSystemName(label.trimmed()); if (label.isEmpty() || customLabels.contains(label)) return; QListWidgetItem *newLabel = new QListWidgetItem(); newLabel->setText(label + " (0)"); @@ -349,7 +350,7 @@ protected slots: invalid = false; label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, label, &ok); if (ok && !label.isEmpty()) { - if (misc::isValidFileSystemName(label)) { + if (fsutils::isValidFileSystemName(label)) { addLabel(label); } else { QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name.")); diff --git a/src/transferlistwidget.cpp b/src/transferlistwidget.cpp index 90cae38d5..a14e79b69 100644 --- a/src/transferlistwidget.cpp +++ b/src/transferlistwidget.cpp @@ -60,6 +60,7 @@ #include "propertieswidget.h" #include "qinisettings.h" #include "iconprovider.h" +#include "fs_utils.h" using namespace libtorrent; @@ -230,7 +231,7 @@ void TransferListWidget::setSelectedTorrentsLocation() { if (!dir.isNull()) { qDebug("New path is %s", qPrintable(dir)); // Check if savePath exists - QDir savePath(misc::expandPath(dir)); + QDir savePath(fsutils::expandPath(dir)); qDebug("New path after clean up is %s", qPrintable(savePath.absolutePath())); foreach (const QString & hash, hashes) { // Actually move storage @@ -587,7 +588,7 @@ void TransferListWidget::askNewLabelForSelection() { invalid = false; const QString label = QInputDialog::getText(this, tr("New Label"), tr("Label:"), QLineEdit::Normal, "", &ok); if (ok && !label.isEmpty()) { - if (misc::isValidFileSystemName(label)) { + if (fsutils::isValidFileSystemName(label)) { setSelectionLabel(label); } else { QMessageBox::warning(this, tr("Invalid label name"), tr("Please don't use any special characters in the label name."));