From 47293827bbd92ce227e5188c10b66deb9f85d5bf Mon Sep 17 00:00:00 2001 From: Tannin Date: Sat, 28 Sep 2013 21:13:57 +0200 Subject: - download progress is now visible in task bar - esp-tooltip now lists all masters, highlighting the missing ones - python plugin will now report a problem if the path contains a semicolon - leak detection now (somewaht) works around the fact that we don't always get a stack trace - bugfix: mod meta-file is now reliably created if it was missing - bugfix: parser for nxm-links didn't handle numbers in the mod name - bugfix: small memory leak --- src/downloadmanager.cpp | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index c8f118f6..bbb34ccc 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -22,6 +22,7 @@ along with Mod Organizer. If not, see . #include "nxmurl.h" #include #include +#include #include "utility.h" #include "json.h" #include "selectiondialog.h" @@ -63,6 +64,7 @@ DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createNew(const Ne info->m_CurrentUrl = 0; info->m_Tries = AUTOMATIC_RETRIES; info->m_State = STATE_STARTED; + info->m_TaskProgressId = TaskProgressManager::instance().getId(); return info; } @@ -105,6 +107,7 @@ DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createFromMeta(con info->m_CurrentUrl = 0; info->m_Urls = metaFile.value("url", "").toString().split(";"); info->m_Tries = 0; + info->m_TaskProgressId = TaskProgressManager::instance().getId(); info->m_NexusInfo.m_Name = metaFile.value("name", 0).toString(); info->m_NexusInfo.m_ModName = metaFile.value("modName", "").toString(); info->m_NexusInfo.m_Version = metaFile.value("version", 0).toString(); @@ -805,6 +808,7 @@ void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) } int oldProgress = info->m_Progress; info->m_Progress = ((info->m_ResumePos + bytesReceived) * 100) / (info->m_ResumePos + bytesTotal); + TaskProgressManager::instance().updateProgress(info->m_TaskProgressId, bytesReceived, bytesTotal); if (oldProgress != info->m_Progress) { emit update(index); } -- cgit v1.3.1 From cffd9eb4e21f0ddcddca68d8eb0f1c80c8ac6ae1 Mon Sep 17 00:00:00 2001 From: Tannin Date: Sat, 5 Oct 2013 14:20:48 +0200 Subject: - hook.dll now doesn't inject to certain applications (currently steam, chrome and firefox) - versioning system improved. Will now report "downgrades" for mods and support a different versioning system (requires manual switch) - updates can now be ignored until a new version is uploaded - new splash screen - bugfix: a few memory leaks (shouldn't account for much) - bugfix: result of GetModuleHandle wasn't zero-terminated in some cases --- src/categories.cpp | 7 ++++ src/categories.h | 4 ++ src/downloadmanager.cpp | 1 + src/installationmanager.cpp | 6 +-- src/main.cpp | 97 ++++++++++++++++++++++++-------------------- src/mainwindow.cpp | 87 +++++++++++++++++++++++++++------------ src/mainwindow.h | 4 ++ src/modinfo.cpp | 30 ++++++++++++-- src/modinfo.h | 49 ++++++++++++++++++++++ src/modinfodialog.cpp | 11 +---- src/modlist.cpp | 34 ++++++++++------ src/modlistsortproxy.cpp | 2 +- src/modlistview.cpp | 4 +- src/nexusinterface.cpp | 10 +++++ src/nexusinterface.h | 1 + src/nxmaccessmanager.cpp | 8 ++++ src/nxmaccessmanager.h | 2 + src/organizer.pro | 7 +++- src/pluginlist.cpp | 4 ++ src/pluginlist.h | 2 + src/profile.cpp | 3 +- src/selfupdater.cpp | 2 - src/shared/gameinfo.cpp | 7 ++++ src/shared/gameinfo.h | 4 +- src/shared/leaktrace.cpp | 1 + src/shared/shared.pro | 10 ++++- src/spawn.cpp | 4 +- src/spawn.h | 4 +- src/splash.png | Bin 103422 -> 260807 bytes 29 files changed, 296 insertions(+), 109 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/categories.cpp b/src/categories.cpp index 62ba3ca5..c084c238 100644 --- a/src/categories.cpp +++ b/src/categories.cpp @@ -43,6 +43,7 @@ QString CategoryFactory::categoriesFilePath() CategoryFactory::CategoryFactory() { + atexit(&cleanup); reset(); QFile categoryFile(categoriesFilePath()); @@ -124,6 +125,12 @@ void CategoryFactory::setParents() } } +void CategoryFactory::cleanup() +{ + delete s_Instance; + s_Instance = NULL; +} + void CategoryFactory::saveCategories() { diff --git a/src/categories.h b/src/categories.h index 75698149..31fccd6d 100644 --- a/src/categories.h +++ b/src/categories.h @@ -180,6 +180,8 @@ private: void setParents(); + static void cleanup(); + private: static CategoryFactory *s_Instance; @@ -188,6 +190,8 @@ private: std::map m_IDMap; std::map m_NexusMap; +private: + }; diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index bbb34ccc..b965d598 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -162,6 +162,7 @@ DownloadManager::~DownloadManager() for (QVector::iterator iter = m_ActiveDownloads.begin(); iter != m_ActiveDownloads.end(); ++iter) { delete *iter; } + m_ActiveDownloads.clear(); } diff --git a/src/installationmanager.cpp b/src/installationmanager.cpp index 378eb38a..87efecf1 100644 --- a/src/installationmanager.cpp +++ b/src/installationmanager.cpp @@ -46,6 +46,7 @@ along with Mod Organizer. If not, see . #include #include #include +#include using namespace MOBase; @@ -678,8 +679,7 @@ bool InstallationManager::install(const QString &fileName, GuessedValue this->m_CurrentArchive->close(); }); - DirectoryTree *filesTree = archiveOpen ? createFilesTree() : NULL; - + QScopedPointer filesTree(archiveOpen ? createFilesTree() : NULL); IPluginInstaller::EInstallResult installResult = IPluginInstaller::RESULT_NOTATTEMPTED; std::sort(m_Installers.begin(), m_Installers.end(), [] (IPluginInstaller *LHS, IPluginInstaller *RHS) { @@ -704,7 +704,7 @@ bool InstallationManager::install(const QString &fileName, GuessedValue (filesTree != NULL) && (installer->isArchiveSupported(*filesTree))) { installResult = installerSimple->install(modName, *filesTree, version, modID); if (installResult == IPluginInstaller::RESULT_SUCCESS) { - mapToArchive(filesTree); + mapToArchive(filesTree.data()); // the simple installer only prepares the installation, the rest works the same for all installers if (!doInstall(modName, modID, version, newestVersion, categoryID)) { installResult = IPluginInstaller::RESULT_FAILED; diff --git a/src/main.cpp b/src/main.cpp index 5a694121..c4431ac4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -18,6 +18,11 @@ along with Mod Organizer. If not, see . */ +#ifdef LEAK_CHECK_WITH_VLD +#include +#include +#endif // LEAK_CHECK_WITH_VLD + #include #include #include @@ -430,61 +435,65 @@ int main(int argc, char *argv[]) application.setStyleFile(settings.value("Settings/style", "").toString()); - // set up main window and its data structures - MainWindow mainWindow(argv[0], settings); - QObject::connect(&mainWindow, SIGNAL(styleChanged(QString)), &application, SLOT(setStyleFile(QString))); - QObject::connect(&instance, SIGNAL(messageSent(QString)), &mainWindow, SLOT(externalMessage(QString))); + int res = 1; + { // scope to control lifetime of mainwindow + // set up main window and its data structures + MainWindow mainWindow(argv[0], settings); + QObject::connect(&mainWindow, SIGNAL(styleChanged(QString)), &application, SLOT(setStyleFile(QString))); + QObject::connect(&instance, SIGNAL(messageSent(QString)), &mainWindow, SLOT(externalMessage(QString))); - mainWindow.setExecutablesList(executablesList); - mainWindow.readSettings(); + mainWindow.setExecutablesList(executablesList); + mainWindow.readSettings(); - QString selectedProfileName = QString::fromUtf8(settings.value("selected_profile", "").toByteArray()); + QString selectedProfileName = QString::fromUtf8(settings.value("selected_profile", "").toByteArray()); - { // see if there is a profile on the command line - int profileIndex = arguments.indexOf("-p", 1); - if ((profileIndex != -1) && (profileIndex < arguments.size() - 1)) { - qDebug("profile overwritten on command line"); - selectedProfileName = arguments.at(profileIndex + 1); + { // see if there is a profile on the command line + int profileIndex = arguments.indexOf("-p", 1); + if ((profileIndex != -1) && (profileIndex < arguments.size() - 1)) { + qDebug("profile overwritten on command line"); + selectedProfileName = arguments.at(profileIndex + 1); + } + arguments.removeAt(profileIndex); + arguments.removeAt(profileIndex); + } + qDebug("configured profile: %s", qPrintable(selectedProfileName)); + + // if we have a command line parameter, it is either a nxm link or + // a binary to start + if ((arguments.size() > 1) && (!isNxmLink(arguments.at(1)))) { + QString exeName = arguments.at(1); + qDebug("starting %s from command line", qPrintable(exeName)); + arguments.removeFirst(); // remove application name (ModOrganizer.exe) + arguments.removeFirst(); // remove binary name + // pass the remaining parameters to the binary + mainWindow.spawnProgram(exeName, arguments.join(" "), selectedProfileName, QDir()); + return 0; } - arguments.removeAt(profileIndex); - arguments.removeAt(profileIndex); - } - qDebug("configured profile: %s", qPrintable(selectedProfileName)); - - // if we have a command line parameter, it is either a nxm link or - // a binary to start - if ((arguments.size() > 1) && (!isNxmLink(arguments.at(1)))) { - QString exeName = arguments.at(1); - qDebug("starting %s from command line", qPrintable(exeName)); - arguments.removeFirst(); // remove application name (ModOrganizer.exe) - arguments.removeFirst(); // remove binary name - // pass the remaining parameters to the binary - mainWindow.spawnProgram(exeName, arguments.join(" "), selectedProfileName, QDir()); - return 0; - } - mainWindow.createFirstProfile(); + mainWindow.createFirstProfile(); - if (selectedProfileName.length() != 0) { - if (!mainWindow.setCurrentProfile(selectedProfileName)) { + if (selectedProfileName.length() != 0) { + if (!mainWindow.setCurrentProfile(selectedProfileName)) { + mainWindow.setCurrentProfile(1); + qWarning("failed to set profile: %s", + selectedProfileName.toUtf8().constData()); + } + } else { mainWindow.setCurrentProfile(1); - qWarning("failed to set profile: %s", - selectedProfileName.toUtf8().constData()); } - } else { - mainWindow.setCurrentProfile(1); - } - qDebug("displaying main window"); - mainWindow.show(); + qDebug("displaying main window"); + mainWindow.show(); - if ((arguments.size() > 1) && - (isNxmLink(arguments.at(1)))) { - qDebug("starting download from command line: %s", qPrintable(arguments.at(1))); - mainWindow.externalMessage(arguments.at(1)); + if ((arguments.size() > 1) && + (isNxmLink(arguments.at(1)))) { + qDebug("starting download from command line: %s", qPrintable(arguments.at(1))); + mainWindow.externalMessage(arguments.at(1)); + } + splash.finish(&mainWindow); + res = application.exec(); } - splash.finish(&mainWindow); - return application.exec(); + return res; } catch (const std::exception &e) { reportError(e.what()); return 1; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 24772db1..1ea35d74 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -139,8 +139,8 @@ MainWindow::MainWindow(const QString &exeName, QSettings &initSettings, QWidget : QMainWindow(parent), ui(new Ui::MainWindow), m_Tutorial(this, "MainWindow"), m_ExeName(exeName), m_OldProfileIndex(-1), m_DirectoryStructure(new DirectoryEntry(L"data", NULL, 0)), - m_ModList(NexusInterface::instance()), m_ModListGroupingProxy(NULL), m_ModListSortProxy(NULL), - m_OldExecutableIndex(-1), m_GamePath(ToQString(GameInfo::instance().getGameDirectory())), + m_ModList(this), m_ModListGroupingProxy(NULL), m_ModListSortProxy(NULL), + m_PluginList(this), m_OldExecutableIndex(-1), m_GamePath(ToQString(GameInfo::instance().getGameDirectory())), m_DownloadManager(NexusInterface::instance(), this), m_InstallationManager(this), m_Translator(NULL), m_TranslatorQt(NULL), m_Updater(NexusInterface::instance(), this), m_CategoryFactory(CategoryFactory::instance()), @@ -149,7 +149,7 @@ MainWindow::MainWindow(const QString &exeName, QSettings &initSettings, QWidget m_GameInfo(new GameInfoImpl()) { ui->setupUi(this); - this->setWindowTitle(ToQString(GameInfo::instance().getGameName()).append(" Mod Organizer v").append(m_Updater.getVersion().canonicalString())); + this->setWindowTitle(ToQString(GameInfo::instance().getGameName()) + " Mod Organizer v" + m_Updater.getVersion().displayString()); m_RefreshProgress = new QProgressBar(statusBar()); m_RefreshProgress->setTextVisible(true); @@ -255,7 +255,7 @@ MainWindow::MainWindow(const QString &exeName, QSettings &initSettings, QWidget connect(&m_Updater, SIGNAL(updateAvailable()), this, SLOT(updateAvailable())); connect(&m_Updater, SIGNAL(motdAvailable(QString)), this, SLOT(motdReceived(QString))); - connect(ExitProxy::instance(), SIGNAL(exit()), this, SLOT(close())); +// connect(ExitProxy::instance(), SIGNAL(exit()), this, SLOT(close())); connect(NexusInterface::instance()->getAccessManager(), SIGNAL(loginSuccessful(bool)), this, SLOT(loginSuccessful(bool))); connect(NexusInterface::instance()->getAccessManager(), SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); @@ -412,7 +412,7 @@ void MainWindow::actionToToolButton(QAction *&sourceAction) button->setToolButtonStyle(ui->toolBar->toolButtonStyle()); button->setToolTip(sourceAction->toolTip()); button->setShortcut(sourceAction->shortcut()); - QMenu *buttonMenu = new QMenu(sourceAction->text()); + QMenu *buttonMenu = new QMenu(sourceAction->text(), button); button->setMenu(buttonMenu); QAction *newAction = ui->toolBar->insertWidget(sourceAction, button); newAction->setObjectName(sourceAction->objectName()); @@ -1499,6 +1499,8 @@ void MainWindow::updateTo(QTreeWidgetItem *subTree, const std::wstring &director updateTo(directoryChild, temp.str(), **current, conflictsOnly); if (directoryChild->childCount() != 0) { subTree->addChild(directoryChild); + } else { + delete directoryChild; } } } @@ -3069,7 +3071,6 @@ void MainWindow::openExplorer_clicked() ::ShellExecuteW(NULL, L"explore", ToWString(modInfo->absolutePath()).c_str(), NULL, NULL, SW_SHOWNORMAL); } - void MainWindow::information_clicked() { try { @@ -3079,7 +3080,6 @@ void MainWindow::information_clicked() } } - void MainWindow::syncOverwrite() { ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); @@ -3091,7 +3091,6 @@ void MainWindow::syncOverwrite() } } - void MainWindow::createModFromOverwrite() { GuessedValue name; @@ -3125,14 +3124,12 @@ void MainWindow::createModFromOverwrite() refreshModList(); } - void MainWindow::cancelModListEditor() { ui->modList->setEnabled(false); ui->modList->setEnabled(true); } - void MainWindow::on_modList_doubleClicked(const QModelIndex &index) { if (!index.isValid()) { @@ -3155,7 +3152,6 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) } } - bool MainWindow::addCategories(QMenu *menu, int targetID) { ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); @@ -3210,7 +3206,6 @@ void MainWindow::saveCategoriesFromMenu(QMenu *menu, int modRow) } } - void MainWindow::saveCategories() { QMenu *menu = qobject_cast(sender()); @@ -3254,8 +3249,6 @@ void MainWindow::saveCategories() refreshFilters(); } - - void MainWindow::savePrimaryCategory() { QMenu *menu = qobject_cast(sender()); @@ -3280,7 +3273,6 @@ void MainWindow::savePrimaryCategory() } } - void MainWindow::checkModsForUpdates() { statusBar()->show(); @@ -3298,6 +3290,45 @@ void MainWindow::checkModsForUpdates() } } +void MainWindow::changeVersioningScheme() { + if (QMessageBox::question(this, tr("Continue?"), + tr("This will try to change the versioning scheme so that the newest version is interpreted as an update to " + "the installed version."), + QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Yes) { + + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + + bool success = false; + + static VersionInfo::VersionScheme schemes[] = { VersionInfo::SCHEME_REGULAR, VersionInfo::SCHEME_DECIMALMARK, VersionInfo::SCHEME_NUMBERSANDLETTERS }; + + for (int i = 0; i < sizeof(schemes) / sizeof(VersionInfo::VersionScheme) && !success; ++i) { + VersionInfo verOld(info->getVersion().canonicalString(), schemes[i]); + VersionInfo verNew(info->getNewestVersion().canonicalString(), schemes[i]); + if (verOld < verNew) { + info->setVersion(verOld); + info->setNewestVersion(verNew); + success = true; + } + } + if (!success) { + QMessageBox::information(this, tr("Sorry"), + tr("I don't know a versioning scheme where %1 is newer than %2.").arg(info->getNewestVersion().canonicalString()).arg(info->getVersion().canonicalString()), + QMessageBox::Ok); + } + } +} + +void MainWindow::ignoreUpdate() { + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + info->ignoreUpdate(true); +} + +void MainWindow::unignoreUpdate() +{ + ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + info->ignoreUpdate(false); +} void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, ModInfo::Ptr info) { @@ -3319,7 +3350,6 @@ void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, ModInf } } - void MainWindow::addPrimaryCategoryCandidates() { QMenu *menu = qobject_cast(sender()); @@ -3333,7 +3363,6 @@ void MainWindow::addPrimaryCategoryCandidates() addPrimaryCategoryCandidates(menu, modInfo); } - void MainWindow::enableVisibleMods() { if (QMessageBox::question(NULL, tr("Confirm"), tr("Really enable all visible mods?"), @@ -3342,7 +3371,6 @@ void MainWindow::enableVisibleMods() } } - void MainWindow::disableVisibleMods() { if (QMessageBox::question(NULL, tr("Confirm"), tr("Really disable all visible mods?"), @@ -3351,7 +3379,6 @@ void MainWindow::disableVisibleMods() } } - void MainWindow::exportModListCSV() { SelectionDialog selection(tr("Choose what to export")); @@ -3406,7 +3433,6 @@ void MainWindow::exportModListCSV() } } - void addMenuAsPushButton(QMenu *menu, QMenu *subMenu) { QPushButton *pushBtn = new QPushButton(subMenu->title()); @@ -3416,13 +3442,13 @@ void addMenuAsPushButton(QMenu *menu, QMenu *subMenu) menu->addAction(action); } - void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) { try { QTreeView *modList = findChild("modList"); - m_ContextRow = mapToModel(&m_ModList, modList->indexAt(pos)).row(); + QModelIndex index = mapToModel(&m_ModList, modList->indexAt(pos)); + m_ContextRow = index.row(); QMenu menu; @@ -3461,6 +3487,17 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) connect(primaryCategoryMenu, SIGNAL(aboutToHide()), this, SLOT(savePrimaryCategory())); addMenuAsPushButton(&menu, primaryCategoryMenu); + menu.addSeparator(); + if (info->downgradeAvailable()) { + menu.addAction(tr("Change versioning scheme"), this, SLOT(changeVersioningScheme())); + } + if (info->updateIgnored()) { + menu.addAction(tr("Un-ignore update"), this, SLOT(unignoreUpdate())); + } else { + menu.addAction(tr("Ignore update"), this, SLOT(ignoreUpdate())); + } + menu.addSeparator(); + menu.addAction(tr("Rename Mod..."), this, SLOT(renameMod_clicked())); menu.addAction(tr("Remove Mod..."), this, SLOT(removeMod_clicked())); menu.addAction(tr("Reinstall Mod"), this, SLOT(reinstallMod_clicked())); @@ -4207,9 +4244,9 @@ void MainWindow::on_actionEndorseMO_triggered() void MainWindow::updateDownloadListDelegate() { if (ui->compactBox->isChecked()) { - ui->downloadView->setItemDelegate(new DownloadListWidgetCompactDelegate(&m_DownloadManager, ui->downloadView)); + ui->downloadView->setItemDelegate(new DownloadListWidgetCompactDelegate(&m_DownloadManager, ui->downloadView, ui->downloadView)); } else { - ui->downloadView->setItemDelegate(new DownloadListWidgetDelegate(&m_DownloadManager, ui->downloadView)); + ui->downloadView->setItemDelegate(new DownloadListWidgetDelegate(&m_DownloadManager, ui->downloadView, ui->downloadView)); } DownloadListSortProxy *sortProxy = new DownloadListSortProxy(&m_DownloadManager, ui->downloadView); @@ -4267,7 +4304,7 @@ void MainWindow::nxmUpdatesAvailable(const std::vector &modIDs, QVariant us } else { std::vector info = ModInfo::getByModID(result["id"].toInt()); for (auto iter = info.begin(); iter != info.end(); ++iter) { - (*iter)->setNewestVersion(VersionInfo(result["version"].toString())); + (*iter)->setNewestVersion(result["version"].toString()); (*iter)->setNexusDescription(result["description"].toString()); if (NexusInterface::instance()->getAccessManager()->loggedIn() && result.contains("voted_by_user")) { diff --git a/src/mainwindow.h b/src/mainwindow.h index 80dca172..dfec5f49 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -466,6 +466,10 @@ private slots: void removeFromToolbar(); void overwriteClosed(int); + void changeVersioningScheme(); + void ignoreUpdate(); + void unignoreUpdate(); + private slots: // ui slots // actions void on_actionAdd_Profile_triggered(); diff --git a/src/modinfo.cpp b/src/modinfo.cpp index 7632a86e..1479f7b4 100644 --- a/src/modinfo.cpp +++ b/src/modinfo.cpp @@ -303,10 +303,11 @@ ModInfoRegular::ModInfoRegular(const QDir &path, DirectoryEntry **directoryStruc QString metaFileName = path.absoluteFilePath("meta.ini"); QSettings metaFile(metaFileName, QSettings::IniFormat); - m_Notes = metaFile.value("notes", "").toString(); - m_NexusID = metaFile.value("modid", -1).toInt(); + m_Notes = metaFile.value("notes", "").toString(); + m_NexusID = metaFile.value("modid", -1).toInt(); m_Version.parse(metaFile.value("version", "").toString()); - m_NewestVersion = metaFile.value("newestVersion", "").toString(); + m_NewestVersion = metaFile.value("newestVersion", "").toString(); + m_IgnoredVersion = metaFile.value("ignoredVersion", "").toString(); m_InstallationFile = metaFile.value("installationFile", "").toString(); m_NexusDescription = metaFile.value("nexusDescription", "").toString(); m_LastNexusQuery = QDateTime::fromString(metaFile.value("lastNexusQuery", "").toString(), Qt::ISODate); @@ -377,6 +378,7 @@ void ModInfoRegular::saveMeta() temp.erase(m_PrimaryCategory); metaFile.setValue("category", QString("%1").arg(m_PrimaryCategory) + "," + SetJoin(temp, ",")); metaFile.setValue("newestVersion", m_NewestVersion.canonicalString()); + metaFile.setValue("ignoredVersion", m_IgnoredVersion.canonicalString()); metaFile.setValue("version", m_Version.canonicalString()); metaFile.setValue("modid", m_NexusID); metaFile.setValue("notes", m_Notes); @@ -396,10 +398,22 @@ void ModInfoRegular::saveMeta() bool ModInfoRegular::updateAvailable() const { + if (m_IgnoredVersion.isValid() && (m_IgnoredVersion == m_NewestVersion)) { + return false; + } return m_NewestVersion.isValid() && (m_Version < m_NewestVersion); } +bool ModInfoRegular::downgradeAvailable() const +{ + if (m_IgnoredVersion.isValid() && (m_IgnoredVersion == m_NewestVersion)) { + return false; + } + return m_NewestVersion.isValid() && (m_NewestVersion < m_Version); +} + + void ModInfoRegular::nxmDescriptionAvailable(int, QVariant, QVariant resultData) { QVariantMap result = resultData.toMap(); @@ -576,6 +590,16 @@ QString ModInfoRegular::absolutePath() const return m_Path; } +void ModInfoRegular::ignoreUpdate(bool ignore) +{ + if (ignore) { + m_IgnoredVersion = m_NewestVersion; + } else { + m_IgnoredVersion.clear(); + } + m_MetaInfoChanged = true; +} + std::vector ModInfoRegular::getFlags() const { diff --git a/src/modinfo.h b/src/modinfo.h index 7e217de7..3b83d207 100644 --- a/src/modinfo.h +++ b/src/modinfo.h @@ -192,6 +192,22 @@ public: **/ virtual bool updateAvailable() const = 0; + /** + * @return true if the update currently available is ignored + */ + virtual bool updateIgnored() const = 0; + + /** + * @brief test if the "newest" version of the mod is older than the installed version + * + * test if there is a newer version of the mod. This does NOT cause + * information to be retrieved from the nexus, it will only test version information already + * available locally. Use checkAllForUpdate() to update this version information + * + * @return true if the newest version is older than the installed one + **/ + virtual bool downgradeAvailable() const = 0; + /** * @brief request an update of nexus description for this mod. * @@ -309,6 +325,11 @@ public: **/ virtual MOBase::VersionInfo getNewestVersion() const = 0; + /** + * @brief ignore the newest version for updates + */ + virtual void ignoreUpdate(bool ignore) = 0; + /** * @brief getter for the nexus mod id * @@ -494,6 +515,22 @@ public: **/ bool updateAvailable() const; + /** + * @return true if the current update is being ignored + */ + virtual bool updateIgnored() const { return m_IgnoredVersion == m_NewestVersion; } + + /** + * @brief test if there is a newer version of the mod + * + * test if there is a newer version of the mod. This does NOT cause + * information to be retrieved from the nexus, it will only test version information already + * available locally. Use checkAllForUpdate() to update this version information + * + * @return true if there is a newer version + **/ + bool downgradeAvailable() const; + /** * @brief request an update of nexus description for this mod. * @@ -620,6 +657,11 @@ public: **/ MOBase::VersionInfo getNewestVersion() const { return m_NewestVersion; } + /** + * @brief ignore the newest version for updates + */ + void ignoreUpdate(bool ignore); + /** * @brief getter for the installation file * @@ -746,6 +788,7 @@ private: bool m_MetaInfoChanged; MOBase::VersionInfo m_NewestVersion; + MOBase::VersionInfo m_IgnoredVersion; EEndorsedState m_EndorsedState; @@ -767,10 +810,13 @@ class ModInfoBackup : public ModInfoRegular public: virtual bool updateAvailable() const { return false; } + virtual bool updateIgnored() const { return false; } + virtual bool downgradeAvailable() const { return false; } virtual bool updateNXMInfo() { return false; } virtual void setNexusID(int) {} virtual void endorse(bool) {} virtual int getFixedPriority() const { return -1; } + virtual void ignoreUpdate(bool) {} virtual bool canBeUpdated() const { return false; } virtual bool canBeEnabled() const { return false; } virtual std::vector getIniTweaks() const { return std::vector(); } @@ -798,12 +844,15 @@ class ModInfoOverwrite : public ModInfo public: virtual bool updateAvailable() const { return false; } + virtual bool updateIgnored() const { return false; } + virtual bool downgradeAvailable() const { return false; } virtual bool updateNXMInfo() { return false; } virtual void setCategory(int, bool) {} virtual bool setName(const QString&) { return false; } virtual void setNotes(const QString&) {} virtual void setNexusID(int) {} virtual void setNewestVersion(const MOBase::VersionInfo&) {} + virtual void ignoreUpdate(bool) {} virtual void setNexusDescription(const QString&) {} virtual void setIsEndorsed(bool) {} virtual void setNeverEndorse() {} diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 75e7e499..b4ae57ea 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -76,7 +76,6 @@ ModInfoDialog::ModInfoDialog(ModInfo::Ptr modInfo, const DirectoryEntry *directo m_UTF8Codec = QTextCodec::codecForName("utf-8"); QListWidget *textFileList = findChild("textFileList"); - QListWidget *iniFileList = findChild("iniFileList"); QListWidget *iniTweaksList = findChild("iniTweaksList"); QListWidget *activeESPList = findChild("activeESPList"); QListWidget *inactiveESPList = findChild("inactiveESPList"); @@ -707,7 +706,7 @@ QString ModInfoDialog::getFileCategory(int categoryID) void ModInfoDialog::updateVersionColor() { // QPalette versionColor; - if (m_ModInfo->getVersion() < m_ModInfo->getNewestVersion()) { + if (m_ModInfo->getVersion() != m_ModInfo->getNewestVersion()) { ui->versionEdit->setStyleSheet("color: red"); // versionColor.setColor(QPalette::Text, Qt::red); ui->versionEdit->setToolTip(tr("Current Version: %1").arg(m_ModInfo->getNewestVersion().canonicalString())); @@ -758,13 +757,7 @@ void ModInfoDialog::modDetailsUpdated(bool success) ui->descriptionView->setHtml(tr("(description incomplete, please visit nexus)")); } - QString version = m_ModInfo->getNewestVersion().canonicalString(); - - if (!version.isEmpty()) { - m_ModInfo->setNewestVersion(version); - - updateVersionColor(); - } + updateVersionColor(); } } diff --git a/src/modlist.cpp b/src/modlist.cpp index b5a7182e..7367b2ae 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -143,13 +143,16 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const } else if (column == COL_NAME) { return modInfo->name(); } else if (column == COL_VERSION) { - QString version = modInfo->getVersion().canonicalString(); - if (version.isEmpty() && modInfo->canBeUpdated()) { - version = "?"; - } else if (version[0] == 'd') { - version.remove(0, 1); + VersionInfo verInfo = modInfo->getVersion(); + if (role == Qt::EditRole) { + return verInfo.canonicalString(); + } else { + QString version = verInfo.displayString(); + if (version.isEmpty() && modInfo->canBeUpdated()) { + version = "?"; + } + return version; } - return version; } else if (column == COL_PRIORITY) { int priority = modInfo->getFixedPriority(); if (priority != INT_MIN) { @@ -241,17 +244,18 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const result.setItalic(true); } } else if (column == COL_VERSION) { - if (modInfo->updateAvailable()) { + if (modInfo->updateAvailable() || modInfo->downgradeAvailable()) { result.setWeight(QFont::Bold); } } return result; } else if (role == Qt::DecorationRole) { if (column == COL_VERSION) { - if (modInfo->updateAvailable() && - modInfo->getNewestVersion().isValid()) { + if (modInfo->updateAvailable()) { return QIcon(":/MO/gui/update_available"); - } else if (modInfo->getVersion().isVersionDate()) { + } else if (modInfo->downgradeAvailable()) { + return QIcon(":/MO/gui/warning"); + } else if (modInfo->getVersion().scheme() == VersionInfo::SCHEME_DATE) { return QIcon(":/MO/gui/version_date"); } } @@ -264,7 +268,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const } else if (column == COL_VERSION) { if (!modInfo->getNewestVersion().isValid()) { return QVariant(); - } else if (modInfo->updateAvailable()) { + } else if (modInfo->updateAvailable() || modInfo->downgradeAvailable()) { return QBrush(Qt::red); } else { return QBrush(Qt::darkGreen); @@ -291,7 +295,13 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const return QString(); } } else if (column == COL_VERSION) { - return tr("installed version: %1, newest version: %2").arg(modInfo->getVersion().canonicalString()).arg(modInfo->getNewestVersion().canonicalString()); + QString text = tr("installed version: %1, newest version: %2").arg(modInfo->getVersion().displayString()).arg(modInfo->getNewestVersion().displayString()); + if (modInfo->downgradeAvailable()) { + text += "
" + tr("The newest version on Nexus seems to be older than the one you have installed. This could either mean the version you have has been withdrawn " + "(i.e. due to a bug) or the author uses a non-standard versioning scheme and that newest version is actually newer. " + "Either way you may want to \"upgrade\"."); + } + return text; } else if (column == COL_CATEGORY) { const std::set &categories = modInfo->getCategories(); std::wostringstream categoryString; diff --git a/src/modlistsortproxy.cpp b/src/modlistsortproxy.cpp index 53c03c6a..c7c3ab28 100644 --- a/src/modlistsortproxy.cpp +++ b/src/modlistsortproxy.cpp @@ -211,7 +211,7 @@ bool ModListSortProxy::filterMatches(ModInfo::Ptr info, bool enabled) const if (enabled) return false; } break; case CategoryFactory::CATEGORY_SPECIAL_UPDATEAVAILABLE: { - if (!info->updateAvailable()) return false; + if (!info->updateAvailable() && !info->downgradeAvailable()) return false; } break; case CategoryFactory::CATEGORY_SPECIAL_NOCATEGORY: { if (info->getCategories().size() > 0) return false; diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 44228d5b..1a4f6266 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -4,7 +4,7 @@ #include -class ModListViewStyle: public QProxyStyle{ +class ModListViewStyle: public QProxyStyle { public: ModListViewStyle(QStyle *style, int indentation); @@ -37,7 +37,7 @@ void ModListViewStyle::drawPrimitive(PrimitiveElement element, const QStyleOptio ModListView::ModListView(QWidget *parent) : QTreeView(parent) { - setStyle(new ModListViewStyle(style(), indentation())); +// setStyle(new ModListViewStyle(style(), indentation())); } void ModListView::dragEnterEvent(QDragEnterEvent *event) diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index cd78ca4c..bee0bb44 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -68,6 +68,7 @@ void NexusBridge::nxmDescriptionAvailable(int modID, QVariant userData, QVariant std::set::iterator iter = m_RequestIDs.find(requestID); if (iter != m_RequestIDs.end()) { m_RequestIDs.erase(iter); + emit descriptionAvailable(modID, userData, resultData); } } @@ -142,6 +143,7 @@ QAtomicInt NexusInterface::NXMRequestInfo::s_NextID(0); NexusInterface::NexusInterface() : m_NMMVersion() { + atexit(&cleanup); m_AccessManager = new NXMAccessManager(this); m_DiskCache = new QNetworkDiskCache(this); @@ -149,6 +151,13 @@ NexusInterface::NexusInterface() } +void NexusInterface::cleanup() +{ + delete NexusInterface::s_Instance; + NexusInterface::s_Instance = NULL; +} + + NXMAccessManager *NexusInterface::getAccessManager() { return m_AccessManager; @@ -405,6 +414,7 @@ void NexusInterface::downloadRequestedNXM(const QString &url) emit requestNXMDownload(url); } +#include void NexusInterface::requestFinished(std::list::iterator iter) { diff --git a/src/nexusinterface.h b/src/nexusinterface.h index 0c304a71..0b53f9d0 100644 --- a/src/nexusinterface.h +++ b/src/nexusinterface.h @@ -294,6 +294,7 @@ private: NexusInterface(); void nextRequest(); void requestFinished(std::list::iterator iter); + static void cleanup(); private: diff --git a/src/nxmaccessmanager.cpp b/src/nxmaccessmanager.cpp index d83ffa61..a05b8a6c 100644 --- a/src/nxmaccessmanager.cpp +++ b/src/nxmaccessmanager.cpp @@ -44,6 +44,14 @@ NXMAccessManager::NXMAccessManager(QObject *parent) { } +NXMAccessManager::~NXMAccessManager() +{ + if (m_LoginReply != NULL) { + m_LoginReply->deleteLater(); + m_LoginReply = NULL; + } +} + QNetworkReply *NXMAccessManager::createRequest( QNetworkAccessManager::Operation operation, const QNetworkRequest &request, diff --git a/src/nxmaccessmanager.h b/src/nxmaccessmanager.h index b0c43978..1d8d36ab 100644 --- a/src/nxmaccessmanager.h +++ b/src/nxmaccessmanager.h @@ -37,6 +37,8 @@ public: explicit NXMAccessManager(QObject *parent); + ~NXMAccessManager(); + bool loggedIn() const; void login(const QString &username, const QString &password); diff --git a/src/organizer.pro b/src/organizer.pro index e89b6e99..a9353361 100644 --- a/src/organizer.pro +++ b/src/organizer.pro @@ -183,7 +183,6 @@ INCLUDEPATH += ../shared ../archive ../uibase ../bsatk ../esptk "$(BOOSTPATH)" LIBS += -L"$(BOOSTPATH)/stage/lib" - CONFIG(debug, debug|release) { OUTDIR = $$OUT_PWD/debug DSTDIR = $$PWD/../../outputd @@ -294,6 +293,12 @@ OTHER_FILES += \ INCLUDEPATH += "$(ZLIBPATH)" "$(ZLIBPATH)/build" "$(BOOSTPATH)" LIBS += -L"$(ZLIBPATH)/build" -lzlibstatic + +# leak detection with vld +#INCLUDEPATH += "E:/Visual Leak Detector/include" +#LIBS += -L"E:/Visual Leak Detector/lib/Win32" +#DEFINES += LEAK_CHECK_WITH_VLD + #SOURCES += modeltest.cpp #HEADERS += modeltest.h #DEFINES += TEST_MODELS diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 39cca6af..e730d3f4 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -90,6 +90,10 @@ PluginList::PluginList(QObject *parent) } +PluginList::~PluginList() +{ +} + QString PluginList::getColumnName(int column) { diff --git a/src/pluginlist.h b/src/pluginlist.h index 3442a9f7..60c9be95 100644 --- a/src/pluginlist.h +++ b/src/pluginlist.h @@ -53,6 +53,8 @@ public: **/ PluginList(QObject *parent = NULL); + ~PluginList(); + /** * @brief does a complete refresh of the list * diff --git a/src/profile.cpp b/src/profile.cpp index 07f7010e..3da12d7d 100644 --- a/src/profile.cpp +++ b/src/profile.cpp @@ -185,7 +185,7 @@ void Profile::writeModlistNow(bool onlyOnTimer) const QString fileName = getModlistFileName(); if (QFile::exists(fileName)) { - shellDelete(QStringList(fileName)); + shellDelete(QStringList(fileName), false, QApplication::activeModalWidget()); } if (!file.copy(fileName)) { @@ -238,6 +238,7 @@ void Profile::createTweakedIniFile() if (error) { reportError(tr("failed to create tweaked ini: %1").arg(getCurrentErrorStringA().c_str())); } + qDebug("%s saved", qPrintable(QDir::toNativeSeparators(tweakedIni))); } diff --git a/src/selfupdater.cpp b/src/selfupdater.cpp index 421fbeab..bdace814 100644 --- a/src/selfupdater.cpp +++ b/src/selfupdater.cpp @@ -126,7 +126,6 @@ void SelfUpdater::startUpdate() void SelfUpdater::download(const QString &downloadLink, const QString &fileName) { - qDebug("download: %s", downloadLink.toUtf8().constData()); QNetworkAccessManager *accessManager = m_Interface->getAccessManager(); QUrl dlUrl(downloadLink); QNetworkRequest request(dlUrl); @@ -324,7 +323,6 @@ void SelfUpdater::nxmDescriptionAvailable(int, QVariant, QVariant resultData, in if (m_NewestVersion.isEmpty()) { QTimer::singleShot(5000, this, SLOT(testForUpdate())); } - VersionInfo currentVersion(m_MOVersion); VersionInfo newestVersion(m_NewestVersion); diff --git a/src/shared/gameinfo.cpp b/src/shared/gameinfo.cpp index 6b53450d..f74e52b4 100644 --- a/src/shared/gameinfo.cpp +++ b/src/shared/gameinfo.cpp @@ -40,6 +40,13 @@ GameInfo* GameInfo::s_Instance = NULL; GameInfo::GameInfo(const std::wstring &omoDirectory, const std::wstring &gameDirectory) : m_GameDirectory(gameDirectory), m_OrganizerDirectory(omoDirectory) { + atexit(&cleanup); +} + + +void GameInfo::cleanup() { + delete GameInfo::s_Instance; + GameInfo::s_Instance = NULL; } diff --git a/src/shared/gameinfo.h b/src/shared/gameinfo.h index 3e022ef4..14f52f05 100644 --- a/src/shared/gameinfo.h +++ b/src/shared/gameinfo.h @@ -176,9 +176,11 @@ private: static bool identifyGame(const std::wstring &omoDirectory, const std::wstring &searchPath); std::wstring getSpecialPath(LPCWSTR name) const; + static void cleanup(); + private: - static GameInfo* s_Instance; + static GameInfo *s_Instance; std::wstring m_MyGamesDirectory; diff --git a/src/shared/leaktrace.cpp b/src/shared/leaktrace.cpp index 83ed4fd0..c3721557 100644 --- a/src/shared/leaktrace.cpp +++ b/src/shared/leaktrace.cpp @@ -114,6 +114,7 @@ static struct __TraceData { } std::map m_Traces; + } __trace; diff --git a/src/shared/shared.pro b/src/shared/shared.pro index ab0bd8a0..992fd7f2 100644 --- a/src/shared/shared.pro +++ b/src/shared/shared.pro @@ -13,9 +13,17 @@ CONFIG += staticlib INCLUDEPATH += ../bsatk "$(BOOSTPATH)" + +# only for custom leak detection +#DEFINES += TRACE_LEAKS +#LIBS += -lDbgHelp + + CONFIG(debug, debug|release) { - LIBS += -L$$OUT_PWD/../bsatk/debug + LIBS += -L$$OUT_PWD/../bsatk/debug LIBS += -lDbgHelp + QMAKE_CXXFLAGS_DEBUG -= -Zi + QMAKE_CXXFLAGS += -Z7 } else { LIBS += -L$$OUT_PWD/../bsatk/release } diff --git a/src/spawn.cpp b/src/spawn.cpp index ab43b687..5639a78c 100644 --- a/src/spawn.cpp +++ b/src/spawn.cpp @@ -156,7 +156,7 @@ HANDLE startBinary(const QFileInfo &binary, const QString &arguments, const QStr return processHandle; } - +/* ExitProxy *ExitProxy::s_Instance = NULL; ExitProxy *ExitProxy::instance() @@ -170,4 +170,4 @@ ExitProxy *ExitProxy::instance() void ExitProxy::emitExit() { emit exit(); -} +}*/ diff --git a/src/spawn.h b/src/spawn.h index e0d1f958..48320fea 100644 --- a/src/spawn.h +++ b/src/spawn.h @@ -31,7 +31,7 @@ along with Mod Organizer. If not, see . * @brief a dirty little trick so we can issue a clean restart from startBinary * @note unused */ -class ExitProxy : public QObject { +/*class ExitProxy : public QObject { Q_OBJECT public: static ExitProxy *instance(); @@ -42,7 +42,7 @@ private: ExitProxy() {} private: static ExitProxy *s_Instance; -}; +};*/ /** diff --git a/src/splash.png b/src/splash.png index 45ace8f8..0137bf72 100644 Binary files a/src/splash.png and b/src/splash.png differ -- cgit v1.3.1 From 54c7131a5e2fa282369e25344ac190d51676c383 Mon Sep 17 00:00:00 2001 From: Tannin Date: Thu, 10 Oct 2013 19:32:01 +0200 Subject: - new toggle to display hidden downloads - hidden downloads can be un-hidden - the installation manager now more thoroughly cleans up the temporary directory after installation - added SkyrimLauncher.exe to the list of auto-detected executables - bugfix: shutting down MO while downloads where active in some occasions didn't work - bugfix: when canceling the only active download the taskbar icon didn't return to normal --- src/downloadlistwidget.cpp | 20 ++++++++--- src/downloadlistwidget.h | 2 ++ src/downloadlistwidgetcompact.cpp | 20 ++++++++--- src/downloadlistwidgetcompact.h | 2 ++ src/downloadmanager.cpp | 58 ++++++++++++++++++++++++++----- src/downloadmanager.h | 24 ++++++++++++- src/installationmanager.cpp | 72 +++++++++++++-------------------------- src/installationmanager.h | 5 +-- src/main.cpp | 5 ++- src/mainwindow.cpp | 6 ++++ src/mainwindow.h | 1 + src/mainwindow.ui | 9 ++++- src/moapplication.cpp | 6 +++- src/moapplication.h | 60 ++++++++++++++++---------------- src/shared/skyriminfo.cpp | 1 + src/version.rc | 4 +-- 16 files changed, 189 insertions(+), 106 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadlistwidget.cpp b/src/downloadlistwidget.cpp index b657ca69..b4d40799 100644 --- a/src/downloadlistwidget.cpp +++ b/src/downloadlistwidget.cpp @@ -208,6 +208,11 @@ void DownloadListWidgetDelegate::issueRemoveFromView() emit removeDownload(m_ContextRow, false); } +void DownloadListWidgetDelegate::issueRestoreToView() +{ + emit restoreDownload(m_ContextRow); +} + void DownloadListWidgetDelegate::issueCancel() { emit cancelDownload(m_ContextRow); @@ -277,13 +282,18 @@ bool DownloadListWidgetDelegate::editorEvent(QEvent *event, QAbstractItemModel * QMenu menu(m_View); m_ContextRow = qobject_cast(model)->mapToSource(index).row(); DownloadManager::DownloadState state = m_Manager->getState(m_ContextRow); + bool hidden = m_Manager->isHidden(m_ContextRow); if (state >= DownloadManager::STATE_READY) { menu.addAction(tr("Install"), this, SLOT(issueInstall())); if (m_Manager->isInfoIncomplete(m_ContextRow)) { menu.addAction(tr("Query Info"), this, SLOT(issueQueryInfo())); } menu.addAction(tr("Delete"), this, SLOT(issueDelete())); - menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); + if (hidden) { + menu.addAction(tr("Un-Hide"), this, SLOT(issueRestoreToView())); + } else { + menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); + } } else if (state == DownloadManager::STATE_DOWNLOADING){ menu.addAction(tr("Cancel"), this, SLOT(issueCancel())); menu.addAction(tr("Pause"), this, SLOT(issuePause())); @@ -295,9 +305,11 @@ bool DownloadListWidgetDelegate::editorEvent(QEvent *event, QAbstractItemModel * menu.addSeparator(); menu.addAction(tr("Delete Installed..."), this, SLOT(issueDeleteCompleted())); menu.addAction(tr("Delete All..."), this, SLOT(issueDeleteAll())); - menu.addSeparator(); - menu.addAction(tr("Remove Installed..."), this, SLOT(issueRemoveFromViewCompleted())); - menu.addAction(tr("Remove All..."), this, SLOT(issueRemoveFromViewAll())); + if (!hidden) { + menu.addSeparator(); + menu.addAction(tr("Remove Installed..."), this, SLOT(issueRemoveFromViewCompleted())); + menu.addAction(tr("Remove All..."), this, SLOT(issueRemoveFromViewAll())); + } menu.exec(mouseEvent->globalPos()); event->accept(); diff --git a/src/downloadlistwidget.h b/src/downloadlistwidget.h index c80200fb..f5bfdbaa 100644 --- a/src/downloadlistwidget.h +++ b/src/downloadlistwidget.h @@ -65,6 +65,7 @@ signals: void installDownload(int index); void queryInfo(int index); void removeDownload(int index, bool deleteFile); + void restoreDownload(int index); void cancelDownload(int index); void pauseDownload(int index); void resumeDownload(int index); @@ -83,6 +84,7 @@ private slots: void issueInstall(); void issueDelete(); void issueRemoveFromView(); + void issueRestoreToView(); void issueCancel(); void issuePause(); void issueResume(); diff --git a/src/downloadlistwidgetcompact.cpp b/src/downloadlistwidgetcompact.cpp index 8dd6e275..d2a71dd5 100644 --- a/src/downloadlistwidgetcompact.cpp +++ b/src/downloadlistwidgetcompact.cpp @@ -195,6 +195,11 @@ void DownloadListWidgetCompactDelegate::issueRemoveFromView() emit removeDownload(m_ContextIndex.row(), false); } +void DownloadListWidgetCompactDelegate::issueRestoreToView() +{ + emit restoreDownload(m_ContextIndex.row()); +} + void DownloadListWidgetCompactDelegate::issueCancel() { emit cancelDownload(m_ContextIndex.row()); @@ -265,13 +270,18 @@ bool DownloadListWidgetCompactDelegate::editorEvent(QEvent *event, QAbstractItem QMenu menu; m_ContextIndex = qobject_cast(model)->mapToSource(index); DownloadManager::DownloadState state = m_Manager->getState(m_ContextIndex.row()); + bool hidden = m_Manager->isHidden(m_ContextIndex.row()); if (state >= DownloadManager::STATE_READY) { menu.addAction(tr("Install"), this, SLOT(issueInstall())); if (m_Manager->isInfoIncomplete(m_ContextIndex.row())) { menu.addAction(tr("Query Info"), this, SLOT(issueQueryInfo())); } menu.addAction(tr("Delete"), this, SLOT(issueDelete())); - menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); + if (hidden) { + menu.addAction(tr("Un-Hide"), this, SLOT(issueRestoreToView())); + } else { + menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); + } } else if (state == DownloadManager::STATE_DOWNLOADING){ menu.addAction(tr("Cancel"), this, SLOT(issueCancel())); menu.addAction(tr("Pause"), this, SLOT(issuePause())); @@ -283,9 +293,11 @@ bool DownloadListWidgetCompactDelegate::editorEvent(QEvent *event, QAbstractItem menu.addSeparator(); menu.addAction(tr("Delete Installed..."), this, SLOT(issueDeleteCompleted())); menu.addAction(tr("Delete All..."), this, SLOT(issueDeleteAll())); - menu.addSeparator(); - menu.addAction(tr("Remove Installed..."), this, SLOT(issueRemoveFromViewCompleted())); - menu.addAction(tr("Remove All..."), this, SLOT(issueRemoveFromViewAll())); + if (!hidden) { + menu.addSeparator(); + menu.addAction(tr("Remove Installed..."), this, SLOT(issueRemoveFromViewCompleted())); + menu.addAction(tr("Remove All..."), this, SLOT(issueRemoveFromViewAll())); + } menu.exec(mouseEvent->globalPos()); event->accept(); diff --git a/src/downloadlistwidgetcompact.h b/src/downloadlistwidgetcompact.h index 78f51840..05d00b9d 100644 --- a/src/downloadlistwidgetcompact.h +++ b/src/downloadlistwidgetcompact.h @@ -65,6 +65,7 @@ signals: void installDownload(int index); void queryInfo(int index); void removeDownload(int index, bool deleteFile); + void restoreDownload(int index); void cancelDownload(int index); void pauseDownload(int index); void resumeDownload(int index); @@ -83,6 +84,7 @@ private slots: void issueInstall(); void issueDelete(); void issueRemoveFromView(); + void issueRestoreToView(); void issueCancel(); void issuePause(); void issueResume(); diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index b965d598..eca5600a 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -69,14 +69,16 @@ DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createNew(const Ne return info; } -DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createFromMeta(const QString &filePath) +DownloadManager::DownloadInfo *DownloadManager::DownloadInfo::createFromMeta(const QString &filePath, bool showHidden) { DownloadInfo *info = new DownloadInfo; QString metaFileName = filePath + ".meta"; QSettings metaFile(metaFileName, QSettings::IniFormat); - if (metaFile.value("removed", false).toBool()) { + if (!showHidden && metaFile.value("removed", false).toBool()) { return NULL; + } else { + info->m_Hidden = metaFile.value("removed", false).toBool(); } QString fileName = QFileInfo(filePath).fileName(); @@ -151,7 +153,7 @@ QString DownloadManager::DownloadInfo::currentURL() DownloadManager::DownloadManager(NexusInterface *nexusInterface, QObject *parent) - : IDownloadManager(parent), m_NexusInterface(nexusInterface), m_DirWatcher() + : IDownloadManager(parent), m_NexusInterface(nexusInterface), m_DirWatcher(), m_ShowHidden(false) { connect(&m_DirWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(directoryChanged(QString))); } @@ -188,13 +190,15 @@ void DownloadManager::pauseAll() ::Sleep(100); bool done = false; + QTime startTime = QTime::currentTime(); // further loops: busy waiting for all downloads to complete. This could be neater... - while (!done) { + while (!done && (startTime.secsTo(QTime::currentTime()) < 5)) { QCoreApplication::processEvents(); done = true; foreach (DownloadInfo *info, m_ActiveDownloads) { if ((info->m_State < STATE_CANCELED) || - (info->m_State != STATE_FETCHINGFILEINFO) || (info->m_State != STATE_FETCHINGMODINFO)) { + (info->m_State == STATE_FETCHINGFILEINFO) || + (info->m_State == STATE_FETCHINGMODINFO)) { done = false; break; } @@ -230,6 +234,12 @@ void DownloadManager::setSupportedExtensions(const QStringList &extensions) refreshList(); } +void DownloadManager::setShowHidden(bool showHidden) +{ + m_ShowHidden = showHidden; + refreshList(); +} + void DownloadManager::refreshList() { // remove finished downloads @@ -267,7 +277,7 @@ void DownloadManager::refreshList() QString fileName = QDir::fromNativeSeparators(m_OutputDirectory) + "/" + file; - DownloadInfo *info = DownloadInfo::createFromMeta(fileName); + DownloadInfo *info = DownloadInfo::createFromMeta(fileName, m_ShowHidden); if (info != NULL) { m_ActiveDownloads.push_front(info); } @@ -437,6 +447,22 @@ void DownloadManager::refreshAlphabeticalTranslation() } +void DownloadManager::restoreDownload(int index) +{ + if ((index < 0) || (index >= m_ActiveDownloads.size())) { + throw MyException(tr("invalid index")); + } + + DownloadInfo *download = m_ActiveDownloads.at(index); + download->m_Hidden = false; + + QString filePath = m_OutputDirectory + "/" + download->m_FileName; + + QSettings metaSettings(filePath.append(".meta"), QSettings::IniFormat); + metaSettings.setValue("removed", false); +} + + void DownloadManager::removeDownload(int index, bool deleteFile) { try { @@ -492,9 +518,13 @@ void DownloadManager::pauseDownload(int index) return; } - if (m_ActiveDownloads.at(index)->m_State == STATE_DOWNLOADING) { - setState(m_ActiveDownloads.at(index), STATE_PAUSING); - qDebug("pausing %d - %s", index, m_ActiveDownloads[index]->m_FileName.toUtf8().constData()); + DownloadInfo *info = m_ActiveDownloads.at(index); + + if (info->m_State == STATE_DOWNLOADING) { + setState(info, STATE_PAUSING); + qDebug("pausing %d - %s", index, info->m_FileName.toUtf8().constData()); + } else if ((info->m_State == STATE_FETCHINGMODINFO) || (info->m_State == STATE_FETCHINGFILEINFO)) { + setState(info, STATE_READY); } } @@ -671,6 +701,14 @@ int DownloadManager::getModID(int index) const return m_ActiveDownloads.at(index)->m_ModID; } +bool DownloadManager::isHidden(int index) const +{ + if ((index < 0) || (index >= m_ActiveDownloads.size())) { + throw MyException(tr("invalid index")); + } + return m_ActiveDownloads.at(index)->m_Hidden; +} + NexusInfo DownloadManager::getNexusInfo(int index) const { @@ -843,6 +881,7 @@ void DownloadManager::createMetaFile(DownloadInfo *info) metaFile.setValue("uninstalled", info->m_State == DownloadManager::STATE_UNINSTALLED); metaFile.setValue("paused", (info->m_State == DownloadManager::STATE_PAUSED) || (info->m_State == DownloadManager::STATE_ERROR)); + metaFile.setValue("removed", info->m_Hidden); // slightly hackish... for (int i = 0; i < m_ActiveDownloads.size(); ++i) { @@ -1110,6 +1149,7 @@ void DownloadManager::downloadFinished() QByteArray data = info->m_Reply->readAll(); info->m_Output.write(data); info->m_Output.close(); + TaskProgressManager::instance().forgetMe(info->m_TaskProgressId); bool error = false; diff --git a/src/downloadmanager.h b/src/downloadmanager.h index 0d49aa35..a42ac073 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -102,8 +102,10 @@ private: NexusInfo m_NexusInfo; + bool m_Hidden; + static DownloadInfo *createNew(const NexusInfo &nexusInfo, int modID, int fileID, const QStringList &URLs); - static DownloadInfo *createFromMeta(const QString &filePath); + static DownloadInfo *createFromMeta(const QString &filePath, bool showHidden); /** * @brief rename the file @@ -168,6 +170,11 @@ public: */ void setSupportedExtensions(const QStringList &extensions); + /** + * @brief sets whether hidden files are to be shown after all + */ + void setShowHidden(bool showHidden); + /** * @brief download from an already open network connection * @@ -263,6 +270,13 @@ public: **/ int getModID(int index) const; + /** + * @brief determine if the specified file is supposed to be hidden + * @param index index of the file to look up + * @return true if the specified file is supposed to be hidden + */ + bool isHidden(int index) const; + /** * @brief retrieve all nexus info of the download specified by index * @@ -352,6 +366,12 @@ public slots: **/ void removeDownload(int index, bool deleteFile); + /** + * @brief restores the specified download to view (which was previously hidden + * @param index index of the download to restore + */ + void restoreDownload(int index); + /** * @brief cancel the specified download. This will lead to the corresponding file to be deleted * @@ -436,6 +456,8 @@ private: std::map m_DownloadFails; + bool m_ShowHidden; + }; #endif // DOWNLOADMANAGER_H diff --git a/src/installationmanager.cpp b/src/installationmanager.cpp index 87efecf1..6b430eea 100644 --- a/src/installationmanager.cpp +++ b/src/installationmanager.cpp @@ -184,11 +184,7 @@ bool InstallationManager::unpackSingleFile(const QString &fileName) QString InstallationManager::extractFile(const QString &fileName) { if (unpackSingleFile(fileName)) { - QString tempFileName = QDir::tempPath().append("/").append(QFileInfo(fileName).fileName()); - - m_FilesToDelete.insert(tempFileName); - - return tempFileName; + return QDir::tempPath().append("/").append(QFileInfo(fileName).fileName()); } else { return QString(); } @@ -571,49 +567,36 @@ bool InstallationManager::doInstall(GuessedValue &modName, int modID, } -void InstallationManager::openFile(const QString &fileName) +bool InstallationManager::wasCancelled() { - unpackSingleFile(fileName); + return m_CurrentArchive->getLastError() == Archive::ERROR_EXTRACT_CANCELLED; +} - QString tempFileName = QDir::tempPath().append("/").append(QFileInfo(fileName).fileName()); - SHELLEXECUTEINFOW execInfo; - memset(&execInfo, 0, sizeof(SHELLEXECUTEINFOW)); - execInfo.cbSize = sizeof(SHELLEXECUTEINFOW); - execInfo.fMask = SEE_MASK_NOCLOSEPROCESS; - execInfo.lpVerb = L"open"; - std::wstring fileNameW = ToWString(tempFileName); - execInfo.lpFile = fileNameW.c_str(); - execInfo.nShow = SW_SHOWNORMAL; - if (!::ShellExecuteExW(&execInfo)) { - qCritical("failed to spawn %s: %d", tempFileName.toUtf8().constData(), ::GetLastError()); - } +void InstallationManager::postInstallCleanup() const +{ + m_CurrentArchive->close(); - m_FilesToDelete.insert(tempFileName); -} + // directories we may want to remove. sorted from longest to shortest to ensure we remove subdirectories first. + auto longestFirst = [](const QString &LHS, const QString &RHS) -> bool { + if (LHS.size() != RHS.size()) return LHS.size() > RHS.size(); + else return LHS < RHS; + }; + std::set> directoriesToRemove(longestFirst); -// copy and pasted from mo_dll -bool EndsWith(LPCWSTR string, LPCWSTR subString) -{ - size_t slen = wcslen(string); - size_t len = wcslen(subString); - if (slen < len) { - return false; + // clean up temp files + // TODO: this doesn't yet remove directories. Also, the files may be left there if this point isn't reached + foreach (const QString &tempFile, m_TempFilesToDelete) { + QFileInfo fileInfo(QDir::tempPath() + "/" + tempFile); + QFile::remove(fileInfo.absoluteFilePath()); + directoriesToRemove.insert(fileInfo.absolutePath()); } - for (size_t i = 0; i < len; ++i) { - if (towlower(string[slen - len + i]) != towlower(subString[i])) { - return false; - } + // try to delete each directory we had temporary files in. the call fails for non-empty directories which is ok + foreach (const QString &dir, directoriesToRemove) { + QDir().rmdir(dir); } - return true; -} - - -bool InstallationManager::wasCancelled() -{ - return m_CurrentArchive->getLastError() == Archive::ERROR_EXTRACT_CANCELLED; } @@ -675,9 +658,7 @@ bool InstallationManager::install(const QString &fileName, GuessedValue bool archiveOpen = m_CurrentArchive->open(ToWString(QDir::toNativeSeparators(fileName)).c_str(), new MethodCallback(this, &InstallationManager::queryPassword)); - ON_BLOCK_EXIT([this] { - this->m_CurrentArchive->close(); - }); + ON_BLOCK_EXIT(std::bind(&InstallationManager::postInstallCleanup, this)); QScopedPointer filesTree(archiveOpen ? createFilesTree() : NULL); IPluginInstaller::EInstallResult installResult = IPluginInstaller::RESULT_NOTATTEMPTED; @@ -729,13 +710,6 @@ bool InstallationManager::install(const QString &fileName, GuessedValue qPrintable(installer->name()), e.what()); } - // clean up temp files - // TODO: this doesn't yet remove directories. Also, the files may be left there if this point isn't reached - foreach (const QString &tempFile, m_TempFilesToDelete) { - QFile::remove(QDir::tempPath() + "/" + tempFile); - } - - // act upon the installation result. at this point the files have already been // extracted to the correct location switch (installResult) { diff --git a/src/installationmanager.h b/src/installationmanager.h index 0e43a15d..1c6f9f19 100644 --- a/src/installationmanager.h +++ b/src/installationmanager.h @@ -168,9 +168,7 @@ private: bool ensureValidModName(MOBase::GuessedValue &name) const; -private slots: - - void openFile(const QString &fileName); + void postInstallCleanup() const; private: @@ -202,7 +200,6 @@ private: QProgressDialog m_InstallationProgress; - std::set m_FilesToDelete; std::set m_TempFilesToDelete; }; diff --git a/src/main.cpp b/src/main.cpp index c4431ac4..7c2a9b0e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -433,7 +433,10 @@ int main(int argc, char *argv[]) qDebug("initializing tutorials"); TutorialManager::init(QDir::fromNativeSeparators(ToQString(GameInfo::instance().getTutorialDir())).append("/")); - application.setStyleFile(settings.value("Settings/style", "").toString()); + if (!application.setStyleFile(settings.value("Settings/style", "").toString())) { + // disable invalid stylesheet + settings.setValue("Settings/style", ""); + } int res = 1; { // scope to control lifetime of mainwindow diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 57201db9..33dc75ed 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -4265,6 +4265,7 @@ void MainWindow::updateDownloadListDelegate() connect(ui->downloadView->itemDelegate(), SIGNAL(installDownload(int)), this, SLOT(installDownload(int))); connect(ui->downloadView->itemDelegate(), SIGNAL(queryInfo(int)), &m_DownloadManager, SLOT(queryInfo(int))); connect(ui->downloadView->itemDelegate(), SIGNAL(removeDownload(int, bool)), &m_DownloadManager, SLOT(removeDownload(int, bool))); + connect(ui->downloadView->itemDelegate(), SIGNAL(restoreDownload(int)), &m_DownloadManager, SLOT(restoreDownload(int))); connect(ui->downloadView->itemDelegate(), SIGNAL(cancelDownload(int)), &m_DownloadManager, SLOT(cancelDownload(int))); connect(ui->downloadView->itemDelegate(), SIGNAL(pauseDownload(int)), &m_DownloadManager, SLOT(pauseDownload(int))); connect(ui->downloadView->itemDelegate(), SIGNAL(resumeDownload(int)), &m_DownloadManager, SLOT(resumeDownload(int))); @@ -4735,3 +4736,8 @@ void MainWindow::on_linkButton_pressed() ui->linkButton->menu()->actions().at(1)->setIcon(linkDesktopFile.exists() ? removeIcon : addIcon); ui->linkButton->menu()->actions().at(2)->setIcon(linkMenuFile.exists() ? removeIcon : addIcon); } + +void MainWindow::on_showHiddenBox_toggled(bool checked) +{ + m_DownloadManager.setShowHidden(checked); +} diff --git a/src/mainwindow.h b/src/mainwindow.h index dfec5f49..ad4ed82e 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -502,6 +502,7 @@ private slots: // ui slots void on_groupCombo_currentIndexChanged(int index); void on_categoriesList_itemSelectionChanged(); void on_linkButton_pressed(); + void on_showHiddenBox_toggled(bool checked); }; #endif // MAINWINDOW_H diff --git a/src/mainwindow.ui b/src/mainwindow.ui index 923df17c..b29136ff 100644 --- a/src/mainwindow.ui +++ b/src/mainwindow.ui @@ -968,7 +968,7 @@ p, li { white-space: pre-wrap; } - + @@ -976,6 +976,13 @@ p, li { white-space: pre-wrap; } + + + + Show Hidden + + + diff --git a/src/moapplication.cpp b/src/moapplication.cpp index efb0b615..ac660c6c 100644 --- a/src/moapplication.cpp +++ b/src/moapplication.cpp @@ -32,7 +32,7 @@ MOApplication::MOApplication(int argc, char **argv) } -void MOApplication::setStyleFile(const QString &styleName) +bool MOApplication::setStyleFile(const QString &styleName) { // remove all files from watch QStringList currentWatch = m_StyleWatcher.files(); @@ -42,11 +42,15 @@ void MOApplication::setStyleFile(const QString &styleName) // set new stylesheet or clear it if (styleName.length() != 0) { QString styleSheetName = applicationDirPath() + "/" + MOBase::ToQString(AppConfig::stylesheetsPath()) + "/" + styleName; + if (!QFile::exists(styleSheetName)) { + return false; + } m_StyleWatcher.addPath(styleSheetName); updateStyle(styleSheetName); } else { setStyleSheet(""); } + return true; } diff --git a/src/moapplication.h b/src/moapplication.h index 3d74031d..dd7f5eab 100644 --- a/src/moapplication.h +++ b/src/moapplication.h @@ -17,33 +17,33 @@ You should have received a copy of the GNU General Public License along with Mod Organizer. If not, see . */ -#ifndef MOAPPLICATION_H -#define MOAPPLICATION_H - -#include -#include - - -class MOApplication : public QApplication { -Q_OBJECT -public: - - MOApplication(int argc, char **argv); - - virtual bool notify (QObject *receiver, QEvent *event); - -public slots: - - void setStyleFile(const QString &style); - -private slots: - - void updateStyle(const QString &fileName); - -private: - - QFileSystemWatcher m_StyleWatcher; -}; - - -#endif // MOAPPLICATION_H +#ifndef MOAPPLICATION_H +#define MOAPPLICATION_H + +#include +#include + + +class MOApplication : public QApplication { +Q_OBJECT +public: + + MOApplication(int argc, char **argv); + + virtual bool notify (QObject *receiver, QEvent *event); + +public slots: + + bool setStyleFile(const QString &style); + +private slots: + + void updateStyle(const QString &fileName); + +private: + + QFileSystemWatcher m_StyleWatcher; +}; + + +#endif // MOAPPLICATION_H diff --git a/src/shared/skyriminfo.cpp b/src/shared/skyriminfo.cpp index 8c6b79ef..71d791f5 100644 --- a/src/shared/skyriminfo.cpp +++ b/src/shared/skyriminfo.cpp @@ -295,6 +295,7 @@ std::vector SkyrimInfo::getExecutables() result.push_back(ExecutableInfo(L"SKSE", L"skse_loader.exe", L"", L"", DEFAULT_CLOSE)); result.push_back(ExecutableInfo(L"SBW", L"SBW.exe", L"", L"", DEFAULT_CLOSE)); result.push_back(ExecutableInfo(L"Skyrim", L"TESV.exe", L"", L"", DEFAULT_CLOSE)); + result.push_back(ExecutableInfo(L"Skyrim Launcher", L"SkyrimLauncher.exe", L"", L"", DEFAULT_CLOSE)); result.push_back(ExecutableInfo(L"BOSS", L"BOSS/BOSS.exe", L"", L"", DEFAULT_STAY)); result.push_back(ExecutableInfo(L"Creation Kit", L"CreationKit.exe", L"", L"", DEFAULT_STAY, L"202480")); diff --git a/src/version.rc b/src/version.rc index 16669011..e71bc1b5 100644 --- a/src/version.rc +++ b/src/version.rc @@ -1,7 +1,7 @@ #include "Winver.h" -#define VER_FILEVERSION 1,0,4,0 -#define VER_FILEVERSION_STR "1,0,4,0\0" +#define VER_FILEVERSION 1,0,5,0 +#define VER_FILEVERSION_STR "1,0,5,0\0" VS_VERSION_INFO VERSIONINFO FILEVERSION VER_FILEVERSION -- cgit v1.3.1 From bdf04f516ca7c5274ff50104662e372ed29aea6b Mon Sep 17 00:00:00 2001 From: Tannin Date: Thu, 10 Oct 2013 21:23:25 +0200 Subject: - MO now warns if a nxm-link for a wrong game was attempted instead of downloading the wrong file - bugfix: in nxmhandler adding a new line with different game but same executable didn't work (the change was silently dropped) --- src/downloadmanager.cpp | 17 +++++++++++++++-- src/downloadmanager.h | 2 +- src/nexusinterface.cpp | 4 +--- 3 files changed, 17 insertions(+), 6 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index eca5600a..779b052c 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -376,6 +376,15 @@ void DownloadManager::startDownload(QNetworkReply *reply, DownloadInfo *newDownl void DownloadManager::addNXMDownload(const QString &url) { NXMUrl nxmInfo(url); + + QString managedGame = ToQString(MOShared::GameInfo::instance().getGameShortName()); + + if (nxmInfo.game().compare(managedGame, Qt::CaseInsensitive) != 0) { + QMessageBox::information(NULL, tr("Wrong Game"), tr("The download link is for a mod for \"%1\" but this instance of MO " + "has been set up for \"%2\".").arg(nxmInfo.game()).arg(managedGame), QMessageBox::Ok); + return; + } + m_RequestIDs.insert(m_NexusInterface->requestFileInfo(nxmInfo.getModId(), nxmInfo.getFileId(), this, QVariant())); } @@ -990,7 +999,7 @@ void DownloadManager::nxmFilesAvailable(int, QVariant userData, QVariant resultD } -void DownloadManager::nxmFileInfoAvailable(int modID, int fileID, QVariant, QVariant resultData, int requestID) +void DownloadManager::nxmFileInfoAvailable(int modID, int fileID, QVariant userData, QVariant resultData, int requestID) { std::set::iterator idIter = m_RequestIDs.find(requestID); if (idIter == m_RequestIDs.end()) { @@ -1007,7 +1016,11 @@ void DownloadManager::nxmFileInfoAvailable(int modID, int fileID, QVariant, QVar info.m_Version = result["version"].toString(); info.m_FileName = result["uri"].toString(); - m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(modID, fileID, this, qVariantFromValue(info))); + if (userData.isValid()) { + m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(modID, fileID, this, qVariantFromValue(info), userData.toString())); + } else { + m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(modID, fileID, this, qVariantFromValue(info))); + } } diff --git a/src/downloadmanager.h b/src/downloadmanager.h index a42ac073..e82ea064 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -125,7 +125,7 @@ private: private: static unsigned int s_NextDownloadID; private: - DownloadInfo() : m_TotalSize(0), m_ReQueried(false) {} + DownloadInfo() : m_TotalSize(0), m_ReQueried(false), m_Hidden(false) {} }; public: diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index bee0bb44..936ff400 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -397,7 +397,7 @@ void NexusInterface::nextRequest() QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/xml"); #pragma message("automatically insert the correct version number") - request.setRawHeader("User-Agent", QString("Mod Organizer v0.99.0 (compatible to Nexus Client v%1)").arg(m_NMMVersion).toUtf8()); + request.setRawHeader("User-Agent", QString("Mod Organizer v1.0.5 (compatible to Nexus Client v%1)").arg(m_NMMVersion).toUtf8()); info.m_Reply = m_AccessManager->get(request); @@ -414,8 +414,6 @@ void NexusInterface::downloadRequestedNXM(const QString &url) emit requestNXMDownload(url); } -#include - void NexusInterface::requestFinished(std::list::iterator iter) { QNetworkReply *reply = iter->m_Reply; -- cgit v1.3.1 From 469cc2d945afebb1291a825339642b5e95f0e223 Mon Sep 17 00:00:00 2001 From: Tannin Date: Sat, 7 Dec 2013 12:48:18 +0100 Subject: - download manager now saves the file times on nexus, for potential later use in version check - nexus interface now supports 301 redirects - now using the new nexus url format - bugfix: "visit on nexus" used an outdated url scheme and thus caused unnecessary redirection --- src/downloadmanager.cpp | 26 ++++++++++++++++--- src/downloadmanager.h | 5 ++++ src/mainwindow.cpp | 2 +- src/nexusinterface.cpp | 59 ++++++++++++++++++++++++++------------------ src/nexusinterface.h | 7 +++--- src/shared/fallout3info.cpp | 4 +-- src/shared/fallout3info.h | 1 + src/shared/falloutnvinfo.cpp | 4 +-- src/shared/falloutnvinfo.h | 1 + src/shared/gameinfo.h | 1 + src/shared/oblivioninfo.cpp | 4 +-- src/shared/oblivioninfo.h | 1 + src/shared/skyriminfo.cpp | 4 +-- src/shared/skyriminfo.h | 1 + 14 files changed, 80 insertions(+), 40 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 779b052c..48484d24 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -153,7 +153,8 @@ QString DownloadManager::DownloadInfo::currentURL() DownloadManager::DownloadManager(NexusInterface *nexusInterface, QObject *parent) - : IDownloadManager(parent), m_NexusInterface(nexusInterface), m_DirWatcher(), m_ShowHidden(false) + : IDownloadManager(parent), m_NexusInterface(nexusInterface), m_DirWatcher(), m_ShowHidden(false), + m_DateExpression("/Date\\((\\d+)\\)/") { connect(&m_DirWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(directoryChanged(QString))); } @@ -851,7 +852,6 @@ void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) setState(info, STATE_PAUSED); } else { if (bytesTotal > info->m_TotalSize) { - qDebug("file size %s: %lld", qPrintable(info->m_FileName), bytesTotal); info->m_TotalSize = bytesTotal; } int oldProgress = info->m_Progress; @@ -883,6 +883,7 @@ void DownloadManager::createMetaFile(DownloadInfo *info) metaFile.setValue("name", info->m_NexusInfo.m_Name); metaFile.setValue("modName", info->m_NexusInfo.m_ModName); metaFile.setValue("version", info->m_NexusInfo.m_Version); + metaFile.setValue("fileTime", info->m_NexusInfo.m_FileTime); metaFile.setValue("fileCategory", info->m_NexusInfo.m_FileCategory); metaFile.setValue("newestVersion", info->m_NexusInfo.m_NewestVersion); metaFile.setValue("category", info->m_NexusInfo.m_Category); @@ -914,11 +915,9 @@ void DownloadManager::nxmDescriptionAvailable(int, QVariant userData, QVariant r DownloadInfo *info = downloadInfoByID(userData.toInt()); if (info == NULL) return; - info->m_NexusInfo.m_Category = result["category_id"].toInt(); info->m_NexusInfo.m_ModName = result["name"].toString().trimmed(); info->m_NexusInfo.m_NewestVersion = result["version"].toString(); - if (info->m_FileID != 0) { setState(info, STATE_READY); } else { @@ -927,6 +926,17 @@ void DownloadManager::nxmDescriptionAvailable(int, QVariant userData, QVariant r } +QDateTime DownloadManager::matchDate(const QString &timeString) +{ + if (m_DateExpression.exactMatch(timeString)) { + return QDateTime::fromMSecsSinceEpoch(m_DateExpression.cap(1).toLongLong()); + } else { + qWarning("date not matched: %s", qPrintable(timeString)); + return QDateTime::currentDateTime(); + } +} + + void DownloadManager::nxmFilesAvailable(int, QVariant userData, QVariant resultData, int requestID) { std::set::iterator idIter = m_RequestIDs.find(requestID); @@ -960,7 +970,11 @@ void DownloadManager::nxmFilesAvailable(int, QVariant userData, QVariant resultD (fileNameVariant == info->m_FileName) || (fileNameVariant == alternativeLocalName)) { info->m_NexusInfo.m_Name = fileInfo["name"].toString(); info->m_NexusInfo.m_Version = fileInfo["version"].toString(); + if (info->m_NexusInfo.m_Version.isEmpty()) { + info->m_NexusInfo.m_Version = info->m_NexusInfo.m_NewestVersion; + } info->m_NexusInfo.m_FileCategory = fileInfo["category_id"].toInt(); + info->m_NexusInfo.m_FileTime = matchDate(fileInfo["date"].toString()); info->m_FileID = fileInfo["id"].toInt(); found = true; break; @@ -1014,7 +1028,11 @@ void DownloadManager::nxmFileInfoAvailable(int modID, int fileID, QVariant userD info.m_Name = result["name"].toString(); info.m_Version = result["version"].toString(); + if (info.m_Version.isEmpty()) { + info.m_Version = info.m_NewestVersion; + } info.m_FileName = result["uri"].toString(); + info.m_FileTime = matchDate(result["date"].toString()); if (userData.isValid()) { m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(modID, fileID, this, qVariantFromValue(info), userData.toString())); diff --git a/src/downloadmanager.h b/src/downloadmanager.h index e82ea064..099e6084 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -46,6 +46,7 @@ struct NexusInfo { QString m_NewestVersion; QString m_FileName; QVariantList m_DownloadMap; + QDateTime m_FileTime; bool m_Set; }; Q_DECLARE_METATYPE(NexusInfo) @@ -437,6 +438,8 @@ private: DownloadInfo *downloadInfoByID(unsigned int id); + QDateTime matchDate(const QString &timeString); + private: static const int AUTOMATIC_RETRIES = 3; @@ -458,6 +461,8 @@ private: bool m_ShowHidden; + QRegExp m_DateExpression; + }; #endif // DOWNLOADMANAGER_H diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index d5330017..cca10279 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3214,7 +3214,7 @@ void MainWindow::visitOnNexus_clicked() { int modID = m_ModList.data(m_ModList.index(m_ContextRow, 0), Qt::UserRole).toInt(); if (modID > 0) { - nexusLinkActivated(QString("%1/downloads/file.php?id=%2").arg(ToQString(GameInfo::instance().getNexusPage())).arg(modID)); + nexusLinkActivated(QString("%1/mods/%2").arg(ToQString(GameInfo::instance().getNexusPage())).arg(modID)); } else { MessageDialog::showMessage(tr("Nexus ID for this Mod is unknown"), this); } diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 6a4ae046..6b5cf19c 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -380,29 +380,33 @@ void NexusInterface::nextRequest() info.m_Timeout->setInterval(60000); QString url; - switch (info.m_Type) { - case NXMRequestInfo::TYPE_DESCRIPTION: { - url = QString("%1/Mods/%2/").arg(info.m_URL).arg(info.m_ModID); - } break; - case NXMRequestInfo::TYPE_FILES: { - url = QString("%1/Files/indexfrommod/%2/").arg(info.m_URL).arg(info.m_ModID); - } break; - case NXMRequestInfo::TYPE_FILEINFO: { - url = QString("%1/Files/%2/").arg(info.m_URL).arg(info.m_FileID); - } break; - case NXMRequestInfo::TYPE_DOWNLOADURL: { - url = QString("%1/Files/download/%2").arg(info.m_URL).arg(info.m_FileID); - } break; - case NXMRequestInfo::TYPE_TOGGLEENDORSEMENT: { - url = QString("%1/Mods/toggleendorsement/%2?lvote=%3").arg(info.m_URL).arg(info.m_ModID).arg(!info.m_Endorse); - } break; - case NXMRequestInfo::TYPE_GETUPDATES: { - QString modIDList = VectorJoin(info.m_ModIDList, ","); - modIDList = "[" + modIDList + "]"; - url = QString("%1/Mods/GetUpdates?ModList=%2").arg(info.m_URL).arg(modIDList); - } break; + if (!info.m_Reroute) { + switch (info.m_Type) { + case NXMRequestInfo::TYPE_DESCRIPTION: { + url = QString("%1/Mods/%2/").arg(info.m_URL).arg(info.m_ModID); + } break; + case NXMRequestInfo::TYPE_FILES: { + url = QString("%1/Files/indexfrommod/%2/").arg(info.m_URL).arg(info.m_ModID); + } break; + case NXMRequestInfo::TYPE_FILEINFO: { + url = QString("%1/Files/%2/").arg(info.m_URL).arg(info.m_FileID); + } break; + case NXMRequestInfo::TYPE_DOWNLOADURL: { + url = QString("%1/Files/download/%2").arg(info.m_URL).arg(info.m_FileID); + } break; + case NXMRequestInfo::TYPE_TOGGLEENDORSEMENT: { + url = QString("%1/Mods/toggleendorsement/%2?lvote=%3").arg(info.m_URL).arg(info.m_ModID).arg(!info.m_Endorse); + } break; + case NXMRequestInfo::TYPE_GETUPDATES: { + QString modIDList = VectorJoin(info.m_ModIDList, ","); + modIDList = "[" + modIDList + "]"; + url = QString("%1/Mods/GetUpdates?ModList=%2").arg(info.m_URL).arg(modIDList); + } break; + } + url.append(QString("?game_id=%1").arg(GameInfo::instance().getNexusGameID())); + } else { + url = info.m_URL; } - QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/xml"); request.setRawHeader("User-Agent", @@ -433,13 +437,21 @@ void NexusInterface::requestFinished(std::list::iterator iter) qWarning("request failed: %s", reply->errorString().toUtf8().constData()); emit nxmRequestFailed(iter->m_ModID, iter->m_UserData, iter->m_ID, reply->errorString()); } else { + int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + if (statusCode == 301) { + // redirect request, return request to queue + iter->m_URL = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); + iter->m_Reroute = true; + m_RequestQueue.enqueue(*iter); + nextRequest(); + return; + } QByteArray data = reply->readAll(); if (data.isNull() || data.isEmpty() || (strcmp(data.constData(), "null") == 0)) { QString nexusError(reply->rawHeader("NexusErrorInfo")); if (nexusError.length() == 0) { nexusError = tr("empty response"); } - emit nxmRequestFailed(iter->m_ModID, iter->m_UserData, iter->m_ID, nexusError); } else { bool ok; @@ -509,7 +521,6 @@ void NexusInterface::requestTimeout() qWarning("invalid sender type"); return; } - qWarning("request timeout"); for (std::list::iterator iter = m_ActiveRequest.begin(); iter != m_ActiveRequest.end(); ++iter) { if (iter->m_Timeout == timer) { // this abort causes a "request failed" which cleans up the rest diff --git a/src/nexusinterface.h b/src/nexusinterface.h index da5fe02a..e7a01b0f 100644 --- a/src/nexusinterface.h +++ b/src/nexusinterface.h @@ -270,18 +270,19 @@ private: QVariant m_UserData; QTimer *m_Timeout; QString m_URL; + bool m_Reroute; int m_ID; int m_Endorse; NXMRequestInfo(int modID, Type type, QVariant userData, const QString &url) : m_ModID(modID), m_FileID(0), m_Reply(NULL), m_Type(type), m_UserData(userData), - m_Timeout(NULL), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} + m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} NXMRequestInfo(std::vector modIDList, Type type, QVariant userData, const QString &url) : m_ModID(-1), m_ModIDList(modIDList), m_FileID(0), m_Reply(NULL), m_Type(type), m_UserData(userData), - m_Timeout(NULL), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} + m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} NXMRequestInfo(int modID, int fileID, Type type, QVariant userData, const QString &url) : m_ModID(modID), m_FileID(fileID), m_Reply(NULL), m_Type(type), m_UserData(userData), - m_Timeout(NULL), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} + m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} private: static QAtomicInt s_NextID; diff --git a/src/shared/fallout3info.cpp b/src/shared/fallout3info.cpp index c673fa1b..864a67be 100644 --- a/src/shared/fallout3info.cpp +++ b/src/shared/fallout3info.cpp @@ -155,13 +155,13 @@ std::wstring Fallout3Info::getSEName() std::wstring Fallout3Info::getNexusPage() { - return L"http://fallout3.nexusmods.com"; + return L"http://www.nexusmods.com/fallout3"; } std::wstring Fallout3Info::getNexusInfoUrlStatic() { - return L"http://fallout3.nexusmods.com"; + return L"http://www.nexusmods.com/fallout3"; } diff --git a/src/shared/fallout3info.h b/src/shared/fallout3info.h index 0fa97d41..4bcb9d37 100644 --- a/src/shared/fallout3info.h +++ b/src/shared/fallout3info.h @@ -76,6 +76,7 @@ public: virtual std::wstring getNexusInfoUrl() { return Fallout3Info::getNexusInfoUrlStatic(); } static int getNexusModIDStatic(); virtual int getNexusModID() { return Fallout3Info::getNexusModIDStatic(); } + virtual int getNexusGameID() { return 120; } virtual void createProfile(const std::wstring &directory, bool useDefaults); virtual void repairProfile(const std::wstring &directory); diff --git a/src/shared/falloutnvinfo.cpp b/src/shared/falloutnvinfo.cpp index 7d7f0098..8df9607d 100644 --- a/src/shared/falloutnvinfo.cpp +++ b/src/shared/falloutnvinfo.cpp @@ -209,13 +209,13 @@ std::wstring FalloutNVInfo::getSEName() std::wstring FalloutNVInfo::getNexusPage() { - return L"http://newvegas.nexusmods.com"; + return L"http://www.nexusmods.com/newvegas"; } std::wstring FalloutNVInfo::getNexusInfoUrlStatic() { - return L"http://newvegas.nexusmods.com"; + return L"http://www.nexusmods.com/newvegas"; } diff --git a/src/shared/falloutnvinfo.h b/src/shared/falloutnvinfo.h index 3960c951..e25d2e02 100644 --- a/src/shared/falloutnvinfo.h +++ b/src/shared/falloutnvinfo.h @@ -77,6 +77,7 @@ public: virtual std::wstring getNexusInfoUrl() { return FalloutNVInfo::getNexusInfoUrlStatic(); } static int getNexusModIDStatic(); virtual int getNexusModID() { return FalloutNVInfo::getNexusModIDStatic(); } + virtual int getNexusGameID() { return 130; } virtual void createProfile(const std::wstring &directory, bool useDefaults); virtual void repairProfile(const std::wstring &directory); diff --git a/src/shared/gameinfo.h b/src/shared/gameinfo.h index 0221dd1b..d517fc1b 100644 --- a/src/shared/gameinfo.h +++ b/src/shared/gameinfo.h @@ -145,6 +145,7 @@ public: virtual std::wstring getNexusPage() = 0; virtual std::wstring getNexusInfoUrl() = 0; virtual int getNexusModID() = 0; + virtual int getNexusGameID() = 0; // clone relevant files to the specified directory virtual void createProfile(const std::wstring &directory, bool useDefaults) = 0; diff --git a/src/shared/oblivioninfo.cpp b/src/shared/oblivioninfo.cpp index b3e65e59..1438de0a 100644 --- a/src/shared/oblivioninfo.cpp +++ b/src/shared/oblivioninfo.cpp @@ -191,13 +191,13 @@ std::wstring OblivionInfo::getSEName() std::wstring OblivionInfo::getNexusPage() { - return L"http://oblivion.nexusmods.com"; + return L"http://www.nexusmods.com/oblivion"; } std::wstring OblivionInfo::getNexusInfoUrlStatic() { - return L"http://oblivion.nexusmods.com"; + return L"http://www.nexusmods.com/oblivion"; } diff --git a/src/shared/oblivioninfo.h b/src/shared/oblivioninfo.h index 6a9f56ca..dfa53575 100644 --- a/src/shared/oblivioninfo.h +++ b/src/shared/oblivioninfo.h @@ -73,6 +73,7 @@ public: virtual std::wstring getNexusInfoUrl() { return OblivionInfo::getNexusInfoUrlStatic(); } static int getNexusModIDStatic(); virtual int getNexusModID() { return OblivionInfo::getNexusModIDStatic(); } + virtual int getNexusGameID() { return 101; } virtual void createProfile(const std::wstring &directory, bool useDefaults); virtual void repairProfile(const std::wstring &directory); diff --git a/src/shared/skyriminfo.cpp b/src/shared/skyriminfo.cpp index 0a0dd98d..a8b9a433 100644 --- a/src/shared/skyriminfo.cpp +++ b/src/shared/skyriminfo.cpp @@ -183,13 +183,13 @@ std::wstring SkyrimInfo::getSEName() std::wstring SkyrimInfo::getNexusPage() { - return L"http://skyrim.nexusmods.com"; + return L"http://www.nexusmods.com/skyrim"; } std::wstring SkyrimInfo::getNexusInfoUrlStatic() { - return L"http://skyrim.nexusmods.com"; + return L"http://www.nexusmods.com/skyrim"; } diff --git a/src/shared/skyriminfo.h b/src/shared/skyriminfo.h index ae5ab81f..7da523a1 100644 --- a/src/shared/skyriminfo.h +++ b/src/shared/skyriminfo.h @@ -81,6 +81,7 @@ public: virtual std::wstring getNexusInfoUrl() { return SkyrimInfo::getNexusInfoUrlStatic(); } static int getNexusModIDStatic(); virtual int getNexusModID() { return SkyrimInfo::getNexusModIDStatic(); } + virtual int getNexusGameID() { return 110; } virtual void createProfile(const std::wstring &directory, bool useDefaults); virtual void repairProfile(const std::wstring &directory); -- cgit v1.3.1 From 4dc3538a7d14dd0f1aaa2e6c172745b63e251c86 Mon Sep 17 00:00:00 2001 From: Tannin Date: Sat, 4 Jan 2014 15:57:14 +0100 Subject: - nxmhandler will now ask before registering itself - downloads from nexus are now displayed before file information is retrieved - logging from the ui is now a bit more informative - download list now scrolls to bottom automatically --- src/downloadlist.cpp | 19 ++-- src/downloadlistsortproxy.cpp | 22 +++-- src/downloadlistwidget.cpp | 179 +++++++++++++++++++++----------------- src/downloadlistwidget.h | 3 + src/downloadlistwidgetcompact.cpp | 148 ++++++++++++++++++------------- src/downloadlistwidgetcompact.h | 2 + src/downloadmanager.cpp | 49 ++++++++++- src/downloadmanager.h | 25 ++++++ src/logbuffer.cpp | 15 +++- src/logbuffer.h | 2 + src/mainwindow.cpp | 12 ++- src/messagedialog.cpp | 1 + src/settings.cpp | 9 ++ src/settings.h | 7 ++ src/settingsdialog.cpp | 6 ++ src/settingsdialog.h | 2 + src/settingsdialog.ui | 44 +++++++--- 17 files changed, 368 insertions(+), 177 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadlist.cpp b/src/downloadlist.cpp index fe021a27..d280cdb6 100644 --- a/src/downloadlist.cpp +++ b/src/downloadlist.cpp @@ -34,9 +34,10 @@ DownloadList::DownloadList(DownloadManager *manager, QObject *parent) int DownloadList::rowCount(const QModelIndex&) const { - return m_Manager->numTotalDownloads(); + return m_Manager->numTotalDownloads() + m_Manager->numPendingDownloads(); } + int DownloadList::columnCount(const QModelIndex&) const { return 3; @@ -75,14 +76,18 @@ QVariant DownloadList::data(const QModelIndex &index, int role) const if (role == Qt::DisplayRole) { return index.row(); } else if (role == Qt::ToolTipRole) { - QString text = m_Manager->getFileName(index.row()) + "\n"; - if (m_Manager->isInfoIncomplete(index.row())) { - text += tr("Information missing, please select \"Query Info\" from the context menu to re-retrieve."); + if (index.row() < m_Manager->numTotalDownloads()) { + QString text = m_Manager->getFileName(index.row()) + "\n"; + if (m_Manager->isInfoIncomplete(index.row())) { + text += tr("Information missing, please select \"Query Info\" from the context menu to re-retrieve."); + } else { + NexusInfo info = m_Manager->getNexusInfo(index.row()); + text += QString("%1 (ID %2) %3").arg(info.m_ModName).arg(m_Manager->getModID(index.row())).arg(info.m_Version); + } + return text; } else { - NexusInfo info = m_Manager->getNexusInfo(index.row()); - text += QString("%1 (ID %2) %3").arg(info.m_ModName).arg(m_Manager->getModID(index.row())).arg(info.m_Version); + return tr("pending download"); } - return text; } else { return QVariant(); } diff --git a/src/downloadlistsortproxy.cpp b/src/downloadlistsortproxy.cpp index fc743574..7abe8579 100644 --- a/src/downloadlistsortproxy.cpp +++ b/src/downloadlistsortproxy.cpp @@ -37,13 +37,16 @@ bool DownloadListSortProxy::lessThan(const QModelIndex &left, { int leftIndex = sourceModel()->data(left).toInt(); int rightIndex = sourceModel()->data(right).toInt(); - - if (left.column() == DownloadList::COL_NAME) { - return m_Manager->getFileName(leftIndex).compare(m_Manager->getFileName(rightIndex), Qt::CaseInsensitive) < 0; - } else if (left.column() == DownloadList::COL_FILETIME) { - return m_Manager->getFileTime(leftIndex) < m_Manager->getFileTime(rightIndex); - } else if (left.column() == DownloadList::COL_STATUS) { - return m_Manager->getState(leftIndex) < m_Manager->getState(rightIndex); + if (leftIndex < m_Manager->numTotalDownloads()) { + if (left.column() == DownloadList::COL_NAME) { + return m_Manager->getFileName(leftIndex).compare(m_Manager->getFileName(rightIndex), Qt::CaseInsensitive) < 0; + } else if (left.column() == DownloadList::COL_FILETIME) { + return m_Manager->getFileTime(leftIndex) < m_Manager->getFileTime(rightIndex); + } else if (left.column() == DownloadList::COL_STATUS) { + return m_Manager->getState(leftIndex) < m_Manager->getState(rightIndex); + } else { + return leftIndex < rightIndex; + } } else { return leftIndex < rightIndex; } @@ -54,6 +57,9 @@ bool DownloadListSortProxy::filterAcceptsRow(int source_row, const QModelIndex&) { if (m_CurrentFilter.length() == 0) { return true; + } else if (source_row < m_Manager->numTotalDownloads()) { + return m_Manager->getFileName(source_row).contains(m_CurrentFilter, Qt::CaseInsensitive); + } else { + return false; } - return m_Manager->getFileName(source_row).contains(m_CurrentFilter, Qt::CaseInsensitive); } diff --git a/src/downloadlistwidget.cpp b/src/downloadlistwidget.cpp index b4d40799..68dd2adf 100644 --- a/src/downloadlistwidget.cpp +++ b/src/downloadlistwidget.cpp @@ -82,80 +82,100 @@ void DownloadListWidgetDelegate::drawCache(QPainter *painter, const QStyleOption } -void DownloadListWidgetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +void DownloadListWidgetDelegate::paintPendingDownload(int downloadIndex) const { - try { - auto iter = m_Cache.find(index.row()); - if (iter != m_Cache.end()) { - drawCache(painter, option, *iter); - return; - } - - m_ItemWidget->resize(QSize(m_View->columnWidth(0) + m_View->columnWidth(1) + m_View->columnWidth(2), option.rect.height())); + std::pair nexusids = m_Manager->getPendingDownload(downloadIndex); + m_NameLabel->setText(tr("< mod %1 file %2 >").arg(nexusids.first).arg(nexusids.second)); + m_SizeLabel->setText("???"); + m_InstallLabel->setVisible(true); + m_InstallLabel->setText(tr("Pending")); + m_Progress->setVisible(false); +} - int downloadIndex = index.data().toInt(); - QString name = m_Manager->getFileName(downloadIndex); - if (name.length() > 53) { - name.truncate(50); - name.append("..."); - } - m_NameLabel->setText(name); - m_SizeLabel->setText(QString::number(m_Manager->getFileSize(downloadIndex) / 1024)); - DownloadManager::DownloadState state = m_Manager->getState(downloadIndex); - if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { - QPalette labelPalette; - m_InstallLabel->setVisible(true); - m_Progress->setVisible(false); +void DownloadListWidgetDelegate::paintRegularDownload(int downloadIndex) const +{ + QString name = m_Manager->getFileName(downloadIndex); + if (name.length() > 53) { + name.truncate(50); + name.append("..."); + } + m_NameLabel->setText(name); + m_SizeLabel->setText(QString::number(m_Manager->getFileSize(downloadIndex) / 1024)); + DownloadManager::DownloadState state = m_Manager->getState(downloadIndex); + if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { + QPalette labelPalette; + m_InstallLabel->setVisible(true); + m_Progress->setVisible(false); #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Paused - Double Click to resume", 0)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Paused - Double Click to resume", 0)); #else - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Paused - Double Click to resume", 0, QApplication::UnicodeUTF8)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Paused - Double Click to resume", 0, QApplication::UnicodeUTF8)); #endif - labelPalette.setColor(QPalette::WindowText, Qt::darkRed); - m_InstallLabel->setPalette(labelPalette); - } else if (state == DownloadManager::STATE_FETCHINGMODINFO) { - m_InstallLabel->setText(tr("Fetching Info 1")); - m_Progress->setVisible(false); - } else if (state == DownloadManager::STATE_FETCHINGFILEINFO) { - m_InstallLabel->setText(tr("Fetching Info 2")); - m_Progress->setVisible(false); - } else if (state >= DownloadManager::STATE_READY) { - QPalette labelPalette; - m_InstallLabel->setVisible(true); - m_Progress->setVisible(false); - if (state == DownloadManager::STATE_INSTALLED) { - // the tr-macro doesn't work here, maybe because the translation is actually associated with DownloadListWidget instead - // of DownloadListWidgetDelegate? + labelPalette.setColor(QPalette::WindowText, Qt::darkRed); + m_InstallLabel->setPalette(labelPalette); + } else if (state == DownloadManager::STATE_FETCHINGMODINFO) { + m_InstallLabel->setText(tr("Fetching Info 1")); + m_Progress->setVisible(false); + } else if (state == DownloadManager::STATE_FETCHINGFILEINFO) { + m_InstallLabel->setText(tr("Fetching Info 2")); + m_Progress->setVisible(false); + } else if (state >= DownloadManager::STATE_READY) { + QPalette labelPalette; + m_InstallLabel->setVisible(true); + m_Progress->setVisible(false); + if (state == DownloadManager::STATE_INSTALLED) { + // the tr-macro doesn't work here, maybe because the translation is actually associated with DownloadListWidget instead + // of DownloadListWidgetDelegate? #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Installed - Double Click to re-install", 0)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Installed - Double Click to re-install", 0)); #else - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Installed - Double Click to re-install", 0, QApplication::UnicodeUTF8)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Installed - Double Click to re-install", 0, QApplication::UnicodeUTF8)); #endif - labelPalette.setColor(QPalette::WindowText, Qt::darkGray); - } else if (state == DownloadManager::STATE_UNINSTALLED) { + labelPalette.setColor(QPalette::WindowText, Qt::darkGray); + } else if (state == DownloadManager::STATE_UNINSTALLED) { #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Uninstalled - Double Click to re-install", 0)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Uninstalled - Double Click to re-install", 0)); #else - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Uninstalled - Double Click to re-install", 0, QApplication::UnicodeUTF8)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Uninstalled - Double Click to re-install", 0, QApplication::UnicodeUTF8)); #endif - labelPalette.setColor(QPalette::WindowText, Qt::lightGray); - } else { + labelPalette.setColor(QPalette::WindowText, Qt::lightGray); + } else { #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Done - Double Click to install", 0)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Done - Double Click to install", 0)); #else - m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Done - Double Click to install", 0, QApplication::UnicodeUTF8)); + m_InstallLabel->setText(QApplication::translate("DownloadListWidget", "Done - Double Click to install", 0, QApplication::UnicodeUTF8)); #endif - labelPalette.setColor(QPalette::WindowText, Qt::darkGreen); - } - m_InstallLabel->setPalette(labelPalette); - if (m_Manager->isInfoIncomplete(downloadIndex)) { - m_NameLabel->setText(" " + m_NameLabel->text()); - } + labelPalette.setColor(QPalette::WindowText, Qt::darkGreen); + } + m_InstallLabel->setPalette(labelPalette); + if (m_Manager->isInfoIncomplete(downloadIndex)) { + m_NameLabel->setText(" " + m_NameLabel->text()); + } + } else { + m_InstallLabel->setVisible(false); + m_Progress->setVisible(true); + m_Progress->setValue(m_Manager->getProgress(downloadIndex)); + } +} + +void DownloadListWidgetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + try { + auto iter = m_Cache.find(index.row()); + if (iter != m_Cache.end()) { + drawCache(painter, option, *iter); + return; + } + + m_ItemWidget->resize(QSize(m_View->columnWidth(0) + m_View->columnWidth(1) + m_View->columnWidth(2), option.rect.height())); + + int downloadIndex = index.data().toInt(); + + if (downloadIndex >= m_Manager->numTotalDownloads()) { + paintPendingDownload(downloadIndex - m_Manager->numTotalDownloads()); } else { - m_InstallLabel->setVisible(false); - m_Progress->setVisible(true); - m_Progress->setValue(m_Manager->getProgress(downloadIndex)); + paintRegularDownload(downloadIndex); } #pragma message("caching disabled because changes in the list (including resorting) doesn't work correctly") @@ -280,29 +300,32 @@ bool DownloadListWidgetDelegate::editorEvent(QEvent *event, QAbstractItemModel * QMouseEvent *mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::RightButton) { QMenu menu(m_View); + bool hidden = false; m_ContextRow = qobject_cast(model)->mapToSource(index).row(); - DownloadManager::DownloadState state = m_Manager->getState(m_ContextRow); - bool hidden = m_Manager->isHidden(m_ContextRow); - if (state >= DownloadManager::STATE_READY) { - menu.addAction(tr("Install"), this, SLOT(issueInstall())); - if (m_Manager->isInfoIncomplete(m_ContextRow)) { - menu.addAction(tr("Query Info"), this, SLOT(issueQueryInfo())); + if (m_ContextRow < m_Manager->numTotalDownloads()) { + DownloadManager::DownloadState state = m_Manager->getState(m_ContextRow); + hidden = m_Manager->isHidden(m_ContextRow); + if (state >= DownloadManager::STATE_READY) { + menu.addAction(tr("Install"), this, SLOT(issueInstall())); + if (m_Manager->isInfoIncomplete(m_ContextRow)) { + menu.addAction(tr("Query Info"), this, SLOT(issueQueryInfo())); + } + menu.addAction(tr("Delete"), this, SLOT(issueDelete())); + if (hidden) { + menu.addAction(tr("Un-Hide"), this, SLOT(issueRestoreToView())); + } else { + menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); + } + } else if (state == DownloadManager::STATE_DOWNLOADING){ + menu.addAction(tr("Cancel"), this, SLOT(issueCancel())); + menu.addAction(tr("Pause"), this, SLOT(issuePause())); + } else if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { + menu.addAction(tr("Remove"), this, SLOT(issueDelete())); + menu.addAction(tr("Resume"), this, SLOT(issueResume())); } - menu.addAction(tr("Delete"), this, SLOT(issueDelete())); - if (hidden) { - menu.addAction(tr("Un-Hide"), this, SLOT(issueRestoreToView())); - } else { - menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); - } - } else if (state == DownloadManager::STATE_DOWNLOADING){ - menu.addAction(tr("Cancel"), this, SLOT(issueCancel())); - menu.addAction(tr("Pause"), this, SLOT(issuePause())); - } else if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { - menu.addAction(tr("Remove"), this, SLOT(issueDelete())); - menu.addAction(tr("Resume"), this, SLOT(issueResume())); - } - menu.addSeparator(); + menu.addSeparator(); + } menu.addAction(tr("Delete Installed..."), this, SLOT(issueDeleteCompleted())); menu.addAction(tr("Delete All..."), this, SLOT(issueDeleteAll())); if (!hidden) { diff --git a/src/downloadlistwidget.h b/src/downloadlistwidget.h index f5bfdbaa..80c4430a 100644 --- a/src/downloadlistwidget.h +++ b/src/downloadlistwidget.h @@ -60,6 +60,9 @@ public: virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + void paintPendingDownload(int downloadIndex) const; + void paintRegularDownload(int downloadIndex) const; + signals: void installDownload(int index); diff --git a/src/downloadlistwidgetcompact.cpp b/src/downloadlistwidgetcompact.cpp index d2a71dd5..e2fbcd24 100644 --- a/src/downloadlistwidgetcompact.cpp +++ b/src/downloadlistwidgetcompact.cpp @@ -82,6 +82,66 @@ void DownloadListWidgetCompactDelegate::drawCache(QPainter *painter, const QStyl } +void DownloadListWidgetCompactDelegate::paintPendingDownload(int downloadIndex) const +{ + std::pair nexusids = m_Manager->getPendingDownload(downloadIndex); + m_NameLabel->setText(tr("< mod %1 file %2 >").arg(nexusids.first).arg(nexusids.second)); + if (m_SizeLabel != NULL) { + m_SizeLabel->setText("???"); + } + m_DoneLabel->setVisible(true); + m_DoneLabel->setText(tr("Pending")); + m_Progress->setVisible(false); +} + + +void DownloadListWidgetCompactDelegate::paintRegularDownload(int downloadIndex) const +{ + QString name = m_Manager->getFileName(downloadIndex); + if (name.length() > 53) { + name.truncate(50); + name.append("..."); + } + m_NameLabel->setText(name); + + DownloadManager::DownloadState state = m_Manager->getState(downloadIndex); + + if ((m_SizeLabel != NULL) && (state >= DownloadManager::STATE_READY)) { + m_SizeLabel->setText(QString::number(m_Manager->getFileSize(downloadIndex) / 1048576)); + } + + if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { + m_DoneLabel->setVisible(true); + m_Progress->setVisible(false); + m_DoneLabel->setText(tr("Paused")); + m_DoneLabel->setForegroundRole(QPalette::Link); + } else if (state == DownloadManager::STATE_FETCHINGMODINFO) { + m_DoneLabel->setText(tr("Fetching Info 1")); + } else if (state == DownloadManager::STATE_FETCHINGFILEINFO) { + m_DoneLabel->setText(tr("Fetching Info 2")); + } else if (state >= DownloadManager::STATE_READY) { + m_DoneLabel->setVisible(true); + m_Progress->setVisible(false); + if (state == DownloadManager::STATE_INSTALLED) { + m_DoneLabel->setText(tr("Installed")); + m_DoneLabel->setForegroundRole(QPalette::Mid); + } else if (state == DownloadManager::STATE_UNINSTALLED) { + m_DoneLabel->setText(tr("Uninstalled")); + m_DoneLabel->setForegroundRole(QPalette::Dark); + } else { + m_DoneLabel->setText(tr("Done")); + m_DoneLabel->setForegroundRole(QPalette::WindowText); + } + if (m_Manager->isInfoIncomplete(downloadIndex)) { + m_NameLabel->setText(" " + m_NameLabel->text()); + } + } else { + m_DoneLabel->setVisible(false); + m_Progress->setVisible(true); + m_Progress->setValue(m_Manager->getProgress(downloadIndex)); + } +} + void DownloadListWidgetCompactDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { #pragma message("This is quite costy - room for optimization?") @@ -100,49 +160,10 @@ void DownloadListWidgetCompactDelegate::paint(QPainter *painter, const QStyleOpt } int downloadIndex = index.data().toInt(); - - QString name = m_Manager->getFileName(downloadIndex); - if (name.length() > 53) { - name.truncate(50); - name.append("..."); - } - m_NameLabel->setText(name); - - DownloadManager::DownloadState state = m_Manager->getState(downloadIndex); - - if ((m_SizeLabel != NULL) && (state >= DownloadManager::STATE_READY)) { - m_SizeLabel->setText(QString::number(m_Manager->getFileSize(downloadIndex) / 1048576)); - } - - if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { - m_DoneLabel->setVisible(true); - m_Progress->setVisible(false); - m_DoneLabel->setText(tr("Paused")); - m_DoneLabel->setForegroundRole(QPalette::Link); - } else if (state == DownloadManager::STATE_FETCHINGMODINFO) { - m_DoneLabel->setText(tr("Fetching Info 1")); - } else if (state == DownloadManager::STATE_FETCHINGFILEINFO) { - m_DoneLabel->setText(tr("Fetching Info 2")); - } else if (state >= DownloadManager::STATE_READY) { - m_DoneLabel->setVisible(true); - m_Progress->setVisible(false); - if (state == DownloadManager::STATE_INSTALLED) { - m_DoneLabel->setText(tr("Installed")); - m_DoneLabel->setForegroundRole(QPalette::Mid); - } else if (state == DownloadManager::STATE_UNINSTALLED) { - m_DoneLabel->setText(tr("Uninstalled")); - m_DoneLabel->setForegroundRole(QPalette::Dark); - } else { - m_DoneLabel->setText(tr("Done")); - m_DoneLabel->setForegroundRole(QPalette::WindowText); - } - if (m_Manager->isInfoIncomplete(downloadIndex)) { - m_NameLabel->setText(" " + m_NameLabel->text()); - } + if (downloadIndex >= m_Manager->numTotalDownloads()) { + paintPendingDownload(downloadIndex - m_Manager->numTotalDownloads()); } else { - m_DoneLabel->setVisible(false); - m_Progress->setVisible(true); - m_Progress->setValue(m_Manager->getProgress(downloadIndex)); + paintRegularDownload(downloadIndex); } #pragma message("caching disabled because changes in the list (including resorting) doesn't work correctly") @@ -268,29 +289,32 @@ bool DownloadListWidgetCompactDelegate::editorEvent(QEvent *event, QAbstractItem QMouseEvent *mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::RightButton) { QMenu menu; + bool hidden = false; m_ContextIndex = qobject_cast(model)->mapToSource(index); - DownloadManager::DownloadState state = m_Manager->getState(m_ContextIndex.row()); - bool hidden = m_Manager->isHidden(m_ContextIndex.row()); - if (state >= DownloadManager::STATE_READY) { - menu.addAction(tr("Install"), this, SLOT(issueInstall())); - if (m_Manager->isInfoIncomplete(m_ContextIndex.row())) { - menu.addAction(tr("Query Info"), this, SLOT(issueQueryInfo())); - } - menu.addAction(tr("Delete"), this, SLOT(issueDelete())); - if (hidden) { - menu.addAction(tr("Un-Hide"), this, SLOT(issueRestoreToView())); - } else { - menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); + if (m_ContextIndex.row() < m_Manager->numTotalDownloads()) { + DownloadManager::DownloadState state = m_Manager->getState(m_ContextIndex.row()); + hidden = m_Manager->isHidden(m_ContextIndex.row()); + if (state >= DownloadManager::STATE_READY) { + menu.addAction(tr("Install"), this, SLOT(issueInstall())); + if (m_Manager->isInfoIncomplete(m_ContextIndex.row())) { + menu.addAction(tr("Query Info"), this, SLOT(issueQueryInfo())); + } + menu.addAction(tr("Delete"), this, SLOT(issueDelete())); + if (hidden) { + menu.addAction(tr("Un-Hide"), this, SLOT(issueRestoreToView())); + } else { + menu.addAction(tr("Remove from View"), this, SLOT(issueRemoveFromView())); + } + } else if (state == DownloadManager::STATE_DOWNLOADING){ + menu.addAction(tr("Cancel"), this, SLOT(issueCancel())); + menu.addAction(tr("Pause"), this, SLOT(issuePause())); + } else if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { + menu.addAction(tr("Remove"), this, SLOT(issueDelete())); + menu.addAction(tr("Resume"), this, SLOT(issueResume())); } - } else if (state == DownloadManager::STATE_DOWNLOADING){ - menu.addAction(tr("Cancel"), this, SLOT(issueCancel())); - menu.addAction(tr("Pause"), this, SLOT(issuePause())); - } else if ((state == DownloadManager::STATE_PAUSED) || (state == DownloadManager::STATE_ERROR)) { - menu.addAction(tr("Remove"), this, SLOT(issueDelete())); - menu.addAction(tr("Resume"), this, SLOT(issueResume())); - } - menu.addSeparator(); + menu.addSeparator(); + } menu.addAction(tr("Delete Installed..."), this, SLOT(issueDeleteCompleted())); menu.addAction(tr("Delete All..."), this, SLOT(issueDeleteAll())); if (!hidden) { diff --git a/src/downloadlistwidgetcompact.h b/src/downloadlistwidgetcompact.h index 05d00b9d..4d7f40de 100644 --- a/src/downloadlistwidgetcompact.h +++ b/src/downloadlistwidgetcompact.h @@ -78,6 +78,8 @@ protected: private: void drawCache(QPainter *painter, const QStyleOptionViewItem &option, const QPixmap &cache) const; + void paintPendingDownload(int downloadIndex) const; + void paintRegularDownload(int downloadIndex) const; private slots: diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 48484d24..61c5113c 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -323,6 +323,7 @@ bool DownloadManager::addDownload(QNetworkReply *reply, const QStringList &URLs, (QMessageBox::question(NULL, tr("Download again?"), tr("A file with the same name has already been downloaded. " "Do you want to download it again? The new file will receive a different name."), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No)) { + removePending(modID, fileID); delete newDownload; return false; } @@ -331,11 +332,24 @@ bool DownloadManager::addDownload(QNetworkReply *reply, const QStringList &URLs, startDownload(reply, newDownload, false); - emit update(-1); +// emit update(-1); return true; } +void DownloadManager::removePending(int modID, int fileID) +{ + emit aboutToUpdate(); + for (auto iter = m_PendingDownloads.begin(); iter != m_PendingDownloads.end(); ++iter) { + if ((iter->first == modID) && (iter->second == fileID)) { + m_PendingDownloads.erase(iter); + break; + } + } + emit update(-1); +} + + void DownloadManager::startDownload(QNetworkReply *reply, DownloadInfo *newDownload, bool resume) { newDownload->m_Reply = reply; @@ -365,11 +379,14 @@ void DownloadManager::startDownload(QNetworkReply *reply, DownloadInfo *newDownl if (!resume) { newDownload->m_PreResumeSize = newDownload->m_Output.size(); + removePending(newDownload->m_ModID, newDownload->m_FileID); + emit aboutToUpdate(); m_ActiveDownloads.append(newDownload); emit update(-1); + emit downloadAdded(); } } @@ -379,14 +396,21 @@ void DownloadManager::addNXMDownload(const QString &url) NXMUrl nxmInfo(url); QString managedGame = ToQString(MOShared::GameInfo::instance().getGameShortName()); - + qDebug("add nxm download", qPrintable(url)); if (nxmInfo.game().compare(managedGame, Qt::CaseInsensitive) != 0) { + qDebug("download requested for wrong game (game: %s, url: %s)", qPrintable(managedGame), qPrintable(nxmInfo.game())); QMessageBox::information(NULL, tr("Wrong Game"), tr("The download link is for a mod for \"%1\" but this instance of MO " "has been set up for \"%2\".").arg(nxmInfo.game()).arg(managedGame), QMessageBox::Ok); return; } - m_RequestIDs.insert(m_NexusInterface->requestFileInfo(nxmInfo.getModId(), nxmInfo.getFileId(), this, QVariant())); + emit aboutToUpdate(); + + m_PendingDownloads.append(std::make_pair(nxmInfo.modId(), nxmInfo.fileId())); + + emit update(-1); + emit downloadAdded(); + m_RequestIDs.insert(m_NexusInterface->requestFileInfo(nxmInfo.modId(), nxmInfo.fileId(), this, QVariant())); } @@ -628,6 +652,19 @@ int DownloadManager::numTotalDownloads() const return m_ActiveDownloads.size(); } +int DownloadManager::numPendingDownloads() const +{ + return m_PendingDownloads.size(); +} + +std::pair DownloadManager::getPendingDownload(int index) +{ + if ((index < 0) || (index >= m_PendingDownloads.size())) { + throw MyException(tr("invalid index")); + } + + return m_PendingDownloads.at(index); +} QString DownloadManager::getFilePath(int index) const { @@ -1025,8 +1062,8 @@ void DownloadManager::nxmFileInfoAvailable(int modID, int fileID, QVariant userD NexusInfo info; QVariantMap result = resultData.toMap(); - info.m_Name = result["name"].toString(); + qDebug("file info received for %s", qPrintable(info.m_Name)); info.m_Version = result["version"].toString(); if (info.m_Version.isEmpty()) { info.m_Version = info.m_NewestVersion; @@ -1121,9 +1158,12 @@ void DownloadManager::nxmDownloadURLsAvailable(int modID, int fileID, QVariant u m_RequestIDs.erase(idIter); } + qDebug("download urls received (modid %d, fileid %d)", modID, fileID); + NexusInfo info = userData.value(); QVariantList resultList = resultData.toList(); if (resultList.length() == 0) { + removePending(modID, fileID); emit showMessage(tr("No download server available. Please try again later.")); return; } @@ -1282,3 +1322,4 @@ void DownloadManager::directoryChanged(const QString&) { refreshList(); } + diff --git a/src/downloadmanager.h b/src/downloadmanager.h index 099e6084..62396666 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -205,6 +205,19 @@ public: **/ int numTotalDownloads() const; + /** + * @brief retrieve number of pending downloads (nexus downloads for which we don't know the name and url yet) + * @return number of pending downloads + */ + int numPendingDownloads() const; + + /** + * @brief retrieve the info of a pending download + * @param index index of the pending download (index in the range [0, numPendingDownloads()[) + * @return pair of modid, fileid + */ + std::pair getPendingDownload(int index); + /** * @brief retrieve the full path to the download specified by index * @@ -357,6 +370,11 @@ signals: */ void downloadSpeed(const QString &serverName, int bytesPerSecond); + /** + * @brief emitted whenever a new download is added to the list + */ + void downloadAdded(); + public slots: /** @@ -440,6 +458,8 @@ private: QDateTime matchDate(const QString &timeString); + void removePending(int modID, int fileID); + private: static const int AUTOMATIC_RETRIES = 3; @@ -447,6 +467,9 @@ private: private: NexusInterface *m_NexusInterface; + + QVector > m_PendingDownloads; + QVector m_ActiveDownloads; QString m_OutputDirectory; @@ -465,4 +488,6 @@ private: }; + + #endif // DOWNLOADMANAGER_H diff --git a/src/logbuffer.cpp b/src/logbuffer.cpp index a3b6f1b5..f930cf10 100644 --- a/src/logbuffer.cpp +++ b/src/logbuffer.cpp @@ -112,13 +112,26 @@ void LogBuffer::log(QtMsgType type, const QMessageLogContext &context, const QSt #else + +char LogBuffer::msgTypeID(QtMsgType type) +{ + switch (type) { + case QtDebugMsg: return 'D'; + case QtWarningMsg: return 'W'; + case QtCriticalMsg: return 'C'; + case QtFatalMsg: return 'F'; + } +} + +#include + void LogBuffer::log(QtMsgType type, const char *message) { QMutexLocker guard(&s_Mutex); if (!s_Instance.isNull()) { s_Instance->logMessage(type, message); } - fprintf(stdout, "%s\n", message); + fprintf(stdout, "[%c] %s: %s\n", msgTypeID(type), qPrintable(QTime::currentTime().toString()), message); fflush(stdout); } diff --git a/src/logbuffer.h b/src/logbuffer.h index de5e887f..68753996 100644 --- a/src/logbuffer.h +++ b/src/logbuffer.h @@ -60,6 +60,8 @@ private: void write() const; + static char msgTypeID(QtMsgType type); + private: static QScopedPointer s_Instance; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3a543e0b..ee7ee139 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -230,9 +230,9 @@ MainWindow::MainWindow(const QString &exeName, QSettings &initSettings, QWidget ui->savegameList->installEventFilter(this); ui->savegameList->setMouseTracking(true); - connect(&m_DownloadManager, SIGNAL(showMessage(QString)), this, SLOT(showMessage(QString))); connect(&m_DownloadManager, SIGNAL(downloadSpeed(QString,int)), this, SLOT(downloadSpeed(QString,int))); + connect(&m_DownloadManager, SIGNAL(downloadAdded()), ui->downloadView, SLOT(scrollToBottom())); connect(ui->savegameList, SIGNAL(itemEntered(QListWidgetItem*)), this, SLOT(saveSelectionChanged(QListWidgetItem*))); @@ -780,6 +780,8 @@ void MainWindow::showEvent(QShowEvent *event) ui->groupCombo->setCurrentIndex(grouping); allowListResize(); + + m_Settings.registerAsNXMHandler(false); } @@ -4024,15 +4026,10 @@ void MainWindow::on_actionSettings_triggered() NexusInterface::instance()->setNMMVersion(m_Settings.getNMMVersion()); } + void MainWindow::on_actionNexus_triggered() { - std::wstring nxmPath = ToWString(QApplication::applicationDirPath() + "/nxmhandler.exe"); - std::wstring executable = ToWString(QApplication::applicationFilePath()); - ::ShellExecuteW(NULL, L"open", nxmPath.c_str(), - (std::wstring(L"reg ") + GameInfo::instance().getGameShortName() + L" \"" + executable + L"\"").c_str(), NULL, SW_SHOWNORMAL); - ::ShellExecuteW(NULL, L"open", GameInfo::instance().getNexusPage(false).c_str(), NULL, NULL, SW_SHOWNORMAL); - ui->tabWidget->setCurrentIndex(4); } @@ -4052,6 +4049,7 @@ void MainWindow::linkClicked(const QString &url) void MainWindow::downloadRequestedNXM(const QString &url) { QString username, password; + qDebug("download requested: %s", qPrintable(url)); if (!m_LoginAttempted && !NexusInterface::instance()->getAccessManager()->loggedIn() && (m_Settings.getNexusLogin(username, password) || diff --git a/src/messagedialog.cpp b/src/messagedialog.cpp index 4a1ef0d6..8cef1b7c 100644 --- a/src/messagedialog.cpp +++ b/src/messagedialog.cpp @@ -81,6 +81,7 @@ void MessageDialog::resizeEvent(QResizeEvent *event) void MessageDialog::showMessage(const QString &text, QWidget *reference) { + qDebug("%s", qPrintable(text)); if (reference != NULL) { MessageDialog *dialog = new MessageDialog(text, reference); dialog->show(); diff --git a/src/settings.cpp b/src/settings.cpp index 8086672a..895094f7 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -102,6 +102,15 @@ bool Settings::pluginBlacklisted(const QString &fileName) const return m_PluginBlacklist.contains(fileName); } +void Settings::registerAsNXMHandler(bool force) +{ + std::wstring nxmPath = ToWString(QCoreApplication::applicationDirPath() + "/nxmhandler.exe"); + std::wstring executable = ToWString(QCoreApplication::applicationFilePath()); + std::wstring mode = force ? L"forcereg" : L"reg"; + ::ShellExecuteW(NULL, L"open", nxmPath.c_str(), + (mode + L" " + GameInfo::instance().getGameShortName() + L" \"" + executable + L"\"").c_str(), NULL, SW_SHOWNORMAL); +} + void Settings::registerPlugin(IPlugin *plugin) { m_Plugins.push_back(plugin); diff --git a/src/settings.h b/src/settings.h index abffc94b..81174440 100644 --- a/src/settings.h +++ b/src/settings.h @@ -256,6 +256,13 @@ public: */ std::vector plugins() const { return m_Plugins; } + /** + * @brief register MO as the handler for nxm links + * @param force set to true to enforce the registration dialog to show up, + * even if the user said earlier not to + */ + void registerAsNXMHandler(bool force); + private: QString obfuscate(const QString &password) const; diff --git a/src/settingsdialog.cpp b/src/settingsdialog.cpp index c8908ddb..bf1f95dc 100644 --- a/src/settingsdialog.cpp +++ b/src/settingsdialog.cpp @@ -29,6 +29,7 @@ along with Mod Organizer. If not, see . #include #define WIN32_LEAN_AND_MEAN #include +#include "settings.h" using namespace MOBase; @@ -165,3 +166,8 @@ void SettingsDialog::deleteBlacklistItem() { ui->pluginBlacklist->takeItem(ui->pluginBlacklist->currentIndex().row()); } + +void SettingsDialog::on_associateButton_clicked() +{ + Settings::instance().registerAsNXMHandler(true); +} diff --git a/src/settingsdialog.h b/src/settingsdialog.h index 718574a0..0bd9fd23 100644 --- a/src/settingsdialog.h +++ b/src/settingsdialog.h @@ -75,6 +75,8 @@ private slots: void deleteBlacklistItem(); + void on_associateButton_clicked(); + private: Ui::SettingsDialog *ui; }; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 39d49a39..bda6726c 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -275,32 +275,29 @@ p, li { white-space: pre-wrap; } - - - QFormLayout::AllNonFixedFieldsGrow - - + + Username - + false - + Password - + false @@ -342,13 +339,40 @@ p, li { white-space: pre-wrap; } - + + + + + Associate with "Download with manager" links + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 4 + - Known Servers (Dynamically updated every download) + Known Servers (updated on download) -- cgit v1.3.1 From 859c0aed984240467e9e59f72aa4c9714df9fb0b Mon Sep 17 00:00:00 2001 From: Tannin Date: Sat, 4 Jan 2014 16:39:38 +0100 Subject: download manager now removed orphaned meta files --- src/downloadmanager.cpp | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 61c5113c..f0f4ba2d 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -218,8 +218,8 @@ void DownloadManager::setOutputDirectory(const QString &outputDirectory) m_DirWatcher.removePaths(directories); } m_OutputDirectory = QDir::fromNativeSeparators(outputDirectory); - m_DirWatcher.addPath(m_OutputDirectory); refreshList(); + m_DirWatcher.addPath(m_OutputDirectory); } @@ -243,6 +243,8 @@ void DownloadManager::setShowHidden(bool showHidden) void DownloadManager::refreshList() { + int downloadsBefore = m_ActiveDownloads.size(); + // remove finished downloads for (QVector::iterator Iter = m_ActiveDownloads.begin(); Iter != m_ActiveDownloads.end();) { if (((*Iter)->m_State == STATE_READY) || ((*Iter)->m_State == STATE_INSTALLED)) { @@ -259,9 +261,22 @@ void DownloadManager::refreshList() } nameFilters.append(QString("*").append(UNFINISHED)); - QDir dir(QDir::fromNativeSeparators(m_OutputDirectory)); + // find orphaned meta files and delete them (sounds cruel but it's better for everyone) + QStringList orphans; + QStringList metaFiles = dir.entryList(QStringList() << "*.meta"); + foreach (const QString &metaFile, metaFiles) { + QString baseFile = metaFile.left(metaFile.length() - 5); + if (!QFile::exists(dir.absoluteFilePath(baseFile))) { + orphans.append(dir.absoluteFilePath(metaFile)); + } + } + if (orphans.size() > 0) { + qDebug("%d orphaned meta files will be deleted", orphans.size()); + shellDelete(orphans, true); + } + // add existing downloads to list foreach (QString file, dir.entryList(nameFilters, QDir::Files, QDir::Time)) { bool Exists = false; @@ -273,6 +288,7 @@ void DownloadManager::refreshList() } } if (Exists) { + qDebug("%s exists", qPrintable(file)); continue; } @@ -283,7 +299,10 @@ void DownloadManager::refreshList() m_ActiveDownloads.push_front(info); } } - qDebug("downloads after refresh: %d", m_ActiveDownloads.size()); + + if (m_ActiveDownloads.size() != downloadsBefore) { + qDebug("downloads after refresh: %d", m_ActiveDownloads.size()); + } emit update(-1); } -- cgit v1.3.1 From a083a2d3b6506ab95d3b18ab0ffa7751750e0249 Mon Sep 17 00:00:00 2001 From: Tannin Date: Mon, 13 Jan 2014 19:32:54 +0100 Subject: - implemented hook for NtQueryDirectoryFile - saves list is now automatically updated on FS changes - optimization: data tree widget is no longer filled completely at once but one directory at a time - bugfix: pending downloads were not removed from list after a failed nxm request - bugfix: there was still a nmm.nexusmods.com link - bugfix: the text "alpha" in version strings wasn't interpreted correctly --- src/downloadmanager.cpp | 6 ++-- src/logbuffer.cpp | 2 +- src/mainwindow.cpp | 67 +++++++++++++++++++++++++++++++++++++++------ src/mainwindow.h | 5 ++++ src/modinfodialog.cpp | 2 +- src/organizer.pro | 10 ++++++- src/shared/directoryentry.h | 2 ++ 7 files changed, 81 insertions(+), 13 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index f0f4ba2d..fdc825f1 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -429,7 +429,7 @@ void DownloadManager::addNXMDownload(const QString &url) emit update(-1); emit downloadAdded(); - m_RequestIDs.insert(m_NexusInterface->requestFileInfo(nxmInfo.modId(), nxmInfo.fileId(), this, QVariant())); + m_RequestIDs.insert(m_NexusInterface->requestFileInfo(nxmInfo.modId(), nxmInfo.fileId(), this, nxmInfo.fileId())); } @@ -1201,7 +1201,7 @@ void DownloadManager::nxmDownloadURLsAvailable(int modID, int fileID, QVariant u } -void DownloadManager::nxmRequestFailed(int modID, QVariant, int requestID, const QString &errorString) +void DownloadManager::nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorString) { std::set::iterator idIter = m_RequestIDs.find(requestID); if (idIter == m_RequestIDs.end()) { @@ -1225,6 +1225,8 @@ void DownloadManager::nxmRequestFailed(int modID, QVariant, int requestID, const break; } } + + removePending(modID, userData.toInt()); emit showMessage(tr("Failed to request file info from nexus: %1").arg(errorString)); } diff --git a/src/logbuffer.cpp b/src/logbuffer.cpp index f930cf10..6f3f640f 100644 --- a/src/logbuffer.cpp +++ b/src/logbuffer.cpp @@ -131,7 +131,7 @@ void LogBuffer::log(QtMsgType type, const char *message) if (!s_Instance.isNull()) { s_Instance->logMessage(type, message); } - fprintf(stdout, "[%c] %s: %s\n", msgTypeID(type), qPrintable(QTime::currentTime().toString()), message); + fprintf(stdout, "%s [%c] %s\n", qPrintable(QTime::currentTime().toString()), msgTypeID(type), message); fflush(stdout); } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 80465fb9..139db3f0 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -256,13 +256,16 @@ MainWindow::MainWindow(const QString &exeName, QSettings &initSettings, QWidget connect(&m_PluginList, SIGNAL(saveTimer()), this, SLOT(savePluginList())); connect(ui->bsaList, SIGNAL(itemsMoved()), this, SLOT(bsaList_itemMoved())); - connect(ui->bsaWarning, SIGNAL(linkActivated(QString)), this, SLOT(linkClicked(QString))); + connect(ui->dataTree, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(expandDataTreeItem(QTreeWidgetItem*))); + connect(&m_DirectoryRefresher, SIGNAL(refreshed()), this, SLOT(directory_refreshed())); connect(&m_DirectoryRefresher, SIGNAL(progress(int)), this, SLOT(refresher_progress(int))); connect(&m_DirectoryRefresher, SIGNAL(error(QString)), this, SLOT(showError(QString))); + connect(&m_SavesWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(refreshSavesIfOpen())); + connect(&m_Settings, SIGNAL(languageChanged(QString)), this, SLOT(languageChange(QString))); connect(&m_Settings, SIGNAL(styleChanged(QString)), this, SIGNAL(styleChanged(QString))); @@ -1526,21 +1529,52 @@ void MainWindow::updateTo(QTreeWidgetItem *subTree, const std::wstring &director std::vector::const_iterator current, end; directoryEntry.getSubDirectories(current, end); for (; current != end; ++current) { - QStringList columns(ToQString((*current)->getName())); + QString pathName = ToQString((*current)->getName()); + QStringList columns(pathName); columns.append(""); - QTreeWidgetItem *directoryChild = new QTreeWidgetItem(columns); - updateTo(directoryChild, temp.str(), **current, conflictsOnly); - if (directoryChild->childCount() != 0) { + if (!(*current)->isEmpty()) { + QTreeWidgetItem *directoryChild = new QTreeWidgetItem(columns); + QTreeWidgetItem *onDemandLoad = new QTreeWidgetItem(QStringList()); + onDemandLoad->setData(0, Qt::UserRole + 0, "__loaded_on_demand__"); + onDemandLoad->setData(0, Qt::UserRole + 1, ToQString(temp.str())); + onDemandLoad->setData(0, Qt::UserRole + 2, conflictsOnly); + directoryChild->addChild(onDemandLoad); subTree->addChild(directoryChild); - } else { - delete directoryChild; +/* updateTo(directoryChild, temp.str(), **current, conflictsOnly); + if (directoryChild->childCount() != 0) { + subTree->addChild(directoryChild); + } else { + delete directoryChild; + }*/ } } } + subTree->sortChildren(0, Qt::AscendingOrder); } +void MainWindow::expandDataTreeItem(QTreeWidgetItem *item) +{ + if ((item->childCount() == 1) && (item->child(0)->data(0, Qt::UserRole).toString() == "__loaded_on_demand__")) { + // read the data we need from the sub-item, then dispose of it + QTreeWidgetItem *onDemandDataItem = item->child(0); + std::wstring path = ToWString(onDemandDataItem->data(0, Qt::UserRole + 1).toString()); + bool conflictsOnly = onDemandDataItem->data(0, Qt::UserRole + 2).toBool(); + item->removeChild(onDemandDataItem); + + std::wstring virtualPath = (path + L"\\").substr(6) + ToWString(item->text(0)); + DirectoryEntry *dir = m_DirectoryStructure->findSubDirectoryRecursive(virtualPath); + if (dir != NULL) { + updateTo(item, path, *dir, conflictsOnly); + } else { + qWarning("failed to update view of %ls", path.c_str()); + } + + } +} + + bool MainWindow::refreshProfiles(bool selectProfile) { QComboBox* profileBox = findChild("profileBox"); @@ -1665,6 +1699,14 @@ void MainWindow::refreshDataTree() } +void MainWindow::refreshSavesIfOpen() +{ + if (ui->tabWidget->currentIndex() == 3) { + refreshSaveList(); + } +} + + void MainWindow::refreshSaveList() { ui->savegameList->clear(); @@ -1680,6 +1722,8 @@ void MainWindow::refreshSaveList() savesDir.setPath(QDir::fromNativeSeparators(ToQString(GameInfo::instance().getDocumentsDir() + L"\\" + path))); } + m_SavesWatcher.addPath(savesDir.absolutePath()); + QStringList filters; filters << ToQString(GameInfo::instance().getSaveGameExtension()); savesDir.setNameFilters(filters); @@ -4399,7 +4443,12 @@ void MainWindow::previewDataFile() QString filePath = QDir::fromNativeSeparators(ToQString(origin.getPath())) + "/" + fileName; if (QFile::exists(filePath)) { // it's very possible the file doesn't exist, because it's inside an archive. we don't support that - preview.addVariant(ToQString(origin.getName()), m_PreviewGenerator.genPreview(filePath)); + QWidget *wid = m_PreviewGenerator.genPreview(filePath); + if (wid == NULL) { + reportError(tr("failed to generate preview for %1").arg(filePath)); + } else { + preview.addVariant(ToQString(origin.getName()), wid); + } } }; @@ -4409,6 +4458,8 @@ void MainWindow::previewDataFile() } if (preview.numVariants() > 0) { preview.exec(); + } else { + QMessageBox::information(this, tr("Sorry"), tr("Sorry, can't preview anything. This function currently does not support extracting from bsas.")); } } diff --git a/src/mainwindow.h b/src/mainwindow.h index 21c121fb..59bee7bb 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -370,6 +370,8 @@ private: PreviewGenerator m_PreviewGenerator; + QFileSystemWatcher m_SavesWatcher; + private slots: void showMessage(const QString &message); @@ -523,6 +525,9 @@ private slots: void ignoreUpdate(); void unignoreUpdate(); + void refreshSavesIfOpen(); + void expandDataTreeItem(QTreeWidgetItem *item); + private slots: // ui slots // actions void on_actionAdd_Profile_triggered(); diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 674e7165..7f221bdc 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -766,7 +766,7 @@ void ModInfoDialog::activateNexusTab() QLineEdit *modIDEdit = findChild("modIDEdit"); int modID = modIDEdit->text().toInt(); if (modID != 0) { - QString nexusLink = QString("%1/downloads/file.php?id=%2").arg(ToQString(GameInfo::instance().getNexusPage())).arg(modID); + QString nexusLink = QString("%1/downloads/file.php?id=%2").arg(ToQString(GameInfo::instance().getNexusPage(false))).arg(modID); QLabel *visitNexusLabel = findChild("visitNexusLabel"); visitNexusLabel->setText(tr("Visit on Nexus").arg(nexusLink)); visitNexusLabel->setToolTip(nexusLink); diff --git a/src/organizer.pro b/src/organizer.pro index 07feb326..25384e69 100644 --- a/src/organizer.pro +++ b/src/organizer.pro @@ -80,7 +80,15 @@ SOURCES += \ ../esptk/subrecord.cpp \ noeditdelegate.cpp \ previewgenerator.cpp \ - previewdialog.cpp + previewdialog.cpp \ + gl/gltexloaders.cpp \ + gl/dds/dds_api.cpp \ + gl/dds/Image.cpp \ + gl/dds/DirectDrawSurface.cpp \ + gl/dds/Stream.cpp \ + gl/dds/BlockDXT.cpp \ + gl/dds/ColorBlock.cpp + HEADERS += \ transfersavesdialog.h \ diff --git a/src/shared/directoryentry.h b/src/shared/directoryentry.h index ad5d179b..15af5e9e 100644 --- a/src/shared/directoryentry.h +++ b/src/shared/directoryentry.h @@ -205,6 +205,8 @@ public: void clear(); bool isPopulated() const { return m_Populated; } + bool isEmpty() const { return (m_Files.size() == 0) && (m_SubDirectories.size() == 0); } + const DirectoryEntry *getParent() const { return m_Parent; } // add files to this directory (and subdirectories) from the specified origin. That origin may exist or not -- cgit v1.3.1 From 40d20ab294ad7afd4b5747b306e45d0f8712a386 Mon Sep 17 00:00:00 2001 From: Tannin Date: Thu, 16 Jan 2014 20:43:42 +0100 Subject: - added an about dialog - updated json library --- src/aboutdialog.cpp | 82 +++ src/aboutdialog.h | 69 ++ src/aboutdialog.ui | 295 +++++++++ src/downloadmanager.cpp | 1 - src/json.cpp | 1110 +++++++++++++++----------------- src/json.h | 298 +++------ src/logbuffer.cpp | 1 + src/mainwindow.cpp | 9 + src/mainwindow.h | 1 + src/modinfodialog.cpp | 3 - src/modlist.cpp | 2 +- src/nexusinterface.cpp | 5 +- src/organizer.pro | 16 +- src/resources/emblem-favorite - 64.png | Bin 0 -> 3710 bytes 14 files changed, 1087 insertions(+), 805 deletions(-) create mode 100644 src/aboutdialog.cpp create mode 100644 src/aboutdialog.h create mode 100644 src/aboutdialog.ui create mode 100644 src/resources/emblem-favorite - 64.png (limited to 'src/downloadmanager.cpp') diff --git a/src/aboutdialog.cpp b/src/aboutdialog.cpp new file mode 100644 index 00000000..94e4e54c --- /dev/null +++ b/src/aboutdialog.cpp @@ -0,0 +1,82 @@ +/* +Copyright (C) 2014 Sebastian Herbord. All rights reserved. + +This file is part of Mod Organizer. + +Mod Organizer is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mod Organizer is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mod Organizer. If not, see . +*/ + + +#include "aboutdialog.h" +#include "ui_aboutdialog.h" +#include + + +AboutDialog::AboutDialog(const QString &version, QWidget *parent) + : QDialog(parent) + , ui(new Ui::AboutDialog) +{ + ui->setupUi(this); + + m_LicenseFiles[LICENSE_LGPL3] = "lgpl-3.0.txt"; + m_LicenseFiles[LICENSE_GPL3] = "gpl-3.0.txt"; + m_LicenseFiles[LICENSE_BSD3] = "bsd3.txt"; + m_LicenseFiles[LICENSE_BOOST] = "boost.txt"; + m_LicenseFiles[LICENSE_CCBY3] = "by-sa3.txt"; + m_LicenseFiles[LICENSE_ZLIB] = "zlib.txt"; + + addLicense("Qt 4.8.5", LICENSE_LGPL3); + addLicense("Qt Json", LICENSE_GPL3); + addLicense("Boost Library", LICENSE_BOOST); + addLicense("Tango Icon Theme", LICENSE_NONE); + addLicense("RRZE Icon Set", LICENSE_CCBY3); + addLicense("7-zip", LICENSE_LGPL3); + addLicense("ZLib", LICENSE_ZLIB); + addLicense("NIF File Format Library", LICENSE_BSD3); + + ui->nameLabel->setText(QString("%1 %2").arg(ui->nameLabel->text()).arg(version)); +#ifdef HGID + ui->revisionLabel->setText(ui->revisionLabel->text() + " " + HGID); +#else + ui->revisionLabel->setText(ui->revisionLabel->text() + " unknown"); +#endif +} + + +AboutDialog::~AboutDialog() +{ + delete ui; +} + + +void AboutDialog::addLicense(const QString &name, Licenses license) +{ + QListWidgetItem *item = new QListWidgetItem(name); + item->setData(Qt::UserRole, license); + ui->creditsList->addItem(item); +} + + +void AboutDialog::on_creditsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem*) +{ + auto iter = m_LicenseFiles.find(current->data(Qt::UserRole).toInt()); + if (iter != m_LicenseFiles.end()) { + QString filePath = qApp->applicationDirPath() + "/license/" + iter->second; +qDebug("%s", qPrintable(filePath)); + QString text = MOBase::readFileText(filePath); + ui->licenseText->setText(text); + } else { + ui->licenseText->setText(tr("No license")); + } +} diff --git a/src/aboutdialog.h b/src/aboutdialog.h new file mode 100644 index 00000000..9c0901a8 --- /dev/null +++ b/src/aboutdialog.h @@ -0,0 +1,69 @@ +#ifndef ABOUTDIALOG_H +/* +Copyright (C) 2014 Sebastian Herbord. All rights reserved. + +This file is part of Mod Organizer. + +Mod Organizer is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Mod Organizer is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Mod Organizer. If not, see . +*/ + + +#define ABOUTDIALOG_H + +#include +#include +#include +#include +#include + +namespace Ui { + class AboutDialog; +} + +class AboutDialog : public QDialog +{ + Q_OBJECT + +public: + explicit AboutDialog(const QString &version, QWidget *parent = 0); + ~AboutDialog(); + +private: + + enum Licenses { + LICENSE_NONE, + LICENSE_LGPL3, + LICENSE_GPL3, + LICENSE_BSD3, + LICENSE_BOOST, + LICENSE_CCBY3, + LICENSE_ZLIB + }; + +private: + + void addLicense(const QString &name, Licenses license); + +private slots: + void on_creditsList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous); + +private: + + Ui::AboutDialog *ui; + + std::map m_LicenseFiles; + +}; + +#endif // ABOUTDIALOG_H diff --git a/src/aboutdialog.ui b/src/aboutdialog.ui new file mode 100644 index 00000000..985700db --- /dev/null +++ b/src/aboutdialog.ui @@ -0,0 +1,295 @@ + + + AboutDialog + + + + 0 + 0 + 508 + 335 + + + + About + + + + + + + + + + + + + :/MO/gui/mo_icon.ico + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + 0 + + + + About + + + + + + Mod Organizer + + + + + + + Revision: + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Copyright 2011-2014 Sebastian Herbord + + + + + + + <html><head/><body><p>This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.</p><p>See the GNU General Public License for more details.</p></body></html> + + + true + + + + + + + + Used Software + + + + + + + + + + + + + Credits + + + + + + Translators + + + + + + QAbstractItemView::NoSelection + + + + pndrev (German) + + + + + DaWul (Spanish) + + + + + Fiama (Spanish) + + + + + Alyndiar (French) + + + + + Jlkawaii (French) + + + + + Rigoletto (French) + + + + + Scythe1912 (Chinese) + + + + + yc0620shen (Chinese) + + + + + miraclefreak (Czech) + + + + + tokcdk (Russian) + + + + + + + + + + + Others + + + + + + QAbstractItemView::NoSelection + + + + blacksol + + + + + DoubleYou + + + + + deathneko11 + + + + + Bridger + + + + + GSDFan + + + + + Uhuru + + + + + Wolverine2710 + + + + + z929669 + + + + + + + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Close + + + + + + + + + + + + + closeButton + clicked() + AboutDialog + accept() + + + 460 + 313 + + + 253 + 167 + + + + + diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index fdc825f1..dd320f70 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -37,7 +37,6 @@ along with Mod Organizer. If not, see . #include -using QtJson::Json; using namespace MOBase; diff --git a/src/json.cpp b/src/json.cpp index 7bfaed39..ca2d728f 100644 --- a/src/json.cpp +++ b/src/json.cpp @@ -1,588 +1,522 @@ -/* Copyright 2011 Eeli Reilin. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL EELI REILIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation - * are those of the authors and should not be interpreted as representing - * official policies, either expressed or implied, of Eeli Reilin. - */ - -/** - * \file json.cpp - */ - -#include "json.h" -#include - -namespace QtJson -{ - - -static QString sanitizeString(QString str) -{ - str.replace(QLatin1String("\\"), QLatin1String("\\\\")); - str.replace(QLatin1String("\""), QLatin1String("\\\"")); - str.replace(QLatin1String("\b"), QLatin1String("\\b")); - str.replace(QLatin1String("\f"), QLatin1String("\\f")); - str.replace(QLatin1String("\n"), QLatin1String("\\n")); - str.replace(QLatin1String("\r"), QLatin1String("\\r")); - str.replace(QLatin1String("\t"), QLatin1String("\\t")); - return QString(QLatin1String("\"%1\"")).arg(str); -} - -static QByteArray join(const QList &list, const QByteArray &sep) -{ - QByteArray res; - Q_FOREACH(const QByteArray &i, list) - { - if(!res.isEmpty()) - { - res += sep; - } - res += i; - } - return res; -} - -/** - * parse - */ -QVariant Json::parse(const QString &json) -{ - bool success = true; - return Json::parse(json, success); -} - -/** - * parse - */ -QVariant Json::parse(const QString &json, bool &success) -{ - success = true; - - //Return an empty QVariant if the JSON data is either null or empty - if(!json.isNull() || !json.isEmpty()) - { - QString data = json; - //We'll start from index 0 - int index = 0; - - //Parse the first value - QVariant value = Json::parseValue(data, index, success); - - //Return the parsed value - return value; - } - else - { - //Return the empty QVariant - return QVariant(); - } -} - -QByteArray Json::serialize(const QVariant &data) -{ - bool success = true; - return Json::serialize(data, success); -} - -QByteArray Json::serialize(const QVariant &data, bool &success) -{ - QByteArray str; - success = true; - - if(!data.isValid()) // invalid or null? - { - str = "null"; - } - else if((data.type() == QVariant::List) || (data.type() == QVariant::StringList)) // variant is a list? - { - QList values; - const QVariantList list = data.toList(); - Q_FOREACH(const QVariant& v, list) - { - QByteArray serializedValue = serialize(v); - if(serializedValue.isNull()) - { - success = false; - break; - } - values << serializedValue; - } - - str = "[ " + join( values, ", " ) + " ]"; - } - else if(data.type() == QVariant::Map) // variant is a map? - { - const QVariantMap vmap = data.toMap(); - QMapIterator it( vmap ); - str = "{ "; - QList pairs; - while(it.hasNext()) - { - it.next(); - QByteArray serializedValue = serialize(it.value()); - if(serializedValue.isNull()) - { - success = false; - break; - } - pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue; - } - str += join(pairs, ", "); - str += " }"; - } - else if((data.type() == QVariant::String) || (data.type() == QVariant::ByteArray)) // a string or a byte array? - { - str = sanitizeString(data.toString()).toUtf8(); - } - else if(data.type() == QVariant::Double) // double? - { - str = QByteArray::number(data.toDouble()); - if(!str.contains(".") && ! str.contains("e")) - { - str += ".0"; - } - } - else if (data.type() == QVariant::Bool) // boolean value? - { - str = data.toBool() ? "true" : "false"; - } - else if (data.type() == QVariant::ULongLong) // large unsigned number? - { - str = QByteArray::number(data.value()); - } - else if ( data.canConvert() ) // any signed number? - { - str = QByteArray::number(data.value()); - } - else if (data.canConvert()) - { - str = sanitizeString(QString::number(data.value())).toUtf8(); - } - else if (data.canConvert()) // can value be converted to string? - { - // this will catch QDate, QDateTime, QUrl, ... - str = sanitizeString(data.toString()).toUtf8(); - } - else - { - success = false; - } - if (success) - { - return str; - } - else - { - return QByteArray(); - } -} - -/** - * parseValue - */ -QVariant Json::parseValue(const QString &json, int &index, bool &success) -{ - //Determine what kind of data we should parse by - //checking out the upcoming token - switch(Json::lookAhead(json, index)) - { - case JsonTokenString: - return Json::parseString(json, index, success); - case JsonTokenNumber: - return Json::parseNumber(json, index); - case JsonTokenCurlyOpen: - return Json::parseObject(json, index, success); - case JsonTokenSquaredOpen: - return Json::parseArray(json, index, success); - case JsonTokenTrue: - Json::nextToken(json, index); - return QVariant(true); - case JsonTokenFalse: - Json::nextToken(json, index); - return QVariant(false); - case JsonTokenNull: - Json::nextToken(json, index); - return QVariant(); - case JsonTokenNone: - break; - } - - //If there were no tokens, flag the failure and return an empty QVariant - success = false; - return QVariant(); -} - -/** - * parseObject - */ -QVariant Json::parseObject(const QString &json, int &index, bool &success) -{ - QVariantMap map; - int token; - - //Get rid of the whitespace and increment index - Json::nextToken(json, index); - - //Loop through all of the key/value pairs of the object - bool done = false; - while(!done) - { - //Get the upcoming token - token = Json::lookAhead(json, index); - - if(token == JsonTokenNone) - { - success = false; - return QVariantMap(); - } - else if(token == JsonTokenComma) - { - Json::nextToken(json, index); - } - else if(token == JsonTokenCurlyClose) - { - Json::nextToken(json, index); - return map; - } - else - { - //Parse the key/value pair's name - QString name = Json::parseString(json, index, success).toString(); - - if(!success) - { - return QVariantMap(); - } - - //Get the next token - token = Json::nextToken(json, index); - - //If the next token is not a colon, flag the failure - //return an empty QVariant - if(token != JsonTokenColon) - { - success = false; - return QVariant(QVariantMap()); - } - - //Parse the key/value pair's value - QVariant value = Json::parseValue(json, index, success); - - if(!success) - { - return QVariantMap(); - } - - //Assign the value to the key in the map - map[name] = value; - } - } - - //Return the map successfully - return QVariant(map); -} - -/** - * parseArray - */ -QVariant Json::parseArray(const QString &json, int &index, bool &success) -{ - QVariantList list; - - Json::nextToken(json, index); - - bool done = false; - while(!done) - { - int token = Json::lookAhead(json, index); - - if(token == JsonTokenNone) - { - success = false; - return QVariantList(); - } - else if(token == JsonTokenComma) - { - Json::nextToken(json, index); - } - else if(token == JsonTokenSquaredClose) - { - Json::nextToken(json, index); - break; - } - else - { - QVariant value = Json::parseValue(json, index, success); - - if(!success) - { - return QVariantList(); - } - - list.push_back(value); - } - } - - return QVariant(list); -} - -/** - * parseString - */ -QVariant Json::parseString(const QString &json, int &index, bool &success) -{ - QString s; - QChar c; - - Json::eatWhitespace(json, index); - - c = json[index++]; - - bool complete = false; - while(!complete) - { - if(index == json.size()) - { - break; - } - - c = json[index++]; - - if(c == '\"') - { - complete = true; - break; - } - else if(c == '\\') - { - if(index == json.size()) - { - break; - } - - c = json[index++]; - - if(c == '\"') - { - s.append('\"'); - } - else if(c == '\\') - { - s.append('\\'); - } - else if(c == '/') - { - s.append('/'); - } - else if(c == 'b') - { - s.append('\b'); - } - else if(c == 'f') - { - s.append('\f'); - } - else if(c == 'n') - { - s.append('\n'); - } - else if(c == 'r') - { - s.append('\r'); - } - else if(c == 't') - { - s.append('\t'); - } - else if(c == 'u') - { - int remainingLength = json.size() - index; - - if(remainingLength >= 4) - { - QString unicodeStr = json.mid(index, 4); - - int symbol = unicodeStr.toInt(0, 16); - - s.append(QChar(symbol)); - - index += 4; - } - else - { - break; - } - } - } - else - { - s.append(c); - } - } - - if(!complete) - { - success = false; - return QVariant(); - } - - return QVariant(s); -} - -/** - * parseNumber - */ -QVariant Json::parseNumber(const QString &json, int &index) -{ - Json::eatWhitespace(json, index); - - int lastIndex = Json::lastIndexOfNumber(json, index); - int charLength = (lastIndex - index) + 1; - QString numberStr; - - numberStr = json.mid(index, charLength); - - index = lastIndex + 1; - - if (numberStr.contains('.')) { - return QVariant(numberStr.toDouble(NULL)); - } else if (numberStr.startsWith('-')) { - return QVariant(numberStr.toLongLong(NULL)); - } else { - return QVariant(numberStr.toULongLong(NULL)); - } -} - -/** - * lastIndexOfNumber - */ -int Json::lastIndexOfNumber(const QString &json, int index) -{ - int lastIndex; - - for(lastIndex = index; lastIndex < json.size(); lastIndex++) - { - if(QString("0123456789+-.eE").indexOf(json[lastIndex]) == -1) - { - break; - } - } - - return lastIndex -1; -} - -/** - * eatWhitespace - */ -void Json::eatWhitespace(const QString &json, int &index) -{ - for(; index < json.size(); index++) - { - if(QString(" \t\n\r").indexOf(json[index]) == -1) - { - break; - } - } -} - -/** - * lookAhead - */ -int Json::lookAhead(const QString &json, int index) -{ - int saveIndex = index; - return Json::nextToken(json, saveIndex); -} - -/** - * nextToken - */ -int Json::nextToken(const QString &json, int &index) -{ - Json::eatWhitespace(json, index); - - if(index == json.size()) - { - return JsonTokenNone; - } - - QChar c = json[index]; - index++; - switch(c.toLatin1()) - { - case '{': return JsonTokenCurlyOpen; - case '}': return JsonTokenCurlyClose; - case '[': return JsonTokenSquaredOpen; - case ']': return JsonTokenSquaredClose; - case ',': return JsonTokenComma; - case '"': return JsonTokenString; - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - case '-': return JsonTokenNumber; - case ':': return JsonTokenColon; - } - - index--; - - int remainingLength = json.size() - index; - - //True - if(remainingLength >= 4) - { - if (json[index] == 't' && json[index + 1] == 'r' && - json[index + 2] == 'u' && json[index + 3] == 'e') - { - index += 4; - return JsonTokenTrue; - } - } - - //False - if (remainingLength >= 5) - { - if (json[index] == 'f' && json[index + 1] == 'a' && - json[index + 2] == 'l' && json[index + 3] == 's' && - json[index + 4] == 'e') - { - index += 5; - return JsonTokenFalse; - } - } - - //Null - if (remainingLength >= 4) - { - if (json[index] == 'n' && json[index + 1] == 'u' && - json[index + 2] == 'l' && json[index + 3] == 'l') - { - index += 4; - return JsonTokenNull; - } - } - - return JsonTokenNone; -} - - -} //end namespace +/** + * QtJson - A simple class for parsing JSON data into a QVariant hierarchies and vice-versa. + * Copyright (C) 2011 Eeli Reilin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file json.cpp + */ + +#include "json.h" + +namespace QtJson { + static QString sanitizeString(QString str); + static QByteArray join(const QList &list, const QByteArray &sep); + static QVariant parseValue(const QString &json, int &index, bool &success); + static QVariant parseObject(const QString &json, int &index, bool &success); + static QVariant parseArray(const QString &json, int &index, bool &success); + static QVariant parseString(const QString &json, int &index, bool &success); + static QVariant parseNumber(const QString &json, int &index); + static int lastIndexOfNumber(const QString &json, int index); + static void eatWhitespace(const QString &json, int &index); + static int lookAhead(const QString &json, int index); + static int nextToken(const QString &json, int &index); + + template + QByteArray serializeMap(const T &map, bool &success) { + QByteArray str = "{ "; + QList pairs; + for (typename T::const_iterator it = map.begin(), itend = map.end(); it != itend; ++it) { + QByteArray serializedValue = serialize(it.value()); + if (serializedValue.isNull()) { + success = false; + break; + } + pairs << sanitizeString(it.key()).toUtf8() + " : " + serializedValue; + } + + str += join(pairs, ", "); + str += " }"; + return str; + } + + + /** + * parse + */ + QVariant parse(const QString &json) { + bool success = true; + return parse(json, success); + } + + /** + * parse + */ + QVariant parse(const QString &json, bool &success) { + success = true; + + // Return an empty QVariant if the JSON data is either null or empty + if (!json.isNull() || !json.isEmpty()) { + QString data = json; + // We'll start from index 0 + int index = 0; + + // Parse the first value + QVariant value = parseValue(data, index, success); + + // Return the parsed value + return value; + } else { + // Return the empty QVariant + return QVariant(); + } + } + + QByteArray serialize(const QVariant &data) { + bool success = true; + return serialize(data, success); + } + + QByteArray serialize(const QVariant &data, bool &success) { + QByteArray str; + success = true; + + if (!data.isValid()) { // invalid or null? + str = "null"; + } else if ((data.type() == QVariant::List) || + (data.type() == QVariant::StringList)) { // variant is a list? + QList values; + const QVariantList list = data.toList(); + Q_FOREACH(const QVariant& v, list) { + QByteArray serializedValue = serialize(v); + if (serializedValue.isNull()) { + success = false; + break; + } + values << serializedValue; + } + + str = "[ " + join( values, ", " ) + " ]"; + } else if (data.type() == QVariant::Hash) { // variant is a hash? + str = serializeMap<>(data.toHash(), success); + } else if (data.type() == QVariant::Map) { // variant is a map? + str = serializeMap<>(data.toMap(), success); + } else if ((data.type() == QVariant::String) || + (data.type() == QVariant::ByteArray)) {// a string or a byte array? + str = sanitizeString(data.toString()).toUtf8(); + } else if (data.type() == QVariant::Double) { // double? + double value = data.toDouble(); + if ((value - value) == 0.0) { + str = QByteArray::number(value, 'g'); + if (!str.contains(".") && ! str.contains("e")) { + str += ".0"; + } + } else { + success = false; + } + } else if (data.type() == QVariant::Bool) { // boolean value? + str = data.toBool() ? "true" : "false"; + } else if (data.type() == QVariant::ULongLong) { // large unsigned number? + str = QByteArray::number(data.value()); + } else if (data.canConvert()) { // any signed number? + str = QByteArray::number(data.value()); + } else if (data.canConvert()) { //TODO: this code is never executed + str = QString::number(data.value()).toUtf8(); + } else if (data.canConvert()) { // can value be converted to string? + // this will catch QDate, QDateTime, QUrl, ... + str = sanitizeString(data.toString()).toUtf8(); + } else { + success = false; + } + + if (success) { + return str; + } else { + return QByteArray(); + } + } + + QString serializeStr(const QVariant &data) { + return QString::fromUtf8(serialize(data)); + } + + QString serializeStr(const QVariant &data, bool &success) { + return QString::fromUtf8(serialize(data, success)); + } + + + /** + * \enum JsonToken + */ + enum JsonToken { + JsonTokenNone = 0, + JsonTokenCurlyOpen = 1, + JsonTokenCurlyClose = 2, + JsonTokenSquaredOpen = 3, + JsonTokenSquaredClose = 4, + JsonTokenColon = 5, + JsonTokenComma = 6, + JsonTokenString = 7, + JsonTokenNumber = 8, + JsonTokenTrue = 9, + JsonTokenFalse = 10, + JsonTokenNull = 11 + }; + + static QString sanitizeString(QString str) { + str.replace(QLatin1String("\\"), QLatin1String("\\\\")); + str.replace(QLatin1String("\""), QLatin1String("\\\"")); + str.replace(QLatin1String("\b"), QLatin1String("\\b")); + str.replace(QLatin1String("\f"), QLatin1String("\\f")); + str.replace(QLatin1String("\n"), QLatin1String("\\n")); + str.replace(QLatin1String("\r"), QLatin1String("\\r")); + str.replace(QLatin1String("\t"), QLatin1String("\\t")); + return QString(QLatin1String("\"%1\"")).arg(str); + } + + static QByteArray join(const QList &list, const QByteArray &sep) { + QByteArray res; + Q_FOREACH(const QByteArray &i, list) { + if (!res.isEmpty()) { + res += sep; + } + res += i; + } + return res; + } + + /** + * parseValue + */ + static QVariant parseValue(const QString &json, int &index, bool &success) { + // Determine what kind of data we should parse by + // checking out the upcoming token + switch(lookAhead(json, index)) { + case JsonTokenString: + return parseString(json, index, success); + case JsonTokenNumber: + return parseNumber(json, index); + case JsonTokenCurlyOpen: + return parseObject(json, index, success); + case JsonTokenSquaredOpen: + return parseArray(json, index, success); + case JsonTokenTrue: + nextToken(json, index); + return QVariant(true); + case JsonTokenFalse: + nextToken(json, index); + return QVariant(false); + case JsonTokenNull: + nextToken(json, index); + return QVariant(); + case JsonTokenNone: + break; + } + + // If there were no tokens, flag the failure and return an empty QVariant + success = false; + return QVariant(); + } + + /** + * parseObject + */ + static QVariant parseObject(const QString &json, int &index, bool &success) { + QVariantMap map; + int token; + + // Get rid of the whitespace and increment index + nextToken(json, index); + + // Loop through all of the key/value pairs of the object + bool done = false; + while (!done) { + // Get the upcoming token + token = lookAhead(json, index); + + if (token == JsonTokenNone) { + success = false; + return QVariantMap(); + } else if (token == JsonTokenComma) { + nextToken(json, index); + } else if (token == JsonTokenCurlyClose) { + nextToken(json, index); + return map; + } else { + // Parse the key/value pair's name + QString name = parseString(json, index, success).toString(); + + if (!success) { + return QVariantMap(); + } + + // Get the next token + token = nextToken(json, index); + + // If the next token is not a colon, flag the failure + // return an empty QVariant + if (token != JsonTokenColon) { + success = false; + return QVariant(QVariantMap()); + } + + // Parse the key/value pair's value + QVariant value = parseValue(json, index, success); + + if (!success) { + return QVariantMap(); + } + + // Assign the value to the key in the map + map[name] = value; + } + } + + // Return the map successfully + return QVariant(map); + } + + /** + * parseArray + */ + static QVariant parseArray(const QString &json, int &index, bool &success) { + QVariantList list; + + nextToken(json, index); + + bool done = false; + while(!done) { + int token = lookAhead(json, index); + + if (token == JsonTokenNone) { + success = false; + return QVariantList(); + } else if (token == JsonTokenComma) { + nextToken(json, index); + } else if (token == JsonTokenSquaredClose) { + nextToken(json, index); + break; + } else { + QVariant value = parseValue(json, index, success); + if (!success) { + return QVariantList(); + } + list.push_back(value); + } + } + + return QVariant(list); + } + + /** + * parseString + */ + static QVariant parseString(const QString &json, int &index, bool &success) { + QString s; + QChar c; + + eatWhitespace(json, index); + + c = json[index++]; + + bool complete = false; + while(!complete) { + if (index == json.size()) { + break; + } + + c = json[index++]; + + if (c == '\"') { + complete = true; + break; + } else if (c == '\\') { + if (index == json.size()) { + break; + } + + c = json[index++]; + + if (c == '\"') { + s.append('\"'); + } else if (c == '\\') { + s.append('\\'); + } else if (c == '/') { + s.append('/'); + } else if (c == 'b') { + s.append('\b'); + } else if (c == 'f') { + s.append('\f'); + } else if (c == 'n') { + s.append('\n'); + } else if (c == 'r') { + s.append('\r'); + } else if (c == 't') { + s.append('\t'); + } else if (c == 'u') { + int remainingLength = json.size() - index; + if (remainingLength >= 4) { + QString unicodeStr = json.mid(index, 4); + + int symbol = unicodeStr.toInt(0, 16); + + s.append(QChar(symbol)); + + index += 4; + } else { + break; + } + } + } else { + s.append(c); + } + } + + if (!complete) { + success = false; + return QVariant(); + } + + return QVariant(s); + } + + /** + * parseNumber + */ + static QVariant parseNumber(const QString &json, int &index) { + eatWhitespace(json, index); + + int lastIndex = lastIndexOfNumber(json, index); + int charLength = (lastIndex - index) + 1; + QString numberStr; + + numberStr = json.mid(index, charLength); + + index = lastIndex + 1; + bool ok; + + if (numberStr.contains('.')) { + return QVariant(numberStr.toDouble(NULL)); + } else if (numberStr.startsWith('-')) { + int i = numberStr.toInt(&ok); + if (!ok) { + qlonglong ll = numberStr.toLongLong(&ok); + return ok ? ll : QVariant(numberStr); + } + return i; + } else { + uint u = numberStr.toUInt(&ok); + if (!ok) { + qulonglong ull = numberStr.toULongLong(&ok); + return ok ? ull : QVariant(numberStr); + } + return u; + } + } + + /** + * lastIndexOfNumber + */ + static int lastIndexOfNumber(const QString &json, int index) { + int lastIndex; + + for(lastIndex = index; lastIndex < json.size(); lastIndex++) { + if (QString("0123456789+-.eE").indexOf(json[lastIndex]) == -1) { + break; + } + } + + return lastIndex -1; + } + + /** + * eatWhitespace + */ + static void eatWhitespace(const QString &json, int &index) { + for(; index < json.size(); index++) { + if (QString(" \t\n\r").indexOf(json[index]) == -1) { + break; + } + } + } + + /** + * lookAhead + */ + static int lookAhead(const QString &json, int index) { + int saveIndex = index; + return nextToken(json, saveIndex); + } + + /** + * nextToken + */ + static int nextToken(const QString &json, int &index) { + eatWhitespace(json, index); + + if (index == json.size()) { + return JsonTokenNone; + } + + QChar c = json[index]; + index++; + switch(c.toLatin1()) { + case '{': return JsonTokenCurlyOpen; + case '}': return JsonTokenCurlyClose; + case '[': return JsonTokenSquaredOpen; + case ']': return JsonTokenSquaredClose; + case ',': return JsonTokenComma; + case '"': return JsonTokenString; + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case '-': return JsonTokenNumber; + case ':': return JsonTokenColon; + } + index--; // ^ WTF? + + int remainingLength = json.size() - index; + + // True + if (remainingLength >= 4) { + if (json[index] == 't' && json[index + 1] == 'r' && + json[index + 2] == 'u' && json[index + 3] == 'e') { + index += 4; + return JsonTokenTrue; + } + } + + // False + if (remainingLength >= 5) { + if (json[index] == 'f' && json[index + 1] == 'a' && + json[index + 2] == 'l' && json[index + 3] == 's' && + json[index + 4] == 'e') { + index += 5; + return JsonTokenFalse; + } + } + + // Null + if (remainingLength >= 4) { + if (json[index] == 'n' && json[index + 1] == 'u' && + json[index + 2] == 'l' && json[index + 3] == 'l') { + index += 4; + return JsonTokenNull; + } + } + + return JsonTokenNone; + } +} //end namespace diff --git a/src/json.h b/src/json.h index d2cfa9a8..a61f6c85 100644 --- a/src/json.h +++ b/src/json.h @@ -1,204 +1,94 @@ -/* Copyright 2011 Eeli Reilin. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO - * EVENT SHALL EELI REILIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation - * are those of the authors and should not be interpreted as representing - * official policies, either expressed or implied, of Eeli Reilin. - */ - -/** - * \file json.h - */ - -#ifndef JSON_H -#define JSON_H - -#include -#include - -namespace QtJson -{ - -/** - * \enum JsonToken - */ -enum JsonToken -{ - JsonTokenNone = 0, - JsonTokenCurlyOpen = 1, - JsonTokenCurlyClose = 2, - JsonTokenSquaredOpen = 3, - JsonTokenSquaredClose = 4, - JsonTokenColon = 5, - JsonTokenComma = 6, - JsonTokenString = 7, - JsonTokenNumber = 8, - JsonTokenTrue = 9, - JsonTokenFalse = 10, - JsonTokenNull = 11 -}; - -/** - * \class Json - * \brief A JSON data parser - * - * Json parses a JSON data into a QVariant hierarchy. - */ -class Json -{ - public: - /** - * Parse a JSON string - * - * \param json The JSON data - */ - static QVariant parse(const QString &json); - - /** - * Parse a JSON string - * - * \param json The JSON data - * \param success The success of the parsing - */ - static QVariant parse(const QString &json, bool &success); - - /** - * This method generates a textual JSON representation - * - * \param data The JSON data generated by the parser. - * \param success The success of the serialization - */ - static QByteArray serialize(const QVariant &data); - - /** - * This method generates a textual JSON representation - * - * \param data The JSON data generated by the parser. - * \param success The success of the serialization - * - * \return QByteArray Textual JSON representation - */ - static QByteArray serialize(const QVariant &data, bool &success); - - private: - /** - * Parses a value starting from index - * - * \param json The JSON data - * \param index The start index - * \param success The success of the parse process - * - * \return QVariant The parsed value - */ - static QVariant parseValue(const QString &json, int &index, - bool &success); - - /** - * Parses an object starting from index - * - * \param json The JSON data - * \param index The start index - * \param success The success of the object parse - * - * \return QVariant The parsed object map - */ - static QVariant parseObject(const QString &json, int &index, - bool &success); - - /** - * Parses an array starting from index - * - * \param json The JSON data - * \param index The starting index - * \param success The success of the array parse - * - * \return QVariant The parsed variant array - */ - static QVariant parseArray(const QString &json, int &index, - bool &success); - - /** - * Parses a string starting from index - * - * \param json The JSON data - * \param index The starting index - * \param success The success of the string parse - * - * \return QVariant The parsed string - */ - static QVariant parseString(const QString &json, int &index, - bool &success); - - /** - * Parses a number starting from index - * - * \param json The JSON data - * \param index The starting index - * - * \return QVariant The parsed number - */ - static QVariant parseNumber(const QString &json, int &index); - - /** - * Get the last index of a number starting from index - * - * \param json The JSON data - * \param index The starting index - * - * \return The last index of the number - */ - static int lastIndexOfNumber(const QString &json, int index); - - /** - * Skip unwanted whitespace symbols starting from index - * - * \param json The JSON data - * \param index The start index - */ - static void eatWhitespace(const QString &json, int &index); - - /** - * Check what token lies ahead - * - * \param json The JSON data - * \param index The starting index - * - * \return int The upcoming token - */ - static int lookAhead(const QString &json, int index); - - /** - * Get the next JSON token - * - * \param json The JSON data - * \param index The starting index - * - * \return int The next JSON token - */ - static int nextToken(const QString &json, int &index); -}; - - -} //end namespace - -#endif //JSON_H +/** + * QtJson - A simple class for parsing JSON data into a QVariant hierarchies and vice-versa. + * Copyright (C) 2011 Eeli Reilin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file json.h + */ + +#ifndef JSON_H +#define JSON_H + +#include +#include + + +/** + * \namespace QtJson + * \brief A JSON data parser + * + * Json parses a JSON data into a QVariant hierarchy. + */ +namespace QtJson { + typedef QVariantMap JsonObject; + typedef QVariantList JsonArray; + + /** + * Parse a JSON string + * + * \param json The JSON data + */ + QVariant parse(const QString &json); + + /** + * Parse a JSON string + * + * \param json The JSON data + * \param success The success of the parsing + */ + QVariant parse(const QString &json, bool &success); + + /** + * This method generates a textual JSON representation + * + * \param data The JSON data generated by the parser. + * + * \return QByteArray Textual JSON representation in UTF-8 + */ + QByteArray serialize(const QVariant &data); + + /** + * This method generates a textual JSON representation + * + * \param data The JSON data generated by the parser. + * \param success The success of the serialization + * + * \return QByteArray Textual JSON representation in UTF-8 + */ + QByteArray serialize(const QVariant &data, bool &success); + + /** + * This method generates a textual JSON representation + * + * \param data The JSON data generated by the parser. + * + * \return QString Textual JSON representation + */ + QString serializeStr(const QVariant &data); + + /** + * This method generates a textual JSON representation + * + * \param data The JSON data generated by the parser. + * \param success The success of the serialization + * + * \return QString Textual JSON representation + */ + QString serializeStr(const QVariant &data, bool &success); +} + +#endif //JSON_H diff --git a/src/logbuffer.cpp b/src/logbuffer.cpp index 6f3f640f..4f72e551 100644 --- a/src/logbuffer.cpp +++ b/src/logbuffer.cpp @@ -120,6 +120,7 @@ char LogBuffer::msgTypeID(QtMsgType type) case QtWarningMsg: return 'W'; case QtCriticalMsg: return 'C'; case QtFatalMsg: return 'F'; + default: return '?'; } } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 76bff3a0..14e27e76 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -56,6 +56,7 @@ along with Mod Organizer. If not, see . #include "savetextasdialog.h" #include "problemsdialog.h" #include "previewdialog.h" +#include "aboutdialog.h" #include #include #include @@ -547,6 +548,12 @@ bool MainWindow::checkForProblems() return false; } +void MainWindow::about() +{ + AboutDialog dialog(m_Updater.getVersion().displayString(), this); + dialog.exec(); +} + void MainWindow::createHelpWidget() { @@ -604,6 +611,8 @@ void MainWindow::createHelpWidget() } buttonMenu->addMenu(tutorialMenu); + buttonMenu->addAction(tr("About"), this, SLOT(about())); + buttonMenu->addAction(tr("About Qt"), qApp, SLOT(aboutQt())); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 59bee7bb..e7b3f7e1 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -527,6 +527,7 @@ private slots: void refreshSavesIfOpen(); void expandDataTreeItem(QTreeWidgetItem *item); + void about(); private slots: // ui slots // actions diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index 7f221bdc..3657d48a 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -22,7 +22,6 @@ along with Mod Organizer. If not, see . #include "report.h" #include "utility.h" -#include "json.h" #include "messagedialog.h" #include "bbcode.h" #include "questionboxmemory.h" @@ -41,8 +40,6 @@ along with Mod Organizer. If not, see . #include -using QtJson::Json; - using namespace MOBase; using namespace MOShared; diff --git a/src/modlist.cpp b/src/modlist.cpp index 7f09654d..e2cb7cf0 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -305,7 +305,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const return QString(); } } else if (column == COL_VERSION) { - QString text = tr("installed version: %1, newest version: %2").arg(modInfo->getVersion().displayString()).arg(modInfo->getNewestVersion().displayString()); + QString text = tr("installed version: \"%1\", newest version: \"%2\"").arg(modInfo->getVersion().displayString()).arg(modInfo->getNewestVersion().displayString()); if (modInfo->downgradeAvailable()) { text += "
" + tr("The newest version on Nexus seems to be older than the one you have installed. This could either mean the version you have has been withdrawn " "(i.e. due to a bug) or the author uses a non-standard versioning scheme and that newest version is actually newer. " diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 309915aa..6b87822a 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -20,14 +20,13 @@ along with Mod Organizer. If not, see . #include "nexusinterface.h" #include "nxmaccessmanager.h" #include "utility.h" -#include "json.h" +#include #include "selectiondialog.h" #include #include #include #include -using QtJson::Json; using namespace MOBase; using namespace MOShared; @@ -458,7 +457,7 @@ void NexusInterface::requestFinished(std::list::iterator iter) emit nxmRequestFailed(iter->m_ModID, iter->m_UserData, iter->m_ID, nexusError); } else { bool ok; - QVariant result = Json::parse(data, ok); + QVariant result = QtJson::parse(data, ok); if (result.isValid() && ok) { switch (iter->m_Type) { case NXMRequestInfo::TYPE_DESCRIPTION: { diff --git a/src/organizer.pro b/src/organizer.pro index dd745edb..fd72dea3 100644 --- a/src/organizer.pro +++ b/src/organizer.pro @@ -47,7 +47,6 @@ SOURCES += \ logbuffer.cpp \ lockeddialog.cpp \ loadmechanism.cpp \ - json.cpp \ installationmanager.cpp \ helper.cpp \ filedialogmemory.cpp \ @@ -80,7 +79,9 @@ SOURCES += \ ../esptk/subrecord.cpp \ noeditdelegate.cpp \ previewgenerator.cpp \ - previewdialog.cpp + previewdialog.cpp \ + aboutdialog.cpp \ + json.cpp HEADERS += \ @@ -116,7 +117,6 @@ HEADERS += \ logbuffer.h \ lockeddialog.h \ loadmechanism.h \ - json.h \ installationmanager.h \ helper.h \ filedialogmemory.h \ @@ -150,7 +150,9 @@ HEADERS += \ ../esptk/espexceptions.h \ noeditdelegate.h \ previewgenerator.h \ - previewdialog.h + previewdialog.h \ + aboutdialog.h \ + json.h FORMS += \ transfersavesdialog.ui \ @@ -180,7 +182,8 @@ FORMS += \ profileinputdialog.ui \ savetextasdialog.ui \ problemsdialog.ui \ - previewdialog.ui + previewdialog.ui \ + aboutdialog.ui INCLUDEPATH += ../shared ../archive ../uibase ../bsatk ../esptk "$(BOOSTPATH)" @@ -246,6 +249,9 @@ DEFINES += UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS NOMINMAX DEFINES += BOOST_DISABLE_ASSERTS NDEBUG #DEFINES += QMLJSDEBUGGER +HGID = $$system(hg id -i) +DEFINES += HGID=\\\"$${HGID}\\\" + SRCDIR = $$PWD SRCDIR ~= s,/,$$QMAKE_DIR_SEP,g OUTDIR ~= s,/,$$QMAKE_DIR_SEP,g diff --git a/src/resources/emblem-favorite - 64.png b/src/resources/emblem-favorite - 64.png new file mode 100644 index 00000000..97b507ed Binary files /dev/null and b/src/resources/emblem-favorite - 64.png differ -- cgit v1.3.1 From e69210b3a78c4a6c63086d84e6bdb2c3b47d8944 Mon Sep 17 00:00:00 2001 From: Tannin Date: Sat, 18 Jan 2014 19:51:58 +0100 Subject: - when a download server returns a text file, it's assumed to be an error and the text displayed as an error - save games can now be deleted from inside MO - bugfix: removing the pending download entry failed if the download-url request failed - bugfix: download manager didn't stop automatically resuming failed downloads under certain circumstances - bugfix: uninstalled downloads were treated as not-finished when refreshing the download list - bugfix: updating the filesystem watcher on the saves directory didn't work correctly --- src/aboutdialog.cpp | 1 - src/downloadmanager.cpp | 33 ++++++++++++++++----------------- src/downloadmanager.h | 2 +- src/mainwindow.cpp | 23 ++++++++++++++++++++++- src/mainwindow.h | 3 ++- src/modinfo.cpp | 4 ++-- src/modinfo.h | 2 +- src/nexusinterface.cpp | 34 +++++++++++++++++----------------- src/nexusinterface.h | 8 ++++---- src/pluginlist.cpp | 1 - src/selfupdater.cpp | 2 +- src/selfupdater.h | 2 +- 12 files changed, 67 insertions(+), 48 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/aboutdialog.cpp b/src/aboutdialog.cpp index 94e4e54c..c7f95640 100644 --- a/src/aboutdialog.cpp +++ b/src/aboutdialog.cpp @@ -73,7 +73,6 @@ void AboutDialog::on_creditsList_currentItemChanged(QListWidgetItem *current, QL auto iter = m_LicenseFiles.find(current->data(Qt::UserRole).toInt()); if (iter != m_LicenseFiles.end()) { QString filePath = qApp->applicationDirPath() + "/license/" + iter->second; -qDebug("%s", qPrintable(filePath)); QString text = MOBase::readFileText(filePath); ui->licenseText->setText(text); } else { diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index dd320f70..31d8bcec 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -26,15 +26,16 @@ along with Mod Organizer. If not, see . #include "utility.h" #include "json.h" #include "selectiondialog.h" +#include #include #include #include #include #include -#include -#include #include #include +#include +#include using namespace MOBase; @@ -246,7 +247,7 @@ void DownloadManager::refreshList() // remove finished downloads for (QVector::iterator Iter = m_ActiveDownloads.begin(); Iter != m_ActiveDownloads.end();) { - if (((*Iter)->m_State == STATE_READY) || ((*Iter)->m_State == STATE_INSTALLED)) { + if (((*Iter)->m_State == STATE_READY) || ((*Iter)->m_State == STATE_INSTALLED) || ((*Iter)->m_State == STATE_UNINSTALLED)) { delete *Iter; Iter = m_ActiveDownloads.erase(Iter); } else { @@ -414,7 +415,7 @@ void DownloadManager::addNXMDownload(const QString &url) NXMUrl nxmInfo(url); QString managedGame = ToQString(MOShared::GameInfo::instance().getGameShortName()); - qDebug("add nxm download", qPrintable(url)); + qDebug("add nxm download: %s", qPrintable(url)); if (nxmInfo.game().compare(managedGame, Qt::CaseInsensitive) != 0) { qDebug("download requested for wrong game (game: %s, url: %s)", qPrintable(managedGame), qPrintable(nxmInfo.game())); QMessageBox::information(NULL, tr("Wrong Game"), tr("The download link is for a mod for \"%1\" but this instance of MO " @@ -1089,11 +1090,7 @@ void DownloadManager::nxmFileInfoAvailable(int modID, int fileID, QVariant userD info.m_FileName = result["uri"].toString(); info.m_FileTime = matchDate(result["date"].toString()); - if (userData.isValid()) { - m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(modID, fileID, this, qVariantFromValue(info), userData.toString())); - } else { - m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(modID, fileID, this, qVariantFromValue(info))); - } + m_RequestIDs.insert(m_NexusInterface->requestDownloadURL(modID, fileID, this, QVariant::fromValue(info))); } @@ -1176,8 +1173,6 @@ void DownloadManager::nxmDownloadURLsAvailable(int modID, int fileID, QVariant u m_RequestIDs.erase(idIter); } - qDebug("download urls received (modid %d, fileid %d)", modID, fileID); - NexusInfo info = userData.value(); QVariantList resultList = resultData.toList(); if (resultList.length() == 0) { @@ -1200,7 +1195,7 @@ void DownloadManager::nxmDownloadURLsAvailable(int modID, int fileID, QVariant u } -void DownloadManager::nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorString) +void DownloadManager::nxmRequestFailed(int modID, int fileID, QVariant userData, int requestID, const QString &errorString) { std::set::iterator idIter = m_RequestIDs.find(requestID); if (idIter == m_RequestIDs.end()) { @@ -1225,7 +1220,7 @@ void DownloadManager::nxmRequestFailed(int modID, QVariant userData, int request } } - removePending(modID, userData.toInt()); + removePending(modID, fileID); emit showMessage(tr("Failed to request file info from nexus: %1").arg(errorString)); } @@ -1243,14 +1238,18 @@ void DownloadManager::downloadFinished() TaskProgressManager::instance().forgetMe(info->m_TaskProgressId); bool error = false; - if ((info->m_State != STATE_CANCELING) && (info->m_State != STATE_PAUSING)) { + bool textData = reply->header(QNetworkRequest::ContentTypeHeader).toString().startsWith("text", Qt::CaseInsensitive); if ((info->m_Output.size() == 0) || ((reply->error() != QNetworkReply::NoError) && (reply->error() != QNetworkReply::OperationCanceledError)) || - reply->header(QNetworkRequest::ContentTypeHeader).toString().startsWith("text", Qt::CaseInsensitive)) { + textData) { if (info->m_Tries == 0) { - emit showMessage(tr("Download failed: %1 (%2)").arg(reply->errorString()).arg(reply->error())); + if (textData && (reply->error() == QNetworkReply::NoError)) { + emit showMessage(tr("Download failed. Server reported: %1").arg(readFileText(info->m_Output.fileName()))); + } else { + emit showMessage(tr("Download failed: %1 (%2)").arg(reply->errorString()).arg(reply->error())); + } } error = true; setState(info, STATE_PAUSING); @@ -1310,7 +1309,7 @@ void DownloadManager::downloadFinished() if ((info->m_Tries > 0) && error) { --info->m_Tries; - resumeDownload(index); + resumeDownloadInt(index); } } else { qWarning("no download index %d", index); diff --git a/src/downloadmanager.h b/src/downloadmanager.h index 62396666..80b99ad2 100644 --- a/src/downloadmanager.h +++ b/src/downloadmanager.h @@ -412,7 +412,7 @@ public slots: void nxmDownloadURLsAvailable(int modID, int fileID, QVariant userData, QVariant resultData, int requestID); - void nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorString); + void nxmRequestFailed(int modID, int fileID, QVariant userData, int requestID, const QString &errorString); private slots: diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 14e27e76..582bc283 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -66,6 +66,7 @@ along with Mod Organizer. If not, see . #include #include #include +#include #include #include #include @@ -1737,6 +1738,9 @@ void MainWindow::refreshSaveList() savesDir.setPath(QDir::fromNativeSeparators(ToQString(GameInfo::instance().getDocumentsDir() + L"\\" + path))); } + if (m_SavesWatcher.directories().length() > 0) { + m_SavesWatcher.removePaths(m_SavesWatcher.directories()); + } m_SavesWatcher.addPath(savesDir.absolutePath()); QStringList filters; @@ -3868,6 +3872,22 @@ void MainWindow::on_categoriesList_itemSelectionChanged() } +void MainWindow::deleteSavegame_clicked() +{ + QListWidgetItem *selectedItem = ui->savegameList->item(m_SelectedSaveGame); + if (selectedItem == NULL) { + return; + } + + QString fileName = selectedItem->data(Qt::UserRole).toString(); + + if (QMessageBox::question(this, tr("Confirm"), tr("Really delete \"%1\"?").arg(selectedItem->text()), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + shellDelete(QStringList() << fileName); + } +} + + void MainWindow::fixMods_clicked() { QListWidgetItem *selectedItem = ui->savegameList->item(m_SelectedSaveGame); @@ -3973,6 +3993,7 @@ void MainWindow::on_savegameList_customContextMenuRequested(const QPoint &pos) QMenu menu; menu.addAction(tr("Fix Mods..."), this, SLOT(fixMods_clicked())); + menu.addAction(tr("Delete"), this, SLOT(deleteSavegame_clicked())); menu.exec(ui->savegameList->mapToGlobal(pos)); } @@ -4721,7 +4742,7 @@ void MainWindow::nxmDownloadURLs(int, int, QVariant, QVariant resultData, int) } -void MainWindow::nxmRequestFailed(int modID, QVariant, int, const QString &errorString) +void MainWindow::nxmRequestFailed(int modID, int, QVariant, int, const QString &errorString) { if (modID == -1) { // must be the update-check that failed diff --git a/src/mainwindow.h b/src/mainwindow.h index e7b3f7e1..c01ce767 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -398,6 +398,7 @@ private slots: void openExplorer_clicked(); void information_clicked(); // savegame context menu + void deleteSavegame_clicked(); void fixMods_clicked(); // data-tree context menu void writeDataToFile(); @@ -464,7 +465,7 @@ private slots: void nxmUpdatesAvailable(const std::vector &modIDs, QVariant userData, QVariant resultData, int requestID); // void nxmEndorsementToggled(int, QVariant, QVariant resultData, int); void nxmDownloadURLs(int modID, int fileID, QVariant userData, QVariant resultData, int requestID); - void nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorString); + void nxmRequestFailed(int modID, int fileID, QVariant userData, int requestID, const QString &errorString); void editCategories(); diff --git a/src/modinfo.cpp b/src/modinfo.cpp index 6569f897..85612b32 100644 --- a/src/modinfo.cpp +++ b/src/modinfo.cpp @@ -345,7 +345,7 @@ ModInfoRegular::ModInfoRegular(const QDir &path, DirectoryEntry **directoryStruc connect(&m_NexusBridge, SIGNAL(descriptionAvailable(int,QVariant,QVariant)), this, SLOT(nxmDescriptionAvailable(int,QVariant,QVariant))); connect(&m_NexusBridge, SIGNAL(endorsementToggled(int,QVariant,QVariant)), this, SLOT(nxmEndorsementToggled(int,QVariant,QVariant))); - connect(&m_NexusBridge, SIGNAL(requestFailed(int,QVariant,QString)), this, SLOT(nxmRequestFailed(int,QVariant,QString))); + connect(&m_NexusBridge, SIGNAL(requestFailed(int,int,QVariant,QString)), this, SLOT(nxmRequestFailed(int,int,QVariant,QString))); } @@ -439,7 +439,7 @@ void ModInfoRegular::nxmEndorsementToggled(int, QVariant, QVariant resultData) } -void ModInfoRegular::nxmRequestFailed(int, QVariant userData, const QString &errorMessage) +void ModInfoRegular::nxmRequestFailed(int, int, QVariant userData, const QString &errorMessage) { QString fullMessage = errorMessage; if (userData.canConvert() && (userData.toInt() == 1)) { diff --git a/src/modinfo.h b/src/modinfo.h index 677d8a82..83654c7e 100644 --- a/src/modinfo.h +++ b/src/modinfo.h @@ -762,7 +762,7 @@ private slots: void nxmDescriptionAvailable(int modID, QVariant userData, QVariant resultData); void nxmEndorsementToggled(int, QVariant userData, QVariant resultData); - void nxmRequestFailed(int modID, QVariant userData, const QString &errorMessage); + void nxmRequestFailed(int modID, int fileID, QVariant userData, const QString &errorMessage); private: diff --git a/src/nexusinterface.cpp b/src/nexusinterface.cpp index 6b87822a..64dd6272 100644 --- a/src/nexusinterface.cpp +++ b/src/nexusinterface.cpp @@ -128,12 +128,12 @@ void NexusBridge::nxmEndorsementToggled(int modID, QVariant userData, QVariant r } } -void NexusBridge::nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorMessage) +void NexusBridge::nxmRequestFailed(int modID, int fileID, QVariant userData, int requestID, const QString &errorMessage) { std::set::iterator iter = m_RequestIDs.find(requestID); if (iter != m_RequestIDs.end()) { m_RequestIDs.erase(iter); - emit requestFailed(modID, userData, errorMessage); + emit requestFailed(modID, fileID, userData, errorMessage); } } @@ -257,8 +257,8 @@ int NexusInterface::requestDescription(int modID, QObject *receiver, QVariant us connect(this, SIGNAL(nxmDescriptionAvailable(int,QVariant,QVariant,int)), receiver, SLOT(nxmDescriptionAvailable(int,QVariant,QVariant,int)), Qt::UniqueConnection); - connect(this, SIGNAL(nxmRequestFailed(int,QVariant,int,QString)), - receiver, SLOT(nxmRequestFailed(int,QVariant,int,QString)), Qt::UniqueConnection); + connect(this, SIGNAL(nxmRequestFailed(int,int,QVariant,int,QString)), + receiver, SLOT(nxmRequestFailed(int,int,QVariant,int,QString)), Qt::UniqueConnection); nextRequest(); return requestInfo.m_ID; @@ -273,8 +273,8 @@ int NexusInterface::requestUpdates(const std::vector &modIDs, QObject *rece connect(this, SIGNAL(nxmUpdatesAvailable(std::vector,QVariant,QVariant,int)), receiver, SLOT(nxmUpdatesAvailable(std::vector,QVariant,QVariant,int)), Qt::UniqueConnection); - connect(this, SIGNAL(nxmRequestFailed(int,QVariant,int,QString)), - receiver, SLOT(nxmRequestFailed(int,QVariant,int,QString)), Qt::UniqueConnection); + connect(this, SIGNAL(nxmRequestFailed(int,int,QVariant,int,QString)), + receiver, SLOT(nxmRequestFailed(int,int,QVariant,int,QString)), Qt::UniqueConnection); nextRequest(); return requestInfo.m_ID; @@ -307,8 +307,8 @@ int NexusInterface::requestFiles(int modID, QObject *receiver, QVariant userData connect(this, SIGNAL(nxmFilesAvailable(int,QVariant,QVariant,int)), receiver, SLOT(nxmFilesAvailable(int,QVariant,QVariant,int)), Qt::UniqueConnection); - connect(this, SIGNAL(nxmRequestFailed(int,QVariant,int,QString)), - receiver, SLOT(nxmRequestFailed(int,QVariant,int,QString)), Qt::UniqueConnection); + connect(this, SIGNAL(nxmRequestFailed(int,int,QVariant,int,QString)), + receiver, SLOT(nxmRequestFailed(int,int,QVariant,int,QString)), Qt::UniqueConnection); // QTimer::singleShot(1000, this, SLOT(fakeFiles())); // static int fID = 42; @@ -327,8 +327,8 @@ int NexusInterface::requestFileInfo(int modID, int fileID, QObject *receiver, QV connect(this, SIGNAL(nxmFileInfoAvailable(int,int,QVariant,QVariant,int)), receiver, SLOT(nxmFileInfoAvailable(int,int,QVariant,QVariant,int)), Qt::UniqueConnection); - connect(this, SIGNAL(nxmRequestFailed(int,QVariant,int,QString)), - receiver, SLOT(nxmRequestFailed(int,QVariant,int,QString)), Qt::UniqueConnection); + connect(this, SIGNAL(nxmRequestFailed(int,int,QVariant,int,QString)), + receiver, SLOT(nxmRequestFailed(int,int,QVariant,int,QString)), Qt::UniqueConnection); nextRequest(); return requestInfo.m_ID; @@ -343,8 +343,8 @@ int NexusInterface::requestDownloadURL(int modID, int fileID, QObject *receiver, connect(this, SIGNAL(nxmDownloadURLsAvailable(int,int,QVariant,QVariant,int)), receiver, SLOT(nxmDownloadURLsAvailable(int,int,QVariant,QVariant,int)), Qt::UniqueConnection); - connect(this, SIGNAL(nxmRequestFailed(int,QVariant,int,QString)), - receiver, SLOT(nxmRequestFailed(int,QVariant,int,QString)), Qt::UniqueConnection); + connect(this, SIGNAL(nxmRequestFailed(int,int,QVariant,int,QString)), + receiver, SLOT(nxmRequestFailed(int,int,QVariant,int,QString)), Qt::UniqueConnection); nextRequest(); return requestInfo.m_ID; @@ -360,8 +360,8 @@ int NexusInterface::requestToggleEndorsement(int modID, bool endorse, QObject *r connect(this, SIGNAL(nxmEndorsementToggled(int,QVariant,QVariant,int)), receiver, SLOT(nxmEndorsementToggled(int,QVariant,QVariant,int)), Qt::UniqueConnection); - connect(this, SIGNAL(nxmRequestFailed(int,QVariant,int,QString)), - receiver, SLOT(nxmRequestFailed(int,QVariant,int,QString)), Qt::UniqueConnection); + connect(this, SIGNAL(nxmRequestFailed(int,int,QVariant,int,QString)), + receiver, SLOT(nxmRequestFailed(int,int,QVariant,int,QString)), Qt::UniqueConnection); nextRequest(); return requestInfo.m_ID; @@ -437,7 +437,7 @@ void NexusInterface::requestFinished(std::list::iterator iter) if (reply->error() != QNetworkReply::NoError) { qWarning("request failed: %s", reply->errorString().toUtf8().constData()); - emit nxmRequestFailed(iter->m_ModID, iter->m_UserData, iter->m_ID, reply->errorString()); + emit nxmRequestFailed(iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, reply->errorString()); } else { int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode == 301) { @@ -454,7 +454,7 @@ void NexusInterface::requestFinished(std::list::iterator iter) if (nexusError.length() == 0) { nexusError = tr("empty response"); } - emit nxmRequestFailed(iter->m_ModID, iter->m_UserData, iter->m_ID, nexusError); + emit nxmRequestFailed(iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, nexusError); } else { bool ok; QVariant result = QtJson::parse(data, ok); @@ -480,7 +480,7 @@ void NexusInterface::requestFinished(std::list::iterator iter) } break; } } else { - emit nxmRequestFailed(iter->m_ModID, iter->m_UserData, iter->m_ID, tr("invalid response")); + emit nxmRequestFailed(iter->m_ModID, iter->m_FileID, iter->m_UserData, iter->m_ID, tr("invalid response")); } } } diff --git a/src/nexusinterface.h b/src/nexusinterface.h index e7a01b0f..7b709e1c 100644 --- a/src/nexusinterface.h +++ b/src/nexusinterface.h @@ -105,7 +105,7 @@ public slots: void nxmFileInfoAvailable(int modID, int fileID, QVariant userData, QVariant resultData, int requestID); void nxmDownloadURLsAvailable(int modID, int fileID, QVariant userData, QVariant resultData, int requestID); void nxmEndorsementToggled(int modID, QVariant userData, QVariant resultData, int requestID); - void nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorMessage); + void nxmRequestFailed(int modID, int fileID, QVariant userData, int requestID, const QString &errorMessage); private: @@ -240,7 +240,7 @@ signals: void nxmFileInfoAvailable(int modID, int fileID, QVariant userData, QVariant resultData, int requestID); void nxmDownloadURLsAvailable(int modID, int fileID, QVariant userData, QVariant resultData, int requestID); void nxmEndorsementToggled(int modID, QVariant userData, QVariant resultData, int requestID); - void nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorString); + void nxmRequestFailed(int modID, int fileID, QVariant userData, int requestID, const QString &errorString); private slots: @@ -276,13 +276,13 @@ private: NXMRequestInfo(int modID, Type type, QVariant userData, const QString &url) : m_ModID(modID), m_FileID(0), m_Reply(NULL), m_Type(type), m_UserData(userData), - m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} + m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} NXMRequestInfo(std::vector modIDList, Type type, QVariant userData, const QString &url) : m_ModID(-1), m_ModIDList(modIDList), m_FileID(0), m_Reply(NULL), m_Type(type), m_UserData(userData), m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} NXMRequestInfo(int modID, int fileID, Type type, QVariant userData, const QString &url) : m_ModID(modID), m_FileID(fileID), m_Reply(NULL), m_Type(type), m_UserData(userData), - m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} + m_Timeout(NULL), m_Reroute(false), m_ID(s_NextID.fetchAndAddAcquire(1)), m_URL(url) {} private: static QAtomicInt s_NextID; diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index a0045ab3..85137390 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -312,7 +312,6 @@ bool PluginList::readLoadOrder(const QString &fileName) void PluginList::readEnabledFrom(const QString &fileName) { -qDebug("read enabled from %s", qPrintable(fileName)); for (std::vector::iterator iter = m_ESPs.begin(); iter != m_ESPs.end(); ++iter) { if (!iter->m_ForceEnabled) { iter->m_Enabled = false; diff --git a/src/selfupdater.cpp b/src/selfupdater.cpp index 2a9ca893..3a0db83f 100644 --- a/src/selfupdater.cpp +++ b/src/selfupdater.cpp @@ -428,7 +428,7 @@ void SelfUpdater::nxmFilesAvailable(int, QVariant userData, QVariant resultData, } -void SelfUpdater::nxmRequestFailed(int, QVariant, int requestID, const QString &errorMessage) +void SelfUpdater::nxmRequestFailed(int, int, QVariant, int requestID, const QString &errorMessage) { if (requestID == m_UpdateRequestID) { m_UpdateRequestID = -1; diff --git a/src/selfupdater.h b/src/selfupdater.h index 2c4c1ecd..14f7e90a 100644 --- a/src/selfupdater.h +++ b/src/selfupdater.h @@ -87,7 +87,7 @@ public slots: void nxmDescriptionAvailable(int modID, QVariant userData, QVariant resultData, int requestID); void nxmFilesAvailable(int modID, QVariant userData, QVariant resultData, int requestID); - void nxmRequestFailed(int modID, QVariant userData, int requestID, const QString &errorMessage); + void nxmRequestFailed(int modID, int fileID, QVariant userData, int requestID, const QString &errorMessage); void nxmDownloadURLsAvailable(int modID, int fileID, QVariant userData, QVariant resultData, int requestID); signals: -- cgit v1.3.1 From 8ab1b479438dd929bc953e554629d1bddca61c9e Mon Sep 17 00:00:00 2001 From: Tannin Date: Tue, 18 Mar 2014 18:29:32 +0100 Subject: - bugfix: if resuming a download failed with the server sending a textual error message, MO tried to display the whole file inside the error message - bugfix: resuming a download didn't trigger a nexus-login when necessary - bugfix: integrated fomod installer only used the first block of data inside a description --- src/downloadmanager.cpp | 2 +- src/mainwindow.cpp | 18 +++++++++++++++++- src/mainwindow.h | 1 + 3 files changed, 19 insertions(+), 2 deletions(-) (limited to 'src/downloadmanager.cpp') diff --git a/src/downloadmanager.cpp b/src/downloadmanager.cpp index 31d8bcec..e747b299 100644 --- a/src/downloadmanager.cpp +++ b/src/downloadmanager.cpp @@ -1246,7 +1246,7 @@ void DownloadManager::downloadFinished() textData) { if (info->m_Tries == 0) { if (textData && (reply->error() == QNetworkReply::NoError)) { - emit showMessage(tr("Download failed. Server reported: %1").arg(readFileText(info->m_Output.fileName()))); + emit showMessage(tr("Download failed. Server reported: %1").arg(QString(data))); } else { emit showMessage(tr("Download failed: %1 (%2)").arg(reply->errorString()).arg(reply->error())); } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index a0af63bd..d4826b30 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3099,6 +3099,22 @@ void MainWindow::reinstallMod_clicked() } +void MainWindow::resumeDownload(int downloadIndex) +{ + if (NexusInterface::instance()->getAccessManager()->loggedIn()) { + m_DownloadManager.resumeDownload(downloadIndex); + } else { + QString username, password; + if (m_Settings.getNexusLogin(username, password)) { + m_PostLoginTasks.push_back(boost::bind(&MainWindow::resumeDownload, _1, downloadIndex)); + NexusInterface::instance()->getAccessManager()->login(username, password); + } else { + MessageDialog::showMessage(tr("You need to be logged in with Nexus to resume a download"), this); + } + } +} + + void MainWindow::endorseMod(ModInfo::Ptr mod) { if (NexusInterface::instance()->getAccessManager()->loggedIn()) { @@ -4685,7 +4701,7 @@ void MainWindow::updateDownloadListDelegate() connect(ui->downloadView->itemDelegate(), SIGNAL(restoreDownload(int)), &m_DownloadManager, SLOT(restoreDownload(int))); connect(ui->downloadView->itemDelegate(), SIGNAL(cancelDownload(int)), &m_DownloadManager, SLOT(cancelDownload(int))); connect(ui->downloadView->itemDelegate(), SIGNAL(pauseDownload(int)), &m_DownloadManager, SLOT(pauseDownload(int))); - connect(ui->downloadView->itemDelegate(), SIGNAL(resumeDownload(int)), &m_DownloadManager, SLOT(resumeDownload(int))); + connect(ui->downloadView->itemDelegate(), SIGNAL(resumeDownload(int)), this, SLOT(resumeDownload(int))); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 250f2a48..46165f0f 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -483,6 +483,7 @@ private slots: void hookUpWindowTutorials(); + void resumeDownload(int downloadIndex); void endorseMod(ModInfo::Ptr mod); void cancelModListEditor(); -- cgit v1.3.1