From f9f31c57dcea9e3173d25e0c85e028891ad57fca Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 9 Feb 2020 02:29:06 -0500 Subject: added support for FilterWidget regexes --- src/mainwindow.cpp | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 8f2dd250..0efb043b 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2075,6 +2075,8 @@ void MainWindow::readSettings() s.geometry().restoreVisibility(ui->menuBar); s.geometry().restoreVisibility(ui->statusBar); + FilterWidget::setOptions(s.interface().filterOptions()); + { // special case in case someone puts 0 in the INI auto v = s.widgets().index(ui->executablesListBox); @@ -2159,6 +2161,8 @@ void MainWindow::storeSettings() m_Filters->saveState(s); m_DataTab->saveState(s); + + s.interface().setFilterOptions(FilterWidget::options()); } QWidget* MainWindow::qtWidget() -- cgit v1.3.1 From 3db95eb4043b8da20e99dd7476bc82468a4609fb Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 9 Feb 2020 04:14:46 -0500 Subject: customizable columns for mod and plugin lists --- src/mainwindow.cpp | 32 -------------------------------- src/mainwindow.h | 3 --- src/modlist.cpp | 10 +--------- src/modlist.h | 6 ------ src/modlistview.cpp | 2 ++ src/organizercore.cpp | 2 -- src/pluginlistview.cpp | 2 ++ 7 files changed, 5 insertions(+), 52 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 0efb043b..3e03c52d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -5818,38 +5818,6 @@ void MainWindow::extractBSATriggered() } } - -void MainWindow::displayColumnSelection(const QPoint &pos) -{ - QMenu menu; - - // display a list of all headers as checkboxes - QAbstractItemModel *model = ui->modList->header()->model(); - for (int i = 1; i < model->columnCount(); ++i) { - QString columnName = model->headerData(i, Qt::Horizontal).toString(); - QCheckBox *checkBox = new QCheckBox(&menu); - checkBox->setText(columnName); - checkBox->setChecked(!ui->modList->header()->isSectionHidden(i)); - QWidgetAction *checkableAction = new QWidgetAction(&menu); - checkableAction->setDefaultWidget(checkBox); - menu.addAction(checkableAction); - } - menu.exec(pos); - - // view/hide columns depending on check-state - int i = 1; - for (const QAction *action : menu.actions()) { - const QWidgetAction *widgetAction = qobject_cast(action); - if (widgetAction != nullptr) { - const QCheckBox *checkBox = qobject_cast(widgetAction->defaultWidget()); - if (checkBox != nullptr) { - ui->modList->header()->setSectionHidden(i, !checkBox->isChecked()); - } - } - ++i; - } -} - void MainWindow::on_bsaList_customContextMenuRequested(const QPoint &pos) { m_ContextItem = ui->bsaList->itemAt(pos); diff --git a/src/mainwindow.h b/src/mainwindow.h index 1016c061..6530d8ad 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -153,9 +153,6 @@ public: ModInfo::Ptr previousModInList(); public slots: - - void displayColumnSelection(const QPoint &pos); - void modorder_changed(); void esplist_changed(); void refresher_progress(int percent); diff --git a/src/modlist.cpp b/src/modlist.cpp index 31eb8387..afc1b65f 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1434,15 +1434,7 @@ bool ModList::toggleSelection(QAbstractItemView *itemView) bool ModList::eventFilter(QObject *obj, QEvent *event) { - if (event->type() == QEvent::ContextMenu) { - QContextMenuEvent *contextEvent = static_cast(event); - QWidget *object = qobject_cast(obj); - if ((object != nullptr) && (contextEvent->reason() == QContextMenuEvent::Mouse)) { - emit requestColumnSelect(object->mapToGlobal(contextEvent->pos())); - - return true; - } - } else if ((event->type() == QEvent::KeyPress) && (m_Profile != nullptr)) { + if ((event->type() == QEvent::KeyPress) && (m_Profile != nullptr)) { QAbstractItemView *itemView = qobject_cast(obj); QKeyEvent *keyEvent = static_cast(event); diff --git a/src/modlist.h b/src/modlist.h index 9a44b761..7452b28b 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -201,12 +201,6 @@ signals: */ void resizeHeaders(); - /** - * @brief requestColumnSelect is emitted whenever the user requested a menu to select visible columns - * @param pos the position to display the menu at - */ - void requestColumnSelect(QPoint pos); - /** * @brief emitted to remove a file origin * @param name name of the orign to remove diff --git a/src/modlistview.cpp b/src/modlistview.cpp index fe2d3e57..c6dbc6ea 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -1,4 +1,5 @@ #include "modlistview.h" +#include #include #include #include @@ -39,6 +40,7 @@ ModListView::ModListView(QWidget *parent) , m_Scrollbar(new ViewMarkingScrollBar(this->model(), this)) { setVerticalScrollBar(m_Scrollbar); + MOBase::setCustomizableColumns(this); } void ModListView::dragEnterEvent(QDragEnterEvent *event) diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 04d78ca8..8124be1d 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -234,8 +234,6 @@ void OrganizerCore::setUserInterface(IUserInterface* ui) SLOT(removeMod_clicked())); connect(&m_ModList, SIGNAL(clearOverwrite()), w, SLOT(clearOverwrite())); - connect(&m_ModList, SIGNAL(requestColumnSelect(QPoint)), w, - SLOT(displayColumnSelection(QPoint))); connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), w, SLOT(fileMoved(QString, QString, QString))); connect(&m_ModList, SIGNAL(modorder_changed()), w, diff --git a/src/pluginlistview.cpp b/src/pluginlistview.cpp index 0fcf8183..4217971d 100644 --- a/src/pluginlistview.cpp +++ b/src/pluginlistview.cpp @@ -1,4 +1,5 @@ #include "pluginlistview.h" +#include #include #include #include @@ -40,6 +41,7 @@ PluginListView::PluginListView(QWidget *parent) , m_Scrollbar(new ViewMarkingScrollBar(this->model(), this)) { setVerticalScrollBar(m_Scrollbar); + MOBase::setCustomizableColumns(this); } void PluginListView::dragEnterEvent(QDragEnterEvent *event) -- cgit v1.3.1 From 763a5d6c08006c319ed92f4088a4d3c211f80cf6 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Thu, 13 Feb 2020 23:03:56 -0500 Subject: more instrumentation tighter mutexes, required thread-safe FileEntry --- src/directoryrefresher.cpp | 106 ++++++++++------ src/envfs.cpp | 2 + src/mainwindow.cpp | 6 +- src/shared/directoryentry.cpp | 282 +++++++++++++++++++++++------------------- src/shared/directoryentry.h | 18 +-- 5 files changed, 241 insertions(+), 173 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index bce3f65a..20d6a52b 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -160,12 +160,14 @@ void DirectoryRefresher::addModFilesToStructure( TimeThis tt("addModFilesToStructure()"); std::wstring directoryW = ToWString(QDir::toNativeSeparators(directory)); + DirectoryStats dummy; if (stealFiles.length() > 0) { stealModFilesIntoStructure( directoryStructure, modName, priority, directory, stealFiles); } else { - directoryStructure->addFromOrigin(ToWString(modName), directoryW, priority); + directoryStructure->addFromOrigin( + ToWString(modName), directoryW, priority, dummy); } } @@ -178,16 +180,20 @@ void DirectoryRefresher::addModToStructure(DirectoryEntry *directoryStructure { TimeThis tt("addModToStructure()"); + DirectoryStats dummy; + if (stealFiles.length() > 0) { stealModFilesIntoStructure( directoryStructure, modName, priority, directory, stealFiles); } else { std::wstring directoryW = ToWString(QDir::toNativeSeparators(directory)); - directoryStructure->addFromOrigin(ToWString(modName), directoryW, priority); + directoryStructure->addFromOrigin( + ToWString(modName), directoryW, priority, dummy); } if (Settings::instance().archiveParsing()) { - addModBSAToStructure(directoryStructure, modName, priority, directory, archives); + addModBSAToStructure( + directoryStructure, modName, priority, directory, archives); } } @@ -198,6 +204,7 @@ struct ModThread std::wstring path; int prio = -1; env::Directory* dir = nullptr; + DirectoryStats* stats = nullptr; std::condition_variable cv; std::mutex mutex; @@ -214,7 +221,8 @@ struct ModThread std::unique_lock lock(mutex); cv.wait(lock, [&]{ return ready; }); - ds->addFromOrigin(modName, path, prio); + SetThisThreadName(QString::fromStdWString(modName + L" refresher")); + ds->addFromOrigin(modName, path, prio, *stats); /*if (Settings::instance().archiveParsing()) { addModBSAToStructure( @@ -229,11 +237,39 @@ struct ModThread } }; +void dumpStats(std::vector& stats) +{ + static int run = 0; + static const std::string file("c:\\tmp\\data.csv"); + + if (run == 0) { + std::ofstream out(file, std::ios::out|std::ios::trunc); + out << fmt::format("what,run,{}", DirectoryStats::csvHeader()) << "\n"; + } + + std::sort(stats.begin(), stats.end(), [](auto&& a, auto&& b){ + return (naturalCompare(QString::fromStdString(a.mod), QString::fromStdString(b.mod)) < 0); + }); + + std::ofstream out(file, std::ios::app); + + DirectoryStats total; + for (const auto& s : stats) { + out << fmt::format("{},{},{}", s.mod, run, s.toCsv()) << "\n"; + total += s; + } + + out << fmt::format("total,{},{}", run, total.toCsv()) << "\n"; + + ++run; +} + void DirectoryRefresher::addMultipleModsFilesToStructure( MOShared::DirectoryEntry *directoryStructure, const std::vector& entries, bool emitProgress) { std::vector dirs(entries.size()); + std::vector stats(entries.size()); { TimeThis tt("walk dirs"); @@ -257,6 +293,9 @@ void DirectoryRefresher::addMultipleModsFilesToStructure( mt.path = QDir::toNativeSeparators(e.absolutePath).toStdWString(); mt.prio = prio; mt.dir = &dirs[i]; + mt.stats = &stats[i]; + + stats[i].mod = entries[i].modName.toStdString(); mt.wakeup(); } @@ -272,23 +311,7 @@ void DirectoryRefresher::addMultipleModsFilesToStructure( threads.join(); } - //std::sort(stats.begin(), stats.end(), [](auto&& a, auto&& b){ - // return (naturalCompare(QString::fromStdString(a.mod), QString::fromStdString(b.mod)) < 0); - //}); - - //static int run = 1; - // - //std::ofstream out("c:\\tmp\\data.csv", std::ios::app); - - //out << fmt::format("what,run,{}", DirectoryStats::csvHeader()); - // - //for (std::size_t i=0; iproperty("managed_game").value(); + IPluginGame *game = qApp->property("managed_game").value(); - std::wstring dataDirectory = - QDir::toNativeSeparators(game->dataDirectory().absolutePath()).toStdWString(); + std::wstring dataDirectory = + QDir::toNativeSeparators(game->dataDirectory().absolutePath()).toStdWString(); - m_DirectoryStructure->addFromOrigin(L"data", dataDirectory, 0); + { + DirectoryStats dummy; + m_DirectoryStructure->addFromOrigin(L"data", dataDirectory, 0, dummy); + } - std::sort(m_Mods.begin(), m_Mods.end(), [](auto lhs, auto rhs) { - return lhs.priority < rhs.priority; - }); + std::sort(m_Mods.begin(), m_Mods.end(), [](auto lhs, auto rhs) { + return lhs.priority < rhs.priority; + }); - addMultipleModsFilesToStructure(m_DirectoryStructure, m_Mods, true); + addMultipleModsFilesToStructure(m_DirectoryStructure, m_Mods, true); - m_DirectoryStructure->getFileRegister()->sortOrigins(); + m_DirectoryStructure->getFileRegister()->sortOrigins(); - emit progress(100); + emit progress(100); - cleanStructure(m_DirectoryStructure); + cleanStructure(m_DirectoryStructure); - emit refreshed(); + emit refreshed(); - //logcounts("after refresh"); + //logcounts("after refresh"); + } } diff --git a/src/envfs.cpp b/src/envfs.cpp index 022ca513..5cd36957 100644 --- a/src/envfs.cpp +++ b/src/envfs.cpp @@ -179,6 +179,8 @@ public: void run() { + MOShared::SetThisThreadName("HandleCloserThread"); + std::unique_lock lock(m_mutex); m_cv.wait(lock, [&]{ return m_ready; }); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3e03c52d..2145011f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -5148,7 +5148,11 @@ void MainWindow::originModified(int originID) { FilesOrigin &origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); origin.enable(false); - m_OrganizerCore.directoryStructure()->addFromOrigin(origin.getName(), origin.getPath(), origin.getPriority()); + + DirectoryStats dummy; + m_OrganizerCore.directoryStructure()->addFromOrigin( + origin.getName(), origin.getPath(), origin.getPriority(), dummy); + DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); } diff --git a/src/shared/directoryentry.cpp b/src/shared/directoryentry.cpp index e1464595..19500167 100644 --- a/src/shared/directoryentry.cpp +++ b/src/shared/directoryentry.cpp @@ -160,19 +160,23 @@ std::string DirectoryStats::toCsv() const { QStringList oss; + auto s = [](auto ns) { + return ns.count() / 1000.0 / 1000.0 / 1000.0; + }; + oss - << QString::number(dirTimes.count()) - << QString::number(fileTimes.count()) - << QString::number(sortTimes.count()) + << QString::number(s(dirTimes)) + << QString::number(s(fileTimes)) + << QString::number(s(sortTimes)) - << QString::number(subdirLookupTimes.count()) - << QString::number(addDirectoryTimes.count()) + << QString::number(s(subdirLookupTimes)) + << QString::number(s(addDirectoryTimes)) - << QString::number(filesLookupTimes.count()) - << QString::number(addFileTimes.count()) - << QString::number(addOriginToFileTimes.count()) - << QString::number(addFileToOriginTimes.count()) - << QString::number(addFileToRegisterTimes.count()) + << QString::number(s(filesLookupTimes)) + << QString::number(s(addFileTimes)) + << QString::number(s(addOriginToFileTimes)) + << QString::number(s(addFileToOriginTimes)) + << QString::number(s(addFileToRegisterTimes)) << QString::number(originExists) << QString::number(originCreate) @@ -323,6 +327,8 @@ FileEntry::~FileEntry() void FileEntry::addOrigin( int origin, FILETIME fileTime, std::wstring_view archive, int order) { + std::scoped_lock lock(m_OriginsMutex); + m_LastAccessed = time(nullptr); if (m_Parent != nullptr) { m_Parent->propagateOrigin(origin); @@ -387,6 +393,8 @@ void FileEntry::addOrigin( bool FileEntry::removeOrigin(int origin) { + std::scoped_lock lock(m_OriginsMutex); + if (m_Origin == origin) { if (!m_Alternatives.empty()) { // find alternative with the highest priority @@ -440,6 +448,8 @@ bool FileEntry::removeOrigin(int origin) void FileEntry::sortOrigins() { + std::scoped_lock lock(m_OriginsMutex); + m_Alternatives.push_back({m_Origin, m_Archive}); std::sort(m_Alternatives.begin(), m_Alternatives.end(), [&](auto&& LHS, auto&& RHS) { @@ -480,6 +490,8 @@ void FileEntry::sortOrigins() bool FileEntry::isFromArchive(std::wstring archiveName) const { + std::scoped_lock lock(m_OriginsMutex); + if (archiveName.length() == 0) { return m_Archive.first.length() != 0; } @@ -499,6 +511,8 @@ bool FileEntry::isFromArchive(std::wstring archiveName) const std::wstring FileEntry::getFullPath(int originID) const { + std::scoped_lock lock(m_OriginsMutex); + if (originID == -1) { bool ignore = false; originID = getOrigin(ignore); @@ -690,27 +704,34 @@ bool FileRegister::indexValid(FileEntry::Index index) const FileEntry::Ptr FileRegister::createFile( std::wstring name, DirectoryEntry *parent, DirectoryStats& stats) { - FileEntry::Index index = generateIndex(); + const auto index = generateIndex(); FileEntry::Ptr p; stats.addFileToRegisterTimes += elapsed([&]{ - std::scoped_lock lock(m_Mutex); + bool inserted = false; + p = FileEntry::Ptr(new FileEntry(index, std::move(name), parent)); - auto r = m_Files.insert_or_assign( - index, FileEntry::Ptr(new FileEntry(index, std::move(name), parent))); + { + std::scoped_lock lock(m_Mutex); + inserted = m_Files.insert_or_assign(index, p).second; + } - if (r.second) { + if (inserted) { ++stats.filesInsertedInRegister; } else { ++stats.filesAssignedInRegister; } - - p = r.first->second; }); return p; } +FileEntry::Index FileRegister::generateIndex() +{ + static std::atomic sIndex(0); + return sIndex++; +} + FileEntry::Ptr FileRegister::getFile(FileEntry::Index index) const { std::scoped_lock lock(m_Mutex); @@ -815,12 +836,6 @@ void FileRegister::sortOrigins() } } -FileEntry::Index FileRegister::generateIndex() -{ - static std::atomic sIndex(0); - return sIndex++; -} - void FileRegister::unregisterFile(FileEntry::Ptr file) { bool ignore; @@ -881,17 +896,13 @@ void DirectoryEntry::clear() } void DirectoryEntry::addFromOrigin( - const std::wstring &originName, const std::wstring &directory, int priority) + const std::wstring &originName, const std::wstring &directory, int priority, + DirectoryStats& stats) { - DirectoryStats dummy; - FilesOrigin &origin = createOrigin(originName, directory, priority, dummy); + FilesOrigin &origin = createOrigin(originName, directory, priority, stats); - if (directory.length() != 0) { - boost::scoped_array buffer(new wchar_t[MAXPATH_UNICODE + 1]); - memset(buffer.get(), L'\0', MAXPATH_UNICODE + 1); - int offset = _snwprintf(buffer.get(), MAXPATH_UNICODE, L"%ls", directory.c_str()); - buffer.get()[offset] = L'\0'; - addFiles(origin, buffer.get(), offset); + if (!directory.empty()) { + addFiles(origin, directory, stats); } m_Populated = true; @@ -1260,58 +1271,80 @@ void DirectoryEntry::removeFiles(const std::set &indices) FileEntry::Ptr DirectoryEntry::insert( std::wstring_view fileName, FilesOrigin &origin, FILETIME fileTime, - std::wstring_view archive, int order) + std::wstring_view archive, int order, DirectoryStats& stats) { - std::scoped_lock lock(m_FilesMutex); - std::wstring fileNameLower = ToLowerCopy(fileName); + FileEntry::Ptr fe; - auto iter = m_Files.find(fileNameLower); - FileEntry::Ptr file; + FileKey key(std::move(fileNameLower)); - if (iter != m_Files.end()) { - file = m_FileRegister->getFile(iter->second); - } else { - DirectoryStats dummy; + { + std::unique_lock lock(m_FilesMutex); + + FilesLookup::iterator itor; + + stats.filesLookupTimes += elapsed([&]{ + itor = m_FilesLookup.find(key); + }); + + if (itor != m_FilesLookup.end()) { + lock.unlock(); + ++stats.fileExists; + fe = m_FileRegister->getFile(itor->second); + } else { + ++stats.fileCreate; + fe = m_FileRegister->createFile( + std::wstring(fileName.begin(), fileName.end()), this, stats); - file = m_FileRegister->createFile( - std::wstring(fileName.begin(), fileName.end()), this, dummy); + stats.addFileTimes += elapsed([&] { + addFileToList(std::move(key.value), fe->getIndex()); + }); - addFileToList(std::move(fileNameLower), file->getIndex()); - // fileNameLower has moved from this point + // fileNameLower has moved from this point + } } - file->addOrigin(origin.getID(), fileTime, archive, order); - origin.addFile(file->getIndex()); + stats.addOriginToFileTimes += elapsed([&]{ + fe->addOrigin(origin.getID(), fileTime, archive, order); + }); + + stats.addFileToOriginTimes += elapsed([&]{ + origin.addFile(fe->getIndex()); + }); - return file; + return fe; } FileEntry::Ptr DirectoryEntry::insert( env::File& file, FilesOrigin &origin, std::wstring_view archive, int order, DirectoryStats& stats) { - std::scoped_lock lock(m_FilesMutex); + FileEntry::Ptr fe; - FilesMap::iterator itor; + { + std::unique_lock lock(m_FilesMutex); - stats.filesLookupTimes += elapsed([&]{ - itor = m_Files.find(file.lcname); - }); + FilesMap::iterator itor; - FileEntry::Ptr fe; + stats.filesLookupTimes += elapsed([&]{ + itor = m_Files.find(file.lcname); + }); - if (itor != m_Files.end()) { - ++stats.fileExists; - fe = m_FileRegister->getFile(itor->second); - } else { - fe = m_FileRegister->createFile(std::move(file.name), this, stats); + if (itor != m_Files.end()) { + lock.unlock(); + ++stats.fileExists; + fe = m_FileRegister->getFile(itor->second); + } else { + ++stats.fileCreate; + fe = m_FileRegister->createFile(std::move(file.name), this, stats); + // file.name has been moved from this point - stats.addFileTimes += elapsed([&]{ - addFileToList(std::move(file.lcname), fe->getIndex()); - }); + stats.addFileTimes += elapsed([&]{ + addFileToList(std::move(file.lcname), fe->getIndex()); + }); - // both file.name and file.lcname have been moved from this point + // file.lcname has been moved from this point + } } stats.addOriginToFileTimes += elapsed([&]{ @@ -1325,91 +1358,75 @@ FileEntry::Ptr DirectoryEntry::insert( return fe; } -void DirectoryEntry::addFiles(FilesOrigin &origin, wchar_t *buffer, int bufferOffset) +void DirectoryEntry::addFiles( + FilesOrigin &origin, const std::wstring& path, DirectoryStats& stats) { struct Context { FilesOrigin& origin; + DirectoryStats& stats; std::stack current; }; - Context cx = {origin}; + Context cx = {origin, stats}; cx.current.push(this); - env::forEachEntry(buffer, &cx, - [](void* pcx, std::wstring_view path) { - Context* cx = (Context*)pcx; - cx->current.push(cx->current.top()->getSubDirectory(path, true, cx->origin.getID())); - }, - - [](void* pcx, std::wstring_view path) { + env::forEachEntry(path, &cx, + [](void* pcx, std::wstring_view path) + { Context* cx = (Context*)pcx; - auto* current= cx->current.top(); + cx->stats.dirTimes += elapsed([&] { + auto* sd = cx->current.top()->getSubDirectory( + path, true, cx->stats, cx->origin.getID()); - { - std::scoped_lock lock(current->m_SubDirMutex); - std::sort(current->m_SubDirectories.begin(), current->m_SubDirectories.end(), &DirCompareByName); - } - - cx->current.pop(); + cx->current.push(sd); + }); }, - [](void* pcx, std::wstring_view path, FILETIME ft) { + [](void* pcx, std::wstring_view path) + { Context* cx = (Context*)pcx; - cx->current.top()->insert(path, cx->origin, ft, L"", -1); - } - ); - - /* - WIN32_FIND_DATAW findData; - _snwprintf_s(buffer + bufferOffset, MAXPATH_UNICODE - bufferOffset, _TRUNCATE, L"\\*"); + cx->stats.dirTimes += elapsed([&] { + auto* current= cx->current.top(); - HANDLE searchHandle = nullptr; - - if (SupportOptimizedFind()) { - searchHandle = ::FindFirstFileExW( - buffer, FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, - FIND_FIRST_EX_LARGE_FETCH); - } else { - searchHandle = ::FindFirstFileExW( - buffer, FindExInfoStandard, &findData, FindExSearchNameMatch, nullptr, 0); - } + { + std::scoped_lock lock(current->m_SubDirMutex); - if (searchHandle != INVALID_HANDLE_VALUE) { - BOOL result = true; + std::sort( + current->m_SubDirectories.begin(), + current->m_SubDirectories.end(), + &DirCompareByName); + } - while (result) { - if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - if ((wcscmp(findData.cFileName, L".") != 0) && - (wcscmp(findData.cFileName, L"..") != 0)) { - int offset = _snwprintf(buffer + bufferOffset, MAXPATH_UNICODE, L"\\%ls", findData.cFileName); + cx->current.pop(); + }); + }, - // recurse into subdirectories - DirectoryEntry* sd = getSubDirectory(findData.cFileName, true, origin.getID()); - sd->addFiles(origin, buffer, bufferOffset + offset); - } - } else { - insert(findData.cFileName, origin, findData.ftLastWriteTime, L"", -1); - } + [](void* pcx, std::wstring_view path, FILETIME ft) + { + Context* cx = (Context*)pcx; - result = ::FindNextFileW(searchHandle, &findData); + cx->stats.fileTimes += elapsed([&]{ + cx->current.top()->insert(path, cx->origin, ft, L"", -1, cx->stats); + }); } - } - - std::sort(m_SubDirectories.begin(), m_SubDirectories.end(), &DirCompareByName); - ::FindClose(searchHandle);*/ + ); } void DirectoryEntry::addFiles( FilesOrigin &origin, BSA::Folder::Ptr archiveFolder, FILETIME &fileTime, const std::wstring &archiveName, int order) { + DirectoryStats dummy; + // add files for (unsigned int fileIdx = 0; fileIdx < archiveFolder->getNumFiles(); ++fileIdx) { BSA::File::Ptr file = archiveFolder->getFile(fileIdx); - auto f = insert(ToWString(file->getName(), true), origin, fileTime, archiveName, order); + auto f = insert( + ToWString(file->getName(), true), origin, fileTime, + archiveName, order, dummy); if (f) { if (file->getUncompressedFileSize() > 0) { @@ -1423,31 +1440,41 @@ void DirectoryEntry::addFiles( // recurse into subdirectories for (unsigned int folderIdx = 0; folderIdx < archiveFolder->getNumSubFolders(); ++folderIdx) { BSA::Folder::Ptr folder = archiveFolder->getSubFolder(folderIdx); - DirectoryEntry *folderEntry = getSubDirectoryRecursive(ToWString(folder->getName(), true), true, origin.getID()); + DirectoryEntry *folderEntry = getSubDirectoryRecursive( + ToWString(folder->getName(), true), true, origin.getID()); folderEntry->addFiles(origin, folder, fileTime, archiveName, order); } } DirectoryEntry *DirectoryEntry::getSubDirectory( - std::wstring_view name, bool create, int originID) + std::wstring_view name, bool create, DirectoryStats& stats, int originID) { + std::wstring nameLc = ToLowerCopy(name); + std::scoped_lock lock(m_SubDirMutex); - std::wstring nameLc = ToLowerCopy(name); - auto itor = m_SubDirectoriesLookup.find(nameLc); + SubDirectoriesLookup::iterator itor; + stats.subdirLookupTimes += elapsed([&] { + itor = m_SubDirectoriesLookup.find(nameLc); + }); if (itor != m_SubDirectoriesLookup.end()) { + ++stats.subdirExists; return itor->second; } if (create) { + ++stats.subdirCreate; + auto* entry = new DirectoryEntry( std::wstring(name.begin(), name.end()), this, originID, m_FileRegister, m_OriginConnection); - addDirectoryToList(entry, std::move(nameLc)); - // nameLc is moved from this point + stats.addDirectoryTimes += elapsed([&] { + addDirectoryToList(entry, std::move(nameLc)); + // nameLc is moved from this point + }); return entry; } else { @@ -1498,16 +1525,19 @@ DirectoryEntry *DirectoryEntry::getSubDirectoryRecursive( } const size_t pos = path.find_first_of(L"\\/"); + DirectoryStats dummy; if (pos == std::wstring::npos) { - return getSubDirectory(path, create); + return getSubDirectory(path, create, dummy); } else { - DirectoryEntry *nextChild = getSubDirectory(path.substr(0, pos), create, originID); + DirectoryEntry *nextChild = getSubDirectory( + path.substr(0, pos), create, dummy, originID); if (nextChild == nullptr) { return nullptr; } else { - return nextChild->getSubDirectoryRecursive(path.substr(pos + 1), create, originID); + return nextChild->getSubDirectoryRecursive( + path.substr(pos + 1), create, originID); } } } diff --git a/src/shared/directoryentry.h b/src/shared/directoryentry.h index 71e8b32c..8f6afbb1 100644 --- a/src/shared/directoryentry.h +++ b/src/shared/directoryentry.h @@ -221,6 +221,7 @@ private: DirectoryEntry *m_Parent; mutable FILETIME m_FileTime; uint64_t m_FileSize, m_CompressedFileSize; + mutable std::mutex m_OriginsMutex; time_t m_LastAccessed; @@ -328,12 +329,14 @@ public: void sortOrigins(); private: + using FileMap = std::map; + mutable std::mutex m_Mutex; - std::map m_Files; + FileMap m_Files; boost::shared_ptr m_OriginConnection; - FileEntry::Index generateIndex(); void unregisterFile(FileEntry::Ptr file); + FileEntry::Index generateIndex(); }; @@ -354,7 +357,7 @@ struct DirectoryEntryFileKey return std::hash()(value); } - const std::wstring value; + std::wstring value; const std::size_t hash; }; @@ -405,7 +408,7 @@ public: // That origin may exist or not void addFromOrigin( const std::wstring &originName, - const std::wstring &directory, int priority); + const std::wstring &directory, int priority, DirectoryStats& stats); void addFromBSA( const std::wstring &originName, std::wstring &directory, @@ -559,14 +562,14 @@ private: FileEntry::Ptr insert( std::wstring_view fileName, FilesOrigin &origin, FILETIME fileTime, - std::wstring_view archive, int order); + std::wstring_view archive, int order, DirectoryStats& stats); FileEntry::Ptr insert( env::File& file, FilesOrigin &origin, std::wstring_view archive, int order, DirectoryStats& stats); void addFiles( - FilesOrigin &origin, wchar_t *buffer, int bufferOffset); + FilesOrigin &origin, const std::wstring& path, DirectoryStats& stats); void addFiles( FilesOrigin &origin, BSA::Folder::Ptr archiveFolder, FILETIME &fileTime, @@ -575,7 +578,8 @@ private: void addDir(FilesOrigin& origin, env::Directory& d, DirectoryStats& stats); DirectoryEntry* getSubDirectory( - std::wstring_view name, bool create, int originID = -1); + std::wstring_view name, bool create, DirectoryStats& stats, + int originID = -1); DirectoryEntry* getSubDirectory( env::Directory& dir, bool create, DirectoryStats& stats, -- cgit v1.3.1 From 88ef0530001d43be8f18fac43a280169b45db852 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 15 Feb 2020 12:25:37 -0500 Subject: error checking in dump() removed a bunch of "{} saved" in the logs --- src/directoryrefresher.cpp | 37 ++++++++++++++++++------------------- src/filetree.cpp | 39 --------------------------------------- src/filetree.h | 4 ---- src/mainwindow.cpp | 4 +--- src/pluginlist.cpp | 5 +---- src/profile.cpp | 6 +----- src/shared/directoryentry.cpp | 34 +++++++++++++++++++++++++++++----- 7 files changed, 50 insertions(+), 79 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index f3285cfc..8bf349f1 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -324,35 +324,34 @@ void DirectoryRefresher::refresh() SetThisThreadName("DirectoryRefresher"); TimeThis tt("refresh"); - for (int i=0; i<1; ++i) { - QMutexLocker locker(&m_RefreshLock); - delete m_DirectoryStructure; + QMutexLocker locker(&m_RefreshLock); + delete m_DirectoryStructure; - m_DirectoryStructure = new DirectoryEntry(L"data", nullptr, 0); - m_DirectoryStructure->getFileRegister()->reserve(m_lastFileCount); + m_DirectoryStructure = new DirectoryEntry(L"data", nullptr, 0); + m_DirectoryStructure->getFileRegister()->reserve(m_lastFileCount); - IPluginGame *game = qApp->property("managed_game").value(); + IPluginGame *game = qApp->property("managed_game").value(); - std::wstring dataDirectory = - QDir::toNativeSeparators(game->dataDirectory().absolutePath()).toStdWString(); + std::wstring dataDirectory = + QDir::toNativeSeparators(game->dataDirectory().absolutePath()).toStdWString(); - { - DirectoryStats dummy; - m_DirectoryStructure->addFromOrigin(L"data", dataDirectory, 0, dummy); - } + { + DirectoryStats dummy; + m_DirectoryStructure->addFromOrigin(L"data", dataDirectory, 0, dummy); + } - std::sort(m_Mods.begin(), m_Mods.end(), [](auto lhs, auto rhs) { - return lhs.priority < rhs.priority; - }); + std::sort(m_Mods.begin(), m_Mods.end(), [](auto lhs, auto rhs) { + return lhs.priority < rhs.priority; + }); - addMultipleModsFilesToStructure(m_DirectoryStructure, m_Mods, true); + addMultipleModsFilesToStructure(m_DirectoryStructure, m_Mods, true); - m_DirectoryStructure->getFileRegister()->sortOrigins(); + m_DirectoryStructure->getFileRegister()->sortOrigins(); - cleanStructure(m_DirectoryStructure); - } + cleanStructure(m_DirectoryStructure); m_lastFileCount = m_DirectoryStructure->getFileRegister()->highestCount(); + log::debug("refresher saw {} files", m_lastFileCount); emit progress(100); emit refreshed(); diff --git a/src/filetree.cpp b/src/filetree.cpp index 45c21c7f..f628dff3 100644 --- a/src/filetree.cpp +++ b/src/filetree.cpp @@ -441,45 +441,6 @@ void FileTree::dumpToFile() const m_core.directoryStructure()->dump(file.toStdWString()); } -void FileTree::dumpToFile( - QFile& out, const QString& parentPath, const DirectoryEntry& entry) const -{ - entry.forEachFile([&](auto&& file) { - bool isArchive = false; - const int originID = file.getOrigin(isArchive); - - if (isArchive) { - // TODO: don't list files from archives. maybe make this an option? - return true; - } - - const auto& origin = m_core.directoryStructure()->getOriginByID(originID); - const auto originName = QString::fromStdWString(origin.getName()); - - const QString path = - parentPath + "\\" + QString::fromStdWString(file.getName()); - - if (out.write(path.toUtf8() + "\t(" + originName.toUtf8() + ")\r\n") == -1) { - QMessageBox::critical( - m_tree->window(), tr("Error"), tr("Failed to write to file %1: %2") - .arg(out.fileName()) - .arg(out.errorString())); - - throw DumpFailed(); - } - - return true; - }); - - entry.forEachDirectory([&](auto&& dir) { - const auto newParentPath = - parentPath + "\\" + QString::fromStdWString(dir.getName()); - - dumpToFile(out, newParentPath, dir); - return true; - }); -} - void FileTree::onExpandedChanged(const QModelIndex& index, bool expanded) { if (auto* item=m_model->itemFromIndex(proxiedIndex(index))) { diff --git a/src/filetree.h b/src/filetree.h index c1458179..2669e53b 100644 --- a/src/filetree.h +++ b/src/filetree.h @@ -65,10 +65,6 @@ private: void toggleVisibility(bool b, FileTreeItem* item=nullptr); QModelIndex proxiedIndex(const QModelIndex& index); - - void dumpToFile( - QFile& out, const QString& parentPath, - const MOShared::DirectoryEntry& entry) const; }; #endif // MODORGANIZER_FILETREE_INCLUDED diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 2145011f..f9f1dfe5 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -4116,9 +4116,7 @@ void MainWindow::saveArchiveList() } } } - if (archiveFile.commitIfDifferent(m_ArchiveListHash)) { - log::debug("{} saved", QDir::toNativeSeparators(m_OrganizerCore.currentProfile()->getArchivesFileName())); - } + archiveFile.commitIfDifferent(m_ArchiveListHash); } else { log::warn("archive list not initialised"); } diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 266fe35c..f348f64c 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -507,7 +507,6 @@ void PluginList::writeLockedOrder(const QString &fileName) const file->write(QString("%1|%2\r\n").arg(iter->first).arg(iter->second).toUtf8()); } file.commit(); - log::debug("{} saved", QDir::toNativeSeparators(fileName)); } @@ -531,9 +530,7 @@ void PluginList::saveTo(const QString &lockedOrderFileName deleterFile->write("\r\n"); } } - if (deleterFile.commitIfDifferent(m_LastSaveHash[deleterFileName])) { - log::debug("{} saved", QDir::toNativeSeparators(deleterFileName)); - } + deleterFile.commitIfDifferent(m_LastSaveHash[deleterFileName]); } else if (QFile::exists(deleterFileName)) { shellDelete(QStringList() << deleterFileName); } diff --git a/src/profile.cpp b/src/profile.cpp index f041a241..19c0d750 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -250,9 +250,7 @@ void Profile::doWriteModlist() } } - if (file.commitIfDifferent(m_LastModlistHash)) { - log::debug("{} saved", QDir::toNativeSeparators(fileName)); - } + file.commitIfDifferent(m_LastModlistHash); } catch (const std::exception &e) { reportError(tr("failed to write mod list: %1").arg(e.what())); return; @@ -292,8 +290,6 @@ void Profile::createTweakedIniFile() reportError(tr("failed to create tweaked ini: %1") .arg(QString::fromStdWString(formatSystemMessage(e)))); } - - log::debug("{} saved", QDir::toNativeSeparators(tweakedIni)); } // static diff --git a/src/shared/directoryentry.cpp b/src/shared/directoryentry.cpp index 394eda7e..6c5ad9ae 100644 --- a/src/shared/directoryentry.cpp +++ b/src/shared/directoryentry.cpp @@ -1685,14 +1685,33 @@ void DirectoryEntry::addFileToList( // fileNameLower has been moved from this point } +struct DumpFailed : public std::runtime_error +{ + using runtime_error::runtime_error; +}; + void DirectoryEntry::dump(const std::wstring& file) const { - std::FILE* f = nullptr; - auto e = _wfopen_s(&f, file.c_str(), L"wb"); + try + { + std::FILE* f = nullptr; + auto e = _wfopen_s(&f, file.c_str(), L"wb"); + + if (e != 0 || !f) { + throw DumpFailed(fmt::format( + "failed to open, {} ({})", std::strerror(e), e)); + } - dump(f, L"Data"); + Guard g([&]{ std::fclose(f); }); - std::fclose(f); + dump(f, L"Data"); + } + catch(DumpFailed& e) + { + log::error( + "failed to write list to '{}': {}", + QString::fromStdWString(file).toStdString(), e.what()); + } } void DirectoryEntry::dump(std::FILE* f, const std::wstring& parentPath) const @@ -1716,7 +1735,12 @@ void DirectoryEntry::dump(std::FILE* f, const std::wstring& parentPath) const const auto line = path + L"\t(" + o.getName() + L")\r\n"; const auto lineu8 = MOShared::ToString(line, true); - std::fwrite(lineu8.data(), lineu8.size(), 1, f); + + if (std::fwrite(lineu8.data(), lineu8.size(), 1, f) != 1) { + const auto e = errno; + throw DumpFailed(fmt::format( + "failed to write, {} ({})", std::strerror(e), e)); + } } } -- cgit v1.3.1 From b1cf498924e461556c8f2fe961172685d92bb03f Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 15 Feb 2020 13:24:56 -0500 Subject: split directoryentry made classes noncopyable, fixed a few unintended copies --- src/CMakeLists.txt | 21 +- src/datatab.cpp | 1 - src/directoryrefresher.cpp | 11 +- src/directoryrefresher.h | 5 +- src/filetree.cpp | 3 + src/filetreeitem.h | 6 +- src/filetreemodel.cpp | 12 +- src/filetreemodel.h | 6 +- src/loglist.h | 3 +- src/main.cpp | 1 + src/mainwindow.cpp | 14 +- src/modinfodialog.cpp | 2 + src/modinfodialogconflicts.cpp | 21 +- src/modinfodialogconflicts.h | 14 +- src/modinfodialogtab.cpp | 2 +- src/modinfowithconflictinfo.cpp | 11 +- src/modlist.cpp | 8 +- src/modlist.h | 1 - src/organizercore.cpp | 7 +- src/organizercore.h | 1 - src/pch.h | 4 + src/pluginlist.cpp | 16 +- src/pluginlist.h | 1 - src/shared/directoryentry.cpp | 745 ++-------------------------------------- src/shared/directoryentry.h | 368 ++------------------ src/shared/fileentry.cpp | 251 ++++++++++++++ src/shared/fileentry.h | 125 +++++++ src/shared/fileregister.cpp | 184 ++++++++++ src/shared/fileregister.h | 58 ++++ src/shared/fileregisterfwd.h | 89 +++++ src/shared/filesorigin.cpp | 137 ++++++++ src/shared/filesorigin.h | 87 +++++ src/shared/originconnection.cpp | 145 ++++++++ src/shared/originconnection.h | 59 ++++ src/syncoverwritedialog.cpp | 7 +- src/syncoverwritedialog.h | 11 +- 36 files changed, 1310 insertions(+), 1127 deletions(-) create mode 100644 src/shared/fileentry.cpp create mode 100644 src/shared/fileentry.h create mode 100644 src/shared/fileregister.cpp create mode 100644 src/shared/fileregister.h create mode 100644 src/shared/fileregisterfwd.h create mode 100644 src/shared/filesorigin.cpp create mode 100644 src/shared/filesorigin.h create mode 100644 src/shared/originconnection.cpp create mode 100644 src/shared/originconnection.h (limited to 'src/mainwindow.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e121c572..85d8af0f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -155,6 +155,10 @@ SET(organizer_SRCS shared/windows_error.cpp shared/error_report.cpp shared/directoryentry.cpp + shared/fileentry.cpp + shared/filesorigin.cpp + shared/fileregister.cpp + shared/originconnection.cpp shared/util.cpp shared/appconfig.cpp shared/leaktrace.cpp @@ -286,6 +290,10 @@ SET(organizer_HDRS shared/windows_error.h shared/error_report.h shared/directoryentry.h + shared/fileentry.h + shared/filesorigin.h + shared/fileregister.h + shared/originconnection.h shared/util.h shared/appconfig.h shared/appconfig.inc @@ -350,8 +358,6 @@ set(browser set(core categories - shared/directoryentry - directoryrefresher installationmanager instancemanager loadmechanism @@ -470,6 +476,15 @@ set(profiles profilesdialog ) +set(register + shared/directoryentry + shared/fileentry + shared/filesorigin + shared/fileregister + shared/originconnection + directoryrefresher +) + set(settings settings settingsutilities @@ -521,7 +536,7 @@ set(widgets set(src_filters application core browser dialogs downloads env executables loot mainwindow - modinfo modinfo\\dialog modlist plugins previews profiles settings + modinfo modinfo\\dialog modlist plugins previews profiles register settings settingsdialog utilities widgets ) diff --git a/src/datatab.cpp b/src/datatab.cpp index 19bfa134..b6119d52 100644 --- a/src/datatab.cpp +++ b/src/datatab.cpp @@ -2,7 +2,6 @@ #include "ui_mainwindow.h" #include "settings.h" #include "organizercore.h" -#include "directoryentry.h" #include "messagedialog.h" #include "filetree.h" #include "filetreemodel.h" diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index 8bf349f1..3b92389a 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -18,6 +18,9 @@ along with Mod Organizer. If not, see . */ #include "directoryrefresher.h" +#include "shared/fileentry.h" +#include "shared/filesorigin.h" +#include "shared/directoryentry.h" #include "iplugingame.h" #include "utility.h" @@ -26,12 +29,16 @@ along with Mod Organizer. If not, see . #include "settings.h" #include "envfs.h" #include "modinfodialogfwd.h" +#include "util.h" + +#include #include #include #include #include -#include + +#include using namespace MOBase; @@ -136,7 +143,7 @@ void DirectoryRefresher::stealModFilesIntoStructure( continue; } QFileInfo fileInfo(filename); - FileEntry::Ptr file = directoryStructure->findFile(ToWString(fileInfo.fileName())); + FileEntryPtr file = directoryStructure->findFile(ToWString(fileInfo.fileName())); if (file.get() != nullptr) { if (file->getOrigin() == 0) { // replace data as the origin on this bsa diff --git a/src/directoryrefresher.h b/src/directoryrefresher.h index 5c829980..2102140c 100644 --- a/src/directoryrefresher.h +++ b/src/directoryrefresher.h @@ -20,7 +20,6 @@ along with Mod Organizer. If not, see . #ifndef DIRECTORYREFRESHER_H #define DIRECTORYREFRESHER_H -#include #include #include #include @@ -59,6 +58,10 @@ public: ~DirectoryRefresher(); + // noncopyable + DirectoryRefresher(const DirectoryRefresher&) = delete; + DirectoryRefresher& operator=(const DirectoryRefresher&) = delete; + /** * @brief retrieve the updated directory structure * diff --git a/src/filetree.cpp b/src/filetree.cpp index f628dff3..cdcf2feb 100644 --- a/src/filetree.cpp +++ b/src/filetree.cpp @@ -3,6 +3,9 @@ #include "filetreeitem.h" #include "organizercore.h" #include "envshell.h" +#include "shared/fileentry.h" +#include "shared/directoryentry.h" +#include "shared/filesorigin.h" #include #include diff --git a/src/filetreeitem.h b/src/filetreeitem.h index 390d5499..2092782e 100644 --- a/src/filetreeitem.h +++ b/src/filetreeitem.h @@ -1,7 +1,7 @@ #ifndef MODORGANIZER_FILETREEITEM_INCLUDED #define MODORGANIZER_FILETREEITEM_INCLUDED -#include "directoryentry.h" +#include "shared/fileregisterfwd.h" #include class FileTreeModel; @@ -126,7 +126,7 @@ public: return m_wsLcFile; } - const MOShared::DirectoryEntry::FileKey& key() const + const MOShared::DirectoryEntryFileKey& key() const { return m_key; } @@ -288,7 +288,7 @@ private: const QString m_virtualParentPath; const std::wstring m_wsFile, m_wsLcFile; - const MOShared::DirectoryEntry::FileKey m_key; + const MOShared::DirectoryEntryFileKey m_key; const QString m_file; const bool m_isDirectory; diff --git a/src/filetreemodel.cpp b/src/filetreemodel.cpp index 2130bf89..1a5433c5 100644 --- a/src/filetreemodel.cpp +++ b/src/filetreemodel.cpp @@ -1,5 +1,9 @@ #include "filetreemodel.h" #include "organizercore.h" +#include "filesorigin.h" +#include "util.h" +#include "shared/directoryentry.h" +#include "shared/fileentry.h" #include using namespace MOBase; @@ -637,7 +641,7 @@ bool FileTreeModel::updateFiles( // removeDisappearingFiles() will add files that are in the tree and still on // the filesystem to this set; addNewFiless() will use this to figure out if // a file is new or not - std::unordered_set seen; + std::unordered_set seen; int firstFileRow = 0; @@ -647,7 +651,7 @@ bool FileTreeModel::updateFiles( void FileTreeModel::removeDisappearingFiles( FileTreeItem& parentItem, const MOShared::DirectoryEntry& parentEntry, - int& firstFileRow, std::unordered_set& seen) + int& firstFileRow, std::unordered_set& seen) { auto& children = parentItem.children(); auto itor = children.begin(); @@ -708,7 +712,7 @@ void FileTreeModel::removeDisappearingFiles( bool FileTreeModel::addNewFiles( FileTreeItem& parentItem, const MOShared::DirectoryEntry& parentEntry, const std::wstring& parentPath, const int firstFileRow, - const std::unordered_set& seen) + const std::unordered_set& seen) { // keeps track of the contiguous files that need to be added to // avoid calling beginAddRows(), etc. for each item @@ -958,7 +962,7 @@ std::wstring FileTreeModel::makeModName( { static const std::wstring Unmanaged = UnmanagedModName().toStdWString(); - const auto origin = m_core.directoryStructure()->getOriginByID(originID); + const auto& origin = m_core.directoryStructure()->getOriginByID(originID); if (origin.getID() == 0) { return Unmanaged; diff --git a/src/filetreemodel.h b/src/filetreemodel.h index 093407b0..5bfb75aa 100644 --- a/src/filetreemodel.h +++ b/src/filetreemodel.h @@ -3,7 +3,7 @@ #include "filetreeitem.h" #include "iconfetcher.h" -#include "directoryentry.h" +#include "shared/fileregisterfwd.h" #include class OrganizerCore; @@ -126,12 +126,12 @@ private: void removeDisappearingFiles( FileTreeItem& parentItem, const MOShared::DirectoryEntry& parentEntry, - int& firstFileRow, std::unordered_set& seen); + int& firstFileRow, std::unordered_set& seen); bool addNewFiles( FileTreeItem& parentItem, const MOShared::DirectoryEntry& parentEntry, const std::wstring& parentPath, int firstFileRow, - const std::unordered_set& seen); + const std::unordered_set& seen); FileTreeItem::Ptr createDirectoryItem( diff --git a/src/loglist.h b/src/loglist.h index 56b95d65..b26f1561 100644 --- a/src/loglist.h +++ b/src/loglist.h @@ -20,8 +20,9 @@ along with Mod Organizer. If not, see . #ifndef LOGBUFFER_H #define LOGBUFFER_H -#include #include +#include +#include class OrganizerCore; diff --git a/src/main.cpp b/src/main.cpp index 6e2220ae..105299a8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -48,6 +48,7 @@ along with Mod Organizer. If not, see . #include "organizercore.h" #include "env.h" #include "envmodule.h" +#include "util.h" #include #include diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f9f1dfe5..adbac94e 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -20,8 +20,6 @@ along with Mod Organizer. If not, see . #include "mainwindow.h" #include "ui_mainwindow.h" -#include "directoryentry.h" -#include "directoryrefresher.h" #include "executableinfo.h" #include "executableslist.h" #include "guessedvalue.h" @@ -89,6 +87,10 @@ along with Mod Organizer. If not, see . #include "envshortcut.h" #include "browserdialog.h" +#include "shared/directoryentry.h" +#include "shared/fileentry.h" +#include "shared/filesorigin.h" + #include #include #include @@ -1870,7 +1872,7 @@ void MainWindow::updateBSAList(const QStringList &defaultArchives, const QString std::vector> items; BSAInvalidation * invalidation = m_OrganizerCore.managedGame()->feature(); - std::vector files = m_OrganizerCore.directoryStructure()->getFiles(); + std::vector files = m_OrganizerCore.directoryStructure()->getFiles(); QStringList plugins = m_OrganizerCore.findFiles("", [](const QString &fileName) -> bool { return fileName.endsWith(".esp", Qt::CaseInsensitive) @@ -1889,7 +1891,7 @@ void MainWindow::updateBSAList(const QStringList &defaultArchives, const QString return false; }; - for (FileEntry::Ptr current : files) { + for (FileEntryPtr current : files) { QFileInfo fileInfo(ToQString(current->getName().c_str())); if (fileInfo.suffix().toLower() == "bsa" || fileInfo.suffix().toLower() == "ba2") { @@ -1942,7 +1944,7 @@ void MainWindow::updateBSAList(const QStringList &defaultArchives, const QString for (auto iter = items.begin(); iter != items.end(); ++iter) { int originID = iter->second->data(1, Qt::UserRole).toInt(); - FilesOrigin origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); + const FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByID(originID); QString modName; const unsigned int modIndex = ModInfo::getIndex(ToQString(origin.getName())); @@ -2504,7 +2506,7 @@ void MainWindow::modRenamed(const QString &oldName, const QString &newName) void MainWindow::fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName) { - const FileEntry::Ptr filePtr = m_OrganizerCore.directoryStructure()->findFile(ToWString(filePath)); + const FileEntryPtr filePtr = m_OrganizerCore.directoryStructure()->findFile(ToWString(filePath)); if (filePtr.get() != nullptr) { try { if (m_OrganizerCore.directoryStructure()->originExists(ToWString(newOriginName))) { diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index bfb8d2c7..c3239e0d 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -29,6 +29,8 @@ along with Mod Organizer. If not, see . #include "modinfodialogcategories.h" #include "modinfodialognexus.h" #include "modinfodialogfiletree.h" +#include "shared/directoryentry.h" +#include "shared/filesorigin.h" #include using namespace MOBase; diff --git a/src/modinfodialogconflicts.cpp b/src/modinfodialogconflicts.cpp index 63d89a1a..b61dbb7b 100644 --- a/src/modinfodialogconflicts.cpp +++ b/src/modinfodialogconflicts.cpp @@ -4,6 +4,9 @@ #include "utility.h" #include "settings.h" #include "organizercore.h" +#include "shared/directoryentry.h" +#include "shared/filesorigin.h" +#include "shared/fileentry.h" using namespace MOShared; using namespace MOBase; @@ -17,7 +20,7 @@ class ConflictItem public: ConflictItem( QString before, QString relativeName, QString after, - FileEntry::Index index, QString fileName, + FileIndex index, QString fileName, bool hasAltOrigins, QString altOrigin, bool archive) : m_before(std::move(before)), m_relativeName(std::move(relativeName)), @@ -65,7 +68,7 @@ public: return m_isArchive; } - FileEntry::Index fileIndex() const + FileIndex fileIndex() const { return m_index; } @@ -104,7 +107,7 @@ private: QString m_before; QString m_relativeName; QString m_after; - FileEntry::Index m_index; + FileIndex m_index; QString m_fileName; bool m_hasAltOrigins; QString m_altOrigin; @@ -1006,8 +1009,8 @@ bool GeneralConflictsTab::update() } ConflictItem GeneralConflictsTab::createOverwriteItem( - FileEntry::Index index, bool archive, QString fileName, QString relativeName, - const FileEntry::AlternativesVector& alternatives) + FileIndex index, bool archive, QString fileName, QString relativeName, + const MOShared::AlternativesVector& alternatives) { const auto& ds = *m_core.directoryStructure(); std::wstring altString; @@ -1028,7 +1031,7 @@ ConflictItem GeneralConflictsTab::createOverwriteItem( } ConflictItem GeneralConflictsTab::createNoConflictItem( - FileEntry::Index index, bool archive, QString fileName, QString relativeName) + FileIndex index, bool archive, QString fileName, QString relativeName) { return ConflictItem( QString(), std::move(relativeName), QString(), index, @@ -1036,7 +1039,7 @@ ConflictItem GeneralConflictsTab::createNoConflictItem( } ConflictItem GeneralConflictsTab::createOverwrittenItem( - FileEntry::Index index, int fileOrigin, bool archive, + FileIndex index, int fileOrigin, bool archive, QString fileName, QString relativeName) { const auto& ds = *m_core.directoryStructure(); @@ -1205,9 +1208,9 @@ void AdvancedConflictsTab::update() } std::optional AdvancedConflictsTab::createItem( - FileEntry::Index index, int fileOrigin, bool archive, + FileIndex index, int fileOrigin, bool archive, QString fileName, QString relativeName, - const MOShared::FileEntry::AlternativesVector& alternatives) + const MOShared::AlternativesVector& alternatives) { const auto& ds = *m_core.directoryStructure(); diff --git a/src/modinfodialogconflicts.h b/src/modinfodialogconflicts.h index c4845019..945f464d 100644 --- a/src/modinfodialogconflicts.h +++ b/src/modinfodialogconflicts.h @@ -4,7 +4,7 @@ #include "modinfodialogtab.h" #include "expanderwidget.h" #include "filterwidget.h" -#include "directoryentry.h" +#include "shared/fileregisterfwd.h" #include #include @@ -52,16 +52,16 @@ private: FilterWidget m_filterNoConflicts; ConflictItem createOverwriteItem( - MOShared::FileEntry::Index index, bool archive, + MOShared::FileIndex index, bool archive, QString fileName, QString relativeName, - const MOShared::FileEntry::AlternativesVector& alternatives); + const MOShared::AlternativesVector& alternatives); ConflictItem createNoConflictItem( - MOShared::FileEntry::Index index, bool archive, + MOShared::FileIndex index, bool archive, QString fileName, QString relativeName); ConflictItem createOverwrittenItem( - MOShared::FileEntry::Index index, int fileOrigin, bool archive, + MOShared::FileIndex index, int fileOrigin, bool archive, QString fileName, QString relativeName); void onOverwriteActivated(const QModelIndex& index); @@ -94,9 +94,9 @@ private: ConflictListModel* m_model; std::optional createItem( - MOShared::FileEntry::Index index, int fileOrigin, bool archive, + MOShared::FileIndex index, int fileOrigin, bool archive, QString fileName, QString relativeName, - const MOShared::FileEntry::AlternativesVector& alternatives); + const MOShared::AlternativesVector& alternatives); }; diff --git a/src/modinfodialogtab.cpp b/src/modinfodialogtab.cpp index 9748d059..d662e2b2 100644 --- a/src/modinfodialogtab.cpp +++ b/src/modinfodialogtab.cpp @@ -1,8 +1,8 @@ #include "modinfodialogtab.h" #include "ui_modinfodialog.h" #include "texteditor.h" -#include "directoryentry.h" #include "modinfo.h" +#include "shared/filesorigin.h" ModInfoDialogTab::ModInfoDialogTab(ModInfoDialogTabContext cx) : ui(cx.ui), m_core(cx.core), m_plugin(cx.plugin), m_parent(cx.parent), diff --git a/src/modinfowithconflictinfo.cpp b/src/modinfowithconflictinfo.cpp index 861782d9..2b4fa11c 100644 --- a/src/modinfowithconflictinfo.cpp +++ b/src/modinfowithconflictinfo.cpp @@ -1,7 +1,8 @@ #include "modinfowithconflictinfo.h" - -#include "directoryentry.h" #include "utility.h" +#include "shared/directoryentry.h" +#include "shared/filesorigin.h" +#include "shared/fileentry.h" #include using namespace MOBase; @@ -98,11 +99,11 @@ void ModInfoWithConflictInfo::doConflictCheck() const if ((*m_DirectoryStructure)->originExists(name)) { FilesOrigin &origin = (*m_DirectoryStructure)->getOriginByName(name); - std::vector files = origin.getFiles(); + std::vector files = origin.getFiles(); std::set checkedDirs; // for all files in this origin - for (FileEntry::Ptr file : files) { + for (FileEntryPtr file : files) { // skip hiidden file check if already found one if (!hasHiddenFiles) { @@ -267,7 +268,7 @@ bool ModInfoWithConflictInfo::isRedundant() const std::wstring name = ToWString(this->name()); if ((*m_DirectoryStructure)->originExists(name)) { FilesOrigin &origin = (*m_DirectoryStructure)->getOriginByName(name); - std::vector files = origin.getFiles(); + std::vector files = origin.getFiles(); bool ignore = false; for (auto iter = files.begin(); iter != files.end(); ++iter) { if ((*iter)->getOrigin(ignore) == origin.getID()) { diff --git a/src/modlist.cpp b/src/modlist.cpp index afc1b65f..e84910fd 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -27,6 +27,10 @@ along with Mod Organizer. If not, see . #include "pluginlist.h" #include "settings.h" #include "modinforegular.h" +#include "shared/directoryentry.h" +#include "shared/fileentry.h" +#include "shared/filesorigin.h" + #include #include #include @@ -872,7 +876,7 @@ void ModList::highlightMods(const QItemSelectionModel *selection, const MOShared for (QModelIndex idx : selection->selectedRows(PluginList::COL_NAME)) { QString modName = idx.data().toString(); - const MOShared::FileEntry::Ptr fileEntry = directoryEntry.findFile(modName.toStdWString()); + const MOShared::FileEntryPtr fileEntry = directoryEntry.findFile(modName.toStdWString()); if (fileEntry.get() != nullptr) { bool archive = false; std::vector>> origins; @@ -881,7 +885,7 @@ void ModList::highlightMods(const QItemSelectionModel *selection, const MOShared origins.insert(origins.end(), std::pair>(fileEntry->getOrigin(archive), fileEntry->getArchive())); } for (auto originInfo : origins) { - MOShared::FilesOrigin &origin = directoryEntry.getOriginByID(originInfo.first); + MOShared::FilesOrigin& origin = directoryEntry.getOriginByID(originInfo.first); for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) { if (ModInfo::getByIndex(i)->internalName() == QString::fromStdWString(origin.getName())) { ModInfo::getByIndex(i)->setPluginSelected(true); diff --git a/src/modlist.h b/src/modlist.h index 7452b28b..d8980dec 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -27,7 +27,6 @@ along with Mod Organizer. If not, see . #include "profile.h" #include -#include #include #include diff --git a/src/organizercore.cpp b/src/organizercore.cpp index a3202153..c9c0bee5 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -34,6 +33,10 @@ #include "previewdialog.h" #include "env.h" #include "envmodule.h" +#include "envfs.h" +#include "shared/directoryentry.h" +#include "shared/filesorigin.h" +#include "shared/fileentry.h" #include #include @@ -810,7 +813,7 @@ QString OrganizerCore::resolvePath(const QString &fileName) const if (m_DirectoryStructure == nullptr) { return QString(); } - const FileEntry::Ptr file + const FileEntryPtr file = m_DirectoryStructure->searchFile(ToWString(fileName), nullptr); if (file.get() != nullptr) { return ToQString(file->getFullPath()); diff --git a/src/organizercore.h b/src/organizercore.h index 223eb6cb..980156d3 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -15,7 +15,6 @@ #include "moshortcut.h" #include "processrunner.h" #include "uilocker.h" -#include #include #include #include diff --git a/src/pch.h b/src/pch.h index 030ee634..c66550be 100644 --- a/src/pch.h +++ b/src/pch.h @@ -5,14 +5,17 @@ #include #include #include +#include #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -21,6 +24,7 @@ #include #include #include +#include #include #include #include diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index f348f64c..4b2eedbd 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -23,6 +23,10 @@ along with Mod Organizer. If not, see . #include "modinfo.h" #include "modlist.h" #include "viewmarkingscrollbar.h" +#include "shared/directoryentry.h" +#include "shared/filesorigin.h" +#include "shared/fileentry.h" + #include #include #include @@ -144,10 +148,10 @@ void PluginList::highlightPlugins(const QItemSelectionModel *selection, const MO if (!selectedMod.isNull() && profile.modEnabled(modIndex)) { QDir dir(selectedMod->absolutePath()); QStringList plugins = dir.entryList(QStringList() << "*.esp" << "*.esm" << "*.esl"); - MOShared::FilesOrigin origin = directoryEntry.getOriginByName(selectedMod->internalName().toStdWString()); + const MOShared::FilesOrigin& origin = directoryEntry.getOriginByName(selectedMod->internalName().toStdWString()); if (plugins.size() > 0) { for (auto plugin : plugins) { - MOShared::FileEntry::Ptr file = directoryEntry.findFile(plugin.toStdWString()); + MOShared::FileEntryPtr file = directoryEntry.findFile(plugin.toStdWString()); if (file && file->getOrigin() != origin.getID()) { const std::vector>> alternatives = file->getAlternatives(); if (std::find_if(alternatives.begin(), alternatives.end(), [&](const std::pair>& element) { return element.first == origin.getID(); }) == alternatives.end()) @@ -185,8 +189,8 @@ void PluginList::refresh(const QString &profileName QStringList availablePlugins; - std::vector files = baseDirectory.getFiles(); - for (FileEntry::Ptr current : files) { + std::vector files = baseDirectory.getFiles(); + for (FileEntryPtr current : files) { if (current.get() == nullptr) { continue; } @@ -217,7 +221,7 @@ void PluginList::refresh(const QString &profileName bool hasIni = baseDirectory.findFile(ToWString(iniPath)).get() != nullptr; std::set loadedArchives; QString candidateName; - for (FileEntry::Ptr archiveCandidate : files) { + for (FileEntryPtr archiveCandidate : files) { candidateName = ToQString(archiveCandidate->getName()); if (candidateName.startsWith(baseName, Qt::CaseInsensitive) && (candidateName.endsWith(".bsa", Qt::CaseInsensitive) || @@ -548,7 +552,7 @@ bool PluginList::saveLoadOrder(DirectoryEntry &directoryStructure) for (ESPInfo &esp : m_ESPs) { std::wstring espName = ToWString(esp.name); - const FileEntry::Ptr fileEntry = directoryStructure.findFile(espName); + const FileEntryPtr fileEntry = directoryStructure.findFile(espName); if (fileEntry.get() != nullptr) { QString fileName; bool archive = false; diff --git a/src/pluginlist.h b/src/pluginlist.h index fb6d0543..cdab18b5 100644 --- a/src/pluginlist.h +++ b/src/pluginlist.h @@ -20,7 +20,6 @@ along with Mod Organizer. If not, see . #ifndef PLUGINLIST_H #define PLUGINLIST_H -#include #include #include "profile.h" #include "loot.h" diff --git a/src/shared/directoryentry.cpp b/src/shared/directoryentry.cpp index 6c5ad9ae..1036dfe6 100644 --- a/src/shared/directoryentry.cpp +++ b/src/shared/directoryentry.cpp @@ -18,21 +18,14 @@ along with Mod Organizer. If not, see . */ #include "directoryentry.h" -#include "windows_error.h" -#include "error_report.h" +#include "originconnection.h" +#include "filesorigin.h" +#include "fileentry.h" #include "envfs.h" -#include +#include "util.h" +#include "windows_error.h" #include -#include -#include -#include -#define WIN32_LEAN_AND_MEAN -#include -#include -#include -#include -#include -#include +#include namespace MOShared { @@ -58,16 +51,6 @@ void elapsedImpl(std::chrono::nanoseconds& out, F&& f) #define elapsed(OUT, F) (F)(); //#define elapsed(OUT, F) elapsedImpl(OUT, F); - -static std::wstring tail(const std::wstring &source, const size_t count) -{ - if (count >= source.length()) { - return source; - } - - return source.substr(source.length() - count); -} - static bool SupportOptimizedFind() { // large fetch and basic info for FindFirstFileEx is supported on win server 2008 r2, win 7 and newer @@ -189,686 +172,6 @@ std::string DirectoryStats::toCsv() const } -class OriginConnection -{ -public: - typedef int Index; - static const int INVALID_INDEX = INT_MIN; - - OriginConnection() - : m_NextID(0) - { - } - - std::pair getOrCreate( - const std::wstring &originName, const std::wstring &directory, int priority, - const boost::shared_ptr& fileRegister, - const boost::shared_ptr& originConnection, - DirectoryStats& stats) - { - std::unique_lock lock(m_Mutex); - - auto itor = m_OriginsNameMap.find(originName); - - if (itor == m_OriginsNameMap.end()) { - FilesOrigin& origin = createOriginNoLock( - originName, directory, priority, fileRegister, originConnection); - - return {origin, true}; - } else { - FilesOrigin& origin = m_Origins[itor->second]; - lock.unlock(); - - origin.enable(true, stats); - return {origin, false}; - } - } - - FilesOrigin& createOrigin( - const std::wstring &originName, const std::wstring &directory, int priority, - boost::shared_ptr fileRegister, - boost::shared_ptr originConnection) - { - std::scoped_lock lock(m_Mutex); - - return createOriginNoLock( - originName, directory, priority, fileRegister, originConnection); - } - - bool exists(const std::wstring &name) - { - std::scoped_lock lock(m_Mutex); - return m_OriginsNameMap.find(name) != m_OriginsNameMap.end(); - } - - FilesOrigin &getByID(Index ID) - { - std::scoped_lock lock(m_Mutex); - return m_Origins[ID]; - } - - const FilesOrigin* findByID(Index ID) const - { - std::scoped_lock lock(m_Mutex); - - auto itor = m_Origins.find(ID); - - if (itor == m_Origins.end()) { - return nullptr; - } else { - return &itor->second; - } - } - - FilesOrigin &getByName(const std::wstring &name) - { - std::scoped_lock lock(m_Mutex); - - std::map::iterator iter = m_OriginsNameMap.find(name); - - if (iter != m_OriginsNameMap.end()) { - return m_Origins[iter->second]; - } else { - std::ostringstream stream; - stream << QObject::tr("invalid origin name: ").toStdString() << ToString(name, true); - throw std::runtime_error(stream.str()); - } - } - - void changePriorityLookup(int oldPriority, int newPriority) - { - std::scoped_lock lock(m_Mutex); - - auto iter = m_OriginsPriorityMap.find(oldPriority); - - if (iter != m_OriginsPriorityMap.end()) { - Index idx = iter->second; - m_OriginsPriorityMap.erase(iter); - m_OriginsPriorityMap[newPriority] = idx; - } - } - - void changeNameLookup(const std::wstring &oldName, const std::wstring &newName) - { - std::scoped_lock lock(m_Mutex); - - auto iter = m_OriginsNameMap.find(oldName); - - if (iter != m_OriginsNameMap.end()) { - Index idx = iter->second; - m_OriginsNameMap.erase(iter); - m_OriginsNameMap[newName] = idx; - } else { - log::error(QObject::tr("failed to change name lookup from {} to {}").toStdString(), oldName, newName); - } - } - -private: - Index m_NextID; - std::map m_Origins; - std::map m_OriginsNameMap; - std::map m_OriginsPriorityMap; - mutable std::mutex m_Mutex; - - Index createID() - { - return m_NextID++; - } - - FilesOrigin& createOriginNoLock( - const std::wstring &originName, const std::wstring &directory, int priority, - boost::shared_ptr fileRegister, - boost::shared_ptr originConnection) - { - int newID = createID(); - - auto itor = m_Origins.insert({newID, FilesOrigin( - newID, originName, directory, priority, - fileRegister, originConnection)}).first; - - m_OriginsNameMap.insert({originName, newID}); - m_OriginsPriorityMap.insert({priority, newID}); - - return itor->second; - } -}; - - -FileEntry::FileEntry() : - m_Index(UINT_MAX), m_Name(), m_Origin(-1), m_Parent(nullptr), - m_FileSize(NoFileSize), m_CompressedFileSize(NoFileSize) -{ -} - -FileEntry::FileEntry(Index index, std::wstring name, DirectoryEntry *parent) : - m_Index(index), m_Name(std::move(name)), m_Origin(-1), m_Archive(L"", -1), m_Parent(parent), - m_FileSize(NoFileSize), m_CompressedFileSize(NoFileSize) -{ -} - -void FileEntry::addOrigin( - int origin, FILETIME fileTime, std::wstring_view archive, int order) -{ - std::scoped_lock lock(m_OriginsMutex); - - if (m_Parent != nullptr) { - m_Parent->propagateOrigin(origin); - } - - if (m_Origin == -1) { - // If this file has no previous origin, this mod is now the origin with no - // alternatives - m_Origin = origin; - m_FileTime = fileTime; - m_Archive = std::pair(std::wstring(archive.begin(), archive.end()), order); - } - else if ( - (m_Parent != nullptr) && ( - (m_Parent->getOriginByID(origin).getPriority() > m_Parent->getOriginByID(m_Origin).getPriority()) || - (archive.size() == 0 && m_Archive.first.size() > 0 )) - ) { - // If this mod has a higher priority than the origin mod OR - // this mod has a loose file and the origin mod has an archived file, - // this mod is now the origin and the previous origin is the first alternative - - auto itor = std::find_if( - m_Alternatives.begin(), m_Alternatives.end(), - [&](auto&& i) { return i.first == m_Origin; }); - - if (itor == m_Alternatives.end()) { - m_Alternatives.push_back({m_Origin, m_Archive}); - } - - m_Origin = origin; - m_FileTime = fileTime; - m_Archive = std::pair(std::wstring(archive.begin(), archive.end()), order); - } - else { - // This mod is just an alternative - bool found = false; - - if (m_Origin == origin) { - // already an origin - return; - } - - for (auto iter = m_Alternatives.begin(); iter != m_Alternatives.end(); ++iter) { - if (iter->first == origin) { - // already an origin - return; - } - - if ((m_Parent != nullptr) && - (m_Parent->getOriginByID(iter->first).getPriority() < m_Parent->getOriginByID(origin).getPriority())) { - m_Alternatives.insert(iter, {origin, {std::wstring(archive.begin(), archive.end()), order}}); - found = true; - break; - } - } - - if (!found) { - m_Alternatives.push_back({origin, {std::wstring(archive.begin(), archive.end()), order}}); - } - } -} - -bool FileEntry::removeOrigin(int origin) -{ - std::scoped_lock lock(m_OriginsMutex); - - if (m_Origin == origin) { - if (!m_Alternatives.empty()) { - // find alternative with the highest priority - auto currentIter = m_Alternatives.begin(); - for (auto iter = m_Alternatives.begin(); iter != m_Alternatives.end(); ++iter) { - if (iter->first != origin) { - //Both files are not from archives. - if (!iter->second.first.size() && !currentIter->second.first.size()) { - if ((m_Parent->getOriginByID(iter->first).getPriority() > m_Parent->getOriginByID(currentIter->first).getPriority())) { - currentIter = iter; - } - } - else { - //Both files are from archives - if (iter->second.first.size() && currentIter->second.first.size()) { - if (iter->second.second > currentIter->second.second) { - currentIter = iter; - } - } - else { - //Only one of the two is an archive, so we change currentIter only if he is the archive one. - if (currentIter->second.first.size()) { - currentIter = iter; - } - } - } - } - } - - int currentID = currentIter->first; - m_Archive = currentIter->second; - m_Alternatives.erase(currentIter); - - m_Origin = currentID; - } else { - m_Origin = -1; - m_Archive = std::pair(L"", -1); - return true; - } - } else { - auto newEnd = std::remove_if( - m_Alternatives.begin(), m_Alternatives.end(), - [&](auto &i) { return i.first == origin; }); - - if (newEnd != m_Alternatives.end()) { - m_Alternatives.erase(newEnd, m_Alternatives.end()); - } - } - return false; -} - -void FileEntry::sortOrigins() -{ - std::scoped_lock lock(m_OriginsMutex); - - m_Alternatives.push_back({m_Origin, m_Archive}); - - std::sort(m_Alternatives.begin(), m_Alternatives.end(), [&](auto&& LHS, auto&& RHS) { - if (!LHS.second.first.size() && !RHS.second.first.size()) { - int l = m_Parent->getOriginByID(LHS.first).getPriority(); - if (l < 0) { - l = INT_MAX; - } - - int r = m_Parent->getOriginByID(RHS.first).getPriority(); - if (r < 0) { - r = INT_MAX; - } - - return l < r; - } - - if (LHS.second.first.size() && RHS.second.first.size()) { - int l = LHS.second.second; if (l < 0) l = INT_MAX; - int r = RHS.second.second; if (r < 0) r = INT_MAX; - - return l < r; - } - - if (RHS.second.first.size()) { - return false; - } - - return true; - }); - - if (!m_Alternatives.empty()) { - m_Origin = m_Alternatives.back().first; - m_Archive = m_Alternatives.back().second; - m_Alternatives.pop_back(); - } -} - -bool FileEntry::isFromArchive(std::wstring archiveName) const -{ - std::scoped_lock lock(m_OriginsMutex); - - if (archiveName.length() == 0) { - return m_Archive.first.length() != 0; - } - - if (m_Archive.first.compare(archiveName) == 0) { - return true; - } - - for (auto alternative : m_Alternatives) { - if (alternative.second.first.compare(archiveName) == 0) { - return true; - } - } - - return false; -} - -std::wstring FileEntry::getFullPath(int originID) const -{ - std::scoped_lock lock(m_OriginsMutex); - - if (originID == -1) { - bool ignore = false; - originID = getOrigin(ignore); - } - - // base directory for origin - const auto* o = m_Parent->findOriginByID(originID); - if (!o) { - return {}; - } - - std::wstring result = o->getPath(); - - // all intermediate directories - recurseParents(result, m_Parent); - - return result + L"\\" + m_Name; -} - -std::wstring FileEntry::getRelativePath() const -{ - std::wstring result; - - // all intermediate directories - recurseParents(result, m_Parent); - - return result + L"\\" + m_Name; -} - -bool FileEntry::recurseParents(std::wstring &path, const DirectoryEntry *parent) const -{ - if (parent == nullptr) { - return false; - } else { - // don't append the topmost parent because it is the virtual data-root - if (recurseParents(path, parent->getParent())) { - path.append(L"\\").append(parent->getName()); - } - - return true; - } -} - - -FilesOrigin::FilesOrigin() - : m_ID(0), m_Disabled(false), m_Name(), m_Path(), m_Priority(0) -{ -} - -FilesOrigin::FilesOrigin(const FilesOrigin &reference) - : m_ID(reference.m_ID) - , m_Disabled(reference.m_Disabled) - , m_Name(reference.m_Name) - , m_Path(reference.m_Path) - , m_Priority(reference.m_Priority) - , m_FileRegister(reference.m_FileRegister) - , m_OriginConnection(reference.m_OriginConnection) -{ -} - -FilesOrigin::FilesOrigin( - int ID, const std::wstring &name, const std::wstring &path, int priority, - boost::shared_ptr fileRegister, - boost::shared_ptr originConnection) : - m_ID(ID), m_Disabled(false), m_Name(name), m_Path(path), - m_Priority(priority), m_FileRegister(fileRegister), - m_OriginConnection(originConnection) -{ -} - -void FilesOrigin::setPriority(int priority) -{ - m_OriginConnection.lock()->changePriorityLookup(m_Priority, priority); - - m_Priority = priority; -} - -void FilesOrigin::setName(const std::wstring &name) -{ - m_OriginConnection.lock()->changeNameLookup(m_Name, name); - - // change path too - if (tail(m_Path, m_Name.length()) == m_Name) { - m_Path = m_Path.substr(0, m_Path.length() - m_Name.length()).append(name); - } - - m_Name = name; -} - -std::vector FilesOrigin::getFiles() const -{ - std::vector result; - - { - std::scoped_lock lock(m_Mutex); - - for (FileEntry::Index fileIdx : m_Files) { - if (FileEntry::Ptr p = m_FileRegister.lock()->getFile(fileIdx)) { - result.push_back(p); - } - } - } - - return result; -} - -FileEntry::Ptr FilesOrigin::findFile(FileEntry::Index index) const -{ - return m_FileRegister.lock()->getFile(index); -} - -void FilesOrigin::enable(bool enabled) -{ - DirectoryStats dummy; - enable(enabled, dummy); -} - -void FilesOrigin::enable(bool enabled, DirectoryStats& stats) -{ - if (!enabled) { - ++stats.originsNeededEnabled; - - std::set copy; - - { - std::scoped_lock lock(m_Mutex); - copy = m_Files; - m_Files.clear(); - } - - m_FileRegister.lock()->removeOriginMulti(copy, m_ID); - } - - m_Disabled = !enabled; -} - -void FilesOrigin::removeFile(FileEntry::Index index) -{ - std::scoped_lock lock(m_Mutex); - - auto iter = m_Files.find(index); - - if (iter != m_Files.end()) { - m_Files.erase(iter); - } -} - -bool FilesOrigin::containsArchive(std::wstring archiveName) -{ - std::scoped_lock lock(m_Mutex); - - for (FileEntry::Index fileIdx : m_Files) { - if (FileEntry::Ptr p = m_FileRegister.lock()->getFile(fileIdx)) { - if (p->isFromArchive(archiveName)) { - return true; - } - } - } - - return false; -} - - -FileRegister::FileRegister(boost::shared_ptr originConnection) - : m_OriginConnection(originConnection), m_NextIndex(0) -{ -} - -bool FileRegister::indexValid(FileEntry::Index index) const -{ - std::scoped_lock lock(m_Mutex); - - if (index < m_Files.size()) { - return (m_Files[index].get() != nullptr); - } - - return false; -} - -FileEntry::Ptr FileRegister::createFile( - std::wstring name, DirectoryEntry *parent, DirectoryStats& stats) -{ - const auto index = generateIndex(); - auto p = FileEntry::Ptr(new FileEntry(index, std::move(name), parent)); - - { - std::scoped_lock lock(m_Mutex); - - if (index >= m_Files.size()) { - m_Files.resize(index + 1); - } - - m_Files[index] = p; - } - - return p; -} - -FileEntry::Index FileRegister::generateIndex() -{ - return m_NextIndex++; -} - -FileEntry::Ptr FileRegister::getFile(FileEntry::Index index) const -{ - std::scoped_lock lock(m_Mutex); - - if (index < m_Files.size()) { - return m_Files[index]; - } else { - return {}; - } -} - -bool FileRegister::removeFile(FileEntry::Index index) -{ - std::scoped_lock lock(m_Mutex); - - if (index < m_Files.size()) { - FileEntry::Ptr p; - m_Files[index].swap(p); - - if (p) { - unregisterFile(p); - return true; - } - } - - log::error(QObject::tr("invalid file index for remove: {}").toStdString(), index); - return false; -} - -void FileRegister::removeOrigin(FileEntry::Index index, int originID) -{ - std::unique_lock lock(m_Mutex); - - if (index < m_Files.size()) { - FileEntry::Ptr& p = m_Files[index]; - - if (p) { - if (p->removeOrigin(originID)) { - m_Files[index] = {}; - lock.unlock(); - unregisterFile(p); - return; - } - } - } - - log::error(QObject::tr("invalid file index for remove (for origin): {}").toStdString(), index); -} - -void FileRegister::removeOriginMulti( - std::set indices, int originID) -{ - std::vector removedFiles; - - { - std::scoped_lock lock(m_Mutex); - - for (auto iter = indices.begin(); iter != indices.end(); ) { - const auto index = *iter; - - if (index < m_Files.size()) { - const auto& p = m_Files[index]; - - if (p && p->removeOrigin(originID)) { - removedFiles.push_back(p); - m_Files[index] = {}; - ++iter; - continue; - } - } - - iter = indices.erase(iter); - } - } - - // optimization: this is only called when disabling an origin and in this case - // we don't have to remove the file from the origin - - // need to remove files from their parent directories. multiple ways to go - // about this: - // a) for each file, search its parents file-list (preferably by name) and - // remove what is found - // b) gather the parent directories, go through the file list for each once - // and remove all files that have been removed - // - // the latter should be faster when there are many files in few directories. - // since this is called only when disabling an origin that is probably - // frequently the case - - std::set parents; - for (const FileEntry::Ptr &file : removedFiles) { - if (file->getParent() != nullptr) { - parents.insert(file->getParent()); - } - } - - for (DirectoryEntry *parent : parents) { - parent->removeFiles(indices); - } -} - -void FileRegister::sortOrigins() -{ - std::scoped_lock lock(m_Mutex); - - for (auto&& p : m_Files) { - if (p) { - p->sortOrigins(); - } - } -} - -void FileRegister::unregisterFile(FileEntry::Ptr file) -{ - bool ignore; - - // unregister from origin - int originID = file->getOrigin(ignore); - m_OriginConnection->getByID(originID).removeFile(file->getIndex()); - const auto& alternatives = file->getAlternatives(); - - for (auto iter = alternatives.begin(); iter != alternatives.end(); ++iter) { - m_OriginConnection->getByID(iter->first).removeFile(file->getIndex()); - } - - // unregister from directory - if (file->getParent() != nullptr) { - file->getParent()->removeFile(file->getIndex()); - } -} - - DirectoryEntry::DirectoryEntry( std::wstring name, DirectoryEntry *parent, int originID) : m_OriginConnection(new OriginConnection), @@ -1046,7 +349,7 @@ int DirectoryEntry::anyOrigin() const bool ignore; for (auto iter = m_Files.begin(); iter != m_Files.end(); ++iter) { - FileEntry::Ptr entry = m_FileRegister->getFile(iter->second); + FileEntryPtr entry = m_FileRegister->getFile(iter->second); if ((entry.get() != nullptr) && !entry->isFromArchive()) { return entry->getOrigin(ignore); } @@ -1064,9 +367,9 @@ int DirectoryEntry::anyOrigin() const return *(m_Origins.begin()); } -std::vector DirectoryEntry::getFiles() const +std::vector DirectoryEntry::getFiles() const { - std::vector result; + std::vector result; for (auto iter = m_Files.begin(); iter != m_Files.end(); ++iter) { result.push_back(m_FileRegister->getFile(iter->second)); @@ -1098,7 +401,7 @@ DirectoryEntry *DirectoryEntry::findSubDirectoryRecursive(const std::wstring &pa return getSubDirectoryRecursive(path, false, -1); } -const FileEntry::Ptr DirectoryEntry::findFile( +const FileEntryPtr DirectoryEntry::findFile( const std::wstring &name, bool alreadyLowerCase) const { FilesLookup::const_iterator iter; @@ -1112,18 +415,18 @@ const FileEntry::Ptr DirectoryEntry::findFile( if (iter != m_FilesLookup.end()) { return m_FileRegister->getFile(iter->second); } else { - return FileEntry::Ptr(); + return FileEntryPtr(); } } -const FileEntry::Ptr DirectoryEntry::findFile(const FileKey& key) const +const FileEntryPtr DirectoryEntry::findFile(const FileKey& key) const { auto iter = m_FilesLookup.find(key); if (iter != m_FilesLookup.end()) { return m_FileRegister->getFile(iter->second); } else { - return FileEntry::Ptr(); + return FileEntryPtr(); } } @@ -1135,7 +438,7 @@ bool DirectoryEntry::hasFile(const std::wstring& name) const bool DirectoryEntry::containsArchive(std::wstring archiveName) { for (auto iter = m_Files.begin(); iter != m_Files.end(); ++iter) { - FileEntry::Ptr entry = m_FileRegister->getFile(iter->second); + FileEntryPtr entry = m_FileRegister->getFile(iter->second); if (entry->isFromArchive(archiveName)) { return true; } @@ -1144,7 +447,7 @@ bool DirectoryEntry::containsArchive(std::wstring archiveName) return false; } -const FileEntry::Ptr DirectoryEntry::searchFile( +const FileEntryPtr DirectoryEntry::searchFile( const std::wstring &path, const DirectoryEntry **directory) const { if (directory != nullptr) { @@ -1157,7 +460,7 @@ const FileEntry::Ptr DirectoryEntry::searchFile( *directory = this; } - return FileEntry::Ptr(); + return FileEntryPtr(); } const size_t len = path.find_first_of(L"\\/"); @@ -1182,14 +485,14 @@ const FileEntry::Ptr DirectoryEntry::searchFile( if (temp != nullptr) { if (len >= path.size()) { log::error(QObject::tr("unexpected end of path").toStdString()); - return FileEntry::Ptr(); + return FileEntryPtr(); } return temp->searchFile(path.substr(len + 1), directory); } } - return FileEntry::Ptr(); + return FileEntryPtr(); } void DirectoryEntry::removeFile(FileEntry::Index index) @@ -1251,7 +554,7 @@ bool DirectoryEntry::remove(const std::wstring &fileName, int *origin) if (iter != m_Files.end()) { if (origin != nullptr) { - FileEntry::Ptr entry = m_FileRegister->getFile(iter->second); + FileEntryPtr entry = m_FileRegister->getFile(iter->second); if (entry.get() != nullptr) { bool ignore; *origin = entry->getOrigin(ignore); @@ -1291,12 +594,12 @@ void DirectoryEntry::removeFiles(const std::set &indices) removeFilesFromList(indices); } -FileEntry::Ptr DirectoryEntry::insert( +FileEntryPtr DirectoryEntry::insert( std::wstring_view fileName, FilesOrigin &origin, FILETIME fileTime, std::wstring_view archive, int order, DirectoryStats& stats) { std::wstring fileNameLower = ToLowerCopy(fileName); - FileEntry::Ptr fe; + FileEntryPtr fe; FileKey key(std::move(fileNameLower)); @@ -1337,11 +640,11 @@ FileEntry::Ptr DirectoryEntry::insert( return fe; } -FileEntry::Ptr DirectoryEntry::insert( +FileEntryPtr DirectoryEntry::insert( env::File& file, FilesOrigin &origin, std::wstring_view archive, int order, DirectoryStats& stats) { - FileEntry::Ptr fe; + FileEntryPtr fe; { std::unique_lock lock(m_FilesMutex); @@ -1730,7 +1033,7 @@ void DirectoryEntry::dump(std::FILE* f, const std::wstring& parentPath) const continue; } - const auto o = m_OriginConnection->getByID(file->getOrigin()); + const auto& o = m_OriginConnection->getByID(file->getOrigin()); const auto path = parentPath + L"\\" + file->getName(); const auto line = path + L"\t(" + o.getName() + L")\r\n"; diff --git a/src/shared/directoryentry.h b/src/shared/directoryentry.h index ce50da44..df946946 100644 --- a/src/shared/directoryentry.h +++ b/src/shared/directoryentry.h @@ -17,29 +17,18 @@ You should have received a copy of the GNU General Public License along with Mod Organizer. If not, see . */ -#ifndef DIRECTORYENTRY_H -#define DIRECTORYENTRY_H +#ifndef MO_REGISTER_DIRECTORYENTRY_INCLUDED +#define MO_REGISTER_DIRECTORYENTRY_INCLUDED - -#include -#include -#include -#include -#include -#include - -#define WIN32_MEAN_AND_LEAN -#include +#include "fileregister.h" #include -#ifndef Q_MOC_RUN -#include -#include -#endif - -#include "util.h" -#include "envfs.h" -namespace MOShared { struct DirectoryEntryFileKey; } +namespace env +{ + class DirectoryWalker; + struct Directory; + struct File; +} namespace std { @@ -57,309 +46,6 @@ namespace std namespace MOShared { -class DirectoryEntry; -class OriginConnection; -class FileRegister; - - -struct DirectoryStats -{ - static constexpr bool EnableInstrumentation = false; - - std::string mod; - - std::chrono::nanoseconds dirTimes; - std::chrono::nanoseconds fileTimes; - std::chrono::nanoseconds sortTimes; - - std::chrono::nanoseconds subdirLookupTimes; - std::chrono::nanoseconds addDirectoryTimes; - - std::chrono::nanoseconds filesLookupTimes; - std::chrono::nanoseconds addFileTimes; - std::chrono::nanoseconds addOriginToFileTimes; - std::chrono::nanoseconds addFileToOriginTimes; - std::chrono::nanoseconds addFileToRegisterTimes; - - int64_t originExists; - int64_t originCreate; - int64_t originsNeededEnabled; - - int64_t subdirExists; - int64_t subdirCreate; - - int64_t fileExists; - int64_t fileCreate; - int64_t filesInsertedInRegister; - int64_t filesAssignedInRegister; - - DirectoryStats(); - - DirectoryStats& operator+=(const DirectoryStats& o); - - static std::string csvHeader(); - std::string toCsv() const; -}; - - -class FileEntry -{ -public: - static constexpr uint64_t NoFileSize = - std::numeric_limits::max(); - - typedef unsigned int Index; - typedef boost::shared_ptr Ptr; - - // a vector of {originId, {archiveName, order}} - // - // if a file is in an archive, archiveName is the name of the bsa and order - // is the order of the associated plugin in the plugins list - // - // is a file is not in an archive, archiveName is empty and order is usually - // -1 - typedef std::vector>> - AlternativesVector; - - FileEntry(); - FileEntry(Index index, std::wstring name, DirectoryEntry *parent); - - Index getIndex() const - { - return m_Index; - } - - void addOrigin( - int origin, FILETIME fileTime, std::wstring_view archive, int order); - - // remove the specified origin from the list of origins that contain this - // file. if no origin is left, the file is effectively deleted and true is - // returned. otherwise, false is returned - bool removeOrigin(int origin); - - void sortOrigins(); - - // gets the list of alternative origins (origins with lower priority than - // the primary one). if sortOrigins has been called, it is sorted by priority - // (ascending) - const AlternativesVector &getAlternatives() const - { - return m_Alternatives; - } - - const std::wstring &getName() const - { - return m_Name; - } - - int getOrigin() const - { - return m_Origin; - } - - int getOrigin(bool &archive) const - { - archive = (m_Archive.first.length() != 0); - return m_Origin; - } - - const std::pair &getArchive() const - { - return m_Archive; - } - - bool isFromArchive(std::wstring archiveName = L"") const; - - // if originID is -1, uses the main origin; if this file doesn't exist in the - // given origin, returns an empty string - // - std::wstring getFullPath(int originID=-1) const; - - std::wstring getRelativePath() const; - - DirectoryEntry *getParent() - { - return m_Parent; - } - - void setFileTime(FILETIME fileTime) const - { - m_FileTime = fileTime; - } - - FILETIME getFileTime() const - { - return m_FileTime; - } - - void setFileSize(uint64_t size, uint64_t compressedSize) - { - m_FileSize = size; - m_CompressedFileSize = compressedSize; - } - - uint64_t getFileSize() const - { - return m_FileSize; - } - - uint64_t getCompressedFileSize() const - { - return m_CompressedFileSize; - } - -private: - Index m_Index; - std::wstring m_Name; - int m_Origin; - std::pair m_Archive; - AlternativesVector m_Alternatives; - DirectoryEntry *m_Parent; - mutable FILETIME m_FileTime; - uint64_t m_FileSize, m_CompressedFileSize; - mutable std::mutex m_OriginsMutex; - - bool recurseParents(std::wstring &path, const DirectoryEntry *parent) const; -}; - - -// represents a mod or the data directory, providing files to the tree -class FilesOrigin -{ - friend class OriginConnection; - -public: - FilesOrigin(); - FilesOrigin(const FilesOrigin &reference); - - // sets priority for this origin, but it will overwrite the existing mapping - // for this priority, the previous origin will no longer be referenced - void setPriority(int priority); - - int getPriority() const - { - return m_Priority; - } - - void setName(const std::wstring &name); - const std::wstring &getName() const - { - return m_Name; - } - - int getID() const - { - return m_ID; - } - - const std::wstring &getPath() const - { - return m_Path; - } - - std::vector getFiles() const; - FileEntry::Ptr findFile(FileEntry::Index index) const; - - void enable(bool enabled, DirectoryStats& stats); - void enable(bool enabled); - - bool isDisabled() const - { - return m_Disabled; - } - - void addFile(FileEntry::Index index) - { - std::scoped_lock lock(m_Mutex); - m_Files.insert(index); - } - - void removeFile(FileEntry::Index index); - - bool containsArchive(std::wstring archiveName); - -private: - int m_ID; - bool m_Disabled; - std::set m_Files; - std::wstring m_Name; - std::wstring m_Path; - int m_Priority; - boost::weak_ptr m_FileRegister; - boost::weak_ptr m_OriginConnection; - mutable std::mutex m_Mutex; - - FilesOrigin( - int ID, const std::wstring &name, const std::wstring &path, int priority, - boost::shared_ptr fileRegister, - boost::shared_ptr originConnection); -}; - - -class FileRegister -{ -public: - FileRegister(boost::shared_ptr originConnection); - - bool indexValid(FileEntry::Index index) const; - - FileEntry::Ptr createFile( - std::wstring name, DirectoryEntry *parent, DirectoryStats& stats); - - FileEntry::Ptr getFile(FileEntry::Index index) const; - - size_t highestCount() const - { - std::scoped_lock lock(m_Mutex); - return m_Files.size(); - } - - void reserve(std::size_t n) - { - m_Files.reserve(n); - } - - bool removeFile(FileEntry::Index index); - void removeOrigin(FileEntry::Index index, int originID); - void removeOriginMulti(std::set indices, int originID); - - void sortOrigins(); - -private: - using FileMap = std::vector; - - mutable std::mutex m_Mutex; - FileMap m_Files; - boost::shared_ptr m_OriginConnection; - std::atomic m_NextIndex; - - void unregisterFile(FileEntry::Ptr file); - FileEntry::Index generateIndex(); -}; - - -struct DirectoryEntryFileKey -{ - DirectoryEntryFileKey(std::wstring v) - : value(std::move(v)), hash(getHash(value)) - { - } - - bool operator==(const DirectoryEntryFileKey& o) const - { - return (value == o.value); - } - - static std::size_t getHash(const std::wstring& value) - { - return std::hash()(value); - } - - std::wstring value; - const std::size_t hash; -}; - - class DirectoryEntry { public: @@ -373,6 +59,10 @@ public: boost::shared_ptr fileRegister, boost::shared_ptr originConnection); + // noncopyable + DirectoryEntry(const DirectoryEntry&) = delete; + DirectoryEntry& operator=(const DirectoryEntry&) = delete; + ~DirectoryEntry(); void clear(); @@ -439,7 +129,7 @@ public: int anyOrigin() const; - std::vector getFiles() const; + std::vector getFiles() const; void getSubDirectories( std::vector::const_iterator &begin, @@ -486,7 +176,7 @@ public: } } - FileEntry::Ptr getFileByIndex(FileEntry::Index index) const + FileEntryPtr getFileByIndex(FileIndex index) const { return m_FileRegister->getFile(index); } @@ -500,8 +190,8 @@ public: * @param name name of the file * @return fileentry object for the file or nullptr if no file matches */ - const FileEntry::Ptr findFile(const std::wstring &name, bool alreadyLowerCase=false) const; - const FileEntry::Ptr findFile(const FileKey& key) const; + const FileEntryPtr findFile(const std::wstring &name, bool alreadyLowerCase=false) const; + const FileEntryPtr findFile(const FileKey& key) const; bool hasFile(const std::wstring& name) const; bool containsArchive(std::wstring archiveName); @@ -512,10 +202,10 @@ public: // if directory is not nullptr, the referenced variable will be set to the // path containing the file // - const FileEntry::Ptr searchFile( + const FileEntryPtr searchFile( const std::wstring &path, const DirectoryEntry **directory=nullptr) const; - void removeFile(FileEntry::Index index); + void removeFile(FileIndex index); // remove the specified file from the tree. This can be a path leading to a // file in a subdirectory @@ -535,13 +225,13 @@ public: const std::wstring &originName, const std::wstring &directory, int priority, DirectoryStats& stats); - void removeFiles(const std::set &indices); + void removeFiles(const std::set &indices); void dump(const std::wstring& file) const; private: - using FilesMap = std::map; - using FilesLookup = std::unordered_map; + using FilesMap = std::map; + using FilesLookup = std::unordered_map; using SubDirectories = std::vector; using SubDirectoriesLookup = std::unordered_map; @@ -563,13 +253,11 @@ private: mutable std::mutex m_OriginsMutex; - DirectoryEntry(const DirectoryEntry &reference); - - FileEntry::Ptr insert( + FileEntryPtr insert( std::wstring_view fileName, FilesOrigin &origin, FILETIME fileTime, std::wstring_view archive, int order, DirectoryStats& stats); - FileEntry::Ptr insert( + FileEntryPtr insert( env::File& file, FilesOrigin &origin, std::wstring_view archive, int order, DirectoryStats& stats); @@ -599,9 +287,9 @@ private: void addDirectoryToList(DirectoryEntry* e, std::wstring nameLc); void removeDirectoryFromList(SubDirectories::iterator itor); - void addFileToList(std::wstring fileNameLower, FileEntry::Index index); - void removeFileFromList(FileEntry::Index index); - void removeFilesFromList(const std::set& indices); + void addFileToList(std::wstring fileNameLower, FileIndex index); + void removeFileFromList(FileIndex index); + void removeFilesFromList(const std::set& indices); struct Context; static void onDirectoryStart(Context* cx, std::wstring_view path); @@ -624,4 +312,4 @@ namespace std } } -#endif // DIRECTORYENTRY_H +#endif // MO_REGISTER_DIRECTORYENTRY_INCLUDED diff --git a/src/shared/fileentry.cpp b/src/shared/fileentry.cpp new file mode 100644 index 00000000..d4e1beb4 --- /dev/null +++ b/src/shared/fileentry.cpp @@ -0,0 +1,251 @@ +#include "fileentry.h" +#include "directoryentry.h" +#include "filesorigin.h" + +namespace MOShared +{ + +FileEntry::FileEntry() : + m_Index(UINT_MAX), m_Name(), m_Origin(-1), m_Parent(nullptr), + m_FileSize(NoFileSize), m_CompressedFileSize(NoFileSize) +{ +} + +FileEntry::FileEntry(Index index, std::wstring name, DirectoryEntry *parent) : + m_Index(index), m_Name(std::move(name)), m_Origin(-1), m_Archive(L"", -1), m_Parent(parent), + m_FileSize(NoFileSize), m_CompressedFileSize(NoFileSize) +{ +} + +void FileEntry::addOrigin( + int origin, FILETIME fileTime, std::wstring_view archive, int order) +{ + std::scoped_lock lock(m_OriginsMutex); + + if (m_Parent != nullptr) { + m_Parent->propagateOrigin(origin); + } + + if (m_Origin == -1) { + // If this file has no previous origin, this mod is now the origin with no + // alternatives + m_Origin = origin; + m_FileTime = fileTime; + m_Archive = std::pair(std::wstring(archive.begin(), archive.end()), order); + } + else if ( + (m_Parent != nullptr) && ( + (m_Parent->getOriginByID(origin).getPriority() > m_Parent->getOriginByID(m_Origin).getPriority()) || + (archive.size() == 0 && m_Archive.first.size() > 0 )) + ) { + // If this mod has a higher priority than the origin mod OR + // this mod has a loose file and the origin mod has an archived file, + // this mod is now the origin and the previous origin is the first alternative + + auto itor = std::find_if( + m_Alternatives.begin(), m_Alternatives.end(), + [&](auto&& i) { return i.first == m_Origin; }); + + if (itor == m_Alternatives.end()) { + m_Alternatives.push_back({m_Origin, m_Archive}); + } + + m_Origin = origin; + m_FileTime = fileTime; + m_Archive = std::pair(std::wstring(archive.begin(), archive.end()), order); + } + else { + // This mod is just an alternative + bool found = false; + + if (m_Origin == origin) { + // already an origin + return; + } + + for (auto iter = m_Alternatives.begin(); iter != m_Alternatives.end(); ++iter) { + if (iter->first == origin) { + // already an origin + return; + } + + if ((m_Parent != nullptr) && + (m_Parent->getOriginByID(iter->first).getPriority() < m_Parent->getOriginByID(origin).getPriority())) { + m_Alternatives.insert(iter, {origin, {std::wstring(archive.begin(), archive.end()), order}}); + found = true; + break; + } + } + + if (!found) { + m_Alternatives.push_back({origin, {std::wstring(archive.begin(), archive.end()), order}}); + } + } +} + +bool FileEntry::removeOrigin(int origin) +{ + std::scoped_lock lock(m_OriginsMutex); + + if (m_Origin == origin) { + if (!m_Alternatives.empty()) { + // find alternative with the highest priority + auto currentIter = m_Alternatives.begin(); + for (auto iter = m_Alternatives.begin(); iter != m_Alternatives.end(); ++iter) { + if (iter->first != origin) { + //Both files are not from archives. + if (!iter->second.first.size() && !currentIter->second.first.size()) { + if ((m_Parent->getOriginByID(iter->first).getPriority() > m_Parent->getOriginByID(currentIter->first).getPriority())) { + currentIter = iter; + } + } + else { + //Both files are from archives + if (iter->second.first.size() && currentIter->second.first.size()) { + if (iter->second.second > currentIter->second.second) { + currentIter = iter; + } + } + else { + //Only one of the two is an archive, so we change currentIter only if he is the archive one. + if (currentIter->second.first.size()) { + currentIter = iter; + } + } + } + } + } + + int currentID = currentIter->first; + m_Archive = currentIter->second; + m_Alternatives.erase(currentIter); + + m_Origin = currentID; + } else { + m_Origin = -1; + m_Archive = std::pair(L"", -1); + return true; + } + } else { + auto newEnd = std::remove_if( + m_Alternatives.begin(), m_Alternatives.end(), + [&](auto &i) { return i.first == origin; }); + + if (newEnd != m_Alternatives.end()) { + m_Alternatives.erase(newEnd, m_Alternatives.end()); + } + } + return false; +} + +void FileEntry::sortOrigins() +{ + std::scoped_lock lock(m_OriginsMutex); + + m_Alternatives.push_back({m_Origin, m_Archive}); + + std::sort(m_Alternatives.begin(), m_Alternatives.end(), [&](auto&& LHS, auto&& RHS) { + if (!LHS.second.first.size() && !RHS.second.first.size()) { + int l = m_Parent->getOriginByID(LHS.first).getPriority(); + if (l < 0) { + l = INT_MAX; + } + + int r = m_Parent->getOriginByID(RHS.first).getPriority(); + if (r < 0) { + r = INT_MAX; + } + + return l < r; + } + + if (LHS.second.first.size() && RHS.second.first.size()) { + int l = LHS.second.second; if (l < 0) l = INT_MAX; + int r = RHS.second.second; if (r < 0) r = INT_MAX; + + return l < r; + } + + if (RHS.second.first.size()) { + return false; + } + + return true; + }); + + if (!m_Alternatives.empty()) { + m_Origin = m_Alternatives.back().first; + m_Archive = m_Alternatives.back().second; + m_Alternatives.pop_back(); + } +} + +bool FileEntry::isFromArchive(std::wstring archiveName) const +{ + std::scoped_lock lock(m_OriginsMutex); + + if (archiveName.length() == 0) { + return m_Archive.first.length() != 0; + } + + if (m_Archive.first.compare(archiveName) == 0) { + return true; + } + + for (auto alternative : m_Alternatives) { + if (alternative.second.first.compare(archiveName) == 0) { + return true; + } + } + + return false; +} + +std::wstring FileEntry::getFullPath(int originID) const +{ + std::scoped_lock lock(m_OriginsMutex); + + if (originID == -1) { + bool ignore = false; + originID = getOrigin(ignore); + } + + // base directory for origin + const auto* o = m_Parent->findOriginByID(originID); + if (!o) { + return {}; + } + + std::wstring result = o->getPath(); + + // all intermediate directories + recurseParents(result, m_Parent); + + return result + L"\\" + m_Name; +} + +std::wstring FileEntry::getRelativePath() const +{ + std::wstring result; + + // all intermediate directories + recurseParents(result, m_Parent); + + return result + L"\\" + m_Name; +} + +bool FileEntry::recurseParents(std::wstring &path, const DirectoryEntry *parent) const +{ + if (parent == nullptr) { + return false; + } else { + // don't append the topmost parent because it is the virtual data-root + if (recurseParents(path, parent->getParent())) { + path.append(L"\\").append(parent->getName()); + } + + return true; + } +} + +} // namespace diff --git a/src/shared/fileentry.h b/src/shared/fileentry.h new file mode 100644 index 00000000..52ce89cd --- /dev/null +++ b/src/shared/fileentry.h @@ -0,0 +1,125 @@ +#ifndef MO_REGISTER_FILEENTRY_INCLUDED +#define MO_REGISTER_FILEENTRY_INCLUDED + +#include "fileregisterfwd.h" + +namespace MOShared +{ + +class FileEntry +{ +public: + static constexpr uint64_t NoFileSize = + std::numeric_limits::max(); + + typedef unsigned int Index; + typedef boost::shared_ptr Ptr; + + FileEntry(); + FileEntry(Index index, std::wstring name, DirectoryEntry *parent); + + // noncopyable + FileEntry(const FileEntry&) = delete; + FileEntry& operator=(const FileEntry&) = delete; + + Index getIndex() const + { + return m_Index; + } + + void addOrigin( + int origin, FILETIME fileTime, std::wstring_view archive, int order); + + // remove the specified origin from the list of origins that contain this + // file. if no origin is left, the file is effectively deleted and true is + // returned. otherwise, false is returned + bool removeOrigin(int origin); + + void sortOrigins(); + + // gets the list of alternative origins (origins with lower priority than + // the primary one). if sortOrigins has been called, it is sorted by priority + // (ascending) + const AlternativesVector &getAlternatives() const + { + return m_Alternatives; + } + + const std::wstring &getName() const + { + return m_Name; + } + + int getOrigin() const + { + return m_Origin; + } + + int getOrigin(bool &archive) const + { + archive = (m_Archive.first.length() != 0); + return m_Origin; + } + + const std::pair &getArchive() const + { + return m_Archive; + } + + bool isFromArchive(std::wstring archiveName = L"") const; + + // if originID is -1, uses the main origin; if this file doesn't exist in the + // given origin, returns an empty string + // + std::wstring getFullPath(int originID=-1) const; + + std::wstring getRelativePath() const; + + DirectoryEntry *getParent() + { + return m_Parent; + } + + void setFileTime(FILETIME fileTime) const + { + m_FileTime = fileTime; + } + + FILETIME getFileTime() const + { + return m_FileTime; + } + + void setFileSize(uint64_t size, uint64_t compressedSize) + { + m_FileSize = size; + m_CompressedFileSize = compressedSize; + } + + uint64_t getFileSize() const + { + return m_FileSize; + } + + uint64_t getCompressedFileSize() const + { + return m_CompressedFileSize; + } + +private: + Index m_Index; + std::wstring m_Name; + int m_Origin; + std::pair m_Archive; + AlternativesVector m_Alternatives; + DirectoryEntry *m_Parent; + mutable FILETIME m_FileTime; + uint64_t m_FileSize, m_CompressedFileSize; + mutable std::mutex m_OriginsMutex; + + bool recurseParents(std::wstring &path, const DirectoryEntry *parent) const; +}; + +} // namespace + +#endif // MO_REGISTER_FILEENTRY_INCLUDED diff --git a/src/shared/fileregister.cpp b/src/shared/fileregister.cpp new file mode 100644 index 00000000..4add0455 --- /dev/null +++ b/src/shared/fileregister.cpp @@ -0,0 +1,184 @@ +#include "fileregister.h" +#include "fileentry.h" +#include "directoryentry.h" +#include "originconnection.h" +#include "filesorigin.h" +#include + +namespace MOShared +{ + +using namespace MOBase; + +FileRegister::FileRegister(boost::shared_ptr originConnection) + : m_OriginConnection(originConnection), m_NextIndex(0) +{ +} + +bool FileRegister::indexValid(FileIndex index) const +{ + std::scoped_lock lock(m_Mutex); + + if (index < m_Files.size()) { + return (m_Files[index].get() != nullptr); + } + + return false; +} + +FileEntryPtr FileRegister::createFile( + std::wstring name, DirectoryEntry *parent, DirectoryStats& stats) +{ + const auto index = generateIndex(); + auto p = FileEntryPtr(new FileEntry(index, std::move(name), parent)); + + { + std::scoped_lock lock(m_Mutex); + + if (index >= m_Files.size()) { + m_Files.resize(index + 1); + } + + m_Files[index] = p; + } + + return p; +} + +FileIndex FileRegister::generateIndex() +{ + return m_NextIndex++; +} + +FileEntryPtr FileRegister::getFile(FileIndex index) const +{ + std::scoped_lock lock(m_Mutex); + + if (index < m_Files.size()) { + return m_Files[index]; + } else { + return {}; + } +} + +bool FileRegister::removeFile(FileIndex index) +{ + std::scoped_lock lock(m_Mutex); + + if (index < m_Files.size()) { + FileEntryPtr p; + m_Files[index].swap(p); + + if (p) { + unregisterFile(p); + return true; + } + } + + log::error(QObject::tr("invalid file index for remove: {}").toStdString(), index); + return false; +} + +void FileRegister::removeOrigin(FileIndex index, int originID) +{ + std::unique_lock lock(m_Mutex); + + if (index < m_Files.size()) { + FileEntryPtr& p = m_Files[index]; + + if (p) { + if (p->removeOrigin(originID)) { + m_Files[index] = {}; + lock.unlock(); + unregisterFile(p); + return; + } + } + } + + log::error(QObject::tr("invalid file index for remove (for origin): {}").toStdString(), index); +} + +void FileRegister::removeOriginMulti( + std::set indices, int originID) +{ + std::vector removedFiles; + + { + std::scoped_lock lock(m_Mutex); + + for (auto iter = indices.begin(); iter != indices.end(); ) { + const auto index = *iter; + + if (index < m_Files.size()) { + const auto& p = m_Files[index]; + + if (p && p->removeOrigin(originID)) { + removedFiles.push_back(p); + m_Files[index] = {}; + ++iter; + continue; + } + } + + iter = indices.erase(iter); + } + } + + // optimization: this is only called when disabling an origin and in this case + // we don't have to remove the file from the origin + + // need to remove files from their parent directories. multiple ways to go + // about this: + // a) for each file, search its parents file-list (preferably by name) and + // remove what is found + // b) gather the parent directories, go through the file list for each once + // and remove all files that have been removed + // + // the latter should be faster when there are many files in few directories. + // since this is called only when disabling an origin that is probably + // frequently the case + + std::set parents; + for (const FileEntryPtr &file : removedFiles) { + if (file->getParent() != nullptr) { + parents.insert(file->getParent()); + } + } + + for (DirectoryEntry *parent : parents) { + parent->removeFiles(indices); + } +} + +void FileRegister::sortOrigins() +{ + std::scoped_lock lock(m_Mutex); + + for (auto&& p : m_Files) { + if (p) { + p->sortOrigins(); + } + } +} + +void FileRegister::unregisterFile(FileEntryPtr file) +{ + bool ignore; + + // unregister from origin + int originID = file->getOrigin(ignore); + m_OriginConnection->getByID(originID).removeFile(file->getIndex()); + const auto& alternatives = file->getAlternatives(); + + for (auto iter = alternatives.begin(); iter != alternatives.end(); ++iter) { + m_OriginConnection->getByID(iter->first).removeFile(file->getIndex()); + } + + // unregister from directory + if (file->getParent() != nullptr) { + file->getParent()->removeFile(file->getIndex()); + } +} + +} // namespace diff --git a/src/shared/fileregister.h b/src/shared/fileregister.h new file mode 100644 index 00000000..d5e360c1 --- /dev/null +++ b/src/shared/fileregister.h @@ -0,0 +1,58 @@ +#ifndef MO_REGISTER_FILESREGISTER_INCLUDED +#define MO_REGISTER_FILESREGISTER_INCLUDED + +#include "fileregisterfwd.h" +#include +#include + +namespace MOShared +{ + +class FileRegister +{ +public: + FileRegister(boost::shared_ptr originConnection); + + // noncopyable + FileRegister(const FileRegister&) = delete; + FileRegister& operator=(const FileRegister&) = delete; + + bool indexValid(FileIndex index) const; + + FileEntryPtr createFile( + std::wstring name, DirectoryEntry *parent, DirectoryStats& stats); + + FileEntryPtr getFile(FileIndex index) const; + + size_t highestCount() const + { + std::scoped_lock lock(m_Mutex); + return m_Files.size(); + } + + void reserve(std::size_t n) + { + m_Files.reserve(n); + } + + bool removeFile(FileIndex index); + void removeOrigin(FileIndex index, int originID); + void removeOriginMulti(std::set indices, int originID); + + void sortOrigins(); + +private: + using FileMap = std::vector; + + mutable std::mutex m_Mutex; + FileMap m_Files; + boost::shared_ptr m_OriginConnection; + std::atomic m_NextIndex; + + void unregisterFile(FileEntryPtr file); + FileIndex generateIndex(); +}; + +} // namespace + +#endif // MO_REGISTER_FILESREGISTER_INCLUDED diff --git a/src/shared/fileregisterfwd.h b/src/shared/fileregisterfwd.h new file mode 100644 index 00000000..b8d33378 --- /dev/null +++ b/src/shared/fileregisterfwd.h @@ -0,0 +1,89 @@ +#ifndef MO_REGISTER_FILEREGISTERFWD_INCLUDED +#define MO_REGISTER_FILEREGISTERFWD_INCLUDED + +namespace MOShared +{ + +struct DirectoryEntryFileKey +{ + DirectoryEntryFileKey(std::wstring v) + : value(std::move(v)), hash(getHash(value)) + { + } + + bool operator==(const DirectoryEntryFileKey& o) const + { + return (value == o.value); + } + + static std::size_t getHash(const std::wstring& value) + { + return std::hash()(value); + } + + std::wstring value; + const std::size_t hash; +}; + + +class DirectoryEntry; +class OriginConnection; +class FileRegister; +class FilesOrigin; +class FileEntry; +struct DirectoryStats; + +using FileEntryPtr = boost::shared_ptr; +using FileIndex = unsigned int; + +// a vector of {originId, {archiveName, order}} +// +// if a file is in an archive, archiveName is the name of the bsa and order +// is the order of the associated plugin in the plugins list +// +// is a file is not in an archive, archiveName is empty and order is usually +// -1 +using AlternativesVector = std::vector>>; + +struct DirectoryStats +{ + static constexpr bool EnableInstrumentation = false; + + std::string mod; + + std::chrono::nanoseconds dirTimes; + std::chrono::nanoseconds fileTimes; + std::chrono::nanoseconds sortTimes; + + std::chrono::nanoseconds subdirLookupTimes; + std::chrono::nanoseconds addDirectoryTimes; + + std::chrono::nanoseconds filesLookupTimes; + std::chrono::nanoseconds addFileTimes; + std::chrono::nanoseconds addOriginToFileTimes; + std::chrono::nanoseconds addFileToOriginTimes; + std::chrono::nanoseconds addFileToRegisterTimes; + + int64_t originExists; + int64_t originCreate; + int64_t originsNeededEnabled; + + int64_t subdirExists; + int64_t subdirCreate; + + int64_t fileExists; + int64_t fileCreate; + int64_t filesInsertedInRegister; + int64_t filesAssignedInRegister; + + DirectoryStats(); + + DirectoryStats& operator+=(const DirectoryStats& o); + + static std::string csvHeader(); + std::string toCsv() const; +}; + +} // namespace + +#endif // MO_REGISTER_FILEREGISTERFWD_INCLUDED diff --git a/src/shared/filesorigin.cpp b/src/shared/filesorigin.cpp new file mode 100644 index 00000000..47ae4b94 --- /dev/null +++ b/src/shared/filesorigin.cpp @@ -0,0 +1,137 @@ +#include "filesorigin.h" +#include "originconnection.h" +#include "fileregister.h" +#include "fileentry.h" + +namespace MOShared +{ + +std::wstring tail(const std::wstring &source, const size_t count) +{ + if (count >= source.length()) { + return source; + } + + return source.substr(source.length() - count); +} + + +FilesOrigin::FilesOrigin() + : m_ID(0), m_Disabled(false), m_Name(), m_Path(), m_Priority(0) +{ +} + +/*FilesOrigin::FilesOrigin(const FilesOrigin &reference) + : m_ID(reference.m_ID) + , m_Disabled(reference.m_Disabled) + , m_Name(reference.m_Name) + , m_Path(reference.m_Path) + , m_Priority(reference.m_Priority) + , m_FileRegister(reference.m_FileRegister) + , m_OriginConnection(reference.m_OriginConnection) +{ +}*/ + +FilesOrigin::FilesOrigin( + int ID, const std::wstring &name, const std::wstring &path, int priority, + boost::shared_ptr fileRegister, + boost::shared_ptr originConnection) : + m_ID(ID), m_Disabled(false), m_Name(name), m_Path(path), + m_Priority(priority), m_FileRegister(fileRegister), + m_OriginConnection(originConnection) +{ +} + +void FilesOrigin::setPriority(int priority) +{ + m_OriginConnection.lock()->changePriorityLookup(m_Priority, priority); + + m_Priority = priority; +} + +void FilesOrigin::setName(const std::wstring &name) +{ + m_OriginConnection.lock()->changeNameLookup(m_Name, name); + + // change path too + if (tail(m_Path, m_Name.length()) == m_Name) { + m_Path = m_Path.substr(0, m_Path.length() - m_Name.length()).append(name); + } + + m_Name = name; +} + +std::vector FilesOrigin::getFiles() const +{ + std::vector result; + + { + std::scoped_lock lock(m_Mutex); + + for (FileIndex fileIdx : m_Files) { + if (FileEntryPtr p = m_FileRegister.lock()->getFile(fileIdx)) { + result.push_back(p); + } + } + } + + return result; +} + +FileEntryPtr FilesOrigin::findFile(FileIndex index) const +{ + return m_FileRegister.lock()->getFile(index); +} + +void FilesOrigin::enable(bool enabled) +{ + DirectoryStats dummy; + enable(enabled, dummy); +} + +void FilesOrigin::enable(bool enabled, DirectoryStats& stats) +{ + if (!enabled) { + ++stats.originsNeededEnabled; + + std::set copy; + + { + std::scoped_lock lock(m_Mutex); + copy = m_Files; + m_Files.clear(); + } + + m_FileRegister.lock()->removeOriginMulti(copy, m_ID); + } + + m_Disabled = !enabled; +} + +void FilesOrigin::removeFile(FileIndex index) +{ + std::scoped_lock lock(m_Mutex); + + auto iter = m_Files.find(index); + + if (iter != m_Files.end()) { + m_Files.erase(iter); + } +} + +bool FilesOrigin::containsArchive(std::wstring archiveName) +{ + std::scoped_lock lock(m_Mutex); + + for (FileIndex fileIdx : m_Files) { + if (FileEntryPtr p = m_FileRegister.lock()->getFile(fileIdx)) { + if (p->isFromArchive(archiveName)) { + return true; + } + } + } + + return false; +} + +} // namespace diff --git a/src/shared/filesorigin.h b/src/shared/filesorigin.h new file mode 100644 index 00000000..4ea21f57 --- /dev/null +++ b/src/shared/filesorigin.h @@ -0,0 +1,87 @@ +#ifndef MO_REGISTER_FILESORIGIN_INCLUDED +#define MO_REGISTER_FILESORIGIN_INCLUDED + +#include "fileregisterfwd.h" + +namespace MOShared +{ + +// represents a mod or the data directory, providing files to the tree +class FilesOrigin +{ +public: + FilesOrigin(); +// FilesOrigin(const FilesOrigin &reference); + + FilesOrigin( + int ID, const std::wstring &name, const std::wstring &path, int priority, + boost::shared_ptr fileRegister, + boost::shared_ptr originConnection); + + // noncopyable + FilesOrigin(const FilesOrigin&) = delete; + FilesOrigin& operator=(const FilesOrigin&) = delete; + FilesOrigin(FilesOrigin&&) = default; + FilesOrigin& operator=(FilesOrigin&&) = default; + + // sets priority for this origin, but it will overwrite the existing mapping + // for this priority, the previous origin will no longer be referenced + void setPriority(int priority); + + int getPriority() const + { + return m_Priority; + } + + void setName(const std::wstring &name); + const std::wstring &getName() const + { + return m_Name; + } + + int getID() const + { + return m_ID; + } + + const std::wstring &getPath() const + { + return m_Path; + } + + std::vector getFiles() const; + FileEntryPtr findFile(FileIndex index) const; + + void enable(bool enabled, DirectoryStats& stats); + void enable(bool enabled); + + bool isDisabled() const + { + return m_Disabled; + } + + void addFile(FileIndex index) + { + std::scoped_lock lock(m_Mutex); + m_Files.insert(index); + } + + void removeFile(FileIndex index); + + bool containsArchive(std::wstring archiveName); + +private: + int m_ID; + bool m_Disabled; + std::set m_Files; + std::wstring m_Name; + std::wstring m_Path; + int m_Priority; + boost::weak_ptr m_FileRegister; + boost::weak_ptr m_OriginConnection; + mutable std::mutex m_Mutex; +}; + +} // namespace + +#endif // MO_REGISTER_FILESORIGIN_INCLUDED diff --git a/src/shared/originconnection.cpp b/src/shared/originconnection.cpp new file mode 100644 index 00000000..a56126cc --- /dev/null +++ b/src/shared/originconnection.cpp @@ -0,0 +1,145 @@ +#include "originconnection.h" +#include "filesorigin.h" +#include "util.h" +#include + +namespace MOShared +{ + +using namespace MOBase; + +OriginConnection::OriginConnection() + : m_NextID(0) +{ +} + +std::pair OriginConnection::getOrCreate( + const std::wstring &originName, const std::wstring &directory, int priority, + const boost::shared_ptr& fileRegister, + const boost::shared_ptr& originConnection, + DirectoryStats& stats) +{ + std::unique_lock lock(m_Mutex); + + auto itor = m_OriginsNameMap.find(originName); + + if (itor == m_OriginsNameMap.end()) { + FilesOrigin& origin = createOriginNoLock( + originName, directory, priority, fileRegister, originConnection); + + return {origin, true}; + } else { + FilesOrigin& origin = m_Origins[itor->second]; + lock.unlock(); + + origin.enable(true, stats); + return {origin, false}; + } +} + +FilesOrigin& OriginConnection::createOrigin( + const std::wstring &originName, const std::wstring &directory, int priority, + boost::shared_ptr fileRegister, + boost::shared_ptr originConnection) +{ + std::scoped_lock lock(m_Mutex); + + return createOriginNoLock( + originName, directory, priority, fileRegister, originConnection); +} + +bool OriginConnection::exists(const std::wstring &name) +{ + std::scoped_lock lock(m_Mutex); + return m_OriginsNameMap.find(name) != m_OriginsNameMap.end(); +} + +FilesOrigin& OriginConnection::getByID(Index ID) +{ + std::scoped_lock lock(m_Mutex); + return m_Origins[ID]; +} + +const FilesOrigin* OriginConnection::findByID(Index ID) const +{ + std::scoped_lock lock(m_Mutex); + + auto itor = m_Origins.find(ID); + + if (itor == m_Origins.end()) { + return nullptr; + } else { + return &itor->second; + } +} + +FilesOrigin& OriginConnection::getByName(const std::wstring &name) +{ + std::scoped_lock lock(m_Mutex); + + std::map::iterator iter = m_OriginsNameMap.find(name); + + if (iter != m_OriginsNameMap.end()) { + return m_Origins[iter->second]; + } else { + std::ostringstream stream; + stream << QObject::tr("invalid origin name: ").toStdString() << ToString(name, true); + throw std::runtime_error(stream.str()); + } +} + +void OriginConnection::changePriorityLookup(int oldPriority, int newPriority) +{ + std::scoped_lock lock(m_Mutex); + + auto iter = m_OriginsPriorityMap.find(oldPriority); + + if (iter != m_OriginsPriorityMap.end()) { + Index idx = iter->second; + m_OriginsPriorityMap.erase(iter); + m_OriginsPriorityMap[newPriority] = idx; + } +} + +void OriginConnection::changeNameLookup(const std::wstring &oldName, const std::wstring &newName) +{ + std::scoped_lock lock(m_Mutex); + + auto iter = m_OriginsNameMap.find(oldName); + + if (iter != m_OriginsNameMap.end()) { + Index idx = iter->second; + m_OriginsNameMap.erase(iter); + m_OriginsNameMap[newName] = idx; + } else { + log::error(QObject::tr("failed to change name lookup from {} to {}").toStdString(), oldName, newName); + } +} + +OriginConnection::Index OriginConnection::createID() +{ + return m_NextID++; +} + +FilesOrigin& OriginConnection::createOriginNoLock( + const std::wstring &originName, const std::wstring &directory, int priority, + boost::shared_ptr fileRegister, + boost::shared_ptr originConnection) +{ + int newID = createID(); + + auto itor = m_Origins.emplace( + std::piecewise_construct, + std::forward_as_tuple(newID), + std::forward_as_tuple( + newID, originName, directory, priority, + fileRegister, originConnection)) + .first; + + m_OriginsNameMap.insert({originName, newID}); + m_OriginsPriorityMap.insert({priority, newID}); + + return itor->second; +} + +} // namespace diff --git a/src/shared/originconnection.h b/src/shared/originconnection.h new file mode 100644 index 00000000..1fbb07ac --- /dev/null +++ b/src/shared/originconnection.h @@ -0,0 +1,59 @@ +#ifndef MO_REGISTER_ORIGINCONNECTION_INCLUDED +#define MO_REGISTER_ORIGINCONNECTION_INCLUDED + +#include "fileregisterfwd.h" + +namespace MOShared +{ + +class OriginConnection +{ +public: + typedef int Index; + static const int INVALID_INDEX = INT_MIN; + + OriginConnection(); + + // noncopyable + OriginConnection(const OriginConnection&) = delete; + OriginConnection& operator=(const OriginConnection&) = delete; + + std::pair getOrCreate( + const std::wstring &originName, const std::wstring &directory, int priority, + const boost::shared_ptr& fileRegister, + const boost::shared_ptr& originConnection, + DirectoryStats& stats); + + FilesOrigin& createOrigin( + const std::wstring &originName, const std::wstring &directory, int priority, + boost::shared_ptr fileRegister, + boost::shared_ptr originConnection); + + bool exists(const std::wstring &name); + + FilesOrigin &getByID(Index ID); + const FilesOrigin* findByID(Index ID) const; + FilesOrigin &getByName(const std::wstring &name); + + void changePriorityLookup(int oldPriority, int newPriority); + + void changeNameLookup(const std::wstring &oldName, const std::wstring &newName); + +private: + Index m_NextID; + std::map m_Origins; + std::map m_OriginsNameMap; + std::map m_OriginsPriorityMap; + mutable std::mutex m_Mutex; + + Index createID(); + + FilesOrigin& createOriginNoLock( + const std::wstring &originName, const std::wstring &directory, int priority, + boost::shared_ptr fileRegister, + boost::shared_ptr originConnection); +}; + +} // namespace + +#endif // MO_REGISTER_ORIGINCONNECTION_INCLUDED diff --git a/src/syncoverwritedialog.cpp b/src/syncoverwritedialog.cpp index b1643b2d..0afb1121 100644 --- a/src/syncoverwritedialog.cpp +++ b/src/syncoverwritedialog.cpp @@ -18,8 +18,11 @@ along with Mod Organizer. If not, see . */ #include "syncoverwritedialog.h" - +#include "shared/directoryentry.h" +#include "shared/fileentry.h" +#include "shared/filesorigin.h" #include "ui_syncoverwritedialog.h" + #include #include #include @@ -92,7 +95,7 @@ void SyncOverwriteDialog::readTree(const QString &path, DirectoryEntry *director newItem = nullptr; } } else { - const FileEntry::Ptr entry = directoryStructure->findFile(ToWString(file)); + const FileEntryPtr entry = directoryStructure->findFile(ToWString(file)); QComboBox* combo = new QComboBox(ui->syncTree); combo->addItem(tr(""), -1); if (entry.get() != nullptr) { diff --git a/src/syncoverwritedialog.h b/src/syncoverwritedialog.h index 79b30a8d..cb4c92fb 100644 --- a/src/syncoverwritedialog.h +++ b/src/syncoverwritedialog.h @@ -20,11 +20,9 @@ along with Mod Organizer. If not, see . #ifndef SYNCOVERWRITEDIALOG_H #define SYNCOVERWRITEDIALOG_H - #include "tutorabledialog.h" +#include "shared/fileregisterfwd.h" #include -#include - namespace Ui { class SyncOverwriteDialog; @@ -33,9 +31,12 @@ class SyncOverwriteDialog; class SyncOverwriteDialog : public MOBase::TutorableDialog { Q_OBJECT - + public: - explicit SyncOverwriteDialog(const QString &path, MOShared::DirectoryEntry *directoryStructure, QWidget *parent = 0); + explicit SyncOverwriteDialog( + const QString &path, MOShared::DirectoryEntry *directoryStructure, + QWidget *parent = 0); + ~SyncOverwriteDialog(); void apply(const QString &modDirectory); -- cgit v1.3.1 From 5e569d0107aefe292b76ac0458f9420077f350a0 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sat, 15 Feb 2020 17:22:12 -0500 Subject: re-enabled archive parsing --- src/directoryrefresher.cpp | 126 ++++++++++++++++++++------------- src/mainwindow.cpp | 1 + src/shared/directoryentry.cpp | 161 ++++++++++++++++++++++++------------------ src/shared/directoryentry.h | 79 ++++++++++++--------- src/shared/util.h | 10 +++ 5 files changed, 223 insertions(+), 154 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index 8a64d4a9..5e1c05a8 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -210,38 +210,41 @@ void DirectoryRefresher::cleanStructure(DirectoryEntry *structure) } } -void DirectoryRefresher::addModBSAToStructure(DirectoryEntry *directoryStructure, const QString &modName, - int priority, const QString &directory, const QStringList &archives) +void DirectoryRefresher::addModBSAToStructure( + DirectoryEntry* root, const QString& modName, + int priority, const QString& directory, const QStringList& archives) { - std::wstring directoryW = ToWString(QDir::toNativeSeparators(directory)); - IPluginGame *game = qApp->property("managed_game").value(); + const IPluginGame *game = qApp->property("managed_game").value(); GamePlugins *gamePlugins = game->feature(); QStringList loadOrder = QStringList(); gamePlugins->getLoadOrder(loadOrder); - for (const QString &archive : archives) { - QFileInfo fileInfo(archive); - if (m_EnabledArchives.find(fileInfo.fileName()) != m_EnabledArchives.end()) { - - int order = -1; + std::vector lo; + for (auto&& s : loadOrder) { + lo.push_back(s.toStdWString()); + } - for (auto plugin : loadOrder) - { - QString name = plugin.left(plugin.size() - 4); - if (fileInfo.fileName().startsWith(name + " - ", Qt::CaseInsensitive) || fileInfo.fileName().startsWith(name + ".", Qt::CaseInsensitive)) { - order = loadOrder.indexOf(plugin); - } - } + std::vector archivesW; + for (auto&& a : archives) { + archivesW.push_back(a.toStdWString()); + } - try { - IPluginGame *game = qApp->property("managed_game").value(); - directoryStructure->addFromBSA(ToWString(modName), directoryW, ToWString(QDir::toNativeSeparators(fileInfo.absoluteFilePath())), priority, order); - } catch (const std::exception &e) { - throw MyException(tr("failed to parse bsa %1: %2").arg(archive, e.what())); - } - } + std::set enabledArchives; + for (auto&& a : m_EnabledArchives) { + enabledArchives.insert(a.toStdWString()); } + + DirectoryStats dummy; + + root->addFromAllBSAs( + modName.toStdWString(), + QDir::toNativeSeparators(directory).toStdWString(), + priority, + archivesW, + enabledArchives, + lo, + dummy); } void DirectoryRefresher::stealModFilesIntoStructure( @@ -329,6 +332,8 @@ struct ModThread std::wstring modName; std::wstring path; int prio = -1; + std::vector archives; + std::set enabledArchives; DirectoryStats* stats = nullptr; env::DirectoryWalker walker; @@ -354,14 +359,21 @@ struct ModThread SetThisThreadName(QString::fromStdWString(modName + L" refresher")); ds->addFromOrigin(walker, modName, path, prio, *stats); - /*if (Settings::instance().archiveParsing()) { - addModBSAToStructure( - directoryStructure, - entries[i].modName, - prio, - entries[i].absolutePath, - entries[i].archives); - }*/ + if (Settings::instance().archiveParsing()) { + const IPluginGame *game = qApp->property("managed_game").value(); + + GamePlugins *gamePlugins = game->feature(); + QStringList loadOrder = QStringList(); + gamePlugins->getLoadOrder(loadOrder); + + std::vector lo; + for (auto&& s : loadOrder) { + lo.push_back(s.toStdWString()); + } + + ds->addFromAllBSAs( + modName, path, prio, archives, enabledArchives, lo, *stats); + } ready = false; } @@ -377,6 +389,7 @@ void DirectoryRefresher::addMultipleModsFilesToStructure( { std::vector stats(entries.size()); + log::debug("refresher: using {} threads", m_threadCount); g_threads.setMax(m_threadCount); for (std::size_t i=0; igetFileRegister()->reserve(m_lastFileCount); + m_Root.reset(new DirectoryEntry(L"data", nullptr, 0)); + m_Root->getFileRegister()->reserve(m_lastFileCount); - IPluginGame *game = qApp->property("managed_game").value(); + IPluginGame *game = qApp->property("managed_game").value(); - std::wstring dataDirectory = - QDir::toNativeSeparators(game->dataDirectory().absolutePath()).toStdWString(); + std::wstring dataDirectory = + QDir::toNativeSeparators(game->dataDirectory().absolutePath()).toStdWString(); - { - DirectoryStats dummy; - m_Root->addFromOrigin(L"data", dataDirectory, 0, dummy); - } + { + DirectoryStats dummy; + m_Root->addFromOrigin(L"data", dataDirectory, 0, dummy); + } - std::sort(m_Mods.begin(), m_Mods.end(), [](auto lhs, auto rhs) { - return lhs.priority < rhs.priority; - }); + std::sort(m_Mods.begin(), m_Mods.end(), [](auto lhs, auto rhs) { + return lhs.priority < rhs.priority; + }); - addMultipleModsFilesToStructure(m_Root.get(), m_Mods, true); + addMultipleModsFilesToStructure(m_Root.get(), m_Mods, true); - m_Root->getFileRegister()->sortOrigins(); + m_Root->getFileRegister()->sortOrigins(); - cleanStructure(m_Root.get()); + cleanStructure(m_Root.get()); - m_lastFileCount = m_Root->getFileRegister()->highestCount(); - log::debug("refresher saw {} files", m_lastFileCount); + m_lastFileCount = m_Root->getFileRegister()->highestCount(); + log::debug("refresher saw {} files", m_lastFileCount); + } emit progress(100); emit refreshed(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index adbac94e..f5749392 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -87,6 +87,7 @@ along with Mod Organizer. If not, see . #include "envshortcut.h" #include "browserdialog.h" +#include "directoryrefresher.h" #include "shared/directoryentry.h" #include "shared/fileentry.h" #include "shared/filesorigin.h" diff --git a/src/shared/directoryentry.cpp b/src/shared/directoryentry.cpp index 7f140750..84d68675 100644 --- a/src/shared/directoryentry.cpp +++ b/src/shared/directoryentry.cpp @@ -67,14 +67,14 @@ static bool SupportOptimizedFind() return (::VerifyVersionInfo(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, mask) == TRUE); } -static bool DirCompareByName(const DirectoryEntry *lhs, const DirectoryEntry *rhs) +static bool DirCompareByName(const DirectoryEntry* lhs, const DirectoryEntry* rhs) { return _wcsicmp(lhs->getName().c_str(), rhs->getName().c_str()) < 0; } DirectoryEntry::DirectoryEntry( - std::wstring name, DirectoryEntry *parent, int originID) : + std::wstring name, DirectoryEntry* parent, int originID) : m_OriginConnection(new OriginConnection), m_Name(std::move(name)), m_Parent(parent), m_Populated(false), m_TopLevel(true) { @@ -83,7 +83,7 @@ DirectoryEntry::DirectoryEntry( } DirectoryEntry::DirectoryEntry( - std::wstring name, DirectoryEntry *parent, int originID, + std::wstring name, DirectoryEntry* parent, int originID, boost::shared_ptr fileRegister, boost::shared_ptr originConnection) : m_FileRegister(fileRegister), m_OriginConnection(originConnection), @@ -166,51 +166,69 @@ void DirectoryEntry::addDir( m_Populated = true; } -void DirectoryEntry::addFromBSA( - const std::wstring &originName, std::wstring &directory, - const std::wstring &fileName, int priority, int order) +void DirectoryEntry::addFromAllBSAs( + const std::wstring& originName, const std::wstring& directory, + int priority, const std::vector& archives, + const std::set& enabledArchives, + const std::vector& loadOrder, + DirectoryStats& stats) { - DirectoryStats dummy; - FilesOrigin &origin = createOrigin(originName, directory, priority, dummy); + for (const auto& archive : archives) { + const std::filesystem::path archivePath(archive); + const auto filename = archivePath.filename().native(); - WIN32_FILE_ATTRIBUTE_DATA fileData; - if (::GetFileAttributesExW(fileName.c_str(), GetFileExInfoStandard, &fileData) == 0) { - throw windows_error(QObject::tr("failed to determine file time").toStdString()); - } + if (!enabledArchives.contains(filename)) { + continue; + } - FILETIME now; - ::GetSystemTimeAsFileTime(&now); + const auto filenameLc = ToLowerCopy(filename); - const double clfSecondsPer100ns = 100. * 1.E-9; + int order = -1; - ((ULARGE_INTEGER *)&now)->QuadPart -= ((double)5) / clfSecondsPer100ns; + for (auto plugin : loadOrder) + { + const auto pluginNameLc = + ToLowerCopy(std::filesystem::path(plugin).stem().native()); + + if (filenameLc.starts_with(pluginNameLc + L" - ") || + filenameLc.starts_with(pluginNameLc + L".")) { + auto itor = std::find(loadOrder.begin(), loadOrder.end(), plugin); + if (itor != loadOrder.end()) { + order = std::distance(loadOrder.begin(), itor); + } + } + } - size_t namePos = fileName.find_last_of(L"\\/"); - if (namePos == std::wstring::npos) { - namePos = 0; + addFromBSA( + originName, directory, archivePath.native(), + priority, order, stats); } - else { - ++namePos; +} + +void DirectoryEntry::addFromBSA( + const std::wstring& originName, const std::wstring& directory, + const std::wstring& archivePath, int priority, int order, DirectoryStats& stats) +{ + FilesOrigin& origin = createOrigin(originName, directory, priority, stats); + const auto archiveName = std::filesystem::path(archivePath).filename().native(); + + if (containsArchive(archiveName)) { + return; } - if (!containsArchive(fileName.substr(namePos)) || ::CompareFileTime(&fileData.ftLastWriteTime, &now) > 0) { - BSA::Archive archive; - BSA::EErrorCode res = archive.read(ToString(fileName, false).c_str(), false); + BSA::Archive archive; + BSA::EErrorCode res = archive.read(ToString(archivePath, false).c_str(), false); - if ((res != BSA::ERROR_NONE) && (res != BSA::ERROR_INVALIDHASHES)) { - std::ostringstream stream; + if ((res != BSA::ERROR_NONE) && (res != BSA::ERROR_INVALIDHASHES)) { + log::error("invalid bsa '{}', error {}", archivePath, res); + return; + } - stream - << QObject::tr("invalid bsa file: ").toStdString() - << ToString(fileName, false) - << " error code " << res << " - " << ::GetLastError(); + const auto ft = ToFILETIME(std::filesystem::last_write_time(archivePath)); - throw std::runtime_error(stream.str()); - } + addFiles(origin, archive.getRoot(), ft, archiveName, order, stats); - addFiles(origin, archive.getRoot(), fileData.ftLastWriteTime, fileName.substr(namePos), order); - m_Populated = true; - } + m_Populated = true; } void DirectoryEntry::propagateOrigin(int origin) @@ -258,7 +276,7 @@ int DirectoryEntry::anyOrigin() const // if we got here, no file directly within this directory is a valid indicator for a mod, thus // we continue looking in subdirectories - for (DirectoryEntry *entry : m_SubDirectories) { + for (DirectoryEntry* entry : m_SubDirectories) { int res = entry->anyOrigin(); if (res != InvalidOriginID){ return res; @@ -279,7 +297,7 @@ std::vector DirectoryEntry::getFiles() const return result; } -DirectoryEntry *DirectoryEntry::findSubDirectory( +DirectoryEntry* DirectoryEntry::findSubDirectory( const std::wstring &name, bool alreadyLowerCase) const { SubDirectoriesLookup::const_iterator itor; @@ -297,9 +315,10 @@ DirectoryEntry *DirectoryEntry::findSubDirectory( return itor->second; } -DirectoryEntry *DirectoryEntry::findSubDirectoryRecursive(const std::wstring &path) +DirectoryEntry* DirectoryEntry::findSubDirectoryRecursive(const std::wstring &path) { - return getSubDirectoryRecursive(path, false, InvalidOriginID); + DirectoryStats dummy; + return getSubDirectoryRecursive(path, false, dummy, InvalidOriginID); } const FileEntryPtr DirectoryEntry::findFile( @@ -349,7 +368,7 @@ bool DirectoryEntry::containsArchive(std::wstring archiveName) } const FileEntryPtr DirectoryEntry::searchFile( - const std::wstring &path, const DirectoryEntry **directory) const + const std::wstring &path, const DirectoryEntry** directory) const { if (directory != nullptr) { *directory = nullptr; @@ -373,7 +392,7 @@ const FileEntryPtr DirectoryEntry::searchFile( if (iter != m_Files.end()) { return m_FileRegister->getFile(iter->second); } else if (directory != nullptr) { - DirectoryEntry *temp = findSubDirectory(path); + DirectoryEntry* temp = findSubDirectory(path); if (temp != nullptr) { *directory = temp; } @@ -381,7 +400,7 @@ const FileEntryPtr DirectoryEntry::searchFile( } else { // file is in a subdirectory, recurse into the matching subdirectory std::wstring pathComponent = path.substr(0, len); - DirectoryEntry *temp = findSubDirectory(pathComponent); + DirectoryEntry* temp = findSubDirectory(pathComponent); if (temp != nullptr) { if (len >= path.size()) { @@ -401,7 +420,7 @@ void DirectoryEntry::removeFile(FileIndex index) removeFileFromList(index); } -bool DirectoryEntry::removeFile(const std::wstring &filePath, int *origin) +bool DirectoryEntry::removeFile(const std::wstring &filePath, int* origin) { size_t pos = filePath.find_first_of(L"\\/"); @@ -411,7 +430,9 @@ bool DirectoryEntry::removeFile(const std::wstring &filePath, int *origin) std::wstring dirName = filePath.substr(0, pos); std::wstring rest = filePath.substr(pos + 1); - DirectoryEntry *entry = getSubDirectoryRecursive(dirName, false); + + DirectoryStats dummy; + DirectoryEntry* entry = getSubDirectoryRecursive(dirName, false, dummy); if (entry != nullptr) { return entry->removeFile(rest, origin); @@ -426,7 +447,7 @@ void DirectoryEntry::removeDir(const std::wstring &path) if (pos == std::string::npos) { for (auto iter = m_SubDirectories.begin(); iter != m_SubDirectories.end(); ++iter) { - DirectoryEntry *entry = *iter; + DirectoryEntry* entry = *iter; if (CaseInsensitiveEqual(entry->getName(), path)) { entry->removeDirRecursive(); @@ -438,7 +459,9 @@ void DirectoryEntry::removeDir(const std::wstring &path) } else { std::wstring dirName = path.substr(0, pos); std::wstring rest = path.substr(pos + 1); - DirectoryEntry *entry = getSubDirectoryRecursive(dirName, false); + + DirectoryStats dummy; + DirectoryEntry* entry = getSubDirectoryRecursive(dirName, false, dummy); if (entry != nullptr) { entry->removeDir(rest); @@ -446,7 +469,7 @@ void DirectoryEntry::removeDir(const std::wstring &path) } } -bool DirectoryEntry::remove(const std::wstring &fileName, int *origin) +bool DirectoryEntry::remove(const std::wstring &fileName, int* origin) { const auto lcFileName = ToLowerCopy(fileName); @@ -661,18 +684,17 @@ void DirectoryEntry::onFile(Context* cx, std::wstring_view path, FILETIME ft) } void DirectoryEntry::addFiles( - FilesOrigin &origin, BSA::Folder::Ptr archiveFolder, FILETIME &fileTime, - const std::wstring &archiveName, int order) + FilesOrigin& origin, const BSA::Folder::Ptr archiveFolder, FILETIME fileTime, + const std::wstring& archiveName, int order, DirectoryStats& stats) { - DirectoryStats dummy; - // add files - for (unsigned int fileIdx = 0; fileIdx < archiveFolder->getNumFiles(); ++fileIdx) { - BSA::File::Ptr file = archiveFolder->getFile(fileIdx); + const auto fileCount = archiveFolder->getNumFiles(); + for (unsigned int i=0; igetFile(i); auto f = insert( ToWString(file->getName(), true), origin, fileTime, - archiveName, order, dummy); + archiveName, order, stats); if (f) { if (file->getUncompressedFileSize() > 0) { @@ -684,16 +706,18 @@ void DirectoryEntry::addFiles( } // recurse into subdirectories - for (unsigned int folderIdx = 0; folderIdx < archiveFolder->getNumSubFolders(); ++folderIdx) { - BSA::Folder::Ptr folder = archiveFolder->getSubFolder(folderIdx); - DirectoryEntry *folderEntry = getSubDirectoryRecursive( - ToWString(folder->getName(), true), true, origin.getID()); + const auto dirCount = archiveFolder->getNumSubFolders(); + for (unsigned int i=0; igetSubFolder(i); + + DirectoryEntry* folderEntry = getSubDirectoryRecursive( + ToWString(folder->getName(), true), true, stats, origin.getID()); - folderEntry->addFiles(origin, folder, fileTime, archiveName, order); + folderEntry->addFiles(origin, folder, fileTime, archiveName, order, stats); } } -DirectoryEntry *DirectoryEntry::getSubDirectory( +DirectoryEntry* DirectoryEntry::getSubDirectory( std::wstring_view name, bool create, DirectoryStats& stats, int originID) { std::wstring nameLc = ToLowerCopy(name); @@ -728,7 +752,7 @@ DirectoryEntry *DirectoryEntry::getSubDirectory( } } -DirectoryEntry *DirectoryEntry::getSubDirectory( +DirectoryEntry* DirectoryEntry::getSubDirectory( env::Directory& dir, bool create, DirectoryStats& stats, int originID) { SubDirectoriesLookup::iterator itor; @@ -764,8 +788,8 @@ DirectoryEntry *DirectoryEntry::getSubDirectory( } } -DirectoryEntry *DirectoryEntry::getSubDirectoryRecursive( - const std::wstring &path, bool create, int originID) +DirectoryEntry* DirectoryEntry::getSubDirectoryRecursive( + const std::wstring& path, bool create, DirectoryStats& stats, int originID) { if (path.length() == 0) { // path ended with a backslash? @@ -773,19 +797,18 @@ DirectoryEntry *DirectoryEntry::getSubDirectoryRecursive( } const size_t pos = path.find_first_of(L"\\/"); - DirectoryStats dummy; if (pos == std::wstring::npos) { - return getSubDirectory(path, create, dummy); + return getSubDirectory(path, create, stats); } else { - DirectoryEntry *nextChild = getSubDirectory( - path.substr(0, pos), create, dummy, originID); + DirectoryEntry* nextChild = getSubDirectory( + path.substr(0, pos), create, stats, originID); if (nextChild == nullptr) { return nullptr; } else { return nextChild->getSubDirectoryRecursive( - path.substr(pos + 1), create, originID); + path.substr(pos + 1), create, stats, originID); } } } @@ -798,7 +821,7 @@ void DirectoryEntry::removeDirRecursive() m_FilesLookup.clear(); - for (DirectoryEntry *entry : m_SubDirectories) { + for (DirectoryEntry* entry : m_SubDirectories) { entry->removeDirRecursive(); delete entry; } diff --git a/src/shared/directoryentry.h b/src/shared/directoryentry.h index 5ca7389d..a28ceeae 100644 --- a/src/shared/directoryentry.h +++ b/src/shared/directoryentry.h @@ -50,10 +50,10 @@ class DirectoryEntry { public: DirectoryEntry( - std::wstring name, DirectoryEntry *parent, OriginID originID); + std::wstring name, DirectoryEntry* parent, OriginID originID); DirectoryEntry( - std::wstring name, DirectoryEntry *parent, OriginID originID, + std::wstring name, DirectoryEntry* parent, OriginID originID, boost::shared_ptr fileRegister, boost::shared_ptr originConnection); @@ -85,7 +85,7 @@ public: return !m_Files.empty(); } - const DirectoryEntry *getParent() const + const DirectoryEntry* getParent() const { return m_Parent; } @@ -93,24 +93,32 @@ public: // add files to this directory (and subdirectories) from the specified origin. // That origin may exist or not void addFromOrigin( - const std::wstring &originName, - const std::wstring &directory, int priority, DirectoryStats& stats); + const std::wstring& originName, + const std::wstring& directory, int priority, DirectoryStats& stats); void addFromOrigin( - env::DirectoryWalker& walker, const std::wstring &originName, - const std::wstring &directory, int priority, DirectoryStats& stats); + env::DirectoryWalker& walker, const std::wstring& originName, + const std::wstring& directory, int priority, DirectoryStats& stats); + + void addFromAllBSAs( + const std::wstring& originName, const std::wstring& directory, + int priority, const std::vector& archives, + const std::set& enabledArchives, + const std::vector& loadOrder, + DirectoryStats& stats); void addFromBSA( - const std::wstring &originName, std::wstring &directory, - const std::wstring &fileName, int priority, int order); + const std::wstring& originName, const std::wstring& directory, + const std::wstring& archivePath, int priority, int order, + DirectoryStats& stats); void addFromList( - const std::wstring &originName, const std::wstring &directory, + const std::wstring& originName, const std::wstring& directory, env::Directory& root, int priority, DirectoryStats& stats); void propagateOrigin(OriginID origin); - const std::wstring &getName() const + const std::wstring& getName() const { return m_Name; } @@ -120,9 +128,9 @@ public: return m_FileRegister; } - bool originExists(const std::wstring &name) const; - FilesOrigin &getOriginByID(OriginID ID) const; - FilesOrigin &getOriginByName(const std::wstring &name) const; + bool originExists(const std::wstring& name) const; + FilesOrigin& getOriginByID(OriginID ID) const; + FilesOrigin& getOriginByName(const std::wstring& name) const; const FilesOrigin* findOriginByID(OriginID ID) const; OriginID anyOrigin() const; @@ -130,8 +138,8 @@ public: std::vector getFiles() const; void getSubDirectories( - std::vector::const_iterator &begin, - std::vector::const_iterator &end) const + std::vector::const_iterator& begin, + std::vector::const_iterator& end) const { begin = m_SubDirectories.begin(); end = m_SubDirectories.end(); @@ -179,16 +187,16 @@ public: return m_FileRegister->getFile(index); } - DirectoryEntry *findSubDirectory( - const std::wstring &name, bool alreadyLowerCase=false) const; + DirectoryEntry* findSubDirectory( + const std::wstring& name, bool alreadyLowerCase=false) const; - DirectoryEntry *findSubDirectoryRecursive(const std::wstring &path); + DirectoryEntry* findSubDirectoryRecursive(const std::wstring& path); /** retrieve a file in this directory by name. * @param name name of the file * @return fileentry object for the file or nullptr if no file matches */ - const FileEntryPtr findFile(const std::wstring &name, bool alreadyLowerCase=false) const; + const FileEntryPtr findFile(const std::wstring& name, bool alreadyLowerCase=false) const; const FileEntryPtr findFile(const DirectoryEntryFileKey& key) const; bool hasFile(const std::wstring& name) const; @@ -201,29 +209,29 @@ public: // path containing the file // const FileEntryPtr searchFile( - const std::wstring &path, const DirectoryEntry **directory=nullptr) const; + const std::wstring& path, const DirectoryEntry** directory=nullptr) const; void removeFile(FileIndex index); // remove the specified file from the tree. This can be a path leading to a // file in a subdirectory - bool removeFile(const std::wstring &filePath, OriginID *origin = nullptr); + bool removeFile(const std::wstring& filePath, OriginID* origin = nullptr); /** * @brief remove the specified directory * @param path directory to remove */ - void removeDir(const std::wstring &path); + void removeDir(const std::wstring& path); - bool remove(const std::wstring &fileName, OriginID *origin); + bool remove(const std::wstring& fileName, OriginID* origin); bool hasContentsFromOrigin(OriginID originID) const; - FilesOrigin &createOrigin( - const std::wstring &originName, - const std::wstring &directory, int priority, DirectoryStats& stats); + FilesOrigin& createOrigin( + const std::wstring& originName, + const std::wstring& directory, int priority, DirectoryStats& stats); - void removeFiles(const std::set &indices); + void removeFiles(const std::set& indices); void dump(const std::wstring& file) const; @@ -242,7 +250,7 @@ private: SubDirectories m_SubDirectories; SubDirectoriesLookup m_SubDirectoriesLookup; - DirectoryEntry *m_Parent; + DirectoryEntry* m_Parent; std::set m_Origins; bool m_Populated; bool m_TopLevel; @@ -252,20 +260,20 @@ private: FileEntryPtr insert( - std::wstring_view fileName, FilesOrigin &origin, FILETIME fileTime, + std::wstring_view fileName, FilesOrigin& origin, FILETIME fileTime, std::wstring_view archive, int order, DirectoryStats& stats); FileEntryPtr insert( - env::File& file, FilesOrigin &origin, + env::File& file, FilesOrigin& origin, std::wstring_view archive, int order, DirectoryStats& stats); void addFiles( - env::DirectoryWalker& walker, FilesOrigin &origin, + env::DirectoryWalker& walker, FilesOrigin& origin, const std::wstring& path, DirectoryStats& stats); void addFiles( - FilesOrigin &origin, BSA::Folder::Ptr archiveFolder, FILETIME &fileTime, - const std::wstring &archiveName, int order); + FilesOrigin& origin, BSA::Folder::Ptr archiveFolder, FILETIME fileTime, + const std::wstring& archiveName, int order, DirectoryStats& stats); void addDir(FilesOrigin& origin, env::Directory& d, DirectoryStats& stats); @@ -278,7 +286,8 @@ private: OriginID originID = InvalidOriginID); DirectoryEntry* getSubDirectoryRecursive( - const std::wstring &path, bool create, OriginID originID = InvalidOriginID); + const std::wstring& path, bool create, DirectoryStats& stats, + OriginID originID = InvalidOriginID); void removeDirRecursive(); diff --git a/src/shared/util.h b/src/shared/util.h index dc6e72ad..1d3cce82 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -21,6 +21,7 @@ along with Mod Organizer. If not, see . #define UTIL_H #include +#include #include class Executable; @@ -51,6 +52,15 @@ QString getUsvfsVersionString(); void SetThisThreadName(const QString& s); void checkDuplicateShortcuts(const QMenu& m); +inline FILETIME ToFILETIME(std::filesystem::file_time_type t) +{ + FILETIME ft; + static_assert(sizeof(t) == sizeof(ft)); + + std::memcpy(&ft, &t, sizeof(FILETIME)); + return ft; +} + } // namespace MOShared -- cgit v1.3.1 From d3fe9ff1faed52da8f647d9294e9ce371b0361e4 Mon Sep 17 00:00:00 2001 From: isanae <14251494+isanae@users.noreply.github.com> Date: Sun, 16 Feb 2020 18:57:38 -0500 Subject: moved TimeThis to uibase fixed progress bar --- src/directoryrefresher.cpp | 34 +++++++++++++++----- src/directoryrefresher.h | 74 ++++++++++++++++++++++++++++++++++++++++---- src/mainwindow.cpp | 16 +++++++--- src/mainwindow.h | 4 ++- src/shared/fileregisterfwd.h | 2 ++ src/shared/util.cpp | 20 ------------ src/shared/util.h | 15 +-------- 7 files changed, 113 insertions(+), 52 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/directoryrefresher.cpp b/src/directoryrefresher.cpp index 5e1c05a8..599dd815 100644 --- a/src/directoryrefresher.cpp +++ b/src/directoryrefresher.cpp @@ -326,8 +326,10 @@ void DirectoryRefresher::addModToStructure(DirectoryEntry *directoryStructure } } + struct ModThread { + DirectoryRefreshProgress* progress = nullptr; DirectoryEntry* ds = nullptr; std::wstring modName; std::wstring path; @@ -375,6 +377,11 @@ struct ModThread modName, path, prio, archives, enabledArchives, lo, *stats); } + if (progress) { + progress->addDone(); + } + + SetThisThreadName(QString::fromStdWString(L"idle refresher")); ready = false; } }; @@ -382,13 +389,22 @@ struct ModThread env::ThreadPool g_threads; +void DirectoryRefresher::updateProgress(const DirectoryRefreshProgress* p) +{ + // careful: called from multiple threads + emit progress(p); +} void DirectoryRefresher::addMultipleModsFilesToStructure( MOShared::DirectoryEntry *directoryStructure, - const std::vector& entries, bool emitProgress) + const std::vector& entries, DirectoryRefreshProgress* progress) { std::vector stats(entries.size()); + if (progress) { + progress->start(entries.size()); + } + log::debug("refresher: using {} threads", m_threadCount); g_threads.setMax(m_threadCount); @@ -405,9 +421,14 @@ void DirectoryRefresher::addMultipleModsFilesToStructure( if (e.stealFiles.length() > 0) { stealModFilesIntoStructure( directoryStructure, e.modName, prio, e.absolutePath, e.stealFiles); + + if (progress) { + progress->addDone(); + } } else { auto& mt = g_threads.request(); + mt.progress = progress; mt.ds = directoryStructure; mt.modName = e.modName.toStdWString(); mt.path = QDir::toNativeSeparators(e.absolutePath).toStdWString(); @@ -430,10 +451,6 @@ void DirectoryRefresher::addMultipleModsFilesToStructure( } catch (const std::exception& ex) { emit error(tr("failed to read mod (%1): %2").arg(e.modName, ex.what())); } - - if (emitProgress) { - emit progress((static_cast(i) * 100) / static_cast(entries.size()) + 1); - } } g_threads.waitForAll(); @@ -447,6 +464,7 @@ void DirectoryRefresher::refresh() { SetThisThreadName("DirectoryRefresher"); TimeThis tt("refresh"); + auto* p = new DirectoryRefreshProgress(this); { QMutexLocker locker(&m_RefreshLock); @@ -468,7 +486,7 @@ void DirectoryRefresher::refresh() return lhs.priority < rhs.priority; }); - addMultipleModsFilesToStructure(m_Root.get(), m_Mods, true); + addMultipleModsFilesToStructure(m_Root.get(), m_Mods, p); m_Root->getFileRegister()->sortOrigins(); @@ -478,6 +496,8 @@ void DirectoryRefresher::refresh() log::debug("refresher saw {} files", m_lastFileCount); } - emit progress(100); + p->finish(); + + emit progress(p); emit refreshed(); } diff --git a/src/directoryrefresher.h b/src/directoryrefresher.h index e81b55dd..bd08dad6 100644 --- a/src/directoryrefresher.h +++ b/src/directoryrefresher.h @@ -20,14 +20,14 @@ along with Mod Organizer. If not, see . #ifndef DIRECTORYREFRESHER_H #define DIRECTORYREFRESHER_H +#include "fileregisterfwd.h" +#include "profile.h" #include #include #include #include #include #include -#include "profile.h" - /** * @brief used to asynchronously generate the virtual view of the combined data directory @@ -38,11 +38,15 @@ class DirectoryRefresher : public QObject Q_OBJECT public: - struct EntryInfo { + struct EntryInfo + { EntryInfo(const QString &modName, const QString &absolutePath, const QStringList &stealFiles, const QStringList &archives, int priority) : modName(modName), absolutePath(absolutePath), stealFiles(stealFiles) - , archives(archives), priority(priority) {} + , archives(archives), priority(priority) + { + } + QString modName; QString absolutePath; QStringList stealFiles; @@ -121,7 +125,10 @@ public: void addMultipleModsFilesToStructure( MOShared::DirectoryEntry *directoryStructure, - const std::vector& entries, bool emitProgress=false); + const std::vector& entries, + DirectoryRefreshProgress* progress=nullptr); + + void updateProgress(const DirectoryRefreshProgress* p); public slots: @@ -132,7 +139,7 @@ public slots: signals: - void progress(int progress); + void progress(const DirectoryRefreshProgress* p); void error(const QString &error); void refreshed(); @@ -149,4 +156,59 @@ private: int priority, const QString &directory, const QStringList &stealFiles); }; + +class DirectoryRefreshProgress : QObject +{ + Q_OBJECT; + +public: + DirectoryRefreshProgress(DirectoryRefresher* r) : + QObject(r), m_refresher(r), m_modCount(0), m_modDone(0), m_finished(false) + { + } + + void start(std::size_t modCount) + { + m_modCount = modCount; + m_modDone = 0; + m_finished = false; + } + + + bool finished() const + { + return m_finished; + } + + int percentDone() const + { + int percent = 100; + + if (m_modCount > 0) { + const double d = static_cast(m_modDone) / m_modCount; + percent = static_cast(d * 100); + } + + return percent; + } + + + void finish() + { + m_finished = true; + } + + void addDone() + { + ++m_modDone; + m_refresher->updateProgress(this); + } + +private: + DirectoryRefresher* m_refresher; + std::size_t m_modCount; + std::atomic m_modDone; + bool m_finished; +}; + #endif // DIRECTORYREFRESHER_H diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f5749392..21a6fa41 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -367,7 +367,10 @@ MainWindow::MainWindow(Settings &settings connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(espFilterChanged(QString))); connect(m_OrganizerCore.directoryRefresher(), SIGNAL(refreshed()), this, SLOT(directory_refreshed())); - connect(m_OrganizerCore.directoryRefresher(), SIGNAL(progress(int)), this, SLOT(refresher_progress(int))); + connect( + m_OrganizerCore.directoryRefresher(), + &DirectoryRefresher::progress, + this, &MainWindow::refresherProgress); connect(m_OrganizerCore.directoryRefresher(), SIGNAL(error(QString)), this, SLOT(showError(QString))); connect(&m_SavesWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(refreshSavesIfOpen())); @@ -2382,10 +2385,15 @@ void MainWindow::setESPListSorting(int index) } } -void MainWindow::refresher_progress(int percent) +void MainWindow::refresherProgress(const DirectoryRefreshProgress* p) { - setEnabled(percent == 100); - ui->statusBar->setProgress(percent); + if (p->finished()) { + setEnabled(true); + ui->statusBar->setProgress(100); + } else { + setEnabled(false); + ui->statusBar->setProgress(p->percentDone()); + } } void MainWindow::directory_refreshed() diff --git a/src/mainwindow.h b/src/mainwindow.h index 6530d8ad..b839e85e 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -31,6 +31,7 @@ along with Mod Organizer. If not, see . #include "tutorialcontrol.h" #include "plugincontainer.h" //class PluginContainer; #include "iplugingame.h" //namespace MOBase { class IPluginGame; } +#include "shared/fileregisterfwd.h" #include class Executable; @@ -155,7 +156,8 @@ public: public slots: void modorder_changed(); void esplist_changed(); - void refresher_progress(int percent); + void refresherProgress(const DirectoryRefreshProgress* p); + void directory_refreshed(); void toolPluginInvoke(); diff --git a/src/shared/fileregisterfwd.h b/src/shared/fileregisterfwd.h index 6348fee1..720e6e30 100644 --- a/src/shared/fileregisterfwd.h +++ b/src/shared/fileregisterfwd.h @@ -1,6 +1,8 @@ #ifndef MO_REGISTER_FILEREGISTERFWD_INCLUDED #define MO_REGISTER_FILEREGISTERFWD_INCLUDED +class DirectoryRefreshProgress; + namespace MOShared { diff --git a/src/shared/util.cpp b/src/shared/util.cpp index 74e386a3..483b36a9 100644 --- a/src/shared/util.cpp +++ b/src/shared/util.cpp @@ -382,26 +382,6 @@ void checkDuplicateShortcuts(const QMenu& m) } // namespace MOShared -TimeThis::TimeThis(QString what) - : m_what(std::move(what)), m_start(Clock::now()) -{ -} - -TimeThis::~TimeThis() -{ - using namespace std::chrono; - - const auto end = Clock::now(); - const auto d = duration_cast(end - m_start).count(); - - if (m_what.isEmpty()) { - log::debug("{} ms", d); - } else { - log::debug("{} {} ms", m_what, d); - } -} - - static bool g_exiting = false; static bool g_canClose = false; diff --git a/src/shared/util.h b/src/shared/util.h index 1d3cce82..2761b64f 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -20,6 +20,7 @@ along with Mod Organizer. If not, see . #ifndef UTIL_H #define UTIL_H +#include #include #include #include @@ -64,20 +65,6 @@ inline FILETIME ToFILETIME(std::filesystem::file_time_type t) } // namespace MOShared -class TimeThis -{ -public: - TimeThis(QString what={}); - ~TimeThis(); - -private: - using Clock = std::chrono::high_resolution_clock; - - QString m_what; - Clock::time_point m_start; -}; - - enum class Exit { None = 0x00, -- cgit v1.3.1