From 87f9003d60bf936a0a06836602cfafa905080710 Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 15 Jun 2018 19:27:03 +0200 Subject: [PATCH 001/112] Prevent users to choose invalid site apis (fix #1306) --- gui/src/sources/sourcessettingswindow.cpp | 67 +++++++++++++++++----- gui/src/sources/sourcessettingswindow.ui | 69 ++++++++++++----------- 2 files changed, 88 insertions(+), 48 deletions(-) diff --git a/gui/src/sources/sourcessettingswindow.cpp b/gui/src/sources/sourcessettingswindow.cpp index 1d75c79b8..32138a86f 100644 --- a/gui/src/sources/sourcessettingswindow.cpp +++ b/gui/src/sources/sourcessettingswindow.cpp @@ -12,6 +12,17 @@ #include "models/source.h" +void setSource(QComboBox *combo, const QStringList &opts, const QStringList &vals, const QStringList &defs, Site *site, QSettings *settings, int index) +{ + const QString &def = defs[index]; + const QString &global = settings->value("source_" + QString::number(index + 1), def).toString(); + const QString &local = site->setting("sources/source_" + QString::number(index + 1), global).toString(); + + combo->clear(); + combo->addItems(opts); + combo->setCurrentIndex(qMax(0, vals.indexOf(local))); +} + SourcesSettingsWindow::SourcesSettingsWindow(Profile *profile, Site *site, QWidget *parent) : QDialog(parent), ui(new Ui::SourcesSettingsWindow), m_site(site), m_globalSettings(profile->getSettings()) { @@ -41,11 +52,19 @@ SourcesSettingsWindow::SourcesSettingsWindow(Profile *profile, Site *site, QWidg // Source order ui->checkSourcesDefault->setChecked(site->setting("sources/usedefault", true).toBool()); - QStringList sources = QStringList() << "" << "xml" << "json" << "regex" << "rss"; - ui->comboSources1->setCurrentIndex(sources.indexOf(site->setting("sources/source_1", m_globalSettings->value("source_1", sources[0]).toString()).toString())); - ui->comboSources2->setCurrentIndex(sources.indexOf(site->setting("sources/source_2", m_globalSettings->value("source_2", sources[1]).toString()).toString())); - ui->comboSources3->setCurrentIndex(sources.indexOf(site->setting("sources/source_3", m_globalSettings->value("source_3", sources[2]).toString()).toString())); - ui->comboSources4->setCurrentIndex(sources.indexOf(site->setting("sources/source_4", m_globalSettings->value("source_4", sources[3]).toString()).toString())); + QStringList defs = QStringList() << "xml" << "json" << "regex" << "rss"; + QStringList sources = QStringList() << ""; + QStringList opts = QStringList() << ""; + for (Api *api : site->getApis()) + { + QString name = api->getName().toLower(); + sources.append(name == "html" ? "regex" : name); + opts.append(api->getName()); + } + setSource(ui->comboSources1, opts, sources, defs, site, m_globalSettings, 0); + setSource(ui->comboSources2, opts, sources, defs, site, m_globalSettings, 1); + setSource(ui->comboSources3, opts, sources, defs, site, m_globalSettings, 2); + setSource(ui->comboSources4, opts, sources, defs, site, m_globalSettings, 3); // Credentials ui->lineAuthPseudo->setText(site->setting("auth/pseudo", "").toString()); @@ -111,8 +130,6 @@ SourcesSettingsWindow::SourcesSettingsWindow(Profile *profile, Site *site, QWidg ui->widgetTestCredentials->hide(); ui->widgetTestLogin->hide(); } - - connect(this, &QDialog::accepted, this, &SourcesSettingsWindow::save); } SourcesSettingsWindow::~SourcesSettingsWindow() @@ -217,13 +234,34 @@ void SourcesSettingsWindow::save() m_site->setSetting("download/throttle_retry", ui->spinThrottleRetry->value(), 0); m_site->setSetting("download/throttle_thumbnail", ui->spinThrottleThumbnail->value(), 0); - QStringList sources = QStringList() << "" << "xml" << "json" << "regex" << "rss"; + QStringList defs = QStringList() << "xml" << "json" << "regex" << "rss"; + QStringList sources = QStringList() << ""; + for (Api *api : m_site->getApis()) + { + QString name = api->getName().toLower(); + sources.append(name == "html" ? "regex" : name); + } + QStringList chosen = QStringList() + << sources[ui->comboSources1->currentIndex()] + << sources[ui->comboSources2->currentIndex()] + << sources[ui->comboSources3->currentIndex()] + << sources[ui->comboSources4->currentIndex()]; m_site->setSetting("sources/usedefault", ui->checkSourcesDefault->isChecked(), true); - m_site->setSetting("sources/source_1", sources[qMax(0, ui->comboSources1->currentIndex())], m_globalSettings->value("source_1", sources[0]).toString()); - m_site->setSetting("sources/source_2", sources[qMax(0, ui->comboSources2->currentIndex())], m_globalSettings->value("source_2", sources[1]).toString()); - m_site->setSetting("sources/source_3", sources[qMax(0, ui->comboSources3->currentIndex())], m_globalSettings->value("source_3", sources[2]).toString()); - m_site->setSetting("sources/source_4", sources[qMax(0, ui->comboSources4->currentIndex())], m_globalSettings->value("source_4", sources[3]).toString()); - + m_site->setSetting("sources/source_1", chosen[0], m_globalSettings->value("source_1", defs[0]).toString()); + m_site->setSetting("sources/source_2", chosen[1], m_globalSettings->value("source_2", defs[1]).toString()); + m_site->setSetting("sources/source_3", chosen[2], m_globalSettings->value("source_3", defs[2]).toString()); + m_site->setSetting("sources/source_4", chosen[3], m_globalSettings->value("source_4", defs[3]).toString()); + + // Ensure at least one source is selected + bool allEmpty = true; + for (const QString &chos : qAsConst(chosen)) + if (!chos.isEmpty()) + allEmpty = false; + if (allEmpty) + { + QMessageBox::critical(this, tr("Error"), tr("You should at least select one source")); + return; + } m_site->setSetting("auth/pseudo", ui->lineAuthPseudo->text(), ""); m_site->setSetting("auth/password", ui->lineAuthPassword->text(), ""); @@ -274,6 +312,7 @@ void SourcesSettingsWindow::save() m_site->setSetting("headers", headers, QMap()); m_site->syncSettings(); - m_site->loadConfig(); + + accept(); } diff --git a/gui/src/sources/sourcessettingswindow.ui b/gui/src/sources/sourcessettingswindow.ui index b241e6371..5aa6dfdec 100644 --- a/gui/src/sources/sourcessettingswindow.ui +++ b/gui/src/sources/sourcessettingswindow.ui @@ -1045,7 +1045,7 @@ 84 - 287 + 262 256 @@ -1061,7 +1061,7 @@ 438 - 287 + 262 345 @@ -1069,22 +1069,6 @@ - - buttonAccept - clicked() - SourcesSettingsWindow - accept() - - - 519 - 287 - - - 368 - 205 - - - pushButton_5 clicked() @@ -1092,8 +1076,8 @@ testLogin() - 453 - 216 + 507 + 218 256 @@ -1108,12 +1092,12 @@ setDisabled(bool) - 168 - 56 + 101 + 42 - 153 - 98 + 101 + 65 @@ -1124,8 +1108,8 @@ testLogin() - 453 - 120 + 507 + 119 273 @@ -1140,8 +1124,8 @@ addCookie() - 442 - 244 + 101 + 199 470 @@ -1156,8 +1140,8 @@ addHeader() - 143 - 244 + 101 + 199 43 @@ -1172,12 +1156,28 @@ setCurrentIndex(int) - 102 - 49 + 146 + 40 + + + 101 + 66 + + + + + buttonAccept + clicked() + SourcesSettingsWindow + save() + + + 490 + 254 - 93 - 89 + 529 + 256 @@ -1187,5 +1187,6 @@ testLogin() addCookie() addHeader() + save() From 4286551fd9ec22ce3f711afed602447ea51dec0b Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 15 Jun 2018 19:42:29 +0200 Subject: [PATCH 002/112] Return const references for expensive types --- gui/src/tabs/search-tab.cpp | 8 ++++---- gui/src/tabs/search-tab.h | 8 ++++---- lib/src/downloader/downloader.cpp | 6 ++---- lib/src/downloader/downloader.h | 5 ++--- lib/src/models/image.cpp | 14 +++++++------- lib/src/models/image.h | 14 +++++++------- lib/src/models/page.cpp | 2 +- lib/src/models/site.cpp | 14 ++++++-------- lib/src/models/site.h | 12 +++++++----- lib/src/tags/tag-api.cpp | 2 +- lib/src/tags/tag-api.h | 2 +- lib/src/tags/tag-database.cpp | 2 +- lib/src/tags/tag-database.h | 2 +- 13 files changed, 44 insertions(+), 47 deletions(-) diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index c58028019..fcc1e3e07 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -1461,12 +1461,12 @@ void searchTab::setFavoriteImage(const QString &name) QList searchTab::sources() { return m_selectedSources; } -QStringList searchTab::selectedImages() +const QStringList &searchTab::selectedImages() { return m_selectedImages; } -QList searchTab::results() +const QList &searchTab::results() { return m_tags; } -QString searchTab::wiki() +const QString &searchTab::wiki() { return m_wiki; } void searchTab::onLoad() @@ -1511,5 +1511,5 @@ int searchTab::imagesPerPage() { return ui_spinImagesPerPage->value(); } int searchTab::columns() { return ui_spinColumns->value(); } -QString searchTab::postFilter() +const QString &searchTab::postFilter() { return m_postFiltering->toPlainText(); } diff --git a/gui/src/tabs/search-tab.h b/gui/src/tabs/search-tab.h index cabddcb4f..b65053cc6 100644 --- a/gui/src/tabs/search-tab.h +++ b/gui/src/tabs/search-tab.h @@ -38,14 +38,14 @@ class searchTab : public QWidget void mouseReleaseEvent(QMouseEvent *e) override; virtual QList sources(); virtual QString tags() const = 0; - QList results(); - QString wiki(); + const QList &results(); + const QString &wiki(); int imagesPerPage(); int columns(); - QString postFilter(); + const QString &postFilter(); virtual void setTags(const QString &tags, bool preload = true) = 0; virtual bool validateImage(const QSharedPointer &img, QString &error); - QStringList selectedImages(); + const QStringList &selectedImages(); void setSources(const QList &sources); void setImagesPerPage(int ipp); void setColumns(int columns); diff --git a/lib/src/downloader/downloader.cpp b/lib/src/downloader/downloader.cpp index c1cc47b98..29eee646c 100644 --- a/lib/src/downloader/downloader.cpp +++ b/lib/src/downloader/downloader.cpp @@ -504,7 +504,7 @@ void Downloader::returnStringList(const QStringList &ret) void Downloader::setData(const QVariant &data) { m_data = data; } -QVariant Downloader::getData() const +const QVariant &Downloader::getData() const { return m_data; } void Downloader::cancel() @@ -526,7 +526,5 @@ int Downloader::imagesMax() const Page *Downloader::lastPage() const { return m_lastPage; } -QList Downloader::getPages() const -{ return m_pages; } -QList Downloader::getSites() const +const QList &Downloader::getSites() const { return m_sites; } diff --git a/lib/src/downloader/downloader.h b/lib/src/downloader/downloader.h index 4c4b2c311..7311f6e90 100644 --- a/lib/src/downloader/downloader.h +++ b/lib/src/downloader/downloader.h @@ -24,9 +24,8 @@ class Downloader : public QObject void getPageTags(); void getImages(); void getUrls(); - QVariant getData() const; - QList getPages() const; - QList getSites() const; + const QVariant &getData() const; + const QList &getSites() const; int ignoredCount() const; int duplicatesCount() const; int pagesCount() const; diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 5ef826693..d016d0f2d 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -817,18 +817,18 @@ QList Image::filteredTags(const QStringList &remove) const } -QString Image::url() const { return m_url; } -QString Image::rating() const { return m_rating; } +const QString &Image::url() const { return m_url; } +const QString &Image::rating() const { return m_rating; } Site *Image::parentSite() const { return m_parentSite; } -QList Image::tags() const { return m_tags; } -QList Image::pools() const { return m_pools; } +const QList &Image::tags() const { return m_tags; } +const QList &Image::pools() const { return m_pools; } qulonglong Image::id() const { return m_id; } int Image::fileSize() const { return m_fileSize; } int Image::width() const { return m_size.width(); } int Image::height() const { return m_size.height(); } -QDateTime Image::createdAt() const { return m_createdAt; } -QUrl Image::fileUrl() const { return m_fileUrl; } -QUrl Image::pageUrl() const { return m_pageUrl; } +const QDateTime &Image::createdAt() const { return m_createdAt; } +const QUrl &Image::fileUrl() const { return m_fileUrl; } +const QUrl &Image::pageUrl() const { return m_pageUrl; } QSize Image::size() const { return m_size; } QPixmap Image::previewImage() const { return m_imagePreview; } const QPixmap &Image::previewImage() { return m_imagePreview; } diff --git a/lib/src/models/image.h b/lib/src/models/image.h index 00811b681..02239a897 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -32,20 +32,20 @@ class Image : public QObject, public Downloadable QMap save(const QStringList &paths, bool addMd5 = true, bool startCommands = false, int count = 1, bool force = false); QMap save(const QString &filename, const QString &path, bool addMd5 = true, bool startCommands = false, int count = 1); QString md5() const; - QString url() const; - QString rating() const; + const QString &url() const; + const QString &rating() const; QString site() const; - QList tags() const; + const QList &tags() const; QList filteredTags(const QStringList &remove) const; QStringList tagsString() const; - QList pools() const; + const QList &pools() const; qulonglong id() const; int fileSize() const; int width() const; int height() const; - QDateTime createdAt() const; - QUrl pageUrl() const; - QUrl fileUrl() const; + const QDateTime &createdAt() const; + const QUrl &pageUrl() const; + const QUrl &fileUrl() const; QSize size() const; QPixmap previewImage() const; const QPixmap &previewImage(); diff --git a/lib/src/models/page.cpp b/lib/src/models/page.cpp index d0b8d2c0c..74608f42a 100644 --- a/lib/src/models/page.cpp +++ b/lib/src/models/page.cpp @@ -37,7 +37,7 @@ Page::Page(Profile *profile, Site *site, const QList &sites, QStringList m_search = tags; // Generate pages - m_siteApis = m_site->getApis(true); + m_siteApis = m_site->getLoggedInApis(); m_pageApis.reserve(m_siteApis.count()); for (Api *api : qAsConst(m_siteApis)) { diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index b86a2deb3..8be8a3a3a 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -341,16 +341,14 @@ void Site::syncSettings() { m_settings->sync(); } MixedSettings *Site::settings() const { return m_settings; } TagDatabase *Site::tagDatabase() const { return m_tagDatabase; } -QString Site::name() const { return m_name; } -QString Site::url() const { return m_url; } -QString Site::type() const { return m_type; } +const QString &Site::name() const { return m_name; } +const QString &Site::url() const { return m_url; } +const QString &Site::type() const { return m_type; } Source *Site::getSource() const { return m_source; } -QList Site::getApis(bool filterAuth) const +const QList &Site::getApis() const { return m_apis; } +QList Site::getLoggedInApis() const { - if (!filterAuth) - return m_apis; - QList ret; bool loggedIn = isLoggedIn(true); for (Api *api : m_apis) @@ -413,7 +411,7 @@ QUrl Site::fixUrl(const QString &url, const QUrl &old) const return QUrl(url); } -QList Site::cookies() const +const QList &Site::cookies() const { return m_cookies; } diff --git a/lib/src/models/site.h b/lib/src/models/site.h index efa03c5e5..82026dd0b 100644 --- a/lib/src/models/site.h +++ b/lib/src/models/site.h @@ -53,10 +53,10 @@ class Site : public QObject Site(const QString &url, Source *source); ~Site() override; void loadConfig(); - QString type() const; - QString name() const; - QString url() const; - QList cookies() const; + const QString &type() const; + const QString &name() const; + const QString &url() const; + const QList &cookies() const; QVariant setting(const QString &key, const QVariant &def = QVariant()); void setSetting(const QString &key, const QVariant &value, const QVariant &def); void syncSettings(); @@ -69,7 +69,9 @@ class Site : public QObject QUrl fixUrl(const QString &url, const QUrl &old = QUrl()) const; // Api - QList getApis(bool filterAuth = false) const; + const QList &getApis() const; + QList getLoggedInApis() const; + Source *getSource() const; Api *firstValidApi() const; Api *detailsApi() const; diff --git a/lib/src/tags/tag-api.cpp b/lib/src/tags/tag-api.cpp index e39a2abcb..6ed3679af 100755 --- a/lib/src/tags/tag-api.cpp +++ b/lib/src/tags/tag-api.cpp @@ -80,7 +80,7 @@ void TagApi::parse() emit finishedLoading(this, LoadResult::Ok); } -QList TagApi::tags() const +const QList &TagApi::tags() const { return m_tags; } diff --git a/lib/src/tags/tag-api.h b/lib/src/tags/tag-api.h index 3f286facf..2955a8d8d 100644 --- a/lib/src/tags/tag-api.h +++ b/lib/src/tags/tag-api.h @@ -24,7 +24,7 @@ class TagApi : public QObject explicit TagApi(Profile *profile, Site *site, Api *api, int page = 1, int limit = 1000, QObject *parent = Q_NULLPTR); ~TagApi() override; void load(bool rateLimit = false); - QList tags() const; + const QList &tags() const; public slots: void abort(); diff --git a/lib/src/tags/tag-database.cpp b/lib/src/tags/tag-database.cpp index 6e08ee5ee..736f61fab 100644 --- a/lib/src/tags/tag-database.cpp +++ b/lib/src/tags/tag-database.cpp @@ -37,7 +37,7 @@ void TagDatabase::loadTypes() f.close(); } -QMap TagDatabase::tagTypes() const +const QMap &TagDatabase::tagTypes() const { return m_tagTypes; } diff --git a/lib/src/tags/tag-database.h b/lib/src/tags/tag-database.h index b30fe581d..a8d52099f 100644 --- a/lib/src/tags/tag-database.h +++ b/lib/src/tags/tag-database.h @@ -17,7 +17,7 @@ class TagDatabase virtual void setTags(const QList &tags) = 0; virtual QMap getTagTypes(const QStringList &tags) const = 0; virtual int count() const = 0; - QMap tagTypes() const; + const QMap &tagTypes() const; protected: explicit TagDatabase(const QString &typeFile); From 5c6be5505916b46b6872712f3e64d4ff06193317 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 16 Jun 2018 17:44:08 +0200 Subject: [PATCH 003/112] Add const everywhere possible --- CrashReporter/crash-reporter-window.cpp | 9 +- cli/src/main.cpp | 40 ++--- e2e/src/main.cpp | 25 +-- e2e/viewer/md.html | 74 +++++++++ gui/src/batch/addgroupwindow.cpp | 3 +- gui/src/batch/addgroupwindow.h | 1 - gui/src/batch/adduniquewindow.cpp | 7 +- gui/src/batch/batchwindow.cpp | 40 ++--- gui/src/batch/batchwindow.h | 1 - gui/src/helpers.h | 1 - gui/src/image-context-menu.h | 1 + gui/src/main/main.cpp | 55 +++---- gui/src/mainwindow.cpp | 3 +- gui/src/mainwindow.h | 4 - gui/src/settings/conditionwindow.cpp | 3 +- gui/src/settings/filenamewindow.cpp | 6 +- gui/src/settings/filenamewindow.h | 1 - gui/src/settings/log-window.h | 1 - gui/src/settings/optionswindow.cpp | 24 ++- gui/src/settings/web-service-window.cpp | 6 +- gui/src/sources/sitewindow.cpp | 1 - gui/src/sources/sitewindow.h | 1 - gui/src/sources/sourcessettingswindow.cpp | 17 +- gui/src/sources/sourcessettingswindow.h | 2 - gui/src/sources/sourceswindow.cpp | 8 +- gui/src/tabs/favorites-tab.cpp | 62 +++---- gui/src/tabs/favorites-tab.h | 2 - gui/src/tabs/pool-tab.cpp | 32 ++-- gui/src/tabs/pool-tab.h | 3 - gui/src/tabs/search-tab.cpp | 155 +++++++++--------- gui/src/tabs/search-tab.h | 9 +- gui/src/tabs/tag-tab.cpp | 30 ++-- gui/src/tabs/tag-tab.h | 3 - gui/src/threads/image-loader-queue.cpp | 2 +- gui/src/threads/image-loader-queue.h | 1 - gui/src/threads/image-loader.h | 1 - gui/src/threads/resizer.cpp | 1 + gui/src/updater/update-dialog.cpp | 4 +- lib/src/commands/commands.cpp | 11 +- lib/src/commands/commands.h | 8 +- lib/src/commands/sql-worker.cpp | 3 +- lib/src/commands/sql-worker.h | 1 - lib/src/custom-network-access-manager.cpp | 10 +- lib/src/danbooru-downloader-importer.cpp | 5 +- lib/src/downloader/download-query-group.cpp | 2 +- lib/src/downloader/download-query-group.h | 5 +- lib/src/downloader/download-query-image.cpp | 2 +- lib/src/downloader/download-query-image.h | 1 - lib/src/downloader/download-query-loader.cpp | 13 +- lib/src/downloader/download-query-loader.h | 1 - lib/src/downloader/extension-rotator.cpp | 7 +- lib/src/downloader/file-downloader.cpp | 7 +- lib/src/downloader/image-downloader.cpp | 14 +- lib/src/functions.cpp | 84 +++++----- lib/src/language-loader.cpp | 4 +- lib/src/loader/downloadable-downloader.cpp | 8 +- lib/src/loader/downloadable-downloader.h | 2 +- lib/src/loader/downloadable.h | 1 + lib/src/loader/loader-data.h | 3 - lib/src/loader/loader-query.cpp | 18 +- lib/src/loader/loader-query.h | 2 - lib/src/loader/loader.h | 2 - lib/src/loader/token.cpp | 8 +- lib/src/loader/token.h | 9 +- lib/src/login/http-get-login.cpp | 2 +- lib/src/login/http-get-login.h | 1 + lib/src/login/http-login.cpp | 7 +- lib/src/login/http-post-login.h | 1 + lib/src/login/login.cpp | 1 + lib/src/login/oauth2-login.cpp | 1 + lib/src/login/url-login.cpp | 4 +- lib/src/mixed-settings.cpp | 2 +- lib/src/mixed-settings.h | 2 - lib/src/models/api/api.cpp | 15 +- lib/src/models/api/api.h | 3 - lib/src/models/api/html-api.cpp | 11 +- lib/src/models/api/javascript-api.cpp | 38 +++-- lib/src/models/api/javascript-api.h | 2 + .../models/api/javascript-console-helper.cpp | 1 + .../models/api/javascript-grabber-helper.cpp | 4 +- lib/src/models/api/json-api.cpp | 10 +- lib/src/models/api/rss-api.cpp | 4 + lib/src/models/api/xml-api.cpp | 7 +- lib/src/models/favorite.cpp | 15 +- lib/src/models/favorite.h | 2 - lib/src/models/filename.cpp | 64 ++++---- lib/src/models/image.cpp | 94 ++++++----- lib/src/models/monitor.cpp | 9 +- lib/src/models/monitor.h | 1 - lib/src/models/page-api.cpp | 31 ++-- lib/src/models/page-api.h | 2 - lib/src/models/page.cpp | 6 +- lib/src/models/pool.cpp | 11 +- lib/src/models/pool.h | 20 +-- lib/src/models/post-filter.cpp | 18 +- lib/src/models/post-filter.h | 2 - lib/src/models/profile.cpp | 15 +- lib/src/models/profile.h | 3 - lib/src/models/site.cpp | 31 ++-- lib/src/models/site.h | 2 - lib/src/models/source.cpp | 13 +- .../reverse-search/reverse-search-engine.cpp | 11 +- .../reverse-search/reverse-search-engine.h | 5 +- .../reverse-search/reverse-search-loader.cpp | 4 +- .../reverse-search/reverse-search-loader.h | 1 - lib/src/secure-file.cpp | 3 +- lib/src/secure-file.h | 1 - lib/src/tags/tag-api.cpp | 4 +- lib/src/tags/tag-database-factory.cpp | 2 +- lib/src/tags/tag-database-in-memory.cpp | 2 +- lib/src/tags/tag-database-sqlite.cpp | 14 +- lib/src/tags/tag-database.cpp | 1 + lib/src/tags/tag-name-format.h | 1 - lib/src/tags/tag-name.h | 2 - lib/src/tags/tag-stylist.cpp | 9 +- lib/src/tags/tag-type.cpp | 2 +- lib/src/tags/tag-type.h | 2 +- lib/src/tags/tag.cpp | 28 ++-- lib/src/tags/tag.h | 21 ++- lib/src/updater/program-updater.cpp | 12 +- lib/src/updater/source-updater.cpp | 4 +- lib/src/updater/source-updater.h | 1 + lib/src/updater/updater.cpp | 8 +- 123 files changed, 750 insertions(+), 713 deletions(-) create mode 100644 e2e/viewer/md.html diff --git a/CrashReporter/crash-reporter-window.cpp b/CrashReporter/crash-reporter-window.cpp index 14935cc6a..20274b42a 100644 --- a/CrashReporter/crash-reporter-window.cpp +++ b/CrashReporter/crash-reporter-window.cpp @@ -1,8 +1,9 @@ +#include #include #include -#include #include #include +#include #include #include #include "crash-reporter-window.h" @@ -15,7 +16,7 @@ QString savePath(const QString &file, bool exists = false) Q_UNUSED(exists); return QDir::toNativeSeparators(QDir::currentPath()+"/tests/resources/"+file); #else - QString check = exists ? file : "settings.ini"; + const QString &check = exists ? file : "settings.ini"; if (QFile(QDir::toNativeSeparators(qApp->applicationDirPath()+"/"+check)).exists()) { return QDir::toNativeSeparators(qApp->applicationDirPath()+"/"+file); } if (QFile(QDir::toNativeSeparators(QDir::currentPath()+"/"+check)).exists()) @@ -35,8 +36,8 @@ CrashReporterWindow::CrashReporterWindow(QWidget *parent) : QMainWindow(parent), QSettings settings(savePath("settings.ini"), QSettings::IniFormat); // Translate UI - QString lang = settings.value("language", "English").toString(); - QLocale locale = QLocale(lang); + const QString lang = settings.value("language", "English").toString(); + const QLocale locale = QLocale(lang); QLocale::setDefault(locale); auto *translator = new QTranslator(this); if (translator->load("crashreporter/"+lang)) diff --git a/cli/src/main.cpp b/cli/src/main.cpp index 0fc260f9f..30216d8d3 100644 --- a/cli/src/main.cpp +++ b/cli/src/main.cpp @@ -22,21 +22,21 @@ int main(int argc, char *argv[]) parser.addHelpOption(); parser.addVersionOption(); - QCommandLineOption tagsOption(QStringList() << "t" << "tags", "Tags to search for.", "tags"); - QCommandLineOption sourceOption(QStringList() << "s" << "sources", "Source websites.", "sources"); - QCommandLineOption pageOption(QStringList() << "p" << "page", "Starting page.", "page", "1"); - QCommandLineOption limitOption(QStringList() << "m" << "max", "Maximum of returned images.", "count"); - QCommandLineOption perPageOption(QStringList() << "i" << "perpage", "Number of images per page.", "count", "20"); - QCommandLineOption pathOption(QStringList() << "l" << "location", "Location to save the results.", "path"); - QCommandLineOption filenameOption(QStringList() << "f" << "filename", "Filename to save the results.", "filename"); - QCommandLineOption userOption(QStringList() << "u" << "user", "Username to connect to the source.", "user"); - QCommandLineOption passwordOption(QStringList() << "w" << "password", "Password to connect to the source.", "password"); - QCommandLineOption blacklistOption(QStringList() << "b" << "blacklist", "Download blacklisted images."); - QCommandLineOption postFilteringOption(QStringList() << "r" << "postfilter", "Filter results.", "filter"); - QCommandLineOption noDuplicatesOption(QStringList() << "n" << "no-duplicates", "Remove duplicates from results."); - QCommandLineOption verboseOption(QStringList() << "d" << "debug", "Show debug messages."); - QCommandLineOption tagsMinOption(QStringList() << "tm" << "tags-min", "Minimum count for tags to be returned.", "count", "0"); - QCommandLineOption tagsFormatOption(QStringList() << "tf" << "tags-format", "Format for returning tags.", "format", "%tag\t%count\t%type"); + const QCommandLineOption tagsOption(QStringList() << "t" << "tags", "Tags to search for.", "tags"); + const QCommandLineOption sourceOption(QStringList() << "s" << "sources", "Source websites.", "sources"); + const QCommandLineOption pageOption(QStringList() << "p" << "page", "Starting page.", "page", "1"); + const QCommandLineOption limitOption(QStringList() << "m" << "max", "Maximum of returned images.", "count"); + const QCommandLineOption perPageOption(QStringList() << "i" << "perpage", "Number of images per page.", "count", "20"); + const QCommandLineOption pathOption(QStringList() << "l" << "location", "Location to save the results.", "path"); + const QCommandLineOption filenameOption(QStringList() << "f" << "filename", "Filename to save the results.", "filename"); + const QCommandLineOption userOption(QStringList() << "u" << "user", "Username to connect to the source.", "user"); + const QCommandLineOption passwordOption(QStringList() << "w" << "password", "Password to connect to the source.", "password"); + const QCommandLineOption blacklistOption(QStringList() << "b" << "blacklist", "Download blacklisted images."); + const QCommandLineOption postFilteringOption(QStringList() << "r" << "postfilter", "Filter results.", "filter"); + const QCommandLineOption noDuplicatesOption(QStringList() << "n" << "no-duplicates", "Remove duplicates from results."); + const QCommandLineOption verboseOption(QStringList() << "d" << "debug", "Show debug messages."); + const QCommandLineOption tagsMinOption(QStringList() << "tm" << "tags-min", "Minimum count for tags to be returned.", "count", "0"); + const QCommandLineOption tagsFormatOption(QStringList() << "tf" << "tags-format", "Format for returning tags.", "format", "%tag\t%count\t%type"); parser.addOption(tagsOption); parser.addOption(sourceOption); parser.addOption(pageOption); @@ -52,11 +52,11 @@ int main(int argc, char *argv[]) parser.addOption(tagsFormatOption); parser.addOption(noDuplicatesOption); parser.addOption(verboseOption); - QCommandLineOption returnCountOption(QStringList() << "rc" << "return-count", "Return total image count."); - QCommandLineOption returnTagsOption(QStringList() << "rt" << "return-tags", "Return tags for a search."); - QCommandLineOption returnPureTagsOption(QStringList() << "rp" << "return-pure-tags", "Return tags."); - QCommandLineOption returnImagesOption(QStringList() << "ri" << "return-images", "Return images url."); - QCommandLineOption downloadOption(QStringList() << "download", "Download found images."); + const QCommandLineOption returnCountOption(QStringList() << "rc" << "return-count", "Return total image count."); + const QCommandLineOption returnTagsOption(QStringList() << "rt" << "return-tags", "Return tags for a search."); + const QCommandLineOption returnPureTagsOption(QStringList() << "rp" << "return-pure-tags", "Return tags."); + const QCommandLineOption returnImagesOption(QStringList() << "ri" << "return-images", "Return images url."); + const QCommandLineOption downloadOption(QStringList() << "download", "Download found images."); parser.addOption(returnCountOption); parser.addOption(returnTagsOption); parser.addOption(returnPureTagsOption); diff --git a/e2e/src/main.cpp b/e2e/src/main.cpp index d321e9099..f83cbf51f 100644 --- a/e2e/src/main.cpp +++ b/e2e/src/main.cpp @@ -1,8 +1,8 @@ #include #include -#include #include #include +#include #include #include #include "functions.h" @@ -13,6 +13,7 @@ #include "models/profile.h" #include "models/site.h" #include "models/source.h" +#include "tags/tag.h" bool opCompare(QString op, int left, int right) @@ -44,13 +45,13 @@ bool jsonCompare(QVariant value, QJsonValue opt) int main(int argc, char *argv[]) { - QCoreApplication app(argc, argv); + const QCoreApplication app(argc, argv); QCommandLineParser parser; parser.addHelpOption(); - QCommandLineOption inputOption(QStringList() << "i" << "input", "Input JSON configuration file", "input"); - QCommandLineOption outputOption(QStringList() << "o" << "output", "Output JSON result file", "output"); + const QCommandLineOption inputOption(QStringList() << "i" << "input", "Input JSON configuration file", "input"); + const QCommandLineOption outputOption(QStringList() << "o" << "output", "Output JSON result file", "output"); parser.addOption(inputOption); parser.addOption(outputOption); parser.process(app); @@ -73,12 +74,12 @@ int main(int argc, char *argv[]) auto allSources = profile->getSources(); auto allSites = profile->getSites(); - auto oldBlacklist = profile->getBlacklist(); + const auto oldBlacklist = profile->getBlacklist(); profile->setBlacklistedTags(QList()); - QJsonObject root = input.object(); - QJsonArray rootSearch = root.value("search").toArray(); - QJsonObject sources = root.value("sources").toObject(); + const QJsonObject root = input.object(); + const QJsonArray rootSearch = root.value("search").toArray(); + const QJsonObject sources = root.value("sources").toObject(); for (const QString &sourceName : sources.keys()) { @@ -88,7 +89,7 @@ int main(int argc, char *argv[]) Source *source = allSources.value(sourceName); QJsonObject sites = sources.value(sourceName).toObject(); - QJsonObject sourceApis = sites.value("apis").toObject(); + const QJsonObject sourceApis = sites.value("apis").toObject(); QJsonArray sourceSearch = rootSearch; if (sites.contains("search")) { sourceSearch = sites.value("search").toArray(); } @@ -119,9 +120,9 @@ int main(int argc, char *argv[]) if (checks.count() > 4) { apiSearch = checks[4].toArray(); } - QString search = apiSearch[0].toString(); - int pagei = apiSearch[1].toDouble(); - int limit = apiSearch[2].toDouble(); + const QString search = apiSearch[0].toString(); + const int pagei = apiSearch[1].toDouble(); + const int limit = apiSearch[2].toDouble(); Api *api = Q_NULLPTR; for (Api *a : site->getApis()) diff --git a/e2e/viewer/md.html b/e2e/viewer/md.html new file mode 100644 index 000000000..eab71ec55 --- /dev/null +++ b/e2e/viewer/md.html @@ -0,0 +1,74 @@ + + + + Source status + + + + + +
+

+        
+ + + + diff --git a/gui/src/batch/addgroupwindow.cpp b/gui/src/batch/addgroupwindow.cpp index a1e4a633b..b5c92cba9 100644 --- a/gui/src/batch/addgroupwindow.cpp +++ b/gui/src/batch/addgroupwindow.cpp @@ -1,4 +1,5 @@ #include "batch/addgroupwindow.h" +#include #include #include "downloader/download-query-group.h" #include "models/profile.h" @@ -39,7 +40,7 @@ AddGroupWindow::AddGroupWindow(Site *selected, Profile *profile, QWidget *parent */ void AddGroupWindow::ok() { - QStringList postFiltering = m_linePostFiltering->toPlainText().split(' ', QString::SkipEmptyParts); + const QStringList postFiltering = m_linePostFiltering->toPlainText().split(' ', QString::SkipEmptyParts); Site *site = m_sites.value(ui->comboSites->currentText()); emit sendData(DownloadQueryGroup(m_lineTags->toPlainText(), ui->spinPage->value(), ui->spinPP->value(), ui->spinLimit->value(), postFiltering, ui->checkBlacklist->isChecked(), site, m_settings->value("Save/filename").toString(), m_settings->value("Save/path").toString())); close(); diff --git a/gui/src/batch/addgroupwindow.h b/gui/src/batch/addgroupwindow.h index 7a417011d..d5ca9bc52 100644 --- a/gui/src/batch/addgroupwindow.h +++ b/gui/src/batch/addgroupwindow.h @@ -3,7 +3,6 @@ #include #include -#include namespace Ui diff --git a/gui/src/batch/adduniquewindow.cpp b/gui/src/batch/adduniquewindow.cpp index 01b469553..943435d44 100644 --- a/gui/src/batch/adduniquewindow.cpp +++ b/gui/src/batch/adduniquewindow.cpp @@ -1,6 +1,5 @@ #include "batch/adduniquewindow.h" #include -#include #include #include "downloader/download-query-image.h" #include "helpers.h" @@ -61,7 +60,7 @@ void AddUniqueWindow::ok(bool close) Api *api = site->detailsApi(); if (api != Q_NULLPTR) { - QString url = api->detailsUrl(ui->lineId->text().toULongLong(), ui->lineMd5->text(), site).url; + const QString url = api->detailsUrl(ui->lineId->text().toULongLong(), ui->lineMd5->text(), site).url; auto details = QMap(); details.insert("page_url", url); @@ -74,8 +73,8 @@ void AddUniqueWindow::ok(bool close) } else { - QString query = (ui->lineId->text().isEmpty() ? "md5:"+ui->lineMd5->text() : "id:"+ui->lineId->text()); - QStringList search = QStringList() << query << "status:any"; + const QString query = (ui->lineId->text().isEmpty() ? "md5:" + ui->lineMd5->text() : "id:" + ui->lineId->text()); + const QStringList search = QStringList() << query << "status:any"; m_page = new Page(m_profile, site, m_sites.values(), search, 1, 1); connect(m_page, &Page::finishedLoading, this, &AddUniqueWindow::replyFinished); m_page->load(); diff --git a/gui/src/batch/batchwindow.cpp b/gui/src/batch/batchwindow.cpp index ca077b141..2e3e9e006 100644 --- a/gui/src/batch/batchwindow.cpp +++ b/gui/src/batch/batchwindow.cpp @@ -2,10 +2,12 @@ #include #include #include -#include +#ifdef Q_OS_WIN + #include +#endif #include #include "functions.h" - +#include "loader/downloadable.h" batchWindow::batchWindow(QSettings *settings, QWidget *parent) @@ -185,7 +187,7 @@ void batchWindow::addImage(const QString &url, int batch, double size) ui->tableWidget->setItem(m_items, 0, id); ui->tableWidget->setItem(m_items, 1, new QTableWidgetItem(QString::number(batch))); ui->tableWidget->setItem(m_items, 2, new QTableWidgetItem(url)); - QString unit = getUnit(&size); + const QString unit = getUnit(&size); ui->tableWidget->setItem(m_items, 3, new QTableWidgetItem(size > 0 ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0) + " " + unit : QString())); ui->tableWidget->setItem(m_items, 4, new QTableWidgetItem()); ui->tableWidget->setItem(m_items, 5, new QTableWidgetItem(QStringLiteral("0 %"))); @@ -213,14 +215,14 @@ void batchWindow::updateColumns() } int batchWindow::indexOf(const QString &url) { - int i = m_urls.indexOf(url); + const int i = m_urls.indexOf(url); if (i < 0 || ui->tableWidget->item(i, 1) == Q_NULLPTR) return -1; return i; } int batchWindow::batch(const QString &url) { - int i = indexOf(url); + const int i = indexOf(url); if (i == -1) return -1; return ui->tableWidget->item(i, 1)->text().toInt(); @@ -233,7 +235,7 @@ void batchWindow::loadingImage(const QString &url) if (m_speeds.size() > m_maxSpeeds) m_maxSpeeds = m_speeds.size(); - int i = indexOf(url); + const int i = indexOf(url); if (i != -1) { static QIcon downloadingIcon(":/images/status/downloading.png"); @@ -252,7 +254,7 @@ void batchWindow::scrollTo(int i) } void batchWindow::imageUrlChanged(const QString &before, const QString &after) { - int i = indexOf(before); + const int i = indexOf(before); if (i != -1) { m_urls[i] = after; @@ -264,14 +266,14 @@ void batchWindow::imageUrlChanged(const QString &before, const QString &after) } void batchWindow::statusImage(const QString &url, int percent) { - int i = indexOf(url); + const int i = indexOf(url); if (i != -1) ui->tableWidget->item(i, 5)->setText(QString::number(percent)+" %"); } void batchWindow::speedImage(const QString &url, double speed) { m_speeds[url] = static_cast(speed); - QString unit = getUnit(&speed)+"/s"; + const QString unit = getUnit(&speed) + "/s"; int i = indexOf(url); if (i != -1) @@ -284,8 +286,8 @@ void batchWindow::sizeImage(const QString &url, double size) int i = indexOf(url); if (i != -1) { - QString unit = getUnit(&size); - QString label = size > 0 + const QString unit = getUnit(&size); + const QString label = size > 0 ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0) + " "+unit : QString(); ui->tableWidget->item(i, 3)->setText(label); @@ -303,7 +305,7 @@ void batchWindow::loadedImage(const QString &url, Downloadable::SaveResult resul drawSpeed(); // Update table - int i = indexOf(url); + const int i = indexOf(url); if (i != -1) { scrollTo(i); @@ -348,25 +350,25 @@ void batchWindow::drawSpeed() { speed += sp.value(); } if (m_speeds.size() == m_maxSpeeds) { m_mean.append(qRound(speed)); } - QString unit = getUnit(&speed) + "/s"; + const QString unit = getUnit(&speed) + "/s"; double speedMean = 0; - int count = qMin(m_mean.count(), 60); + const int count = qMin(m_mean.count(), 60); if (count > 0) { for (int i = m_mean.count() - count; i < m_mean.count() - 1; i++) { speedMean += m_mean[i]; } speedMean = static_cast(speedMean/count); } - QString unitMean = getUnit(&speedMean)+"/s"; + const QString unitMean = getUnit(&speedMean) + "/s"; - int elapsed = m_start->elapsed(); - int remaining = m_images > 0 ? (elapsed * m_imagesCount) / m_images : 0; + const int elapsed = m_start->elapsed(); + const int remaining = m_images > 0 ? (elapsed * m_imagesCount) / m_images : 0; QTime tElapsed, tRemaining; tElapsed = tElapsed.addMSecs(elapsed); tRemaining = tRemaining.addMSecs(remaining); - QString fElapsed = elapsed > 3600000 ? tr("h 'h' m 'm' s 's'") : (elapsed > 60000 ? tr("m 'm' s 's'") : tr("s 's'")); - QString fRemaining = remaining > 3600000 ? tr("h 'h' m 'm' s 's'") : (remaining > 60000 ? tr("m 'm' s 's'") : tr("s 's'")); + const QString fElapsed = elapsed > 3600000 ? tr("h 'h' m 'm' s 's'") : (elapsed > 60000 ? tr("m 'm' s 's'") : tr("s 's'")); + const QString fRemaining = remaining > 3600000 ? tr("h 'h' m 'm' s 's'") : (remaining > 60000 ? tr("m 'm' s 's'") : tr("s 's'")); ui->labelSpeed->setText(QLocale::system().toString(speed, 'f', speed < 10 ? 2 : 0)+" "+unit); ui->labelSpeed->setToolTip(tr("Average speed: %1 %2

Elapsed time: %3
Remaining time: %4").arg(QLocale::system().toString(speedMean, 'f', speedMean < 10 ? 2 : 0), unitMean, tElapsed.toString(fElapsed), tRemaining.toString(fRemaining))); diff --git a/gui/src/batch/batchwindow.h b/gui/src/batch/batchwindow.h index dded63cce..ca2d7acec 100644 --- a/gui/src/batch/batchwindow.h +++ b/gui/src/batch/batchwindow.h @@ -2,7 +2,6 @@ #define BATCHWINDOW_H #include -#include #include #include #include "loader/downloadable.h" diff --git a/gui/src/helpers.h b/gui/src/helpers.h index 3146d7273..57ef227a8 100644 --- a/gui/src/helpers.h +++ b/gui/src/helpers.h @@ -2,7 +2,6 @@ #define HELPERS_H #include -#include #include diff --git a/gui/src/image-context-menu.h b/gui/src/image-context-menu.h index 931d5b1ea..910a5acbe 100644 --- a/gui/src/image-context-menu.h +++ b/gui/src/image-context-menu.h @@ -6,6 +6,7 @@ #include "reverse-search/reverse-search-engine.h" +class QSettings; class mainWindow; class ImageContextMenu : public QMenu diff --git a/gui/src/main/main.cpp b/gui/src/main/main.cpp index 59ca2f9c3..6dfcbd46a 100644 --- a/gui/src/main/main.cpp +++ b/gui/src/main/main.cpp @@ -25,7 +25,6 @@ #include -#include #include "downloader/downloader.h" #include "functions.h" #include "mainwindow.h" @@ -70,8 +69,8 @@ int main(int argc, char *argv[]) QStringList toCopy = QStringList() << "sites/" << "themes/" << "webservices/"; for (const QString &tgt : toCopy) { - QString from = savePath(tgt, true, false); - QString to = savePath(tgt, true, true); + const QString from = savePath(tgt, true, false); + const QString to = savePath(tgt, true, true); if (!QDir(to).exists() && QDir(from).exists()) copyRecursively(from, to); } @@ -81,24 +80,24 @@ int main(int argc, char *argv[]) parser.addVersionOption(); #if !defined(USE_CLI) - QCommandLineOption cliOption(QStringList() << "c" << "cli", "Disable the GUI."); + const QCommandLineOption cliOption(QStringList() << "c" << "cli", "Disable the GUI."); parser.addOption(cliOption); #endif - QCommandLineOption tagsOption(QStringList() << "t" << "tags", "Tags to search for.", "tags"); - QCommandLineOption sourceOption(QStringList() << "s" << "sources", "Source websites.", "sources"); - QCommandLineOption pageOption(QStringList() << "p" << "page", "Starting page.", "page", "1"); - QCommandLineOption limitOption(QStringList() << "m" << "max", "Maximum of returned images.", "count"); - QCommandLineOption perpageOption(QStringList() << "i" << "perpage", "Number of images per page.", "count", "20"); - QCommandLineOption pathOption(QStringList() << "l" << "location", "Location to save the results.", "path"); - QCommandLineOption filenameOption(QStringList() << "f" << "filename", "Filename to save the results.", "filename"); - QCommandLineOption userOption(QStringList() << "u" << "user", "Username to connect to the source.", "user"); - QCommandLineOption passwordOption(QStringList() << "w" << "password", "Password to connect to the source.", "password"); - QCommandLineOption blacklistOption(QStringList() << "b" << "blacklist", "Download blacklisted images."); - QCommandLineOption postfilteringOption(QStringList() << "r" << "postfilter", "Filter results.", "filter"); - QCommandLineOption noDuplicatesOption(QStringList() << "n" << "no-duplicates", "Remove duplicates from results."); - QCommandLineOption verboseOption(QStringList() << "d" << "debug", "Show debug messages."); - QCommandLineOption tagsMinOption(QStringList() << "tm" << "tags-min", "Minimum count for tags to be returned.", "count", "0"); - QCommandLineOption tagsFormatOption(QStringList() << "tf" << "tags-format", "Format for returning tags.", "format", "%tag\t%count\t%type"); + const QCommandLineOption tagsOption(QStringList() << "t" << "tags", "Tags to search for.", "tags"); + const QCommandLineOption sourceOption(QStringList() << "s" << "sources", "Source websites.", "sources"); + const QCommandLineOption pageOption(QStringList() << "p" << "page", "Starting page.", "page", "1"); + const QCommandLineOption limitOption(QStringList() << "m" << "max", "Maximum of returned images.", "count"); + const QCommandLineOption perpageOption(QStringList() << "i" << "perpage", "Number of images per page.", "count", "20"); + const QCommandLineOption pathOption(QStringList() << "l" << "location", "Location to save the results.", "path"); + const QCommandLineOption filenameOption(QStringList() << "f" << "filename", "Filename to save the results.", "filename"); + const QCommandLineOption userOption(QStringList() << "u" << "user", "Username to connect to the source.", "user"); + const QCommandLineOption passwordOption(QStringList() << "w" << "password", "Password to connect to the source.", "password"); + const QCommandLineOption blacklistOption(QStringList() << "b" << "blacklist", "Download blacklisted images."); + const QCommandLineOption postfilteringOption(QStringList() << "r" << "postfilter", "Filter results.", "filter"); + const QCommandLineOption noDuplicatesOption(QStringList() << "n" << "no-duplicates", "Remove duplicates from results."); + const QCommandLineOption verboseOption(QStringList() << "d" << "debug", "Show debug messages."); + const QCommandLineOption tagsMinOption(QStringList() << "tm" << "tags-min", "Minimum count for tags to be returned.", "count", "0"); + const QCommandLineOption tagsFormatOption(QStringList() << "tf" << "tags-format", "Format for returning tags.", "format", "%tag\t%count\t%type"); parser.addOption(tagsOption); parser.addOption(sourceOption); parser.addOption(pageOption); @@ -114,11 +113,11 @@ int main(int argc, char *argv[]) parser.addOption(tagsFormatOption); parser.addOption(noDuplicatesOption); parser.addOption(verboseOption); - QCommandLineOption returnCountOption(QStringList() << "rc" << "return-count", "Return total image count."); - QCommandLineOption returnTagsOption(QStringList() << "rt" << "return-tags", "Return tags for a search."); - QCommandLineOption returnPureTagsOption(QStringList() << "rp" << "return-pure-tags", "Return tags."); - QCommandLineOption returnImagesOption(QStringList() << "ri" << "return-images", "Return images url."); - QCommandLineOption downloadOption(QStringList() << "download", "Download found images."); + const QCommandLineOption returnCountOption(QStringList() << "rc" << "return-count", "Return total image count."); + const QCommandLineOption returnTagsOption(QStringList() << "rt" << "return-tags", "Return tags for a search."); + const QCommandLineOption returnPureTagsOption(QStringList() << "rp" << "return-pure-tags", "Return tags."); + const QCommandLineOption returnImagesOption(QStringList() << "ri" << "return-images", "Return images url."); + const QCommandLineOption downloadOption(QStringList() << "download", "Download found images."); parser.addOption(returnCountOption); parser.addOption(returnTagsOption); parser.addOption(returnPureTagsOption); @@ -128,12 +127,12 @@ int main(int argc, char *argv[]) parser.process(app); #if !defined(USE_CLI) - bool gui = !parser.isSet(cliOption); + const bool gui = !parser.isSet(cliOption); #else - bool gui = false; + const bool gui = false; #endif - bool verbose = parser.isSet(verboseOption); + const bool verbose = parser.isSet(verboseOption); #if !defined(QT_DEBUG) Logger::setupMessageOutput(gui || verbose); #endif @@ -193,7 +192,7 @@ int main(int argc, char *argv[]) { // Check for updates QSettings *settings = profile->getSettings(); - int cfuInterval = settings->value("check_for_updates", 24*60*60).toInt(); + const int cfuInterval = settings->value("check_for_updates", 24*60*60).toInt(); QDateTime lastCfu = settings->value("last_check_for_updates", QDateTime()).toDateTime(); if (cfuInterval >= 0 && (!lastCfu.isValid() || lastCfu.addSecs(cfuInterval) <= QDateTime::currentDateTime())) { diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 71e572959..bd28a9a66 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -51,7 +51,6 @@ #include "tags/tag-stylist.h" #include "theme-loader.h" #include "ui/QAffiche.h" -#include "updater/update-dialog.h" #include "utils/blacklist-fix/blacklist-fix-1.h" #include "utils/empty-dirs-fix/empty-dirs-fix-1.h" #include "utils/md5-fix/md5-fix.h" @@ -1518,7 +1517,7 @@ void mainWindow::getAllImages() m_progressDialog->setCount(m_getAllRemaining.count()); for (const BatchDownloadImage &download : qAsConst(m_getAllRemaining)) { - int siteId = download.siteId(m_groupBatchs); + const int siteId = download.siteId(m_groupBatchs); QSharedPointer img = download.image; // We add the image diff --git a/gui/src/mainwindow.h b/gui/src/mainwindow.h index 949ac11c8..965eab992 100644 --- a/gui/src/mainwindow.h +++ b/gui/src/mainwindow.h @@ -3,14 +3,10 @@ #define CLOSED_TAB_HISTORY_MAX 20 -#include #include #include -#include #include #include -#include -#include #include #include #include diff --git a/gui/src/settings/conditionwindow.cpp b/gui/src/settings/conditionwindow.cpp index d324c6fa1..b2c7b7bd3 100644 --- a/gui/src/settings/conditionwindow.cpp +++ b/gui/src/settings/conditionwindow.cpp @@ -2,7 +2,8 @@ #include "ui_conditionwindow.h" -conditionWindow::conditionWindow(QWidget *parent) : QDialog(parent), ui(new Ui::conditionWindow) +conditionWindow::conditionWindow(QWidget *parent) + : QDialog(parent), ui(new Ui::conditionWindow) { ui->setupUi(this); } diff --git a/gui/src/settings/filenamewindow.cpp b/gui/src/settings/filenamewindow.cpp index 551481cc6..d17963437 100644 --- a/gui/src/settings/filenamewindow.cpp +++ b/gui/src/settings/filenamewindow.cpp @@ -1,7 +1,7 @@ #include "settings/filenamewindow.h" #include +#include #include -#include #include #include "models/filename.h" #include "models/image.h" @@ -62,7 +62,7 @@ void FilenameWindow::on_lineClassic_textChanged(QString text) { QString cap = date.cap(1); QString format; - for (QChar c : cap) + for (const QChar &c : cap) { if (c == 'Y') { format += "' + date.getFullYear() + '"; } @@ -140,7 +140,7 @@ void FilenameWindow::done(int r) if (det.isEmpty()) { - int reply = QMessageBox::question(this, tr("Warning"), tr("You script contains error, are you sure you want to save it?"), QMessageBox::Yes | QMessageBox::Cancel); + const int reply = QMessageBox::question(this, tr("Warning"), tr("You script contains error, are you sure you want to save it?"), QMessageBox::Yes | QMessageBox::Cancel); if (reply == QMessageBox::Cancel) { return; diff --git a/gui/src/settings/filenamewindow.h b/gui/src/settings/filenamewindow.h index 0ee812857..fbd05d509 100644 --- a/gui/src/settings/filenamewindow.h +++ b/gui/src/settings/filenamewindow.h @@ -3,7 +3,6 @@ #include #include -#include #if defined(USE_QSCINTILLA) #include diff --git a/gui/src/settings/log-window.h b/gui/src/settings/log-window.h index 33e2cb9cd..16b30b269 100644 --- a/gui/src/settings/log-window.h +++ b/gui/src/settings/log-window.h @@ -2,7 +2,6 @@ #define LOG_WINDOW_H #include -#include #include diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index 0c405e430..08342d447 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -1,10 +1,8 @@ #include "settings/optionswindow.h" #include -#include #include #include #include -#include #include #include #include @@ -157,7 +155,7 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) ui->lineArtistsKeepNThenAdd->setText(settings->value("artist_multiple_keepNThenAdd_add", " (+ %count%)").toString()); ui->lineArtistsSeparator->setText(settings->value("artist_sep", "+").toString()); ui->lineArtistsReplaceAll->setText(settings->value("artist_value", "multiple artists").toString()); - QString artistMultiple = settings->value("artist_multiple", "replaceAll").toString(); + const QString artistMultiple = settings->value("artist_multiple", "replaceAll").toString(); if (artistMultiple == "keepAll") { ui->radioArtistsKeepAll->setChecked(true); } else if (artistMultiple == "keepN") { ui->radioArtistsKeepN->setChecked(true); } else if (artistMultiple == "keepNThenAdd") { ui->radioArtistsKeepNThenAdd->setChecked(true); } @@ -172,7 +170,7 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) ui->lineCopyrightsKeepNThenAdd->setText(settings->value("copyright_multiple_keepNThenAdd_add", " (+ %count%)").toString()); ui->lineCopyrightsSeparator->setText(settings->value("copyright_sep", "+").toString()); ui->lineCopyrightsReplaceAll->setText(settings->value("copyright_value", "crossover").toString()); - QString copyrightMultiple = settings->value("copyright_multiple", "replaceAll").toString(); + const QString copyrightMultiple = settings->value("copyright_multiple", "replaceAll").toString(); if (copyrightMultiple == "keepAll") { ui->radioCopyrightsKeepAll->setChecked(true); } else if (copyrightMultiple == "keepN") { ui->radioCopyrightsKeepN->setChecked(true); } else if (copyrightMultiple == "keepNThenAdd") { ui->radioCopyrightsKeepNThenAdd->setChecked(true); } @@ -186,7 +184,7 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) ui->lineCharactersKeepNThenAdd->setText(settings->value("character_multiple_keepNThenAdd_add", " (+ %count%)").toString()); ui->lineCharactersSeparator->setText(settings->value("character_sep", "+").toString()); ui->lineCharactersReplaceAll->setText(settings->value("character_value", "group").toString()); - QString characterMultiple = settings->value("character_multiple", "replaceAll").toString(); + const QString characterMultiple = settings->value("character_multiple", "replaceAll").toString(); if (characterMultiple == "keepAll") { ui->radioCharactersKeepAll->setChecked(true); } else if (characterMultiple == "keepN") { ui->radioCharactersKeepN->setChecked(true); } else if (characterMultiple == "keepNThenAdd") { ui->radioCharactersKeepNThenAdd->setChecked(true); } @@ -200,7 +198,7 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) ui->lineSpeciesKeepNThenAdd->setText(settings->value("species_multiple_keepNThenAdd_add", " (+ %count%)").toString()); ui->lineSpeciesSeparator->setText(settings->value("species_sep", "+").toString()); ui->lineSpeciesReplaceAll->setText(settings->value("species_value", "multiple").toString()); - QString speciesMultiple = settings->value("species_multiple", "keepAll").toString(); + const QString speciesMultiple = settings->value("species_multiple", "keepAll").toString(); if (speciesMultiple == "keepAll") { ui->radioSpeciesKeepAll->setChecked(true); } else if (speciesMultiple == "keepN") { ui->radioSpeciesKeepN->setChecked(true); } else if (speciesMultiple == "keepNThenAdd") { ui->radioSpeciesKeepNThenAdd->setChecked(true); } @@ -214,7 +212,7 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) ui->lineMetasKeepNThenAdd->setText(settings->value("meta_multiple_keepNThenAdd_add", " (+ %count%)").toString()); ui->lineMetasSeparator->setText(settings->value("meta_sep", "+").toString()); ui->lineMetasReplaceAll->setText(settings->value("meta_value", "multiple").toString()); - QString metaMultiple = settings->value("meta_multiple", "keepAll").toString(); + const QString metaMultiple = settings->value("meta_multiple", "keepAll").toString(); if (metaMultiple == "keepAll") { ui->radioMetasKeepAll->setChecked(true); } else if (metaMultiple == "keepN") { ui->radioMetasKeepN->setChecked(true); } else if (metaMultiple == "keepNThenAdd") { ui->radioMetasKeepNThenAdd->setChecked(true); } @@ -631,7 +629,7 @@ void optionsWindow::setWebService(ReverseSearchEngine rse, const QByteArray &fav void optionsWindow::moveUpWebService(int id) { - int i = m_webServicesIds[id]; + const int i = m_webServicesIds[id]; if (i == 0) return; @@ -640,7 +638,7 @@ void optionsWindow::moveUpWebService(int id) void optionsWindow::moveDownWebService(int id) { - int i = m_webServicesIds[id]; + const int i = m_webServicesIds[id]; if (i == m_webServicesIds.count() - 1) return; @@ -651,7 +649,7 @@ int sortByOrder(const ReverseSearchEngine &a, const ReverseSearchEngine &b) { return a.order() < b.order(); } void optionsWindow::swapWebServices(int a, int b) { - int pos = m_webServices[b].order(); + const int pos = m_webServices[b].order(); m_webServices[b].setOrder(m_webServices[a].order()); m_webServices[a].setOrder(pos); @@ -667,7 +665,7 @@ void optionsWindow::swapWebServices(int a, int b) void optionsWindow::setColor(QLineEdit *lineEdit, bool button) { - QString text = lineEdit->text(); + const QString text = lineEdit->text(); QColor color = button ? QColorDialog::getColor(QColor(text), this, tr("Choose a color")) : QColor(text); @@ -858,7 +856,7 @@ void optionsWindow::save() QStringList types = QStringList() << "text" << "icon" << "both" << "hide"; settings->setValue("Sources/Types", types.at(ui->comboSources->currentIndex())); - int i = ui->comboSourcesLetters->currentIndex(); + const int i = ui->comboSourcesLetters->currentIndex(); settings->setValue("Sources/Letters", (i == 0 ? ui->spinSourcesLetters->value() : -i)); settings->setValue("preloadAllTabs", ui->checkPreloadAllTabs->isChecked()); @@ -1144,7 +1142,7 @@ void optionsWindow::save() if (settings->value("Proxy/use", false).toBool()) { - bool useSystem = settings->value("Proxy/useSystem", false).toBool(); + const bool useSystem = settings->value("Proxy/useSystem", false).toBool(); QNetworkProxyFactory::setUseSystemConfiguration(useSystem); if (!useSystem) diff --git a/gui/src/settings/web-service-window.cpp b/gui/src/settings/web-service-window.cpp index 0e56d4f6e..cd311480b 100644 --- a/gui/src/settings/web-service-window.cpp +++ b/gui/src/settings/web-service-window.cpp @@ -31,7 +31,7 @@ WebServiceWindow::~WebServiceWindow() void WebServiceWindow::getFavicon() { QUrl url(ui->lineUrl->text()); - QString favicon = url.scheme() + "://" + url.authority() + "/favicon.ico"; + const QString favicon = url.scheme() + "://" + url.authority() + "/favicon.ico"; m_faviconReply = m_networkAccessManager->get(QNetworkRequest(QUrl(favicon))); connect(m_faviconReply, &QNetworkReply::finished, this, &WebServiceWindow::faviconReceived); @@ -69,8 +69,8 @@ void WebServiceWindow::save() } // Emit the success signal - QString name = ui->lineName->text(); - QString url = ui->lineUrl->text(); + const QString name = ui->lineName->text(); + const QString url = ui->lineUrl->text(); emit validated(ReverseSearchEngine(id, QString(), name, url, order), faviconData); deleteLater(); diff --git a/gui/src/sources/sitewindow.cpp b/gui/src/sources/sitewindow.cpp index 5b77a2a8f..332275313 100644 --- a/gui/src/sources/sitewindow.cpp +++ b/gui/src/sources/sitewindow.cpp @@ -1,5 +1,4 @@ #include "sources/sitewindow.h" -#include #include #include #include "functions.h" diff --git a/gui/src/sources/sitewindow.h b/gui/src/sources/sitewindow.h index 974dce13f..0738e3663 100644 --- a/gui/src/sources/sitewindow.h +++ b/gui/src/sources/sitewindow.h @@ -2,7 +2,6 @@ #define SITE_WINDOW_H #include -#include namespace Ui diff --git a/gui/src/sources/sourcessettingswindow.cpp b/gui/src/sources/sourcessettingswindow.cpp index 32138a86f..3be0306d0 100644 --- a/gui/src/sources/sourcessettingswindow.cpp +++ b/gui/src/sources/sourcessettingswindow.cpp @@ -1,6 +1,5 @@ #include "sources/sourcessettingswindow.h" #include -#include #include #include #include @@ -52,12 +51,12 @@ SourcesSettingsWindow::SourcesSettingsWindow(Profile *profile, Site *site, QWidg // Source order ui->checkSourcesDefault->setChecked(site->setting("sources/usedefault", true).toBool()); - QStringList defs = QStringList() << "xml" << "json" << "regex" << "rss"; + static const QStringList defs = QStringList() << "xml" << "json" << "regex" << "rss"; QStringList sources = QStringList() << ""; QStringList opts = QStringList() << ""; for (Api *api : site->getApis()) { - QString name = api->getName().toLower(); + const QString name = api->getName().toLower(); sources.append(name == "html" ? "regex" : name); opts.append(api->getName()); } @@ -71,9 +70,9 @@ SourcesSettingsWindow::SourcesSettingsWindow(Profile *profile, Site *site, QWidg ui->lineAuthPassword->setText(site->setting("auth/password", "").toString()); // Login - QStringList types = QStringList() << "url" << "get" << "post" << "oauth1" << "oauth2"; - QString defaultType = site->setting("login/parameter", true).toBool() ? "url" : site->setting("login/method", "post").toString(); - QString type = site->setting("login/type", defaultType).toString(); + static const QStringList types = QStringList() << "url" << "get" << "post" << "oauth1" << "oauth2"; + const QString defaultType = site->setting("login/parameter", true).toBool() ? "url" : site->setting("login/method", "post").toString(); + const QString type = site->setting("login/type", defaultType).toString(); ui->comboLoginType->setCurrentIndex(types.indexOf(type)); ui->lineLoginGetUrl->setText(site->setting("login/get/url", type != "get" ? "" : site->setting("login/url", "").toString()).toString()); ui->lineLoginGetPseudo->setText(site->setting("login/get/pseudo", type != "get" ? "" : site->setting("login/pseudo", "").toString()).toString()); @@ -160,7 +159,7 @@ void SourcesSettingsWindow::on_buttonAuthHash_clicked() void SourcesSettingsWindow::deleteSite() { - int reponse = QMessageBox::question(this, tr("Delete a site"), tr("Are you sure you want to delete the site %1?").arg(m_site->name()), QMessageBox::Yes | QMessageBox::No); + const int reponse = QMessageBox::question(this, tr("Delete a site"), tr("Are you sure you want to delete the site %1?").arg(m_site->name()), QMessageBox::Yes | QMessageBox::No); if (reponse == QMessageBox::Yes) { QFile f(m_site->getSource()->getPath() + "/sites.txt"); @@ -208,7 +207,7 @@ void SourcesSettingsWindow::loginTested(Site*, Site::LoginResult result) void SourcesSettingsWindow::setLoginStatus(const QString &msg) { - QString italic = QStringLiteral("%1").arg(msg); + const QString italic = QStringLiteral("%1").arg(msg); ui->labelTestCredentials->setText(italic); ui->labelTestLogin->setText(italic); } @@ -238,7 +237,7 @@ void SourcesSettingsWindow::save() QStringList sources = QStringList() << ""; for (Api *api : m_site->getApis()) { - QString name = api->getName().toLower(); + const QString name = api->getName().toLower(); sources.append(name == "html" ? "regex" : name); } QStringList chosen = QStringList() diff --git a/gui/src/sources/sourcessettingswindow.h b/gui/src/sources/sourcessettingswindow.h index 9dee38e16..99ac79f20 100644 --- a/gui/src/sources/sourcessettingswindow.h +++ b/gui/src/sources/sourcessettingswindow.h @@ -2,8 +2,6 @@ #define SOURCESSETTINGSWINDOW_H #include -#include -#include #include "models/site.h" diff --git a/gui/src/sources/sourceswindow.cpp b/gui/src/sources/sourceswindow.cpp index 5ba5dd139..831fe505b 100644 --- a/gui/src/sources/sourceswindow.cpp +++ b/gui/src/sources/sourceswindow.cpp @@ -331,7 +331,7 @@ void sourcesWindow::checkForSourceIssuesReceived() for (const QString &issue : issues) { - int index = issue.indexOf(':'); + const int index = issue.indexOf(':'); if (issue.isEmpty() || index < 0) return; @@ -353,12 +353,12 @@ QMap sourcesWindow::loadPresets(QSettings *settings) const { QMap ret; - int size = settings->beginReadArray("SourcePresets"); + const int size = settings->beginReadArray("SourcePresets"); for (int i = 0; i < size; ++i) { settings->setArrayIndex(i); - QString name = settings->value("name").toString(); - QStringList sources = settings->value("sources").toStringList(); + const QString name = settings->value("name").toString(); + const QStringList sources = settings->value("sources").toStringList(); ret.insert(name, sources); } settings->endArray(); diff --git a/gui/src/tabs/favorites-tab.cpp b/gui/src/tabs/favorites-tab.cpp index 8af492b22..2f97bda55 100644 --- a/gui/src/tabs/favorites-tab.cpp +++ b/gui/src/tabs/favorites-tab.cpp @@ -26,14 +26,14 @@ favoritesTab::favoritesTab(Profile *profile, mainWindow *parent) ui->setupUi(this); // Promote favorites layout into fixed-size grid layout - int hSpace = m_settings->value("Margins/horizontal", 6).toInt(); - int vSpace = m_settings->value("Margins/vertical", 6).toInt(); + const int hSpace = m_settings->value("Margins/horizontal", 6).toInt(); + const int vSpace = m_settings->value("Margins/vertical", 6).toInt(); m_favoritesLayout = new FixedSizeGridLayout(hSpace, vSpace); - bool fixedWidthLayout = m_settings->value("resultsFixedWidthLayout", false).toBool(); + const bool fixedWidthLayout = m_settings->value("resultsFixedWidthLayout", false).toBool(); if (fixedWidthLayout) { - int borderSize = m_settings->value("borders", 3).toInt(); - qreal upscale = m_settings->value("thumbnailUpscale", 1.0).toDouble(); + const int borderSize = m_settings->value("borders", 3).toInt(); + const qreal upscale = m_settings->value("thumbnailUpscale", 1.0).toDouble(); m_favoritesLayout->setFixedWidth(qFloor(FAVORITES_THUMB_SIZE * upscale + borderSize * 2)); } QWidget *layoutWidget = new QWidget; @@ -111,9 +111,9 @@ void favoritesTab::closeEvent(QCloseEvent *e) void favoritesTab::updateFavorites() { - QStringList assoc = QStringList() << "name" << "note" << "lastviewed"; - QString order = assoc[ui->comboOrder->currentIndex()]; - bool reverse = (ui->comboAsc->currentIndex() == 1); + static const QStringList assoc = QStringList() << "name" << "note" << "lastviewed"; + const QString &order = assoc[ui->comboOrder->currentIndex()]; + const bool reverse = (ui->comboAsc->currentIndex() == 1); if (order == "note") { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByNote); } @@ -124,17 +124,17 @@ void favoritesTab::updateFavorites() if (reverse) { m_favorites = reversed(m_favorites); } - QString format = tr("MM/dd/yyyy"); + const QString format = tr("MM/dd/yyyy"); clearLayout(m_favoritesLayout); QString display = m_settings->value("favorites_display", "ind").toString(); - qreal upscale = m_settings->value("thumbnailUpscale", 1.0).toDouble(); - int borderSize = m_settings->value("borders", 3).toInt(); - int dim = qFloor(FAVORITES_THUMB_SIZE * upscale + borderSize * 2); + const qreal upscale = m_settings->value("thumbnailUpscale", 1.0).toDouble(); + const int borderSize = m_settings->value("borders", 3).toInt(); + const int dim = qFloor(FAVORITES_THUMB_SIZE * upscale + borderSize * 2); for (Favorite &fav : m_favorites) { - QString xt = tr("Name: %1
Note: %2 %
Last view: %3").arg(fav.getName(), QString::number(fav.getNote()), fav.getLastViewed().toString(format)); + const QString xt = tr("Name: %1
Note: %2 %
Last view: %3").arg(fav.getName(), QString::number(fav.getNote()), fav.getLastViewed().toString(format)); QWidget *w = new QWidget(ui->scrollAreaWidgetContents); auto *l = new QVBoxLayout; l->setMargin(0); @@ -246,13 +246,13 @@ void favoritesTab::getPage() if (m_checkboxes.at(i)->isChecked()) { actuals.append(keys.at(i)); } } - bool unloaded = m_settings->value("getunloadedpages", false).toBool(); + const bool unloaded = m_settings->value("getunloadedpages", false).toBool(); for (int i = 0; i < actuals.count(); i++) { - auto page = m_pages[actuals[i]].first(); - QString search = m_currentTags+" "+m_settings->value("add").toString().toLower().trimmed(); - int perpage = unloaded ? ui->spinImagesPerPage->value() : page->images().count(); - QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); + const auto &page = m_pages[actuals[i]].first(); + const QString search = m_currentTags+" "+m_settings->value("add").toString().toLower().trimmed(); + const int perpage = unloaded ? ui->spinImagesPerPage->value() : page->images().count(); + const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); emit batchAddGroup(DownloadQueryGroup(m_settings, search, ui->spinPage->value(), perpage, perpage, postFiltering, m_sites.value(actuals.at(i)))); } @@ -268,18 +268,18 @@ void favoritesTab::getAll() for (const QString &actual : actuals) { - QSharedPointer page = m_pages[actual].first(); + const auto &page = m_pages[actual].first(); - int highLimit = page->highLimit(); - int currentCount = page->images().count(); - int imageCount = page->imagesCount(); - int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); - int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; + const int highLimit = page->highLimit(); + const int currentCount = page->images().count(); + const int imageCount = page->imagesCount(); + const int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); + const int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; if ((perPage == 0 && total == 0) || (currentCount == 0 && imageCount <= 0)) continue; - QString search = m_currentTags + " " + m_settings->value("add").toString().toLower().trimmed(); - QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); + const QString search = m_currentTags + " " + m_settings->value("add").toString().toLower().trimmed(); + const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); Site *site = m_sites.value(actual); emit batchAddGroup(DownloadQueryGroup(m_settings, search, 1, perPage, total, postFiltering, site)); @@ -295,7 +295,7 @@ QString favoritesTab::tags() const void favoritesTab::loadFavorite(const QString &name) { - int index = name.isEmpty() ? m_currentFav : m_favorites.indexOf(Favorite(name)); + const int index = name.isEmpty() ? m_currentFav : m_favorites.indexOf(Favorite(name)); if (index < 0) return; @@ -328,7 +328,7 @@ void favoritesTab::viewed() { if (m_currentTags.isEmpty()) { - int reponse = QMessageBox::question(this, tr("Mark as viewed"), tr("Are you sure you want to mark all your favorites as viewed?"), QMessageBox::Yes | QMessageBox::No); + const int reponse = QMessageBox::question(this, tr("Mark as viewed"), tr("Are you sure you want to mark all your favorites as viewed?"), QMessageBox::Yes | QMessageBox::No); if (reponse == QMessageBox::Yes) { for (const Favorite &fav : qAsConst(m_favorites)) @@ -344,7 +344,7 @@ void favoritesTab::setFavoriteViewed(const QString &tag) { log(QStringLiteral("Marking \"%1\" as viewed...").arg(tag)); - int index = tag.isEmpty() ? m_currentFav : m_favorites.indexOf(Favorite(tag)); + const int index = tag.isEmpty() ? m_currentFav : m_favorites.indexOf(Favorite(tag)); if (index < 0) return; @@ -371,11 +371,11 @@ void favoritesTab::favoritesBack() } void favoritesTab::favoriteProperties(const QString &name) { - int index = name.isEmpty() ? m_currentFav : m_favorites.indexOf(Favorite(name)); + const int index = name.isEmpty() ? m_currentFav : m_favorites.indexOf(Favorite(name)); if (index < 0) return; - Favorite fav = m_favorites[index]; + const Favorite fav = m_favorites[index]; favoriteWindow *fwin = new favoriteWindow(m_profile, fav, this); fwin->show(); } diff --git a/gui/src/tabs/favorites-tab.h b/gui/src/tabs/favorites-tab.h index 1cc5858d6..d79d18e81 100644 --- a/gui/src/tabs/favorites-tab.h +++ b/gui/src/tabs/favorites-tab.h @@ -1,8 +1,6 @@ #ifndef FAVORITES_TAB_H #define FAVORITES_TAB_H -#include -#include #include "tabs/search-tab.h" diff --git a/gui/src/tabs/pool-tab.cpp b/gui/src/tabs/pool-tab.cpp index 178f3a5e2..7e8a67a86 100644 --- a/gui/src/tabs/pool-tab.cpp +++ b/gui/src/tabs/pool-tab.cpp @@ -1,8 +1,8 @@ #include "tabs/pool-tab.h" +#include #include #include #include "downloader/download-query-group.h" -#include "helpers.h" #include "mainwindow.h" #include "models/page.h" #include "models/site.h" @@ -139,30 +139,30 @@ bool poolTab::read(const QJsonObject &json, bool preload) void poolTab::getPage() { - auto page = m_pages[ui->comboSites->currentText()].first(); + const auto &page = m_pages[ui->comboSites->currentText()].first(); - bool unloaded = m_settings->value("getunloadedpages", false).toBool(); - int perPage = unloaded ? ui->spinImagesPerPage->value() : page->images().count(); - QString tags = "pool:"+QString::number(ui->spinPool->value())+" "+m_search->toPlainText()+" "+m_settings->value("add").toString().trimmed(); - QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); + const bool unloaded = m_settings->value("getunloadedpages", false).toBool(); + const int perPage = unloaded ? ui->spinImagesPerPage->value() : page->images().count(); + const QString tags = "pool:"+QString::number(ui->spinPool->value())+" "+m_search->toPlainText()+" "+m_settings->value("add").toString().trimmed(); + const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); Site *site = m_sites.value(ui->comboSites->currentText()); emit batchAddGroup(DownloadQueryGroup(m_settings, tags, ui->spinPage->value(), perPage, perPage, postFiltering, site)); } void poolTab::getAll() { - QSharedPointer page = m_pages[ui->comboSites->currentText()].first(); + const auto &page = m_pages[ui->comboSites->currentText()].first(); - int highLimit = page->highLimit(); - int currentCount = page->images().count(); - int imageCount = page->imagesCount(); - int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); - int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; + const int highLimit = page->highLimit(); + const int currentCount = page->images().count(); + const int imageCount = page->imagesCount(); + const int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); + const int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; if ((perPage == 0 && total == 0) || (currentCount == 0 && imageCount <= 0)) return; - QString search = "pool:"+QString::number(ui->spinPool->value())+" "+m_search->toPlainText()+" "+m_settings->value("add").toString().trimmed(); - QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); + const QString search = "pool:"+QString::number(ui->spinPool->value())+" "+m_search->toPlainText()+" "+m_settings->value("add").toString().trimmed(); + const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); Site *site = m_sites.value(ui->comboSites->currentText()); emit batchAddGroup(DownloadQueryGroup(m_settings, search, 1, perPage, total, postFiltering, site)); @@ -183,14 +183,14 @@ void poolTab::setPool(int id, const QString &site) { activateWindow(); ui->spinPool->setValue(id); - int index = ui->comboSites->findText(site); + const int index = ui->comboSites->findText(site); if (index != -1) { ui->comboSites->setCurrentIndex(index); } load(); } void poolTab::setSite(const QString &site) { - int index = ui->comboSites->findText(site); + const int index = ui->comboSites->findText(site); if (index != -1) { ui->comboSites->setCurrentIndex(index); } } diff --git a/gui/src/tabs/pool-tab.h b/gui/src/tabs/pool-tab.h index 588c9e4da..e3b6669fc 100644 --- a/gui/src/tabs/pool-tab.h +++ b/gui/src/tabs/pool-tab.h @@ -1,10 +1,7 @@ #ifndef POOL_TAB_H #define POOL_TAB_H -#include #include -#include -#include #include "tabs/search-tab.h" diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index fcc1e3e07..b03d086b7 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -1,10 +1,13 @@ #include "tabs/search-tab.h" +#include #include #include #include #include #include +#include #include "downloader/download-query-image.h" +#include "downloader/image-downloader.h" #include "functions.h" #include "helpers.h" #include "image-context-menu.h" @@ -15,7 +18,7 @@ #include "models/page.h" #include "models/post-filter.h" #include "models/profile.h" -#include "reverse-search/reverse-search-loader.h" +#include "models/site.h" #include "sources/sourceswindow.h" #include "ui/fixed-size-grid-layout.h" #include "ui/QBouton.h" @@ -48,7 +51,7 @@ searchTab::searchTab(Profile *profile, mainWindow *parent) for (auto it = m_sites.begin(); it != m_sites.end(); ++it) { Site *site = it.value(); - QStringList modifiers = site->getApis().first()->modifiers(); + const QStringList modifiers = site->getApis().first()->modifiers(); m_completion.append(modifiers); } @@ -62,7 +65,7 @@ void searchTab::init() { m_endlessLoadingEnabled = true; m_endlessLoadOffset = 0; - auto infinite = m_settings->value("infiniteScroll", "disabled"); + const QString infinite = m_settings->value("infiniteScroll", "disabled").toString(); // Always hide scroll button before results are loaded if (ui_buttonEndlessLoad != nullptr) @@ -140,7 +143,7 @@ void searchTab::setTagsFromPages(const QMap> // If we already have this tag in the list, we increase its count if (tagsGot.contains(tag.text())) { - int index = tagsGot.indexOf(tag.text()); + const int index = tagsGot.indexOf(tag.text()); tagList[index].setCount(tagList[index].count() + tag.count()); } else @@ -194,7 +197,7 @@ QStringList searchTab::reasonsToFail(Page* page, const QStringList &completion, if (abs(comp.length() - tag.length()) > lev) continue; - int d = levenshtein(tag, comp); + const int d = levenshtein(tag, comp); if (d < lev) { if (results[tag].isEmpty()) @@ -334,12 +337,12 @@ void searchTab::finishedLoading(Page* page) m_validImages.insert(page, validImages); // Remove already existing images for merged results - bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); - QList> imgs = merged ? mergeResults(page->page(), validImages) : validImages; + const bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); + const QList> imgs = merged ? mergeResults(page->page(), validImages) : validImages; m_images.append(imgs); - int maxPage = page->pagesCount(); + const int maxPage = page->pagesCount(); if (maxPage > m_pagemax || m_pagemax == -1) m_pagemax = maxPage; ui_buttonNextPage->setEnabled(m_pagemax > ui_spinPage->value() || page->imagesCount() == -1 || page->pagesCount() == -1 || (page->imagesCount() == 0 && page->images().count() > 0)); @@ -358,7 +361,7 @@ void searchTab::failedLoading(Page *page) if (m_stop) return; - bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); + const bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); addResultsPage(page, QList>(), merged); postLoading(page, page->images()); @@ -368,7 +371,7 @@ void searchTab::httpsRedirect(Page *page) { QSettings *settings = m_profile->getSettings(); - QString action = settings->value("ssl_autocorrect", "ask").toString(); + const QString action = settings->value("ssl_autocorrect", "ask").toString(); bool setSsl = action == "always"; if (action == "ask") @@ -406,8 +409,8 @@ void searchTab::postLoading(Page *page, const QList> &imgs { m_page++; - bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); - bool finished = m_page == m_pages.count() || (merged && ui_progressMergeResults != nullptr && ui_progressMergeResults->value() == ui_progressMergeResults->maximum()); + const bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); + const bool finished = m_page == m_pages.count() || (merged && ui_progressMergeResults != nullptr && ui_progressMergeResults->value() == ui_progressMergeResults->maximum()); if (merged) { @@ -444,8 +447,8 @@ void searchTab::postLoading(Page *page, const QList> &imgs bool allFinished = true; for (auto ps : qAsConst(m_pages)) { - int pagesCount = ps.first()->pagesCount(); - int imagesPerPage = ps.first()->imagesPerPage(); + const int pagesCount = ps.first()->pagesCount(); + const int imagesPerPage = ps.first()->imagesPerPage(); if (ps.last()->page() < pagesCount && ps.last()->pageImageCount() >= imagesPerPage) allFinished = false; } @@ -471,7 +474,7 @@ void searchTab::finishedLoadingTags(Page *page) m_parent->setWiki(m_wiki); } - int maxPage = page->pagesCount(); + const int maxPage = page->pagesCount(); if (maxPage > m_pagemax || m_pagemax == -1) m_pagemax = maxPage; ui_buttonNextPage->setEnabled(m_pagemax > ui_spinPage->value() || page->imagesCount() == -1 || page->pagesCount() == -1 || (page->imagesCount() == 0 && page->images().count() > 0)); @@ -570,7 +573,7 @@ void searchTab::finishedLoadingPreview() bool download = false; if (!detected.isEmpty()) { - int reponse = QMessageBox::question(this, "Grabber", tr("Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway?").arg(whitelisted.join(", "), detected.join(", ")), QMessageBox::Yes | QMessageBox::Open | QMessageBox::No); + const int reponse = QMessageBox::question(this, "Grabber", tr("Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway?").arg(whitelisted.join(", "), detected.join(", ")), QMessageBox::Yes | QMessageBox::Open | QMessageBox::No); if (reponse == QMessageBox::Yes) { download = true; } else if (reponse == QMessageBox::Open) @@ -587,7 +590,7 @@ void searchTab::finishedLoadingPreview() } } - bool merge = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked() && !m_images.empty(); + const bool merge = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked() && !m_images.empty(); addResultsImage(img, img->page(), merge); } @@ -618,7 +621,7 @@ QList> searchTab::mergeResults(int page, const QList> searchTab::mergeResults(int page, const QList &img : results) { QString md5 = img->md5(); - double proportion = getImageKnownTagProportion(img); + const double proportion = getImageKnownTagProportion(img); if (md5.isEmpty() || ((!pageMd5s.contains(md5) || proportion > pageMd5s[md5]) && !containsMergedMd5(page, md5))) { @@ -692,12 +695,12 @@ void searchTab::addResultsPage(Page *page, const QList> &i if (merged) return; - int pos = m_pages.keys().indexOf(page->website()); + const int pos = m_pages.keys().indexOf(page->website()); if (pos < 0) return; - int page_x = pos % ui_spinColumns->value(); - int page_y = (pos / ui_spinColumns->value()) * 2; + const int page_x = pos % ui_spinColumns->value(); + const int page_y = (pos / ui_spinColumns->value()) * 2; Site *site = page->site(); if (!m_siteLabels.contains(site)) @@ -723,14 +726,14 @@ void searchTab::setMergedLabelText(QLabel *txt, const QList first = ps.first(); - int imagesCount = first->imagesCount(); + const QSharedPointer first = ps.first(); + const int imagesCount = first->imagesCount(); if (imagesCount > 0) sumImages += first->imagesCount(); - for (QSharedPointer p : ps) + for (const QSharedPointer &p : ps) { - int pagesCount = p->pagesCount(); + const int pagesCount = p->pagesCount(); if (pagesCount > maxPage) maxPage = pagesCount; @@ -748,23 +751,23 @@ void searchTab::setMergedLabelText(QLabel *txt, const QListurl().toString().toHtmlEscaped()+"\">"+p->site()->name()+""; } } - QString page = firstPage != lastPage ? QStringLiteral("%1-%2").arg(firstPage).arg(lastPage) : QString::number(lastPage); + const QString page = firstPage != lastPage ? QStringLiteral("%1-%2").arg(firstPage).arg(lastPage) : QString::number(lastPage); txt->setText(QString(links + " - Page %1 of %2 (%3 of max %4)").arg(page).arg(maxPage).arg(imgs.count()).arg(sumImages)); } void searchTab::setPageLabelText(QLabel *txt, Page *page, const QList> &imgs, const QString &noResultsMessage) { - int pageCount = page->pagesCount(); - int imageCount = page->imagesCount(); + const int pageCount = page->pagesCount(); + const int imageCount = page->imagesCount(); int firstPage = imgs.count() > 0 ? page->page() : 0; int lastPage = imgs.count() > 0 ? page->page() : 0; int totalCount = 0; - for (QSharedPointer p : m_pages[page->website()]) + for (const QSharedPointer &p : m_pages[page->website()]) { if (p->images().count() == 0) continue; @@ -785,14 +788,14 @@ void searchTab::setPageLabelText(QLabel *txt, Page *page, const QListshow(); ui_labelMeant->setText(meant); } - QString msg = noResultsMessage == nullptr ? tr("No result") : noResultsMessage; + const QString msg = noResultsMessage == nullptr ? tr("No result") : noResultsMessage; txt->setText("url().toString().toHtmlEscaped()+"\">"+page->site()->name()+" - "+msg+(reasons.count() > 0 ? "
"+tr("Possible reasons: %1").arg(reasons.join(", ")) : QString())); } else { - QString pageCountStr = pageCount > 0 ? (page->pagesCount(false) == -1 ? "~" : QString()) + QString::number(pageCount) : "?"; - QString imageCountStr = imageCount > 0 ? (page->imagesCount(false) == -1 ? "~" : QString()) + QString::number(imageCount) : "?"; - QString pageLabel = firstPage != lastPage ? QString("%1-%2").arg(firstPage).arg(lastPage) : QString::number(lastPage); + const QString pageCountStr = pageCount > 0 ? (page->pagesCount(false) == -1 ? "~" : QString()) + QString::number(pageCount) : "?"; + const QString imageCountStr = imageCount > 0 ? (page->imagesCount(false) == -1 ? "~" : QString()) + QString::number(imageCount) : "?"; + const QString pageLabel = firstPage != lastPage ? QString("%1-%2").arg(firstPage).arg(lastPage) : QString::number(lastPage); txt->setText("url().toString().toHtmlEscaped()+"\">"+page->site()->name()+" - "+tr("Page %1 of %2 (%3 of %4)").arg(pageLabel, pageCountStr).arg(totalCount).arg(imageCountStr)); } @@ -818,13 +821,13 @@ void searchTab::setPageLabelText(QLabel *txt, Page *page, const QList img) { - QColor color = img->color(); + const QColor &color = img->color(); - bool resizeInsteadOfCropping = m_settings->value("resizeInsteadOfCropping", true).toBool(); - bool resultsScrollArea = m_settings->value("resultsScrollArea", true).toBool(); - bool fixedWidthLayout = m_settings->value("resultsFixedWidthLayout", false).toBool(); - int borderSize = m_settings->value("borders", 3).toInt(); - qreal upscale = m_settings->value("thumbnailUpscale", 1.0).toDouble(); + const bool resizeInsteadOfCropping = m_settings->value("resizeInsteadOfCropping", true).toBool(); + const bool resultsScrollArea = m_settings->value("resultsScrollArea", true).toBool(); + const bool fixedWidthLayout = m_settings->value("resultsFixedWidthLayout", false).toBool(); + const int borderSize = m_settings->value("borders", 3).toInt(); + const qreal upscale = m_settings->value("thumbnailUpscale", 1.0).toDouble(); QBouton *l = new QBouton(position, resizeInsteadOfCropping, resultsScrollArea, borderSize, color, this); l->setCheckable(true); @@ -842,7 +845,7 @@ QBouton *searchTab::createImageThumbnail(int position, QSharedPointer img if (fixedWidthLayout) { - int dim = qFloor(FIXED_IMAGE_WIDTH * upscale + borderSize * 2); + const int dim = qFloor(FIXED_IMAGE_WIDTH * upscale + borderSize * 2); l->setFixedSize(dim, dim); } @@ -855,13 +858,13 @@ QBouton *searchTab::createImageThumbnail(int position, QSharedPointer img QString getImageAlreadyExists(Image *img, Profile *profile) { QSettings *settings = profile->getSettings(); - QString path = settings->value("Save/path").toString().replace("\\", "/"); - QString fn = settings->value("Save/filename").toString(); + const QString path = settings->value("Save/path").toString().replace("\\", "/"); + const QString fn = settings->value("Save/filename").toString(); if (!Filename(fn).needExactTags(img->parentSite())) { QStringList files = img->path(fn, path, 0, true, false, true, true, true); - for (QString file : files) + for (const QString &file : files) { if (QFile(file).exists()) return file; @@ -917,8 +920,8 @@ void searchTab::contextSaveImage(int position) { QFile(already).remove(); } else { - QString fn = m_settings->value("Save/filename").toString(); - QString path = m_settings->value("Save/path").toString(); + const QString fn = m_settings->value("Save/filename").toString(); + const QString path = m_settings->value("Save/path").toString(); if (m_boutons.contains(img)) { connect(img, &Image::downloadProgressImage, m_boutons[img], &QBouton::setProgress); } @@ -950,8 +953,8 @@ void searchTab::contextSaveImageAs(int position) Filename format(fn); QStringList filenames = format.path(*img, m_profile); - QString filename = filenames.first().section(QDir::separator(), -1); - QString lastDir = m_settings->value("Zoom/lastDir").toString(); + const QString filename = filenames.first().section(QDir::separator(), -1); + const QString lastDir = m_settings->value("Zoom/lastDir").toString(); QString path = QFileDialog::getSaveFileName(this, tr("Save image"), QDir::toNativeSeparators(lastDir + "/" + filename), "Images (*.png *.gif *.jpg *.jpeg)"); if (!path.isEmpty()) @@ -973,8 +976,8 @@ void searchTab::contextSaveImageAs(int position) } void searchTab::contextSaveSelected() { - QString fn = m_settings->value("Save/filename").toString(); - QString path = m_settings->value("Save/path").toString(); + const QString fn = m_settings->value("Save/filename").toString(); + const QString path = m_settings->value("Save/path").toString(); for (const QSharedPointer &img : qAsConst(m_selectedImagesPtrs)) { @@ -1101,7 +1104,7 @@ void searchTab::updateCheckboxes() qDeleteAll(m_checkboxes); m_checkboxes.clear(); - int n = m_settings->value("Sources/Letters", 3).toInt(); + const int n = m_settings->value("Sources/Letters", 3).toInt(); int m = n; for (auto it = m_sites.begin(); it != m_sites.end(); ++it) @@ -1138,12 +1141,12 @@ void searchTab::webZoom(int id) if (id < 0 || id >= m_images.count()) return; - QSharedPointer image = m_images.at(id); + const QSharedPointer &image = m_images.at(id); QStringList detected = PostFilter::blacklisted(image->tokens(m_profile), m_profile->getBlacklist()); if (!detected.isEmpty()) { - int reply = QMessageBox::question(parentWidget(), tr("Blacklist"), tr("%n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway?", "", detected.size()).arg(detected.join(", ")), QMessageBox::Yes | QMessageBox::No); + const int reply = QMessageBox::question(parentWidget(), tr("Blacklist"), tr("%n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway?", "", detected.size()).arg(detected.join(", ")), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::No) { return; } } @@ -1191,7 +1194,7 @@ void searchTab::unselectImage(QSharedPointer img) { if (m_selectedImagesPtrs.contains(img)) { - int pos = m_selectedImagesPtrs.indexOf(img); + const int pos = m_selectedImagesPtrs.indexOf(img); m_selectedImagesPtrs.removeAt(pos); m_selectedImages.removeAt(pos); } @@ -1199,12 +1202,12 @@ void searchTab::unselectImage(QSharedPointer img) void searchTab::toggleImage(QSharedPointer img) { - bool selected = m_selectedImagesPtrs.contains(img); + const bool selected = m_selectedImagesPtrs.contains(img); m_boutons[img.data()]->setChecked(!selected); if (selected) { - int pos = m_selectedImagesPtrs.indexOf(img); + const int pos = m_selectedImagesPtrs.indexOf(img); m_selectedImagesPtrs.removeAt(pos); m_selectedImages.removeAt(pos); } @@ -1274,7 +1277,7 @@ void searchTab::loadTags(QStringList tags) log(QStringLiteral("Loading results...")); // Enable or disable scroll mode - bool resultsScrollArea = m_settings->value("resultsScrollArea", true).toBool(); + const bool resultsScrollArea = m_settings->value("resultsScrollArea", true).toBool(); ui_scrollAreaResults->setScrollEnabled(resultsScrollArea); // Append "additional tags" setting @@ -1284,7 +1287,7 @@ void searchTab::loadTags(QStringList tags) m_lastPages.clear(); for (Site *sel : qAsConst(m_selectedSources)) { - QString site = sel->url(); + const QString &site = sel->url(); if (m_pages.contains(site)) m_lastPages.insert(site, m_pages[site].last()); } @@ -1297,7 +1300,7 @@ void searchTab::loadTags(QStringList tags) ui_buttonGetSel->setEnabled(false); // Get the search values - QString search = tags.join(" "); + const QString search = tags.join(" "); if (!m_from_history) { addHistory(search, ui_spinPage->value(), ui_spinImagesPerPage->value(), ui_spinColumns->value()); } @@ -1314,7 +1317,7 @@ void searchTab::loadTags(QStringList tags) ui_buttonFirstPage->setEnabled(ui_spinPage->value() > 1); ui_buttonPreviousPage->setEnabled(ui_spinPage->value() > 1); - bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); + const bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); m_pageMergedMode = merged; if (merged) m_layouts.insert(nullptr, createImagesLayout(m_settings)); @@ -1329,7 +1332,7 @@ void searchTab::endlessLoad() if (!m_endlessLoadingEnabled) return; - bool rememberPage = m_settings->value("infiniteScrollRememberPage", false).toBool(); + const bool rememberPage = m_settings->value("infiniteScrollRememberPage", false).toBool(); if (rememberPage) ui_spinPage->setValue(ui_spinPage->value() + 1); @@ -1341,10 +1344,10 @@ void searchTab::endlessLoad() void searchTab::loadPage() { - bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); - int perpage = ui_spinImagesPerPage->value(); - int currentPage = ui_spinPage->value() + m_endlessLoadOffset; - QStringList tags = m_lastTags.split(' '); + const bool merged = ui_checkMergeResults != nullptr && ui_checkMergeResults->isChecked(); + const int perpage = ui_spinImagesPerPage->value(); + const int currentPage = ui_spinPage->value() + m_endlessLoadOffset; + const QStringList tags = m_lastTags.split(' '); setEndlessLoadingMode(false); for (Site *site : loadSites()) @@ -1405,15 +1408,15 @@ void searchTab::addLayout(QLayout *layout, int row, int column) FixedSizeGridLayout *searchTab::createImagesLayout(QSettings *settings) { - int hSpace = settings->value("Margins/horizontal", 6).toInt(); - int vSpace = settings->value("Margins/vertical", 6).toInt(); + const int hSpace = settings->value("Margins/horizontal", 6).toInt(); + const int vSpace = settings->value("Margins/vertical", 6).toInt(); auto *l = new FixedSizeGridLayout(hSpace, vSpace); - bool fixedWidthLayout = settings->value("resultsFixedWidthLayout", false).toBool(); + const bool fixedWidthLayout = settings->value("resultsFixedWidthLayout", false).toBool(); if (fixedWidthLayout) { - int borderSize = settings->value("borders", 3).toInt(); - qreal upscale = settings->value("thumbnailUpscale", 1.0).toDouble(); + const int borderSize = settings->value("borders", 3).toInt(); + const qreal upscale = settings->value("thumbnailUpscale", 1.0).toDouble(); l->setFixedWidth(qFloor(FIXED_IMAGE_WIDTH * upscale + borderSize * 2)); } @@ -1443,7 +1446,7 @@ void searchTab::toggleSource(const QString &url) { Site *site = m_sites.value(url); - int removed = m_selectedSources.removeAll(site); + const int removed = m_selectedSources.removeAll(site); if (removed == 0) m_selectedSources.append(site); } @@ -1461,12 +1464,12 @@ void searchTab::setFavoriteImage(const QString &name) QList searchTab::sources() { return m_selectedSources; } -const QStringList &searchTab::selectedImages() +const QStringList &searchTab::selectedImages() const { return m_selectedImages; } -const QList &searchTab::results() +const QList &searchTab::results() const { return m_tags; } -const QString &searchTab::wiki() +const QString &searchTab::wiki() const { return m_wiki; } void searchTab::onLoad() @@ -1511,5 +1514,5 @@ int searchTab::imagesPerPage() { return ui_spinImagesPerPage->value(); } int searchTab::columns() { return ui_spinColumns->value(); } -const QString &searchTab::postFilter() +QString searchTab::postFilter() { return m_postFiltering->toPlainText(); } diff --git a/gui/src/tabs/search-tab.h b/gui/src/tabs/search-tab.h index b65053cc6..250cf34da 100644 --- a/gui/src/tabs/search-tab.h +++ b/gui/src/tabs/search-tab.h @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -38,14 +37,14 @@ class searchTab : public QWidget void mouseReleaseEvent(QMouseEvent *e) override; virtual QList sources(); virtual QString tags() const = 0; - const QList &results(); - const QString &wiki(); + const QList &results() const; + const QString &wiki() const; int imagesPerPage(); int columns(); - const QString &postFilter(); + QString postFilter(); virtual void setTags(const QString &tags, bool preload = true) = 0; virtual bool validateImage(const QSharedPointer &img, QString &error); - const QStringList &selectedImages(); + const QStringList &selectedImages() const; void setSources(const QList &sources); void setImagesPerPage(int ipp); void setColumns(int columns); diff --git a/gui/src/tabs/tag-tab.cpp b/gui/src/tabs/tag-tab.cpp index 96de6e7ae..a5e98e68b 100644 --- a/gui/src/tabs/tag-tab.cpp +++ b/gui/src/tabs/tag-tab.cpp @@ -1,8 +1,8 @@ #include "tabs/tag-tab.h" +#include #include #include #include "downloader/download-query-group.h" -#include "helpers.h" #include "models/page.h" #include "models/site.h" #include "searchwindow.h" @@ -93,7 +93,7 @@ void tagTab::load() search.prepend("md5:"); } - QStringList tags = search.split(" ", QString::SkipEmptyParts); + const QStringList tags = search.split(" ", QString::SkipEmptyParts); loadTags(tags); } @@ -175,19 +175,19 @@ void tagTab::getPage() if (m_checkboxes.at(i)->isChecked()) { actuals.append(keys.at(i)); } } - bool unloaded = m_settings->value("getunloadedpages", false).toBool(); + const bool unloaded = m_settings->value("getunloadedpages", false).toBool(); for (int i = 0; i < actuals.count(); i++) { if (m_pages.contains(actuals[i])) { - auto page = m_pages[actuals[i]].first(); + const auto &page = m_pages[actuals[i]].first(); - int perpage = unloaded ? ui->spinImagesPerPage->value() : (page->images().count() > ui->spinImagesPerPage->value() ? page->images().count() : ui->spinImagesPerPage->value()); + const int perpage = unloaded ? ui->spinImagesPerPage->value() : (page->images().count() > ui->spinImagesPerPage->value() ? page->images().count() : ui->spinImagesPerPage->value()); if (perpage <= 0 || page->images().count() <= 0) continue; - QString search = page->search().join(' '); - QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); + const QString search = page->search().join(' '); + const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); emit batchAddGroup(DownloadQueryGroup(m_settings, search, ui->spinPage->value(), perpage, perpage, postFiltering, m_sites.value(actuals.at(i)))); } } @@ -206,18 +206,18 @@ void tagTab::getAll() for (const QString &actual : actuals) { - QSharedPointer page = m_pages[actual].first(); + const auto &page = m_pages[actual].first(); - int highLimit = page->highLimit(); - int currentCount = page->images().count(); - int imageCount = page->imagesCount(); - int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); - int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; + const int highLimit = page->highLimit(); + const int currentCount = page->images().count(); + const int imageCount = page->imagesCount(); + const int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); + const int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; if ((perPage == 0 && total == 0) || (currentCount == 0 && imageCount <= 0)) continue; - QString search = page->search().join(' '); - QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); + const QString search = page->search().join(' '); + const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); Site *site = m_sites.value(actual); emit batchAddGroup(DownloadQueryGroup(m_settings, search, 1, perPage, total, postFiltering, site)); diff --git a/gui/src/tabs/tag-tab.h b/gui/src/tabs/tag-tab.h index 06c2a6d72..e477db6a4 100644 --- a/gui/src/tabs/tag-tab.h +++ b/gui/src/tabs/tag-tab.h @@ -1,10 +1,7 @@ #ifndef TAG_TAB_H #define TAG_TAB_H -#include #include -#include -#include #include "tabs/search-tab.h" diff --git a/gui/src/threads/image-loader-queue.cpp b/gui/src/threads/image-loader-queue.cpp index 0f805ced0..70e86db5a 100644 --- a/gui/src/threads/image-loader-queue.cpp +++ b/gui/src/threads/image-loader-queue.cpp @@ -4,7 +4,7 @@ ImageLoaderQueue::ImageLoaderQueue(ImageLoader *imageLoader, QObject* parent) - : QObject(parent), m_waiting(false), m_cancelNext(false), m_hasNext(false), m_next(QByteArray()) + : QObject(parent), m_next(QByteArray()), m_waiting(false), m_cancelNext(false), m_hasNext(false) { connect(this, &ImageLoaderQueue::loadImage, imageLoader, &ImageLoader::load); connect(imageLoader, &ImageLoader::finished, this, &ImageLoaderQueue::loadingSuccess); diff --git a/gui/src/threads/image-loader-queue.h b/gui/src/threads/image-loader-queue.h index 9a655d451..c86845d54 100644 --- a/gui/src/threads/image-loader-queue.h +++ b/gui/src/threads/image-loader-queue.h @@ -1,7 +1,6 @@ #ifndef IMAGE_LOADER_QUEUE_H #define IMAGE_LOADER_QUEUE_H -#include #include diff --git a/gui/src/threads/image-loader.h b/gui/src/threads/image-loader.h index 7a418a868..e786a0c37 100644 --- a/gui/src/threads/image-loader.h +++ b/gui/src/threads/image-loader.h @@ -1,7 +1,6 @@ #ifndef IMAGE_LOADER_H #define IMAGE_LOADER_H -#include #include diff --git a/gui/src/threads/resizer.cpp b/gui/src/threads/resizer.cpp index 2f25f7183..f1c29298c 100644 --- a/gui/src/threads/resizer.cpp +++ b/gui/src/threads/resizer.cpp @@ -1,4 +1,5 @@ #include "threads/resizer.h" +#include Resizer::Resizer(QObject *parent) diff --git a/gui/src/updater/update-dialog.cpp b/gui/src/updater/update-dialog.cpp index d83bf4276..58c7fb363 100644 --- a/gui/src/updater/update-dialog.cpp +++ b/gui/src/updater/update-dialog.cpp @@ -29,7 +29,7 @@ UpdateDialog::~UpdateDialog() void UpdateDialog::resizeToFit() { ui->scrollArea->setVisible(ui->checkShowChangelog->isChecked()); - int width = ui->labelUpdateAvailable->size().width(); + const int width = ui->labelUpdateAvailable->size().width(); ui->labelUpdateAvailable->setMinimumWidth(width); adjustSize(); @@ -50,7 +50,7 @@ void UpdateDialog::checkForUpdatesDone(const QString &newVersion, bool available return; } - bool hasChangelog = !changelog.isEmpty(); + const bool hasChangelog = !changelog.isEmpty(); if (hasChangelog) { ui->labelChangelog->setTextFormat(Qt::RichText); diff --git a/lib/src/commands/commands.cpp b/lib/src/commands/commands.cpp index ddaa93b0e..a7c00e457 100644 --- a/lib/src/commands/commands.cpp +++ b/lib/src/commands/commands.cpp @@ -1,5 +1,4 @@ #include "commands/commands.h" -#include #include #include "commands/sql-worker.h" #include "functions.h" @@ -40,12 +39,12 @@ Commands::~Commands() m_sqlWorker->deleteLater(); } -bool Commands::start() +bool Commands::start() const { return m_sqlWorker->connect(); } -bool Commands::before() +bool Commands::before() const { if (!m_mysqlSettings.before.isEmpty()) return sqlExec(m_mysqlSettings.before); @@ -97,7 +96,7 @@ bool Commands::image(const Image &img, const QString &path) bool Commands::tag(const Image &img, const Tag &tag, bool after) { - QString original = QString(tag.text()).replace(" ", "_"); + const QString original = QString(tag.text()).replace(" ", "_"); QString command = after ? m_commandTagAfter : m_commandTagBefore; if (!command.isEmpty()) @@ -145,7 +144,7 @@ bool Commands::tag(const Image &img, const Tag &tag, bool after) return true; } -bool Commands::after() +bool Commands::after() const { if (!m_mysqlSettings.after.isEmpty()) return sqlExec(m_mysqlSettings.after); @@ -153,7 +152,7 @@ bool Commands::after() return true; } -bool Commands::sqlExec(const QString &sql) +bool Commands::sqlExec(const QString &sql) const { QMetaObject::invokeMethod(m_sqlWorker, "execute", Qt::QueuedConnection, Q_ARG(QString, sql)); return true; diff --git a/lib/src/commands/commands.h b/lib/src/commands/commands.h index 21f9c0a9b..fdba996e8 100644 --- a/lib/src/commands/commands.h +++ b/lib/src/commands/commands.h @@ -24,12 +24,12 @@ class Commands public: explicit Commands(Profile *profile); ~Commands(); - bool start(); - bool before(); + bool start() const; + bool before() const; bool image(const Image &img, const QString &path); bool tag(const Image &img, const Tag &tag, bool after); - bool after(); - bool sqlExec(const QString &sql); + bool after() const; + bool sqlExec(const QString &sql) const; private: Profile *m_profile; diff --git a/lib/src/commands/sql-worker.cpp b/lib/src/commands/sql-worker.cpp index ab0fe0c05..567e320d8 100644 --- a/lib/src/commands/sql-worker.cpp +++ b/lib/src/commands/sql-worker.cpp @@ -1,5 +1,4 @@ #include "commands/sql-worker.h" -#include #include #include #include @@ -26,7 +25,7 @@ bool SqlWorker::connect() db.setUserName(m_user); db.setPassword(m_password); - int portSeparator = m_host.lastIndexOf(':'); + const int portSeparator = m_host.lastIndexOf(':'); if (portSeparator > 0) { db.setHostName(m_host.left(portSeparator)); diff --git a/lib/src/commands/sql-worker.h b/lib/src/commands/sql-worker.h index e6e8ca31d..d36e0d229 100644 --- a/lib/src/commands/sql-worker.h +++ b/lib/src/commands/sql-worker.h @@ -1,7 +1,6 @@ #ifndef SQL_WORKER_H #define SQL_WORKER_H -#include #include #include diff --git a/lib/src/custom-network-access-manager.cpp b/lib/src/custom-network-access-manager.cpp index 5f7a77dfa..7477ea34a 100644 --- a/lib/src/custom-network-access-manager.cpp +++ b/lib/src/custom-network-access-manager.cpp @@ -1,6 +1,6 @@ #include "custom-network-access-manager.h" #include -#include +#include #include "functions.h" #include "vendor/qcustomnetworkreply.h" @@ -23,7 +23,7 @@ QNetworkReply *CustomNetworkAccessManager::get(const QNetworkRequest &request) QString host = request.url().host(); QString path = "tests/resources/pages/" + host + "/" + md5 + "." + ext; - bool fromQueue = !CustomNetworkAccessManager::NextFiles.isEmpty(); + const bool fromQueue = !CustomNetworkAccessManager::NextFiles.isEmpty(); if (fromQueue) { path = CustomNetworkAccessManager::NextFiles.dequeue(); } @@ -47,8 +47,8 @@ QNetworkReply *CustomNetworkAccessManager::get(const QNetworkRequest &request) } QFile f(path); - bool opened = f.open(QFile::ReadOnly); - bool logFilename = !opened || !fromQueue; + const bool opened = f.open(QFile::ReadOnly); + const bool logFilename = !opened || !fromQueue; if (!opened) { md5 = QString(QCryptographicHash::hash(request.url().toString().toLatin1(), QCryptographicHash::Md5).toHex()); @@ -75,7 +75,7 @@ QNetworkReply *CustomNetworkAccessManager::get(const QNetworkRequest &request) if (logFilename) { qDebug() << ("Reply from file: " + request.url().toString() + " -> " + f.fileName()); } - QByteArray content = f.readAll(); + const QByteArray content = f.readAll(); auto *reply = new QCustomNetworkReply(this); reply->setHttpStatusCode(200, "OK"); diff --git a/lib/src/danbooru-downloader-importer.cpp b/lib/src/danbooru-downloader-importer.cpp index c0ffe33f6..956cce8c6 100644 --- a/lib/src/danbooru-downloader-importer.cpp +++ b/lib/src/danbooru-downloader-importer.cpp @@ -1,13 +1,14 @@ #include "danbooru-downloader-importer.h" #include #include +#include DanbooruDownloaderImporter::DanbooruDownloaderImporter() : m_firefoxProfilePath(QString()) { QSettings cfg(QSettings::IniFormat, QSettings::UserScope, "Mozilla", "Firefox"); - QString path = QFileInfo(cfg.fileName()).absolutePath() + "/Firefox"; + const QString path = QFileInfo(cfg.fileName()).absolutePath() + "/Firefox"; if (QFile::exists(path + "/profiles.ini")) { QSettings profiles(path + "/profiles.ini", QSettings::IniFormat); @@ -26,7 +27,7 @@ void DanbooruDownloaderImporter::import(QSettings *dest) const if (prefs.exists() && prefs.open(QIODevice::ReadOnly | QIODevice::Text)) return; - QString source = prefs.readAll(); + const QString source = prefs.readAll(); QRegularExpression rx("user_pref\\(\"danbooru.downloader.([^\"]+)\", ([^\\)]+)\\);"); QMap firefox, assoc; assoc["blacklist"] = "blacklistedtags"; diff --git a/lib/src/downloader/download-query-group.cpp b/lib/src/downloader/download-query-group.cpp index d93c94e32..3c4188446 100644 --- a/lib/src/downloader/download-query-group.cpp +++ b/lib/src/downloader/download-query-group.cpp @@ -66,7 +66,7 @@ bool DownloadQueryGroup::read(const QJsonObject &json, const QMap -#include #include #include #include "downloader/download-query.h" @@ -15,8 +14,8 @@ class DownloadQueryGroup : public DownloadQuery public: // Constructors DownloadQueryGroup() = default; - explicit DownloadQueryGroup(QSettings *settings, const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, Site *site, const QString &unk = ""); - explicit DownloadQueryGroup(const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, bool getBlacklisted, Site *site, const QString &filename, const QString &path, const QString &unk = ""); + explicit DownloadQueryGroup(QSettings *settings, const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, Site *site, const QString &unk = QString()); + explicit DownloadQueryGroup(const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, bool getBlacklisted, Site *site, const QString &filename, const QString &path, const QString &unk = QString()); // Serialization QString toString(const QString &separator) const override; diff --git a/lib/src/downloader/download-query-image.cpp b/lib/src/downloader/download-query-image.cpp index adbc73312..84b334142 100644 --- a/lib/src/downloader/download-query-image.cpp +++ b/lib/src/downloader/download-query-image.cpp @@ -99,7 +99,7 @@ bool DownloadQueryImage::read(const QJsonObject &json, const QMap #include -#include #include #include #include "downloader/download-query.h" diff --git a/lib/src/downloader/download-query-loader.cpp b/lib/src/downloader/download-query-loader.cpp index 34b1c75d3..2b3d4da46 100644 --- a/lib/src/downloader/download-query-loader.cpp +++ b/lib/src/downloader/download-query-loader.cpp @@ -2,7 +2,6 @@ #include #include #include -#include #include "downloader/download-query-group.h" #include "downloader/download-query-image.h" #include "logger.h" @@ -23,8 +22,8 @@ bool DownloadQueryLoader::load(const QString &path, QList &u // Version 1 and 2 are plain text if (header.startsWith("[IGL ")) { - QString fieldSeparator(QChar(29)); - QString lineSeparator(QChar(28)); + const QChar fieldSeparator(29); + const QChar lineSeparator(28); // Read the remaining file QString links = f.readAll(); @@ -38,7 +37,7 @@ bool DownloadQueryLoader::load(const QString &path, QList &u QStringList infos = link.split(fieldSeparator); if (infos.size() == 9) { - QString source = infos[6]; + const QString &source = infos[6]; if (!sites.contains(source)) continue; @@ -46,7 +45,7 @@ bool DownloadQueryLoader::load(const QString &path, QList &u } else { - QString source = infos[5]; + const QString &source = infos[5]; if (!sites.contains(source) || infos.at(1).toInt() < 0 || infos.at(2).toInt() < 1 || infos.at(3).toInt() < 1) continue; @@ -70,11 +69,11 @@ bool DownloadQueryLoader::load(const QString &path, QList &u // Other versions are JSON-based f.reset(); - QByteArray data = f.readAll(); + const QByteArray data = f.readAll(); QJsonDocument loadDoc = QJsonDocument::fromJson(data); QJsonObject object = loadDoc.object(); - int version = object["version"].toInt(); + const int version = object["version"].toInt(); switch (version) { case 3: diff --git a/lib/src/downloader/download-query-loader.h b/lib/src/downloader/download-query-loader.h index d8b2200de..e0aad4653 100644 --- a/lib/src/downloader/download-query-loader.h +++ b/lib/src/downloader/download-query-loader.h @@ -1,7 +1,6 @@ #ifndef DOWNLOAD_QUERY_LOADER_H #define DOWNLOAD_QUERY_LOADER_H -#include #include #include diff --git a/lib/src/downloader/extension-rotator.cpp b/lib/src/downloader/extension-rotator.cpp index 9a9116abf..b3a780f68 100644 --- a/lib/src/downloader/extension-rotator.cpp +++ b/lib/src/downloader/extension-rotator.cpp @@ -1,4 +1,5 @@ #include "downloader/extension-rotator.h" +#include ExtensionRotator::ExtensionRotator(const ExtensionRotator &other) @@ -11,7 +12,7 @@ ExtensionRotator::ExtensionRotator(const ExtensionRotator &other) ExtensionRotator::ExtensionRotator(const QString &initialExtension, const QStringList &extensions, QObject *parent) : QObject(parent), m_initialExtension(initialExtension), m_extensions(extensions) { - int index = extensions.indexOf(initialExtension); + const int index = extensions.indexOf(initialExtension); // If the initial extension is not in the list, we return the first one if (index < 0) @@ -34,8 +35,8 @@ QString ExtensionRotator::next() QString next = m_extensions[m_next % m_extensions.length()]; // If we did a full loop, that means we finished - bool isLast = m_next == m_extensions.size(); - bool isNotFound = m_extensions.indexOf(m_initialExtension) < 0; + const bool isLast = m_next == m_extensions.size(); + const bool isNotFound = m_extensions.indexOf(m_initialExtension) < 0; if (next == m_initialExtension || (isLast && isNotFound)) return QString(); diff --git a/lib/src/downloader/file-downloader.cpp b/lib/src/downloader/file-downloader.cpp index 1cda721a7..559ff1704 100644 --- a/lib/src/downloader/file-downloader.cpp +++ b/lib/src/downloader/file-downloader.cpp @@ -1,4 +1,5 @@ #include "downloader/file-downloader.h" +#include #include "functions.h" #define WRITE_BUFFER_SIZE (200 * 1024) @@ -16,7 +17,7 @@ bool FileDownloader::start(QNetworkReply *reply, const QStringList &paths) { m_copies = paths; m_file.setFileName(m_copies.takeFirst()); - bool ok = m_file.open(QFile::WriteOnly | QFile::Truncate); + const bool ok = m_file.open(QFile::WriteOnly | QFile::Truncate); m_writeError = false; m_reply = reply; @@ -46,10 +47,10 @@ void FileDownloader::replyReadyRead() void FileDownloader::replyFinished() { QByteArray data = m_reply->readAll(); - qint64 written = m_file.write(data); + const qint64 written = m_file.write(data); m_file.close(); - bool failedLastWrite = data.length() > 0 && written < 0; + const bool failedLastWrite = data.length() > 0 && written < 0; if (m_reply->error() != QNetworkReply::NoError || failedLastWrite) { m_file.remove(); diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index b3f9b4f0e..2ff4df27d 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -1,9 +1,11 @@ #include "downloader/image-downloader.h" #include #include "extension-rotator.h" +#include "file-downloader.h" #include "functions.h" #include "logger.h" #include "models/filename.h" +#include "models/image.h" #include "models/profile.h" #include "models/site.h" #include "models/source.h" @@ -47,7 +49,7 @@ void ImageDownloader::loadedSave() // Use a random temporary file if we need the MD5 or equivalent if (m_temporaryPath.isEmpty()) { - QString tmpDir = !m_path.isEmpty() ? m_path : QDir::tempPath(); + const QString tmpDir = !m_path.isEmpty() ? m_path : QDir::tempPath(); m_temporaryPath = tmpDir + "/" + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; } @@ -94,7 +96,7 @@ void ImageDownloader::loadImage() connect(m_reply, &QNetworkReply::downloadProgress, this, &ImageDownloader::downloadProgressImage); // Create download root directory - QString rootDir = m_temporaryPath.section(QDir::separator(), 0, -2); + const QString rootDir = m_temporaryPath.section(QDir::separator(), 0, -2); if (!QDir(rootDir).exists() && !QDir().mkpath(rootDir)) { log(QStringLiteral("Impossible to create the destination folder: %1.").arg(rootDir), Logger::Error); @@ -137,11 +139,11 @@ void ImageDownloader::networkError(QNetworkReply::NetworkError error, const QStr QSettings *settings = m_image->parentSite()->getSource()->getProfile()->getSettings(); ExtensionRotator *extensionRotator = m_image->extensionRotator(); - bool sampleFallback = settings->value("Save/samplefallback", true).toBool(); + const bool sampleFallback = settings->value("Save/samplefallback", true).toBool(); QString newext = extensionRotator != nullptr ? extensionRotator->next() : QString(); - bool shouldFallback = sampleFallback && !m_image->url(Image::Size::Sample).isEmpty(); - bool isLast = newext.isEmpty() || (shouldFallback && m_tryingSample); + const bool shouldFallback = sampleFallback && !m_image->url(Image::Size::Sample).isEmpty(); + const bool isLast = newext.isEmpty() || (shouldFallback && m_tryingSample); if (m_rotate && (!isLast || (shouldFallback && !m_tryingSample))) { @@ -210,7 +212,7 @@ QMap ImageDownloader::postSaving(QMap -#include #include #include #include #include #include -#include #include #include #include @@ -14,7 +12,6 @@ #include #include #include -#include #ifdef Q_OS_WIN #include #else @@ -49,7 +46,7 @@ QMap> getFilenames(QSettings *settings) QMap> tokens; settings->beginGroup(QStringLiteral("Filenames")); - int count = settings->childKeys().count() / 3; + const int count = settings->childKeys().count() / 3; for (int i = 0; i < count; i++) { if (settings->contains(QString::number(i) + "_cond")) @@ -134,7 +131,7 @@ QDateTime qDateTimeFromString(QString str) { QDateTime date; - uint toInt = str.toUInt(); + const uint toInt = str.toUInt(); if (toInt != 0) { date.setTime_t(toInt); @@ -177,12 +174,12 @@ QDateTime qDateTimeFromString(QString str) } QStringList months = QStringList() << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec"; - int year = str.midRef(26, 4).toInt(); - int month = months.indexOf(str.mid(4, 3)) + 1; - int day = str.midRef(8, 2).toInt(); - qreal decay = str.midRef(20, 5).toDouble() / 100; + const int year = str.midRef(26, 4).toInt(); + const int month = months.indexOf(str.mid(4, 3)) + 1; + const int day = str.midRef(8, 2).toInt(); + const qreal decay = str.midRef(20, 5).toDouble() / 100; - QTime time = QTime::fromString(str.mid(11, 8), QStringLiteral("HH:mm:ss")); + const QTime time = QTime::fromString(str.mid(11, 8), QStringLiteral("HH:mm:ss")); date.setDate(QDate(year, month, day)); date.setTime(time); date.setOffsetFromUtc(qFloor(3600 * decay)); @@ -194,7 +191,7 @@ QDateTime qDateTimeFromString(QString str) QString getUnit(double *value) { QStringList units = FILESIZE_UNITS; - int multiplier = FILESIZE_MULTIPLIER; + const int multiplier = FILESIZE_MULTIPLIER; int power = 0; while (*value >= multiplier && power < units.count() - 1) @@ -208,9 +205,9 @@ QString getUnit(double *value) QString formatFilesize(double size) { - QString unit = getUnit(&size); - double round = size > 100 ? 1 : (size >= 10 ? 10 : 100); - double roundedSize = static_cast(static_cast(size * round + 0.5)) / round; + const QString unit = getUnit(&size); + const double round = size > 100 ? 1 : (size >= 10 ? 10 : 100); + const double roundedSize = static_cast(static_cast(size * round + 0.5)) / round; return QStringLiteral("%1 %2").arg(roundedSize).arg(unit); } @@ -218,7 +215,7 @@ bool validSavePath(const QString &file, bool writable) { QString nativeFile = QDir::toNativeSeparators(file); QFileInfo info(nativeFile); - bool isWritable = info.isWritable() && !nativeFile.startsWith(QLatin1String("C:\\Program Files")); + const bool isWritable = info.isWritable() && !nativeFile.startsWith(QLatin1String("C:\\Program Files")); return info.exists() && (!writable || isWritable); } @@ -230,7 +227,7 @@ bool validSavePath(const QString &file, bool writable) */ QString savePath(const QString &file, bool exists, bool writable) { - QString check = exists ? file : QStringLiteral("settings.ini"); + const QString &check = exists ? file : QStringLiteral("settings.ini"); if (isTestModeEnabled()) { @@ -375,7 +372,7 @@ QMap domToMap(const QDomElement &dom) QMap details; for (QDomNode n = dom.firstChild(); !n.isNull(); n = n.nextSibling()) { - auto type = n.firstChild().nodeType(); + const auto type = n.firstChild().nodeType(); if (type == QDomNode::TextNode || type == QDomNode::CDATASectionNode) { details[n.nodeName()] = n.firstChild().nodeValue(); } else @@ -430,7 +427,7 @@ QString getExtension(const QUrl &url) QString getExtension(const QString &url) { QString ext; - int pPos = url.lastIndexOf('.'); + const int pPos = url.lastIndexOf('.'); if (pPos != -1 && pPos > url.indexOf('/', 7)) { ext = url.right(url.length() - pPos - 1); @@ -442,10 +439,10 @@ QString getExtension(const QString &url) QString setExtension(QString url, const QString &extension) { - int pPos = url.lastIndexOf('.'); + const int pPos = url.lastIndexOf('.'); if (pPos != -1 && pPos > url.indexOf('/', 7)) { - int qPos = url.indexOf('?', pPos); + const int qPos = url.indexOf('?', pPos); if (qPos != -1) url.replace(pPos + 1, qPos - pPos - 1, extension); else @@ -462,7 +459,7 @@ bool isUrl(const QString &str) QString fixFilename(QString fn, QString path, int maxlength, bool invalidChars) { - QString sep = QDir::separator(); + const QString sep = QDir::separator(); fn = QDir::toNativeSeparators(fn); path = QDir::toNativeSeparators(path); if (!path.endsWith(sep) && !path.isEmpty() && !fn.isEmpty()) @@ -480,7 +477,7 @@ QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, Q_UNUSED(invalidChars); // Fix parameters - QString sep = QStringLiteral("/"); + const QString sep = QStringLiteral("/"); QString filename = path + fn; // Divide filename @@ -489,7 +486,7 @@ QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, if (!fn.isEmpty()) { file = parts.takeLast();; - int lastDot = file.lastIndexOf('.'); + const int lastDot = file.lastIndexOf('.'); if (lastDot != -1) { ext = file.right(file.length() - lastDot - 1); @@ -513,7 +510,7 @@ QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, filename = (dirpart.isEmpty() ? QString() : dirpart + (!fn.isEmpty() ? sep : QString())) + file; // A filename cannot exceed a certain length - int extlen = ext.isEmpty() ? 0 : ext.length() + 1; + const int extlen = ext.isEmpty() ? 0 : ext.length() + 1; if (file.length() > maxlength - extlen) file = file.left(maxlength - extlen).trimmed(); if (file.length() > 255 - extlen) @@ -521,7 +518,7 @@ QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, // Get separation between filename and path int index = -1; - int pathGroups = path.count(sep); + const int pathGroups = path.count(sep); for (int i = 0; i < pathGroups; ++i) index = filename.indexOf(sep, index + 1); @@ -544,7 +541,7 @@ QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, QString fixFilenameWindows(const QString &fn, const QString &path, int maxlength, bool invalidChars) { // Fix parameters - QString sep = QStringLiteral("\\"); + const QString sep = QStringLiteral("\\"); maxlength = maxlength == 0 ? MAX_PATH : maxlength; QString filename = path + fn; @@ -561,7 +558,7 @@ QString fixFilenameWindows(const QString &fn, const QString &path, int maxlength { filename.replace('<', '_').replace('>', '_').replace(':', '_').remove('"').replace('/', '_').replace('|', '_').remove('?').replace('*', '_'); } // Fobidden directories or filenames - QStringList forbidden = QStringList() << "CON" << "PRN" << "AUX" << "NUL" << "COM1" << "COM2" << "COM3" << "COM4" << "COM5" << "COM6" << "COM7" << "COM8" << "COM9" << "LPT1" << "LPT2" << "LPT3" << "LPT4" << "LPT5" << "LPT6" << "LPT7" << "LPT8" << "LPT9"; + static const QStringList forbidden = QStringList() << "CON" << "PRN" << "AUX" << "NUL" << "COM1" << "COM2" << "COM3" << "COM4" << "COM5" << "COM6" << "COM7" << "COM8" << "COM9" << "LPT1" << "LPT2" << "LPT3" << "LPT4" << "LPT5" << "LPT6" << "LPT7" << "LPT8" << "LPT9"; // Divide filename QStringList parts = filename.split(sep); @@ -569,7 +566,7 @@ QString fixFilenameWindows(const QString &fn, const QString &path, int maxlength if (!fn.isEmpty()) { file = parts.takeLast(); - int lastDot = file.lastIndexOf('.'); + const int lastDot = file.lastIndexOf('.'); if (lastDot != -1) { ext = file.right(file.length() - lastDot - 1); @@ -608,7 +605,7 @@ QString fixFilenameWindows(const QString &fn, const QString &path, int maxlength // Get separation between filename and path int index = -1; - int pathGroups = path.count(sep); + const int pathGroups = path.count(sep); for (int i = 0; i < pathGroups - (!drive.isEmpty() ? 1 : 0); ++i) { index = filename.indexOf(sep, index + 1); } index += drive.length(); @@ -624,12 +621,12 @@ QString fixFilenameWindows(const QString &fn, const QString &path, int maxlength QString getExtensionFromHeader(const QByteArray &data12) { - QByteArray data8 = data12.left(8); - QByteArray data48 = data12.mid(4, 8); - QByteArray data6 = data12.left(6); - QByteArray data4 = data12.left(4); - QByteArray data3 = data12.left(3); - QByteArray data2 = data12.left(2); + const QByteArray data8 = data12.left(8); + const QByteArray data48 = data12.mid(4, 8); + const QByteArray data6 = data12.left(6); + const QByteArray data4 = data12.left(4); + const QByteArray data3 = data12.left(3); + const QByteArray data2 = data12.left(2); // GIF if (data6 == "GIF87a" || data6 == "GIF89a") @@ -688,17 +685,18 @@ QString parseMarkdown(QString str) str.replace("\\r\\n", "\\n"); // Headers - QRegularExpression header(QStringLiteral("^(#+)([^#].*)$"), QRegularExpression::MultilineOption); + static const QRegularExpression header(QStringLiteral("^(#+)([^#].*)$"), QRegularExpression::MultilineOption); auto matches = header.globalMatch(str); - while (matches.hasNext()) { + while (matches.hasNext()) + { auto match = matches.next(); - int level = qMax(1, qMin(6, match.captured(1).length())); - QString result = "" + match.captured(2).trimmed() + ""; + const int level = qMax(1, qMin(6, match.captured(1).length())); + const QString result = "" + match.captured(2).trimmed() + ""; str.replace(match.captured(0), result); } // Issue links - QRegularExpression issueLinks("(issue|fix) #(\\d+)"); + static const QRegularExpression issueLinks("(issue|fix) #(\\d+)"); str.replace(issueLinks, "\\1 #\\2"); // Line breaks to HTML @@ -730,7 +728,7 @@ QString qFontToCss(const QFont &font) { size = QString::number(font.pixelSize())+"px"; } // Should be "font.weight() * 8 + 100", but linux doesn't handle weight the same way windows do - QString weight = QString::number(font.weight() * 8); + const QString weight = QString::number(font.weight() * 8); QStringList decorations; if (font.strikeOut()) { decorations.append("line-through"); } @@ -768,7 +766,7 @@ QList> listFilesFromDirectory(const QDir &dir, const continue; QString path = it.filePath(); - QString fileName = path.right(path.length() - dir.absolutePath().length() - 1); + const QString fileName = path.right(path.length() - dir.absolutePath().length() - 1); if (!files.isEmpty()) { @@ -811,7 +809,7 @@ QMap multiMatchToMap(const QRegularExpressionMatch &match, con if (val.isEmpty()) continue; - int underscorePos = group.lastIndexOf('_'); + const int underscorePos = group.lastIndexOf('_'); bool ok; group.midRef(underscorePos + 1).toInt(&ok); if (underscorePos != -1 && ok) diff --git a/lib/src/language-loader.cpp b/lib/src/language-loader.cpp index 1ed21cd08..e7c07b364 100644 --- a/lib/src/language-loader.cpp +++ b/lib/src/language-loader.cpp @@ -16,8 +16,8 @@ QMap LanguageLoader::getAllLanguages() const QMap languages; for (const QString &languageFile : languageFiles) { - QString lang = languageFile.left(languageFile.length() - 3); - QString fullLang = fullLanguages.value(lang, lang).toString(); + const QString lang = languageFile.left(languageFile.length() - 3); + const QString fullLang = fullLanguages.value(lang, lang).toString(); languages[lang] = fullLang; } diff --git a/lib/src/loader/downloadable-downloader.cpp b/lib/src/loader/downloadable-downloader.cpp index ae81a1b8e..e6789cf4a 100644 --- a/lib/src/loader/downloadable-downloader.cpp +++ b/lib/src/loader/downloadable-downloader.cpp @@ -33,7 +33,7 @@ void DownloadableDownloader::save() void DownloadableDownloader::preloaded() { - QString url = m_downloadable->url(Downloadable::Size::Full); + const QString url = m_downloadable->url(Downloadable::Size::Full); QStringList paths = !m_paths.isEmpty() ? m_paths : m_downloadable->paths(m_filename, m_folder, m_count); // Sometimes we don't even need to download the image to save it @@ -60,9 +60,9 @@ void DownloadableDownloader::preloaded() log(QStringLiteral("Loading and saving image in %1").arg(m_paths.first())); m_url = m_site->fixUrl(url); QNetworkReply *reply = m_site->get(m_url, Q_NULLPTR, QStringLiteral("image"), Q_NULLPTR); // TODO(Bionus) - QObject::connect(&m_fileDownloader, &FileDownloader::writeError, this, &DownloadableDownloader::writeError, Qt::UniqueConnection); - QObject::connect(&m_fileDownloader, &FileDownloader::networkError, this, &DownloadableDownloader::networkError, Qt::UniqueConnection); - QObject::connect(&m_fileDownloader, &FileDownloader::success, this, &DownloadableDownloader::success, Qt::UniqueConnection); + connect(&m_fileDownloader, &FileDownloader::writeError, this, &DownloadableDownloader::writeError, Qt::UniqueConnection); + connect(&m_fileDownloader, &FileDownloader::networkError, this, &DownloadableDownloader::networkError, Qt::UniqueConnection); + connect(&m_fileDownloader, &FileDownloader::success, this, &DownloadableDownloader::success, Qt::UniqueConnection); // If we can't start writing for some reason, return an error if (!m_fileDownloader.start(reply, m_paths)) diff --git a/lib/src/loader/downloadable-downloader.h b/lib/src/loader/downloadable-downloader.h index aee60538f..6232c7d5c 100644 --- a/lib/src/loader/downloadable-downloader.h +++ b/lib/src/loader/downloadable-downloader.h @@ -1,8 +1,8 @@ #ifndef DOWNLOADABLE_DOWNLOADER_H #define DOWNLOADABLE_DOWNLOADER_H +#include #include -#include #include "downloader/file-downloader.h" #include "loader/downloadable.h" #include "models/filename.h" diff --git a/lib/src/loader/downloadable.h b/lib/src/loader/downloadable.h index f4ba09e12..46e41332b 100644 --- a/lib/src/loader/downloadable.h +++ b/lib/src/loader/downloadable.h @@ -1,6 +1,7 @@ #ifndef DOWNLOADABLE_H #define DOWNLOADABLE_H +#include #include #include #include "loader/token.h" diff --git a/lib/src/loader/loader-data.h b/lib/src/loader/loader-data.h index f16e276bd..694d37690 100644 --- a/lib/src/loader/loader-data.h +++ b/lib/src/loader/loader-data.h @@ -2,10 +2,7 @@ #define LOADER_DATA_H #include -#include #include -#include -#include #include "loader/downloadable.h" diff --git a/lib/src/loader/loader-query.cpp b/lib/src/loader/loader-query.cpp index 5ccfc2629..027caeb5e 100644 --- a/lib/src/loader/loader-query.cpp +++ b/lib/src/loader/loader-query.cpp @@ -33,14 +33,14 @@ LoaderData LoaderQuery::next() // Options Profile *profile = m_site->getSource()->getProfile(); - QStringList tags = m_options["tags"].toStringList(); - int page = m_options["page"].toInt(); - int perPage = m_options["perPage"].toInt(); - int limit = m_options["limit"].toInt(); - QStringList postFiltering = m_options["postFiltering"].toStringList(); - bool getBlacklisted = m_options["getBlacklisted"].toBool(); - // QStringList blacklist = m_options["blacklist"].toStringList(); - QList blacklist; + const QStringList tags = m_options["tags"].toStringList(); + const int page = m_options["page"].toInt(); + const int perPage = m_options["perPage"].toInt(); + const int limit = m_options["limit"].toInt(); + const QStringList postFiltering = m_options["postFiltering"].toStringList(); + const bool getBlacklisted = m_options["getBlacklisted"].toBool(); + // const QStringList blacklist = m_options["blacklist"].toStringList(); + const QList blacklist; // Load results QEventLoop loop; @@ -65,7 +65,7 @@ LoaderData LoaderQuery::next() } // Paging - int pageCount = qCeil(static_cast(limit) / perPage); + const int pageCount = qCeil(static_cast(limit) / perPage); m_offset++; m_finished = m_offset == pageCount; diff --git a/lib/src/loader/loader-query.h b/lib/src/loader/loader-query.h index 9bb90a386..859fd1ade 100644 --- a/lib/src/loader/loader-query.h +++ b/lib/src/loader/loader-query.h @@ -1,8 +1,6 @@ #ifndef LOADER_QUERY_H #define LOADER_QUERY_H -#include -#include #include diff --git a/lib/src/loader/loader.h b/lib/src/loader/loader.h index 891b3b64f..f04679c6a 100644 --- a/lib/src/loader/loader.h +++ b/lib/src/loader/loader.h @@ -1,8 +1,6 @@ #ifndef LOADER_H #define LOADER_H -#include -#include #include diff --git a/lib/src/loader/token.cpp b/lib/src/loader/token.cpp index 2c3b7b90d..2be23584c 100644 --- a/lib/src/loader/token.cpp +++ b/lib/src/loader/token.cpp @@ -12,20 +12,20 @@ Token::Token(const QVariant &value, const QString &whatToDoDefault, const QStrin {} -QVariant Token::value() const +const QVariant &Token::value() const { return m_value; } QString Token::toString() const { return m_value.toString(); } -QString Token::whatToDoDefault() const +const QString &Token::whatToDoDefault() const { return m_whatToDoDefault; } -QString Token::emptyDefault() const +const QString &Token::emptyDefault() const { return m_emptyDefault; } -QString Token::multipleDefault() const +const QString &Token::multipleDefault() const { return m_multipleDefault; } diff --git a/lib/src/loader/token.h b/lib/src/loader/token.h index d79d84cfa..0f25b305a 100644 --- a/lib/src/loader/token.h +++ b/lib/src/loader/token.h @@ -1,7 +1,6 @@ #ifndef TOKEN_H #define TOKEN_H -#include #include @@ -12,13 +11,13 @@ class Token explicit Token(const QVariant &value, const QVariant &def = QVariant()); explicit Token(const QVariant &value, const QString &whatToDoDefault, const QString &emptyDefault, const QString &multipleDefault); - QVariant value() const; + const QVariant &value() const; template T value() const { return m_value.value(); } QString toString() const; - QString whatToDoDefault() const; - QString emptyDefault() const; - QString multipleDefault() const; + const QString &whatToDoDefault() const; + const QString &emptyDefault() const; + const QString &multipleDefault() const; private: QVariant m_value; diff --git a/lib/src/login/http-get-login.cpp b/lib/src/login/http-get-login.cpp index c4d3b00fd..18e4b955a 100644 --- a/lib/src/login/http-get-login.cpp +++ b/lib/src/login/http-get-login.cpp @@ -12,7 +12,7 @@ QNetworkReply *HttpGetLogin::getReply(const QString &loginUrl, const QUrlQuery & { QUrl url = m_site->fixUrl(loginUrl); url.setQuery(query); - QNetworkRequest request(url); + const QNetworkRequest request(url); return m_manager->get(request); } diff --git a/lib/src/login/http-get-login.h b/lib/src/login/http-get-login.h index e2fe38acf..3f2a069cd 100644 --- a/lib/src/login/http-get-login.h +++ b/lib/src/login/http-get-login.h @@ -1,6 +1,7 @@ #ifndef HTTP_GET_LOGIN_H #define HTTP_GET_LOGIN_H +#include #include "login/http-login.h" diff --git a/lib/src/login/http-login.cpp b/lib/src/login/http-login.cpp index 1d3e91a24..dd1c9a9f3 100644 --- a/lib/src/login/http-login.cpp +++ b/lib/src/login/http-login.cpp @@ -1,6 +1,7 @@ #include "login/http-login.h" #include #include +#include #include #include "custom-network-access-manager.h" #include "mixed-settings.h" @@ -18,8 +19,8 @@ bool HttpLogin::isTestable() const void HttpLogin::login() { - QString username = m_settings->value("auth/pseudo").toString(); - QString password = m_settings->value("auth/password").toString(); + const QString username = m_settings->value("auth/pseudo").toString(); + const QString password = m_settings->value("auth/password").toString(); QUrlQuery query; query.addQueryItem(m_settings->value("login/" + m_type + "/pseudo").toString(), username); @@ -39,7 +40,7 @@ void HttpLogin::login() void HttpLogin::loginFinished() { - QString cookieName = m_settings->value("login/" + m_type + "/cookie").toString(); + const QString cookieName = m_settings->value("login/" + m_type + "/cookie").toString(); QNetworkCookieJar *cookieJar = m_manager->cookieJar(); QList cookies = cookieJar->cookiesForUrl(m_loginReply->url()); diff --git a/lib/src/login/http-post-login.h b/lib/src/login/http-post-login.h index a2b6355cc..748ba2fce 100644 --- a/lib/src/login/http-post-login.h +++ b/lib/src/login/http-post-login.h @@ -1,6 +1,7 @@ #ifndef HTTP_POST_LOGIN_H #define HTTP_POST_LOGIN_H +#include #include "login/http-login.h" diff --git a/lib/src/login/login.cpp b/lib/src/login/login.cpp index ea1cc1fa1..4e125b57f 100644 --- a/lib/src/login/login.cpp +++ b/lib/src/login/login.cpp @@ -1,4 +1,5 @@ #include "login/login.h" +#include QString Login::complementUrl(QString url, const QString &loginPart) const diff --git a/lib/src/login/oauth2-login.cpp b/lib/src/login/oauth2-login.cpp index 0765b79cd..8619019e1 100644 --- a/lib/src/login/oauth2-login.cpp +++ b/lib/src/login/oauth2-login.cpp @@ -1,6 +1,7 @@ #include "login/oauth2-login.h" #include #include +#include #include "logger.h" #include "mixed-settings.h" #include "models/site.h" diff --git a/lib/src/login/url-login.cpp b/lib/src/login/url-login.cpp index 89a3d631f..c6c1f27e2 100644 --- a/lib/src/login/url-login.cpp +++ b/lib/src/login/url-login.cpp @@ -17,7 +17,7 @@ bool UrlLogin::isTestable() const void UrlLogin::login() { - int maxPageAnonymous = m_settings->value("login/maxPage", 0).toInt(); + const int maxPageAnonymous = m_settings->value("login/maxPage", 0).toInt(); m_page = new Page(m_site->getSource()->getProfile(), m_site, QList() << m_site, QStringList(), maxPageAnonymous); connect(m_page, &Page::finishedLoading, this, &UrlLogin::loginFinished); connect(m_page, &Page::failedLoading, this, &UrlLogin::loginFinished); @@ -40,7 +40,7 @@ QString UrlLogin::complementUrl(QString url, const QString &loginPart) const QString pseudo = m_settings->value("auth/pseudo").toString(); QString password = m_settings->value("auth/password").toString(); - bool hasLoginString = !loginPart.isEmpty() && (!pseudo.isEmpty() || !password.isEmpty()); + const bool hasLoginString = !loginPart.isEmpty() && (!pseudo.isEmpty() || !password.isEmpty()); url.replace("{login}", hasLoginString ? loginPart : QString()); // Basic GET auth diff --git a/lib/src/mixed-settings.cpp b/lib/src/mixed-settings.cpp index 59e010cea..919f2bfdb 100644 --- a/lib/src/mixed-settings.cpp +++ b/lib/src/mixed-settings.cpp @@ -74,7 +74,7 @@ void MixedSettings::beginGroup(const QString &prefix) void MixedSettings::endGroup() { - for (QSettings *setting :qAsConst( m_settings)) + for (QSettings *setting : qAsConst( m_settings)) setting->endGroup(); } diff --git a/lib/src/mixed-settings.h b/lib/src/mixed-settings.h index 7f9f98334..b9b3fd832 100644 --- a/lib/src/mixed-settings.h +++ b/lib/src/mixed-settings.h @@ -1,8 +1,6 @@ #ifndef MIXED_SETTINGS_H #define MIXED_SETTINGS_H -#include -#include #include diff --git a/lib/src/models/api/api.cpp b/lib/src/models/api/api.cpp index 840620b3c..e1f783896 100644 --- a/lib/src/models/api/api.cpp +++ b/lib/src/models/api/api.cpp @@ -2,7 +2,6 @@ #include #include "logger.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/site.h" #include "models/source.h" @@ -15,7 +14,7 @@ Api::Api(const QString &name, const QMap &data) { if (it.key().startsWith(prefix)) { - QString k = it.key().right(it.key().length() - prefix.length() - 1); + const QString k = it.key().right(it.key().length() - prefix.length() - 1); m_data["Urls/" + k] = it.value(); } } @@ -40,9 +39,9 @@ PageUrl Api::pageUrl(const QString &tt, int page, int limit, int lastPage, int l { search = m_data.value("DefaultTag"); } // Find page number - int forced = forcedLimit(); - int pidLimit = forced > 0 ? forced : limit; - int pid = pidLimit * (page - 1); + const int forced = forcedLimit(); + const int pidLimit = forced > 0 ? forced : limit; + const int pid = pidLimit * (page - 1); page = page - 1 + m_data.value("FirstPage").toInt(); // Custom URL for pool search @@ -79,7 +78,7 @@ PageUrl Api::pageUrl(const QString &tt, int page, int limit, int lastPage, int l else if (m_data.contains("Urls/MaxPage")) { maxPage = m_data.value("Urls/MaxPage").toInt(); } - bool isAltPage = maxPage >= 0 && page > maxPage && page - 1 <= lastPage && lastPage <= page + 1; + const bool isAltPage = maxPage >= 0 && page > maxPage && page - 1 <= lastPage && lastPage <= page + 1; if (m_data.contains("Urls/NormalPage")) { url.replace("{cpage}", isAltPage ? "{altpage}" : m_data.value("Urls/NormalPage")); } if (isAltPage) @@ -206,7 +205,7 @@ QString Api::parseSetImageUrl(Site *site, const QString &settingUrl, const QStri QStringList reps = value(settingReplaces).split('&'); for (const QString &rep : reps) { - QRegularExpression rgx(rep.left(rep.indexOf("->"))); + const QRegularExpression rgx(rep.left(rep.indexOf("->"))); ret.replace(rgx, rep.right(rep.size() - rep.indexOf("->") - 2)); } } @@ -279,7 +278,7 @@ int Api::forcedLimit() const { return contains("Urls/Limit") ? value("Urls/Limit").toInt() : 0; } int Api::maxLimit() const { - int forced = forcedLimit(); + const int forced = forcedLimit(); if (forced > 0) return forced; diff --git a/lib/src/models/api/api.h b/lib/src/models/api/api.h index b43e188a7..6979022b4 100644 --- a/lib/src/models/api/api.h +++ b/lib/src/models/api/api.h @@ -1,9 +1,6 @@ #ifndef API_H #define API_H -#include -#include -#include #include "models/image.h" #include "tags/tag.h" diff --git a/lib/src/models/api/html-api.cpp b/lib/src/models/api/html-api.cpp index 67f5df752..787ac0431 100644 --- a/lib/src/models/api/html-api.cpp +++ b/lib/src/models/api/html-api.cpp @@ -2,6 +2,7 @@ #include #include #include "functions.h" +#include "models/api/api.h" #include "models/site.h" #include "tags/tag-database.h" #include "vendor/json.h" @@ -29,7 +30,7 @@ ParsedPage HtmlApi::parsePage(Page *parentPage, const QString &source, int first int id = 0; while (matches.hasNext()) { - auto match = matches.next(); + const auto &match = matches.next(); QMap d = multiMatchToMap(match, rxImages.namedCaptureGroups()); // JSON elements @@ -74,14 +75,14 @@ ParsedPage HtmlApi::parsePage(Page *parentPage, const QString &source, int first { QRegularExpression rxlast(value("Regex/LastPage")); auto match = rxlast.match(source); - int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; + const int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; if (cnt > 0) { int pagesCount = cnt; if (value("Urls/Tags").contains("{pid}") || (contains("Urls/PagePart") && value("Urls/PagePart").contains("{pid}"))) { - int forced = forcedLimit(); - int ppid = forced > 0 ? forced : limit; + const int forced = forcedLimit(); + const int ppid = forced > 0 ? forced : limit; pagesCount = qFloor(static_cast(pagesCount) / static_cast(ppid)) + 1; } ret.pageCount = pagesCount; @@ -93,7 +94,7 @@ ParsedPage HtmlApi::parsePage(Page *parentPage, const QString &source, int first { QRegularExpression rxlast(value("Regex/Count")); auto match = rxlast.match(source); - int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; + const int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; if (cnt > 0) { ret.imageCount = cnt; } } diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index 79d1ea24f..7cb790dd1 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -1,6 +1,7 @@ #include "models/api/javascript-api.h" #include #include +#include #include #include "functions.h" #include "logger.h" @@ -42,7 +43,7 @@ void JavascriptApi::fillUrlObject(const QJSValue &result, Site *site, PageUrl &r // Script errors and exceptions if (result.isError()) { - QString err = QStringLiteral("Uncaught exception at line %1: %2").arg(result.property("lineNumber").toInt()).arg(result.toString()); + const QString err = QStringLiteral("Uncaught exception at line %1: %2").arg(result.property("lineNumber").toInt()).arg(result.toString()); ret.error = err; log(err, Logger::Error); return; @@ -100,7 +101,7 @@ PageUrl JavascriptApi::pageUrl(const QString &search, int page, int limit, int l const QStringList &authKeys = settings->childKeys(); for (const QString &key : authKeys) { - QString value = settings->value(key).toString(); + const QString value = settings->value(key).toString(); if (key == QLatin1String("pseudo") && !auth.hasProperty("login")) { auth.setProperty("login", value); } if (key == QLatin1String("password") && !auth.hasProperty("password_hash")) @@ -119,7 +120,7 @@ PageUrl JavascriptApi::pageUrl(const QString &search, int page, int limit, int l previous.setProperty("maxId", lastPageMaxId); } - QJSValue result = urlFunction.call(QList() << query << opts << previous); + const QJSValue result = urlFunction.call(QList() << query << opts << previous); fillUrlObject(result, site, ret); return ret; @@ -135,7 +136,7 @@ QList JavascriptApi::makeTags(const QJSValue &tags, Site *site) const { it.next(); - QJSValue tag = it.value(); + const QJSValue tag = it.value(); if (tag.isString()) { ret.append(Tag(tag.toString())); @@ -144,9 +145,9 @@ QList JavascriptApi::makeTags(const QJSValue &tags, Site *site) const else if (!tag.isObject()) { continue; } - int id = tag.hasProperty("id") && !tag.property("id").isUndefined() ? tag.property("id").toInt() : 0; - QString text = tag.property("name").toString(); - int count = tag.hasProperty("count") && !tag.property("count").isUndefined() ? tag.property("count").toInt() : 0; + const int id = tag.hasProperty("id") && !tag.property("id").isUndefined() ? tag.property("id").toInt() : 0; + const QString text = tag.property("name").toString(); + const int count = tag.hasProperty("count") && !tag.property("count").isUndefined() ? tag.property("count").toInt() : 0; QString type; int typeId; @@ -160,7 +161,7 @@ QList JavascriptApi::makeTags(const QJSValue &tags, Site *site) const if (tag.hasProperty("typeId") && !tag.property("typeId").isUndefined()) { typeId = tag.property("typeId").toInt(); } - TagType tagType = !type.isEmpty() ? TagType(type) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); + const TagType tagType = !type.isEmpty() ? TagType(type) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); ret.append(Tag(id, text, tagType, count)); } @@ -194,7 +195,7 @@ ParsedPage JavascriptApi::parsePage(Page *parentPage, const QString &source, int if (results.hasProperty("images")) { - QJSValue images = results.property("images"); + const QJSValue images = results.property("images"); QJSValueIterator it(images); while (it.hasNext()) { @@ -282,7 +283,7 @@ PageUrl JavascriptApi::tagsUrl(int page, int limit, Site *site) const const QStringList &authKeys = settings->childKeys(); for (const QString &key : authKeys) { - QString value = settings->value(key).toString(); + const QString value = settings->value(key).toString(); if (key == QLatin1String("pseudo") && !auth.hasProperty("login")) { auth.setProperty("login", value); } if (key == QLatin1String("password") && !auth.hasProperty("password_hash")) @@ -292,7 +293,7 @@ PageUrl JavascriptApi::tagsUrl(int page, int limit, Site *site) const settings->endGroup(); opts.setProperty("auth", auth); - QJSValue result = urlFunction.call(QList() << query << opts); + const QJSValue result = urlFunction.call(QList() << query << opts); fillUrlObject(result, site, ret); return ret; @@ -344,7 +345,7 @@ PageUrl JavascriptApi::detailsUrl(qulonglong id, const QString &md5, Site *site) return ret; } - QJSValue result = urlFunction.call(QList() << QString::number(id) << md5); + const QJSValue result = urlFunction.call(QList() << QString::number(id) << md5); fillUrlObject(result, site, ret); return ret; @@ -377,7 +378,7 @@ ParsedDetails JavascriptApi::parseDetails(const QString &source, Site *site) con if (results.hasProperty("pools")) { - QJSValue images = results.property("pools"); + const QJSValue images = results.property("pools"); QJSValueIterator it(images); while (it.hasNext()) { @@ -387,10 +388,10 @@ ParsedDetails JavascriptApi::parseDetails(const QString &source, Site *site) con if (!pool.isObject()) continue; - int id = pool.hasProperty("id") ? pool.property("id").toInt() : 0; - QString name = pool.property("name").toString(); - int next = pool.hasProperty("next") ? pool.property("next").toInt() : 0; - int previous = pool.hasProperty("previous") ? pool.property("previous").toInt() : 0; + const int id = pool.hasProperty("id") ? pool.property("id").toInt() : 0; + const QString name = pool.property("name").toString(); + const int next = pool.hasProperty("next") ? pool.property("next").toInt() : 0; + const int previous = pool.hasProperty("previous") ? pool.property("previous").toInt() : 0; ret.pools.append(Pool(id, name, 0, next, previous)); } @@ -421,7 +422,7 @@ PageUrl JavascriptApi::checkUrl() const return ret; } - QJSValue result = urlFunction.call(); + const QJSValue result = urlFunction.call(); fillUrlObject(result, Q_NULLPTR, ret); return ret; @@ -440,6 +441,7 @@ ParsedCheck JavascriptApi::parseCheck(const QString &source) const if (result.isError()) { ret.error = QStringLiteral("Uncaught exception at line %1: %2").arg(result.property("lineNumber").toInt()).arg(result.toString()); + ret.ok = false; return ret; } diff --git a/lib/src/models/api/javascript-api.h b/lib/src/models/api/javascript-api.h index 3667c4825..811a6d530 100644 --- a/lib/src/models/api/javascript-api.h +++ b/lib/src/models/api/javascript-api.h @@ -4,8 +4,10 @@ #include #include #include "models/api/api.h" +#include "tags/tag.h" +class Page; class Site; class JavascriptApi : public Api diff --git a/lib/src/models/api/javascript-console-helper.cpp b/lib/src/models/api/javascript-console-helper.cpp index 997991a24..aec2b9335 100644 --- a/lib/src/models/api/javascript-console-helper.cpp +++ b/lib/src/models/api/javascript-console-helper.cpp @@ -1,4 +1,5 @@ #include "models/api/javascript-console-helper.h" +#include #include "logger.h" diff --git a/lib/src/models/api/javascript-grabber-helper.cpp b/lib/src/models/api/javascript-grabber-helper.cpp index 8a8297fe3..84b697482 100644 --- a/lib/src/models/api/javascript-grabber-helper.cpp +++ b/lib/src/models/api/javascript-grabber-helper.cpp @@ -1,4 +1,6 @@ #include "models/api/javascript-grabber-helper.h" +#include +#include #include #include "logger.h" @@ -54,7 +56,7 @@ QJSValue JavascriptGrabberHelper::_parseXMLRec(const QDomNode &node) const { QJSValue obj = m_engine.newObject(); - auto type = node.nodeType(); + const auto type = node.nodeType(); // Element node if (type == QDomNode::ElementNode) diff --git a/lib/src/models/api/json-api.cpp b/lib/src/models/api/json-api.cpp index 82734ed69..6225788ee 100644 --- a/lib/src/models/api/json-api.cpp +++ b/lib/src/models/api/json-api.cpp @@ -1,3 +1,4 @@ +#include "models/api/api.h" #include "models/api/json-api.h" #include "models/page.h" #include "models/site.h" @@ -40,12 +41,11 @@ ParsedPage JsonApi::parsePage(Page *parentPage, const QString &source, int first for (int i = 0; i < postsKey.count() && sourc.isEmpty(); ++i) { sourc = data.value(postsKey[i]).toList(); } - QMap sc; for (int id = 0; id < sourc.count(); id++) { QList tags; - sc = sourc.at(id + first).toMap(); + QMap sc = sourc.at(id + first).toMap(); QMap d; if (sc.contains("tag_string")) { @@ -107,7 +107,7 @@ ParsedPage JsonApi::parsePage(Page *parentPage, const QString &source, int first for (const QVariant &variant : variants) { auto variantInfo = variant.toMap(); - int bitrate = variantInfo.value("bitrate").toInt(); + const int bitrate = variantInfo.value("bitrate").toInt(); if (bitrate > maxBitrate) { maxBitrate = bitrate; @@ -152,7 +152,7 @@ ParsedPage JsonApi::parsePage(Page *parentPage, const QString &source, int first QMap scTypes = sc["tags"].toMap(); for (auto it = scTypes.begin(); it != scTypes.end(); ++it) { - TagType tType(it.key()); + const TagType tType(it.key()); QList tagList = it.value().toList(); for (const QVariant &iTag : tagList) { tags.append(Tag(iTag.toString(), tType)); } @@ -244,7 +244,7 @@ ParsedTags JsonApi::parseTags(const QString &source, Site *site) const typeId = sc.value("type").toInt(); } - TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); + const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); ret.tags.append(Tag(id, name, tagType, count)); } diff --git a/lib/src/models/api/rss-api.cpp b/lib/src/models/api/rss-api.cpp index a936d56f4..64f83d690 100644 --- a/lib/src/models/api/rss-api.cpp +++ b/lib/src/models/api/rss-api.cpp @@ -1,6 +1,10 @@ #include "models/api/rss-api.h" +#include #include #include +#include +#include "models/api/api.h" +#include "models/page.h" RssApi::RssApi(const QMap &data) diff --git a/lib/src/models/api/xml-api.cpp b/lib/src/models/api/xml-api.cpp index 3a4a2dd4a..95dc975a7 100644 --- a/lib/src/models/api/xml-api.cpp +++ b/lib/src/models/api/xml-api.cpp @@ -1,5 +1,6 @@ #include "models/api/xml-api.h" #include +#include "models/api/api.h" #include "models/site.h" #include "tags/tag-database.h" @@ -27,7 +28,7 @@ ParsedPage XmlApi::parsePage(Page *parentPage, const QString &source, int first, // Getting last page int count = docElem.attributes().namedItem("count").nodeValue().toInt(); - QString database = docElem.attributes().namedItem("type").nodeValue(); + const QString database = docElem.attributes().namedItem("type").nodeValue(); if (count == 0 && database == QLatin1String("array")) { count = docElem.elementsByTagName("total-count").at(0).toElement().text().toInt(); } if (count > 0) @@ -72,7 +73,7 @@ ParsedPage XmlApi::parsePage(Page *parentPage, const QString &source, int first, for (int typeId = 0; typeId < tagTypes.count(); ++typeId) { QDomNode tagType = tagTypes.at(typeId); - TagType tType(tagType.nodeName()); + const TagType tType(tagType.nodeName()); QDomNodeList tagList = tagType.childNodes(); for (int iTag = 0; iTag < tagList.count(); ++iTag) { tags.append(Tag(tagList.at(iTag).toElement().text(), tType)); } @@ -152,7 +153,7 @@ ParsedTags XmlApi::parseTags(const QString &source, Site *site) const typeId = node.namedItem("type").toElement().text().toInt(); } - TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); + const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); ret.tags.append(Tag(id, name, tagType, count)); } diff --git a/lib/src/models/favorite.cpp b/lib/src/models/favorite.cpp index 989422e37..7d69ddfa7 100644 --- a/lib/src/models/favorite.cpp +++ b/lib/src/models/favorite.cpp @@ -1,5 +1,4 @@ #include "models/favorite.h" -#include #include #include "functions.h" @@ -65,9 +64,11 @@ Favorite Favorite::fromString(const QString &path, const QString &text) { QStringList xp = text.split("|"); - QString tag = xp.takeFirst(); - int note = xp.isEmpty() ? 50 : xp.takeFirst().toInt(); - QDateTime lastViewed = xp.isEmpty() ? QDateTime(QDate(2000, 1, 1), QTime(0, 0, 0, 0)) : QDateTime::fromString(xp.takeFirst(), Qt::ISODate); + const QString tag = xp.takeFirst(); + const int note = xp.isEmpty() ? 50 : xp.takeFirst().toInt(); + const QDateTime lastViewed = xp.isEmpty() + ? QDateTime(QDate(2000, 1, 1), QTime(0, 0, 0, 0)) + : QDateTime::fromString(xp.takeFirst(), Qt::ISODate); QString thumbPath = path + "/thumbs/" + (QString(tag).remove('\\').remove('/').remove(':').remove('*').remove('?').remove('"').remove('<').remove('>').remove('|')) + ".png"; if (!QFile::exists(thumbPath)) @@ -93,9 +94,9 @@ void Favorite::toJson(QJsonObject &json) const } Favorite Favorite::fromJson(const QString &path, const QJsonObject &json, const QMap &sites) { - QString tag = json["tag"].toString(); - int note = json["note"].toInt(); - QDateTime lastViewed = QDateTime::fromString(json["lastViewed"].toString(), Qt::ISODate); + const QString tag = json["tag"].toString(); + const int note = json["note"].toInt(); + const QDateTime lastViewed = QDateTime::fromString(json["lastViewed"].toString(), Qt::ISODate); QString thumbPath = path + "/thumbs/" + (QString(tag).remove('\\').remove('/').remove(':').remove('*').remove('?').remove('"').remove('<').remove('>').remove('|')) + ".png"; if (!QFile::exists(thumbPath)) diff --git a/lib/src/models/favorite.h b/lib/src/models/favorite.h index 7e3109dba..abe81826a 100644 --- a/lib/src/models/favorite.h +++ b/lib/src/models/favorite.h @@ -1,8 +1,6 @@ #ifndef FAVORITE_H #define FAVORITE_H -#include -#include #include #include #include "models/monitor.h" diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index e57a9b901..7ffb98e9e 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -5,11 +5,11 @@ #include #include #include "functions.h" -#include "post-filter.h" #include "models/api/api.h" #include "models/image.h" #include "models/profile.h" #include "models/site.h" +#include "post-filter.h" Filename::Filename(const QString &format) @@ -40,14 +40,14 @@ QString Filename::expandConditionals(const QString &text, const QStringList &tag matches = reg.globalMatch(text); while (matches.hasNext()) { - auto match = matches.next(); - bool ignore = !match.captured(1).isEmpty(); - bool invert = !match.captured(2).isEmpty(); - QString fullToken = match.captured(3); - QString token = match.captured(4); + const auto match = matches.next(); + const bool ignore = !match.captured(1).isEmpty(); + const bool invert = !match.captured(2).isEmpty(); + const QString &fullToken = match.captured(3); + const QString &token = match.captured(4); if ((tokens.contains(token) && !isVariantEmpty(tokens[token].value())) == !invert) { - QString rep = ignore || invert ? QString() : fullToken; + const QString &rep = ignore || invert ? QString() : fullToken; ret.replace(match.captured(0), rep); } else @@ -59,13 +59,13 @@ QString Filename::expandConditionals(const QString &text, const QStringList &tag matches = reg.globalMatch(text); while (matches.hasNext()) { - auto match = matches.next(); - bool ignore = !match.captured(1).isEmpty(); - bool invert = !match.captured(2).isEmpty(); - QString tag = match.captured(3); + const auto match = matches.next(); + const bool ignore = !match.captured(1).isEmpty(); + const bool invert = !match.captured(2).isEmpty(); + const QString &tag = match.captured(3); if (tags.contains(tag, Qt::CaseInsensitive) == !invert) { - QString rep = ignore ? QString() : this->cleanUpValue(tag, QMap(), settings); + const QString &rep = ignore ? QString() : this->cleanUpValue(tag, QMap(), settings); ret.replace(match.captured(0), rep); } else @@ -96,7 +96,7 @@ QList Filename::getReplace(const QString &key, const Token &token, QSetti { ret.append(Token(settings->value(key + "_empty", token.emptyDefault()).toString())); } else if (value.size() > settings->value(key + "_multiple_limit", 1).toInt()) { - QString whatToDo = settings->value(key + "_multiple", token.whatToDoDefault()).toString(); + const QString &whatToDo = settings->value(key + "_multiple", token.whatToDoDefault()).toString(); if (whatToDo == QLatin1String("keepAll")) { ret.append(Token(value)); } else if (whatToDo == QLatin1String("multiple")) @@ -107,12 +107,12 @@ QList Filename::getReplace(const QString &key, const Token &token, QSetti } else if (whatToDo == QLatin1String("keepN")) { - int keepN = settings->value(key + "_multiple_keepN", 1).toInt(); + const int keepN = settings->value(key + "_multiple_keepN", 1).toInt(); ret.append(Token(QStringList(value.mid(0, qMax(1, keepN))))); } else if (whatToDo == QLatin1String("keepNThenAdd")) { - int keepN = settings->value(key + "_multiple_keepNThenAdd_keep", 1).toInt(); + const int keepN = settings->value(key + "_multiple_keepNThenAdd_keep", 1).toInt(); QString thenAdd = settings->value(key + "_multiple_keepNThenAdd_add", " (+ %count%)").toString(); thenAdd.replace("%total%", QString::number(value.size())); thenAdd.replace("%count%", QString::number(value.size() - keepN)); @@ -148,8 +148,8 @@ void Filename::setJavaScriptVariables(QJSEngine &engine, QSettings *settings, co if (val.type() == QVariant::StringList) { QStringList vals = val.toStringList(); - QString mainSeparator = settings->value("Save/separator", " ").toString(); - QString tagSeparator = fixSeparator(settings->value("Save/" + key + "_sep", mainSeparator).toString()); + const QString mainSeparator = settings->value("Save/separator", " ").toString(); + const QString tagSeparator = fixSeparator(settings->value("Save/" + key + "_sep", mainSeparator).toString()); if (key != "all" && key != "tags") { obj.setProperty(key + "s", engine.toScriptValue(vals)); } @@ -194,8 +194,8 @@ bool Filename::matchConditionalFilename(QString cond, QSettings *settings, const return result.toBool(); } - QStringList options = cond.split(' '); - QStringList matches = PostFilter::filter(tokens, options); + const QStringList options = cond.split(' '); + const QStringList matches = PostFilter::filter(tokens, options); return matches.isEmpty(); } @@ -205,20 +205,20 @@ QList> Filename::expandTokens(const QString &filename, QMap QList> ret; ret.append(tokens); - bool isJavascript = filename.startsWith(QLatin1String("javascript:")); + const bool isJavascript = filename.startsWith(QLatin1String("javascript:")); for (const QString &key : tokens.keys()) { const Token &token = tokens[key]; if (token.value().type() != QVariant::StringList) continue; - bool hasToken = !isJavascript && filename.contains(QRegularExpression("%"+key+"(?::[^%]+)?%")); - bool hasVar = isJavascript && filename.contains(key); + const bool hasToken = !isJavascript && filename.contains(QRegularExpression("%"+key+"(?::[^%]+)?%")); + const bool hasVar = isJavascript && filename.contains(key); if (!hasToken && !hasVar) continue; QList reps = getReplace(key, token, settings); - int cnt = ret.count(); + const int cnt = ret.count(); for (int i = 0; i < cnt; ++i) { ret[i].insert(key, reps[0]); @@ -303,7 +303,7 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin QString cFilename = QString(filename); QString hasNum; QString numOptions; - QStringList namespaces = replaces["all_namespaces"].value().toStringList(); + const QStringList namespaces = replaces["all_namespaces"].value().toStringList(); // Conditionals if (complex) @@ -315,13 +315,13 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin int p = 0; while ((p = replacerx.indexIn(cFilename, p)) != -1) { - QString key = replacerx.cap(1); - QString options = replacerx.captureCount() > 1 ? replacerx.cap(2) : QString(); + const QString &key = replacerx.cap(1); + const QString &options = replacerx.captureCount() > 1 ? replacerx.cap(2) : QString(); if (replaces.contains(key)) { - QVariant val = replaces[key].value(); - QString res = optionedValue(val, key, options, settings, namespaces); + const QVariant &val = replaces[key].value(); + const QString &res = optionedValue(val, key, options, settings, namespaces); cFilename.replace(replacerx.cap(0), res); p += res.length(); } @@ -343,7 +343,7 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin if (!hasNum.isEmpty()) { - int mid = QDir::toNativeSeparators(cFilename).lastIndexOf(QDir::separator()); + const int mid = QDir::toNativeSeparators(cFilename).lastIndexOf(QDir::separator()); QDir dir(folder + (mid >= 0 ? QDir::separator() + cFilename.left(mid) : QString())); QString cRight = mid >= 0 ? cFilename.right(cFilename.length() - mid - 1) : cFilename; QString filter = QString(cRight).replace(hasNum, "*"); @@ -380,7 +380,7 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin fns[i].replace(QRegularExpression(" */ *"), "/"); // Max filename size option - int limit = !maxLength ? 0 : settings->value("Save/limit").toInt(); + const int limit = !maxLength ? 0 : settings->value("Save/limit").toInt(); fns[i] = fixFilename(fns[i], folder, limit); } @@ -394,7 +394,7 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin fns[i] = QDir::toNativeSeparators(fns[i]); // We remove empty directory names - QChar sep = QDir::separator(); + const QChar sep = QDir::separator(); fns[i].replace(QRegularExpression("(.)" + QRegularExpression::escape(sep) + "{2,}"), QString("\\1") + sep); } } @@ -443,7 +443,7 @@ QString Filename::optionedValue(const QVariant &val, const QString &key, const Q // Type-specific options if (val.type() == QVariant::DateTime) { - QString format = options.value("format", QObject::tr("MM-dd-yyyy HH.mm")); + const QString format = options.value("format", QObject::tr("MM-dd-yyyy HH.mm")); res = val.toDateTime().toString(format); } else if (val.type() == QVariant::Int) diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index d016d0f2d..7995a28a9 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -1,9 +1,13 @@ +#include #include +#include +#include #include #include "commands/commands.h" #include "downloader/extension-rotator.h" -#include "downloader/file-downloader.h" +#include "favorite.h" #include "functions.h" +#include "loader/token.h" #include "models/api/api.h" #include "models/filename.h" #include "models/image.h" @@ -11,9 +15,9 @@ #include "models/post-filter.h" #include "models/profile.h" #include "models/site.h" -#include "models/source.h" #include "tags/tag-database.h" #include "tags/tag-stylist.h" +#include "tags/tag-type.h" #define MAX_LOAD_FILESIZE (1024*1024*50) @@ -144,11 +148,11 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* QStringList types = QStringList() << "general" << "artist" << "character" << "copyright" << "model" << "species" << "meta"; for (const QString &typ : types) { - QString key = "tags_" + typ; + const QString key = "tags_" + typ; if (!details.contains(key)) continue; - TagType ttype(typ); + const TagType ttype(typ); QStringList t = details[key].split(' ', QString::SkipEmptyParts); for (QString tg : t) { @@ -161,8 +165,8 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* QString tgs = QString(details["tags"]).replace(QRegularExpression("[\r\n\t]+"), " "); // Automatically find tag separator and split the list - int commas = tgs.count(", "); - int spaces = tgs.count(" "); + const int commas = tgs.count(", "); + const int spaces = tgs.count(" "); const QStringList &t = commas >= 10 || (commas > 0 && (spaces - commas) / commas < 2) ? tgs.split(", ", QString::SkipEmptyParts) : tgs.split(" ", QString::SkipEmptyParts); @@ -171,10 +175,10 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* { tg.replace("&", "&"); - int colon = tg.indexOf(':'); + const int colon = tg.indexOf(':'); if (colon != -1) { - QString tp = tg.left(colon).toLower(); + const QString tp = tg.left(colon).toLower(); if (tp == "user") { m_author = tg.mid(colon + 1); } else if (tp == "score") @@ -208,21 +212,21 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* // Get file url and try to improve it to save bandwidth m_url = m_fileUrl.toString(); - QString ext = getExtension(m_url); + const QString ext = getExtension(m_url); if (details.contains("ext") && !details["ext"].isEmpty()) { - QString realExt = details["ext"]; + const QString realExt = details["ext"]; if (ext != realExt) { setFileExtension(realExt); } } else if (ext == QLatin1String("jpg") && !m_previewUrl.isEmpty()) { bool fixed = false; - QString previewExt = getExtension(details["preview_url"]); + const QString previewExt = getExtension(details["preview_url"]); if (!m_sampleUrl.isEmpty()) { // Guess extension from sample url - QString sampleExt = getExtension(details["sample_url"]); + const QString sampleExt = getExtension(details["sample_url"]); if (sampleExt != QLatin1String("jpg") && sampleExt != QLatin1String("png") && sampleExt != ext && previewExt == ext) { m_url = setExtension(m_url, sampleExt); @@ -255,7 +259,7 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* m_previewUrl = removeCacheUrl(m_previewUrl.toString()); // We use the sample URL as the URL for zip files (ugoira) or if the setting is set - bool downloadOriginals = m_settings->value("Save/downloadoriginals", true).toBool(); + const bool downloadOriginals = m_settings->value("Save/downloadoriginals", true).toBool(); if (!m_sampleUrl.isEmpty() && (getExtension(m_url) == "zip" || !downloadOriginals)) m_url = m_sampleUrl.toString(); @@ -267,8 +271,8 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* { m_createdAt = QDateTime::fromString(details["date"], Qt::ISODate); } // Setup extension rotator - bool animated = hasTag("gif") || hasTag("animated_gif") || hasTag("mp4") || hasTag("animated_png") || hasTag("webm") || hasTag("animated"); - QStringList extensions = animated + const bool animated = hasTag("gif") || hasTag("animated_gif") || hasTag("mp4") || hasTag("animated_png") || hasTag("webm") || hasTag("animated"); + const QStringList extensions = animated ? QStringList() << "webm" << "mp4" << "gif" << "jpg" << "png" << "jpeg" << "swf" : QStringList() << "jpg" << "png" << "gif" << "jpeg" << "webm" << "swf" << "mp4"; m_extensionRotator = new ExtensionRotator(getExtension(m_url), extensions, this); @@ -337,7 +341,7 @@ void Image::parseDetails() return; } - int statusCode = m_loadDetails->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + const int statusCode = m_loadDetails->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode == 429) { log(QStringLiteral("Details limit reached (429). New try.")); @@ -345,7 +349,7 @@ void Image::parseDetails() return; } - QString source = QString::fromUtf8(m_loadDetails->readAll()); + const QString source = QString::fromUtf8(m_loadDetails->readAll()); // Get an api able to parse details Api *api = m_parentSite->detailsApi(); @@ -372,7 +376,7 @@ void Image::parseDetails() // Image url if (!ret.imageUrl.isEmpty()) { - QString before = m_url; + const QString before = m_url; QUrl newUrl = m_parentSite->fixUrl(ret.imageUrl, before); m_url = newUrl.toString(); @@ -513,11 +517,11 @@ void Image::finishedImageS(bool inMemory) if (m_loadImage->error() == QNetworkReply::ContentNotFoundError) { - bool sampleFallback = m_settings->value("Save/samplefallback", true).toBool(); + const bool sampleFallback = m_settings->value("Save/samplefallback", true).toBool(); QString newext = m_extensionRotator != nullptr ? m_extensionRotator->next() : ""; - bool shouldFallback = sampleFallback && !m_sampleUrl.isEmpty(); - bool isLast = newext.isEmpty() || (shouldFallback && m_tryingSample); + const bool shouldFallback = sampleFallback && !m_sampleUrl.isEmpty(); + const bool isLast = newext.isEmpty() || (shouldFallback && m_tryingSample); if (!isLast || (shouldFallback && !m_tryingSample)) { @@ -549,8 +553,8 @@ void Image::finishedImageS(bool inMemory) { m_fileSize = m_data.size(); } } - QNetworkReply::NetworkError error = m_loadImage->error(); - QString errorString = m_loadImage->errorString(); + const QNetworkReply::NetworkError error = m_loadImage->error(); + const QString errorString = m_loadImage->errorString(); m_loadedImage = (error == QNetworkReply::ContentNotFoundError || error == QNetworkReply::NoError); m_loadImageError = error; @@ -635,16 +639,16 @@ Image::SaveResult Image::save(const QString &path, bool force, bool basic, bool QFile f(path); if (!f.exists() || force) { - QPair md5action = m_profile->md5Action(md5()); - QString whatToDo = md5action.first; - QString md5Duplicate = md5action.second; + const QPair md5action = m_profile->md5Action(md5()); + const QString &whatToDo = md5action.first; + const QString &md5Duplicate = md5action.second; // Only create the destination directory if we're going to put a file there if (md5Duplicate.isEmpty() || force || whatToDo != "ignore") { - QString p = path.section(QDir::separator(), 0, -2); - QDir path_to_file(p), dir; - if (!path_to_file.exists() && !dir.mkpath(p)) + const QString p = path.section(QDir::separator(), 0, -2); + QDir pathToFile(p), dir; + if (!pathToFile.exists() && !dir.mkpath(p)) { log(QStringLiteral("Impossible to create the destination folder: %1.").arg(p), Logger::Error); return SaveResult::Error; @@ -724,11 +728,11 @@ void Image::postSaving(const QString &path, bool addMd5, bool startCommands, int for (auto it = logFiles.begin(); it != logFiles.end(); ++it) { auto logFile = it.value(); - QString textfileFormat = logFile["content"].toString(); + const QString textfileFormat = logFile["content"].toString(); QStringList cont = this->path(textfileFormat, "", count, true, true, false, false, false); if (!cont.isEmpty()) { - int locationType = logFile["locationType"].toInt(); + const int locationType = logFile["locationType"].toInt(); QString contents = cont.first(); // File path @@ -746,7 +750,7 @@ void Image::postSaving(const QString &path, bool addMd5, bool startCommands, int // Append to file if necessary QFile fileTags(fileTagsPath); - bool append = fileTags.exists(); + const bool append = fileTags.exists(); if (fileTags.open(QFile::WriteOnly | QFile::Append | QFile::Text)) { if (append) @@ -785,7 +789,7 @@ QMap Image::save(const QStringList &paths, bool addM } QMap Image::save(const QString &filename, const QString &path, bool addMd5, bool startCommands, int count) { - QStringList paths = this->path(filename, path, count, true, false, true, true, true); + const QStringList paths = this->path(filename, path, count, true, false, true, true, true); return save(paths, addMd5, startCommands, count, false); } @@ -847,8 +851,8 @@ void Image::setSavePath(const QString &path) bool Image::shouldDisplaySample() const { - bool getOriginals = m_settings->value("Save/downloadoriginals", true).toBool(); - bool viewSample = m_settings->value("Zoom/viewSamples", false).toBool(); + const bool getOriginals = m_settings->value("Save/downloadoriginals", true).toBool(); + const bool viewSample = m_settings->value("Zoom/viewSamples", false).toBool(); return !m_sampleUrl.isEmpty() && (!getOriginals || viewSample); } @@ -878,11 +882,11 @@ void Image::setData(const QByteArray &d) m_data = d; // Detect file extension from data headers - bool headerDetection = m_settings->value("Save/headerDetection", true).toBool(); + const bool headerDetection = m_settings->value("Save/headerDetection", true).toBool(); if (headerDetection) { QString ext = getExtensionFromHeader(m_data.left(12)); - QString currentExt = getExtension(m_url); + const QString currentExt = getExtension(m_url); if (!ext.isEmpty() && ext != currentExt) { log(QStringLiteral("Setting image extension from header: '%1' (was '%2').").arg(ext, currentExt), Logger::Info); @@ -941,7 +945,7 @@ QString Image::tooltip() const .arg(m_name.isEmpty() ? " " : tr("Name: %1
").arg(m_name)); double size = m_fileSize; - QString unit = getUnit(&size); + const QString unit = getUnit(&size); return QStringLiteral("%1%2%3%4%5%6%7%8") .arg(m_tags.isEmpty() ? " " : tr("Tags: %1

").arg(stylishedTags(m_profile).join(" "))) @@ -956,9 +960,9 @@ QString Image::tooltip() const QList Image::detailsData() const { - QString unknown = tr("Unknown"); - QString yes = tr("yes"); - QString no = tr("no"); + const QString unknown = tr("Unknown"); + const QString yes = tr("yes"); + const QString no = tr("no"); return { QStrP(tr("Tags"), stylishedTags(m_profile).join(' ')), @@ -1066,7 +1070,7 @@ void Image::setFileExtension(const QString &ext) bool Image::isVideo() const { - QString ext = getExtension(m_url).toLower(); + const QString ext = getExtension(m_url).toLower(); return ext == "mp4" || ext == "webm"; } QString Image::isAnimated() const @@ -1113,7 +1117,7 @@ QMap Image::generateTokens(Profile *profile) const { QSettings *settings = profile->getSettings(); QStringList ignore = profile->getIgnored(); - QStringList remove = settings->value("ignoredtags").toString().split(' ', QString::SkipEmptyParts); + const QStringList remove = settings->value("ignoredtags").toString().split(' ', QString::SkipEmptyParts); QMap tokens; @@ -1160,7 +1164,7 @@ QMap Image::generateTokens(Profile *profile) const QMap details; for (const Tag &tag : filteredTags(remove)) { - QString t = tag.text(); + const QString t = tag.text(); details[ignore.contains(t, Qt::CaseInsensitive) ? "general" : tag.type().name()].append(t); details["alls"].append(t); @@ -1225,7 +1229,7 @@ Image::SaveResult Image::preSave(const QString &path) void Image::postSave(QMap result, bool addMd5, bool startCommands, int count) { const QString &path = result.firstKey(); - Image::SaveResult res = result[path]; + const Image::SaveResult res = result[path]; postSaving(path, addMd5 && res == SaveResult::Saved, startCommands, count); } diff --git a/lib/src/models/monitor.cpp b/lib/src/models/monitor.cpp index 9aece3976..c7ba473d3 100644 --- a/lib/src/models/monitor.cpp +++ b/lib/src/models/monitor.cpp @@ -1,4 +1,5 @@ #include "models/monitor.h" +#include #include "models/site.h" @@ -60,10 +61,10 @@ void Monitor::toJson(QJsonObject &json) const Monitor Monitor::fromJson(const QJsonObject &json, const QMap &sites) { Site *site = sites.value(json["site"].toString()); - int interval = json["interval"].toInt(); - QDateTime lastCheck = QDateTime::fromString(json["lastCheck"].toString(), Qt::ISODate); - int cumulated = json["cumulated"].toInt(); - bool preciseCumulated = json["preciseCumulated"].toBool(); + const int interval = json["interval"].toInt(); + const QDateTime lastCheck = QDateTime::fromString(json["lastCheck"].toString(), Qt::ISODate); + const int cumulated = json["cumulated"].toInt(); + const bool preciseCumulated = json["preciseCumulated"].toBool(); return Monitor(site, interval, lastCheck, cumulated, preciseCumulated); } diff --git a/lib/src/models/monitor.h b/lib/src/models/monitor.h index 42f56f1b6..a436934e1 100644 --- a/lib/src/models/monitor.h +++ b/lib/src/models/monitor.h @@ -3,7 +3,6 @@ #include #include -#include class Site; diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 7dc4082a1..03a426c26 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -1,16 +1,17 @@ #include "models/page-api.h" -#include +#include #include #include #include #include "functions.h" +#include "image.h" #include "logger.h" #include "models/api/api.h" #include "models/page.h" #include "models/post-filter.h" #include "models/profile.h" #include "models/site.h" -#include "vendor/json.h" +#include "tags/tag.h" PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, const QStringList &tags, int page, int limit, const QStringList &postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) @@ -46,7 +47,7 @@ void PageApi::setLastPage(Page *page) void PageApi::updateUrls() { QString url; - QString search = m_search.join(" "); + QString search = m_search.join(' '); m_errors.clear(); // URL searches @@ -138,10 +139,10 @@ void PageApi::parse() log(QStringLiteral("[%1][%2] Redirecting page %3 to %4").arg(m_site->url(), m_format, m_url.toString().toHtmlEscaped(), newUrl.toString().toHtmlEscaped()), Logger::Info); // HTTP -> HTTPS redirects - bool ssl = m_site->setting("ssl", false).toBool(); + const bool ssl = m_site->setting("ssl", false).toBool(); if (!ssl && newUrl.path() == m_url.path() && newUrl.scheme() == "https" && m_url.scheme() == "http") { - bool notThisSite = m_site->setting("ssl_never_correct", false).toBool(); + const bool notThisSite = m_site->setting("ssl_never_correct", false).toBool(); if (!notThisSite) { emit httpsRedirect(); } } @@ -152,7 +153,7 @@ void PageApi::parse() } // Detect HTTP 429 usage limit reached - int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + const int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode == 429) { log(QStringLiteral("[%1][%2] Limit reached (429). New try.").arg(m_site->url(), m_format), Logger::Warning); @@ -178,7 +179,7 @@ void PageApi::parseActual() return; } - int first = m_smart && m_blim > 0 ? ((m_page - 1) * m_imagesPerPage) % m_blim : 0; + const int first = m_smart && m_blim > 0 ? ((m_page - 1) * m_imagesPerPage) % m_blim : 0; // Parse source ParsedPage page = m_api->parsePage(m_parentPage, m_source, first, m_imagesPerPage); @@ -320,8 +321,8 @@ int PageApi::imagesCount(bool guess) const if (m_imagesCount < 0 && m_pagesCount >= 0) { - int forcedLimit = m_api->forcedLimit(); - int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; + const int forcedLimit = m_api->forcedLimit(); + const int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; return m_pagesCount * perPage; } @@ -338,8 +339,8 @@ int PageApi::pagesCount(bool guess) const if (m_pagesCount < 0 && m_imagesCount >= 0) { - int forcedLimit = m_api->forcedLimit(); - int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; + const int forcedLimit = m_api->forcedLimit(); + const int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; return qCeil(static_cast(m_imagesCount) / perPage); } @@ -372,8 +373,8 @@ void PageApi::setImageCount(int count, bool sure) if (sure) { - int forcedLimit = m_api->forcedLimit(); - int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; + const int forcedLimit = m_api->forcedLimit(); + const int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; setPageCount(qCeil(static_cast(count) / perPage), true); } } @@ -388,8 +389,8 @@ void PageApi::setPageCount(int count, bool sure) if (sure) { - int forcedLimit = m_api->forcedLimit(); - int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; + const int forcedLimit = m_api->forcedLimit(); + const int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; setImageCount(count * perPage, false); } } diff --git a/lib/src/models/page-api.h b/lib/src/models/page-api.h index 3c6bb7c4e..026b3c096 100644 --- a/lib/src/models/page-api.h +++ b/lib/src/models/page-api.h @@ -1,8 +1,6 @@ #ifndef PAGE_API_H #define PAGE_API_H -#include -#include #include "models/image.h" #include "tags/tag.h" diff --git a/lib/src/models/page.cpp b/lib/src/models/page.cpp index 74608f42a..3d33585b2 100644 --- a/lib/src/models/page.cpp +++ b/lib/src/models/page.cpp @@ -1,9 +1,9 @@ #include "models/page.h" +#include #include "functions.h" #include "logger.h" #include "models/api/api.h" #include "models/site.h" -#include "vendor/json.h" Page::Page(Profile *profile, Site *site, const QList &sites, QStringList tags, int page, int limit, const QStringList &postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) @@ -183,7 +183,7 @@ int Page::imagesCount(bool guess) const { if (m_regexApi >= 0 && !m_pageApis[m_currentApi]->isImageCountSure()) { - int count = m_pageApis[m_regexApi]->imagesCount(guess); + const int count = m_pageApis[m_regexApi]->imagesCount(guess); if (count >= 0) return count; } @@ -193,7 +193,7 @@ int Page::pagesCount(bool guess) const { if (m_regexApi >= 0 && !m_pageApis[m_currentApi]->isPageCountSure()) { - int count = m_pageApis[m_regexApi]->pagesCount(guess); + const int count = m_pageApis[m_regexApi]->pagesCount(guess); if (count >= 0) return count; } diff --git a/lib/src/models/pool.cpp b/lib/src/models/pool.cpp index 511adf880..944a3d29b 100644 --- a/lib/src/models/pool.cpp +++ b/lib/src/models/pool.cpp @@ -1,12 +1,13 @@ #include "pool.h" +#include Pool::Pool(int id, const QString &name, int current, int next, int previous) : m_id(id), m_name(name), m_current(current), m_next(next), m_previous(previous) { } -int Pool::id() const { return m_id; } -QString Pool::name() const { return m_name; } -int Pool::current() const { return m_current; } -int Pool::next() const { return m_next; } -int Pool::previous() const { return m_previous; } +int Pool::id() const { return m_id; } +const QString &Pool::name() const { return m_name; } +int Pool::current() const { return m_current; } +int Pool::next() const { return m_next; } +int Pool::previous() const { return m_previous; } diff --git a/lib/src/models/pool.h b/lib/src/models/pool.h index a388b1c39..c172841a8 100644 --- a/lib/src/models/pool.h +++ b/lib/src/models/pool.h @@ -10,18 +10,18 @@ class Pool explicit Pool(int id, const QString &name, int current, int next = 0, int previous = 0); // Getters - int id() const; - QString name() const; - int current() const; - int next() const; - int previous() const; + int id() const; + const QString &name() const; + int current() const; + int next() const; + int previous() const; private: - int m_id; - QString m_name; - int m_current; - int m_next; - int m_previous; + int m_id; + QString m_name; + int m_current; + int m_next; + int m_previous; }; #endif // POOL_H diff --git a/lib/src/models/post-filter.cpp b/lib/src/models/post-filter.cpp index d1fe6f158..3d1555cda 100644 --- a/lib/src/models/post-filter.cpp +++ b/lib/src/models/post-filter.cpp @@ -1,6 +1,4 @@ #include "post-filter.h" -#include -#include #include "functions.h" #include "loader/token.h" @@ -28,8 +26,8 @@ QString PostFilter::match(const QMap &tokens, QString filter, bo // Tokens if (filter.startsWith('%') && filter.endsWith('%')) { - QString key = filter.mid(1, filter.length() - 2); - bool cond = tokens.contains(key) && !isVariantEmpty(tokens[key].value()); + const QString key = filter.mid(1, filter.length() - 2); + const bool cond = tokens.contains(key) && !isVariantEmpty(tokens[key].value()); if (cond && invert) { return QObject::tr("image has a \"%1\" token").arg(key); } @@ -40,7 +38,7 @@ QString PostFilter::match(const QMap &tokens, QString filter, bo // Meta-tags else if (filter.contains(":")) { - QString type = filter.section(':', 0, 0).toLower(); + const QString type = filter.section(':', 0, 0).toLower(); filter = filter.section(':', 1).toLower(); if (!tokens.contains(type)) { @@ -48,7 +46,7 @@ QString PostFilter::match(const QMap &tokens, QString filter, bo return QObject::tr("unknown type \"%1\" (available types: \"%2\")").arg(type, keys.join("\", \"")); } - QVariant token = tokens[type].value(); + const QVariant &token = tokens[type].value(); if (token.type() == QVariant::Int || token.type() == QVariant::DateTime || token.type() == QVariant::ULongLong) { int input = 0; @@ -112,7 +110,7 @@ QString PostFilter::match(const QMap &tokens, QString filter, bo if (assoc.contains(filter)) filter = assoc[filter]; - bool cond = !filter.isEmpty() && token.toString().toLower().startsWith(filter.at(0)); + const bool cond = !filter.isEmpty() && token.toString().toLower().startsWith(filter.at(0)); if (!cond && !invert) { return QObject::tr("image is not \"%1\"").arg(filter); } if (cond && invert) @@ -121,7 +119,7 @@ QString PostFilter::match(const QMap &tokens, QString filter, bo else if (type == "source") { QRegExp rx(filter + "*", Qt::CaseInsensitive, QRegExp::Wildcard); - bool cond = rx.exactMatch(token.toString()); + const bool cond = rx.exactMatch(token.toString()); if (!cond && !invert) { return QObject::tr("image's source does not starts with \"%1\"").arg(filter); } if (cond && invert) @@ -129,9 +127,9 @@ QString PostFilter::match(const QMap &tokens, QString filter, bo } else { - QString input = token.toString(); + const QString input = token.toString(); - bool cond = input == filter; + const bool cond = input == filter; if (!cond && !invert) { return QObject::tr("image's %1 does not match").arg(type); } diff --git a/lib/src/models/post-filter.h b/lib/src/models/post-filter.h index 282d88b0a..516725a70 100644 --- a/lib/src/models/post-filter.h +++ b/lib/src/models/post-filter.h @@ -1,8 +1,6 @@ #ifndef POST_FILTER_H #define POST_FILTER_H -#include -#include #include diff --git a/lib/src/models/profile.cpp b/lib/src/models/profile.cpp index 146818ecf..727c6a0b2 100644 --- a/lib/src/models/profile.cpp +++ b/lib/src/models/profile.cpp @@ -1,9 +1,8 @@ #include "models/profile.h" -#include -#include #include #include #include +#include #include "commands/commands.h" #include "functions.h" #include "models/site.h" @@ -43,7 +42,7 @@ Profile::Profile(const QString &path) QFile fileFavoritesJson(m_path + "/favorites.json"); if (fileFavoritesJson.open(QFile::ReadOnly | QFile::Text)) { - QByteArray data = fileFavoritesJson.readAll(); + const QByteArray data = fileFavoritesJson.readAll(); QJsonDocument loadDoc = QJsonDocument::fromJson(data); QJsonObject object = loadDoc.object(); @@ -257,8 +256,8 @@ void Profile::syncIgnored() QString Profile::tempPath() const { - QString tmp = QDir::tempPath(); - QString subDir = "Grabber"; + const QString tmp = QDir::tempPath(); + const QString subDir = "Grabber"; QDir(tmp).mkpath(subDir); return tmp + QDir::separator() + subDir; } @@ -322,11 +321,11 @@ void Profile::removeIgnored(const QString &tag) QPair Profile::md5Action(const QString &md5) { QString action = m_settings->value("Save/md5Duplicates", "save").toString(); - bool keepDeleted = m_settings->value("Save/keepDeletedMd5", false).toBool(); + const bool keepDeleted = m_settings->value("Save/keepDeletedMd5", false).toBool(); - bool contains = !md5.isEmpty() && m_md5s.contains(md5); + const bool contains = !md5.isEmpty() && m_md5s.contains(md5); QString path = contains ? m_md5s[md5] : QString(); - bool exists = contains && QFile::exists(path); + const bool exists = contains && QFile::exists(path); if (contains && !exists) { diff --git a/lib/src/models/profile.h b/lib/src/models/profile.h index 00a0ef85a..f2c53173c 100644 --- a/lib/src/models/profile.h +++ b/lib/src/models/profile.h @@ -1,9 +1,6 @@ #ifndef PROFILE_H #define PROFILE_H -#include -#include -#include #include #include #include "models/favorite.h" diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index 8be8a3a3a..4f8ced906 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -1,12 +1,9 @@ #include "models/site.h" -#include -#include #include #include #include #include #include -#include #include "custom-network-access-manager.h" #include "functions.h" #include "logger.h" @@ -54,7 +51,7 @@ Site::Site(const QString &url, Source *source) void Site::loadConfig() { - QString siteDir = m_source->getPath() + "/" + m_url + "/"; + const QString siteDir = m_source->getPath() + "/" + m_url + "/"; if (m_settings != nullptr) m_settings->deleteLater(); @@ -80,7 +77,7 @@ void Site::loadConfig() { for (int i = 0; i < 4; ++i) { - QString def = defaults.count() > i ? defaults[i] : QString(); + const QString def = defaults.count() > i ? defaults[i] : QString(); sources << m_settings->value("sources/source_" + QString::number(i + 1), def).toString(); } sources.removeAll(""); @@ -102,7 +99,7 @@ void Site::loadConfig() } // Auth information - QString type = m_settings->value("login/type", "url").toString(); + const QString type = m_settings->value("login/type", "url").toString(); if (type == "url") m_login = new UrlLogin(this, m_manager, m_settings); else if (type == "oauth2") @@ -208,7 +205,7 @@ bool Site::canTestLogin() const */ void Site::loginFinished(Login::Result result) { - bool ok = result == Login::Result::Success; + const bool ok = result == Login::Result::Success; m_loggedIn = ok ? LoginStatus::LoggedIn : LoginStatus::LoggedOut; log(QStringLiteral("[%1] Login finished: %2.").arg(m_url, ok ? "success" : "failure")); @@ -276,8 +273,8 @@ void Site::getAsync(QueryType type, const QUrl &url, const std::functionmakeRequest(url, page, ref, img); + const QNetworkRequest request = this->makeRequest(url, page, ref, img); return this->getRequest(request); } @@ -307,14 +304,14 @@ QNetworkReply *Site::getRequest(const QNetworkRequest &request) void Site::loadTags(int page, int limit) { - QString protocol = (m_settings->value("ssl", false).toBool() ? QStringLiteral("https") : QStringLiteral("http")); + const QString protocol = (m_settings->value("ssl", false).toBool() ? QStringLiteral("https") : QStringLiteral("http")); m_tagsReply = get(QUrl(protocol + "://"+m_url+"/tags.json?search[hide_empty]=yes&limit="+QString::number(limit)+"&page=" + QString::number(page))); connect(m_tagsReply, &QNetworkReply::finished, this, &Site::finishedTags); } void Site::finishedTags() { - QString source = m_tagsReply->readAll(); + const QString source = m_tagsReply->readAll(); m_tagsReply->deleteLater(); QList tags; QVariant src = Json::parse(source); @@ -325,7 +322,7 @@ void Site::finishedTags() for (int id = 0; id < sourc.count(); id++) { QMap sc = sourc.at(id).toMap(); - int cat = sc.value("category").toInt(); + const int cat = sc.value("category").toInt(); tags.append(Tag(sc.value("name").toString(), cat == 0 ? "general" : (cat == 1 ? "artist" : (cat == 3 ? "copyright" : "character")), sc.value("post_count").toInt(), @@ -350,7 +347,7 @@ const QList &Site::getApis() const { return m_apis; } QList Site::getLoggedInApis() const { QList ret; - bool loggedIn = isLoggedIn(true); + const bool loggedIn = isLoggedIn(true); for (Api *api : m_apis) if (!api->needAuth() || loggedIn) ret.append(api); @@ -359,7 +356,7 @@ QList Site::getLoggedInApis() const } Api *Site::firstValidApi() const { - bool loggedIn = isLoggedIn(true); + const bool loggedIn = isLoggedIn(true); for (Api *api : m_apis) if (!api->needAuth() || loggedIn) return api; @@ -386,8 +383,8 @@ QUrl Site::fixUrl(const QString &url, const QUrl &old) const if (url.isEmpty()) return QUrl(); - bool ssl = m_settings->value("ssl", false).toBool(); - QString protocol = (ssl ? QStringLiteral("https") : QStringLiteral("http")); + const bool ssl = m_settings->value("ssl", false).toBool(); + const QString protocol = (ssl ? QStringLiteral("https") : QStringLiteral("http")); if (url.startsWith("//")) { return QUrl(protocol + ":" + url); } diff --git a/lib/src/models/site.h b/lib/src/models/site.h index 82026dd0b..e2f9d5de1 100644 --- a/lib/src/models/site.h +++ b/lib/src/models/site.h @@ -1,8 +1,6 @@ #ifndef SITE_H #define SITE_H -#include -#include #include #include #include diff --git a/lib/src/models/source.cpp b/lib/src/models/source.cpp index df62ba352..351d55dc0 100644 --- a/lib/src/models/source.cpp +++ b/lib/src/models/source.cpp @@ -1,11 +1,6 @@ #include "models/source.h" -#include -#include -#include -#include #include #include -#include #include "functions.h" #include "models/api/api.h" #include "models/api/html-api.h" @@ -71,7 +66,7 @@ Source::Source(Profile *profile, const QString &dir) QFile file(m_dir + "/model.xml"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { - QString fileContents = file.readAll(); + const QString fileContents = file.readAll(); QDomDocument doc; QString errorMsg; int errorLine, errorColumn; @@ -92,7 +87,7 @@ Source::Source(Profile *profile, const QString &dir) }; // Javascript models - bool enableJs = m_profile->getSettings()->value("enableJsModels", true).toBool(); + const bool enableJs = m_profile->getSettings()->value("enableJsModels", true).toBool(); QFile js(m_dir + "/model.js"); if (enableJs && js.exists() && js.open(QIODevice::ReadOnly | QIODevice::Text)) { @@ -122,7 +117,7 @@ Source::Source(Profile *profile, const QString &dir) const QJSValue &tagFormat = m_jsSource.property("tagFormat"); if (!tagFormat.isUndefined()) { - auto caseFormat = caseAssoc.value(tagFormat.property("case").toString(), TagNameFormat::Lower); + const auto caseFormat = caseAssoc.value(tagFormat.property("case").toString(), TagNameFormat::Lower); m_tagNameFormat = TagNameFormat(caseFormat, tagFormat.property("wordSeparator").toString()); } } @@ -170,7 +165,7 @@ Source::Source(Profile *profile, const QString &dir) { log(QStringLiteral("No valid source has been found in the model.xml file from %1.").arg(m_name)); } // Read tag naming format - auto caseFormat = caseAssoc.value(details.value("TagFormat/Case", "lower"), TagNameFormat::Lower); + const auto caseFormat = caseAssoc.value(details.value("TagFormat/Case", "lower"), TagNameFormat::Lower); m_tagNameFormat = TagNameFormat(caseFormat, details.value("TagFormat/WordSeparator", "_")); } } diff --git a/lib/src/reverse-search/reverse-search-engine.cpp b/lib/src/reverse-search/reverse-search-engine.cpp index 33f9226a9..90b0b87a7 100644 --- a/lib/src/reverse-search/reverse-search-engine.cpp +++ b/lib/src/reverse-search/reverse-search-engine.cpp @@ -1,5 +1,6 @@ #include "reverse-search/reverse-search-engine.h" #include +#include #include "functions.h" @@ -38,11 +39,11 @@ void ReverseSearchEngine::searchByUrl(const QUrl &url) const } -int ReverseSearchEngine::id() const { return m_id; } -QIcon ReverseSearchEngine::icon() const { return m_icon; } -QString ReverseSearchEngine::name() const { return m_name; } -QString ReverseSearchEngine::tpl() const { return m_tpl; } -int ReverseSearchEngine::order() const { return m_order; } +int ReverseSearchEngine::id() const { return m_id; } +QIcon ReverseSearchEngine::icon() const { return m_icon; } +const QString &ReverseSearchEngine::name() const { return m_name; } +const QString &ReverseSearchEngine::tpl() const { return m_tpl; } +int ReverseSearchEngine::order() const { return m_order; } void ReverseSearchEngine::setId(int id) { m_id = id; } void ReverseSearchEngine::setOrder(int order) { m_order = order; } diff --git a/lib/src/reverse-search/reverse-search-engine.h b/lib/src/reverse-search/reverse-search-engine.h index 3a512fc71..ad9ec2e8d 100644 --- a/lib/src/reverse-search/reverse-search-engine.h +++ b/lib/src/reverse-search/reverse-search-engine.h @@ -3,7 +3,6 @@ #include #include -#include class ReverseSearchEngine @@ -15,8 +14,8 @@ class ReverseSearchEngine int id() const; QIcon icon() const; - QString name() const; - QString tpl() const; + const QString &name() const; + const QString &tpl() const; int order() const; void setId(int id); diff --git a/lib/src/reverse-search/reverse-search-loader.cpp b/lib/src/reverse-search/reverse-search-loader.cpp index a1ec4b347..9bfac09a3 100644 --- a/lib/src/reverse-search/reverse-search-loader.cpp +++ b/lib/src/reverse-search/reverse-search-loader.cpp @@ -28,8 +28,8 @@ QList ReverseSearchLoader::getAllReverseSearchEngines() con for (const QString &group : webGroups) { m_settings->beginGroup(group); - int id = group.toInt(); - int order = m_settings->value("order").toInt(); + const int id = group.toInt(); + const int order = m_settings->value("order").toInt(); ret.insert(order, ReverseSearchEngine(id, savePath("webservices/" + group + ".ico"), m_settings->value("name").toString(), m_settings->value("url").toString(), order)); m_settings->endGroup(); } diff --git a/lib/src/reverse-search/reverse-search-loader.h b/lib/src/reverse-search/reverse-search-loader.h index 6bf2e78d7..ee51a5d12 100644 --- a/lib/src/reverse-search/reverse-search-loader.h +++ b/lib/src/reverse-search/reverse-search-loader.h @@ -1,7 +1,6 @@ #ifndef REVERSE_SEARCH_LOADER_H #define REVERSE_SEARCH_LOADER_H -#include #include diff --git a/lib/src/secure-file.cpp b/lib/src/secure-file.cpp index 2aad29708..21b8362c5 100644 --- a/lib/src/secure-file.cpp +++ b/lib/src/secure-file.cpp @@ -1,6 +1,7 @@ #include "secure-file.h" #include #include +#include SecureFile::SecureFile(const QString &filename, const QString &key) @@ -9,7 +10,7 @@ SecureFile::SecureFile(const QString &filename, const QString &key) quint64 SecureFile::generateIntKey(const QString &key) const { - auto data = QByteArray::fromRawData((const char*)key.utf16(), key.length() * 2); + const auto data = QByteArray::fromRawData((const char*)key.utf16(), key.length() * 2); QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5); Q_ASSERT(hash.size() == 16); QDataStream stream(hash); diff --git a/lib/src/secure-file.h b/lib/src/secure-file.h index 679a0fe18..b74013811 100644 --- a/lib/src/secure-file.h +++ b/lib/src/secure-file.h @@ -2,7 +2,6 @@ #define SECURE_FILE_H #include -#include #include "vendor/simplecrypt.h" diff --git a/lib/src/tags/tag-api.cpp b/lib/src/tags/tag-api.cpp index 6ed3679af..a7e05105f 100755 --- a/lib/src/tags/tag-api.cpp +++ b/lib/src/tags/tag-api.cpp @@ -1,17 +1,15 @@ #include "tags/tag-api.h" -#include #include #include "functions.h" #include "logger.h" #include "models/api/api.h" #include "models/site.h" -#include "vendor/json.h" TagApi::TagApi(Profile *profile, Site *site, Api *api, int page, int limit, QObject *parent) : QObject(parent), m_profile(profile), m_site(site), m_api(api), m_page(page), m_limit(limit), m_reply(Q_NULLPTR) { - QString url = api->tagsUrl(page, limit, site).url; + const QString url = api->tagsUrl(page, limit, site).url; m_url = m_site->fixUrl(url); } diff --git a/lib/src/tags/tag-database-factory.cpp b/lib/src/tags/tag-database-factory.cpp index 4fa6eadbe..984eb792d 100644 --- a/lib/src/tags/tag-database-factory.cpp +++ b/lib/src/tags/tag-database-factory.cpp @@ -9,7 +9,7 @@ TagDatabase *TagDatabaseFactory::Create(QString directory) if (!directory.endsWith("/") && !directory.endsWith("\\")) directory += "/"; - QString typesFile = directory + "tag-types.txt"; + const QString typesFile = directory + "tag-types.txt"; if (QFile::exists(directory + "tags.db")) return new TagDatabaseSqlite(typesFile, directory + "tags.db"); diff --git a/lib/src/tags/tag-database-in-memory.cpp b/lib/src/tags/tag-database-in-memory.cpp index 436642d83..c47bf268e 100644 --- a/lib/src/tags/tag-database-in-memory.cpp +++ b/lib/src/tags/tag-database-in-memory.cpp @@ -67,7 +67,7 @@ bool TagDatabaseInMemory::save() i.next(); TagType tagType = i.value(); - int tagTypeId = tagTypes.contains(tagType.name()) ? tagTypes[tagType.name()] : -1; + const int tagTypeId = tagTypes.contains(tagType.name()) ? tagTypes[tagType.name()] : -1; file.write(QString(i.key() + "," + QString::number(tagTypeId) + "\n").toUtf8()); } diff --git a/lib/src/tags/tag-database-sqlite.cpp b/lib/src/tags/tag-database-sqlite.cpp index 48de9e280..dc8fa33ea 100644 --- a/lib/src/tags/tag-database-sqlite.cpp +++ b/lib/src/tags/tag-database-sqlite.cpp @@ -72,7 +72,7 @@ void TagDatabaseSqlite::setTags(const QList &tags) for (const Tag &tag : tags) { - QString type = tag.type().name(); + const QString &type = tag.type().name(); addQuery.bindValue(":id", tag.id()); addQuery.bindValue(":tag", tag.text()); addQuery.bindValue(":ttype", tagTypes.contains(type) ? tagTypes[type] : -1); @@ -114,7 +114,7 @@ QMap TagDatabaseSqlite::getTagTypes(const QStringList &tags) c return ret; // Execute query - QString sql = "SELECT tag, ttype FROM tags WHERE tag IN (" + formatted.join(",") + ")"; + const QString sql = "SELECT tag, ttype FROM tags WHERE tag IN (" + formatted.join(",") + ")"; QSqlQuery query(m_database); query.setForwardOnly(true); if (!query.exec(sql)) @@ -123,12 +123,12 @@ QMap TagDatabaseSqlite::getTagTypes(const QStringList &tags) c return ret; } - int idTag = query.record().indexOf("tag"); - int idTtype = query.record().indexOf("ttype"); + const int idTag = query.record().indexOf("tag"); + const int idTtype = query.record().indexOf("ttype"); while (query.next()) { - QString tag = query.value(idTag).toString(); - TagType type = m_tagTypes[query.value(idTtype).toInt()]; + const QString tag = query.value(idTag).toString(); + const TagType type = m_tagTypes[query.value(idTtype).toInt()]; ret.insert(tag, type); m_cache.insert(tag, type); } @@ -142,7 +142,7 @@ int TagDatabaseSqlite::count() const return m_count; QSqlQuery query(m_database); - QString sql = QStringLiteral("SELECT COUNT(*) FROM tags"); + const QString sql = QStringLiteral("SELECT COUNT(*) FROM tags"); if (!query.exec(sql) || !query.next()) { log(QStringLiteral("SQL error when getting tag count: %1").arg(query.lastError().text()), Logger::Error); diff --git a/lib/src/tags/tag-database.cpp b/lib/src/tags/tag-database.cpp index 736f61fab..5ec6e2a06 100644 --- a/lib/src/tags/tag-database.cpp +++ b/lib/src/tags/tag-database.cpp @@ -2,6 +2,7 @@ #include #include #include +#include "tag-type.h" TagDatabase::TagDatabase(const QString &typeFile) diff --git a/lib/src/tags/tag-name-format.h b/lib/src/tags/tag-name-format.h index b1c12fa31..87a168b4e 100644 --- a/lib/src/tags/tag-name-format.h +++ b/lib/src/tags/tag-name-format.h @@ -2,7 +2,6 @@ #define TAG_NAME_FORMAT_H #include -#include #include diff --git a/lib/src/tags/tag-name.h b/lib/src/tags/tag-name.h index 1313637f5..ae02b4f85 100644 --- a/lib/src/tags/tag-name.h +++ b/lib/src/tags/tag-name.h @@ -2,8 +2,6 @@ #define TAG_NAME_H #include -#include -#include #include "tags/tag-name-format.h" diff --git a/lib/src/tags/tag-stylist.cpp b/lib/src/tags/tag-stylist.cpp index 0ee383afb..c39270783 100644 --- a/lib/src/tags/tag-stylist.cpp +++ b/lib/src/tags/tag-stylist.cpp @@ -1,6 +1,7 @@ #include "tags/tag-stylist.h" #include #include "functions.h" +#include "models/favorite.h" #include "models/profile.h" #include "tags/tag.h" @@ -52,11 +53,11 @@ QString TagStylist::stylished(const Tag &tag, bool count, bool noUnderscores) co QFont font; font.fromString(m_profile->getSettings()->value("Coloring/Fonts/" + key).toString()); - QString color = m_profile->getSettings()->value("Coloring/Colors/" + key, defaults.at(tlist.indexOf(key))).toString(); - QString style = "color:" + color + "; " + qFontToCss(font); + const QString color = m_profile->getSettings()->value("Coloring/Colors/" + key, defaults.at(tlist.indexOf(key))).toString(); + const QString style = "color:" + color + "; " + qFontToCss(font); - QString ret; - ret = "" + (noUnderscores ? tag.text().replace('_', ' ') : tag.text()) + ""; + QString txt = tag.text(); + QString ret = "" + (noUnderscores ? txt.replace('_', ' ') : tag.text()) + ""; if (count && tag.count() > 0) ret += " (" + QString("%L1").arg(tag.count()) + ")"; diff --git a/lib/src/tags/tag-type.cpp b/lib/src/tags/tag-type.cpp index f9f69cf96..9306b4f7a 100644 --- a/lib/src/tags/tag-type.cpp +++ b/lib/src/tags/tag-type.cpp @@ -9,7 +9,7 @@ TagType::TagType(const QString &name) : m_name(name) {} -QString TagType::name() const +const QString &TagType::name() const { return m_name; } diff --git a/lib/src/tags/tag-type.h b/lib/src/tags/tag-type.h index 1ee4eea4e..ae38ca273 100644 --- a/lib/src/tags/tag-type.h +++ b/lib/src/tags/tag-type.h @@ -10,7 +10,7 @@ class TagType public: TagType(); explicit TagType(const QString &name); - QString name() const; + const QString &name() const; int number() const; private: diff --git a/lib/src/tags/tag.cpp b/lib/src/tags/tag.cpp index a463e5278..558ba3d66 100644 --- a/lib/src/tags/tag.cpp +++ b/lib/src/tags/tag.cpp @@ -2,8 +2,8 @@ #include #include #include -#include #include "functions.h" +#include "tag-type.h" QMap stringListToMap(const QStringList &list) @@ -37,7 +37,7 @@ Tag::Tag(int id, const QString &text, const TagType &type, int count, const QStr m_text = htmlEncoded.toPlainText().replace(' ', '_'); // Sometimes a type is found with multiple words, only the first is relevant - int typeSpace = m_type.name().indexOf(' '); + const int typeSpace = m_type.name().indexOf(' '); if (typeSpace != -1) { m_type = TagType(m_type.name().left(typeSpace)); } @@ -48,7 +48,7 @@ Tag::Tag(int id, const QString &text, const TagType &type, int count, const QStr m_text = m_text.left(m_text.length() - 9); } - int sepPos = m_text.indexOf(':'); + const int sepPos = m_text.indexOf(':'); if (sepPos != -1 && weakTypes.contains(m_type.name())) { static QStringList prep = QStringList() @@ -61,8 +61,8 @@ Tag::Tag(int id, const QString &text, const TagType &type, int count, const QStr << QStringLiteral("unknown") << QStringLiteral("oc"); - QString pre = Tag::GetType(m_text.left(sepPos)); - int prepIndex = prep.indexOf(pre); + const QString pre = Tag::GetType(m_text.left(sepPos)); + const int prepIndex = prep.indexOf(pre); if (prepIndex != -1) { m_type = TagType(Tag::GetType(prep[prepIndex], stringListToMap(prep))); @@ -120,7 +120,7 @@ QList Tag::FromRegexp(const QString &rx, const QString &source) auto matches = rxtags.globalMatch(source); while (matches.hasNext()) { - auto match = matches.next(); + const auto &match = matches.next(); Tag tag = Tag::FromCapture(match, rxtags.namedCaptureGroups()); if (!got.contains(tag.text())) @@ -156,7 +156,7 @@ QString Tag::GetType(QString type, QMap ids) if (type.length() == 1) { - int typeId = type.toInt(); + const int typeId = type.toInt(); if (ids.contains(typeId)) return ids[typeId]; } @@ -170,11 +170,11 @@ void Tag::setType(const TagType &type) { m_type = type; } void Tag::setCount(int count) { m_count = count; } void Tag::setRelated(const QStringList &r) { m_related = r; } -int Tag::id() const { return m_id; } -QString Tag::text() const { return m_text; } -TagType Tag::type() const { return m_type; } -int Tag::count() const { return m_count; } -QStringList Tag::related() const { return m_related; } +int Tag::id() const { return m_id; } +const QString &Tag::text() const { return m_text; } +const TagType &Tag::type() const { return m_type; } +int Tag::count() const { return m_count; } +const QStringList &Tag::related() const { return m_related; } bool sortTagsByType(const Tag &s1, const Tag &s2) { @@ -187,8 +187,8 @@ bool sortTagsByType(const Tag &s1, const Tag &s2) << QStringLiteral("character") << QStringLiteral("copyright"); - int t1 = typeOrder.indexOf(s1.type().name()); - int t2 = typeOrder.indexOf(s2.type().name()); + const int t1 = typeOrder.indexOf(s1.type().name()); + const int t2 = typeOrder.indexOf(s2.type().name()); return t1 == t2 ? sortTagsByName(s1, s2) : t1 > t2; } bool sortTagsByName(const Tag &s1, const Tag &s2) diff --git a/lib/src/tags/tag.h b/lib/src/tags/tag.h index 8696f9951..4d33ad34a 100644 --- a/lib/src/tags/tag.h +++ b/lib/src/tags/tag.h @@ -4,7 +4,6 @@ #include #include #include -#include #include "tags/tag-type.h" @@ -23,18 +22,18 @@ class Tag void setType(const TagType &type); void setCount(int count); void setRelated(const QStringList &related); - int id() const; - QString text() const; - TagType type() const; - int count() const; - QStringList related() const; + int id() const; + const QString &text() const; + const TagType &type() const; + int count() const; + const QStringList &related() const; private: - int m_id; - QString m_text; - TagType m_type; - int m_count; - QStringList m_related; + int m_id; + QString m_text; + TagType m_type; + int m_count; + QStringList m_related; }; bool sortTagsByType(const Tag &, const Tag &); diff --git a/lib/src/updater/program-updater.cpp b/lib/src/updater/program-updater.cpp index 8f9bb4b7a..07cbfdd89 100644 --- a/lib/src/updater/program-updater.cpp +++ b/lib/src/updater/program-updater.cpp @@ -19,11 +19,11 @@ ProgramUpdater::ProgramUpdater(const QString &baseUrl) void ProgramUpdater::checkForUpdates() const { #ifdef NIGHTLY - QUrl url(m_baseUrl + "/releases/tags/nightly"); + const QUrl url(m_baseUrl + "/releases/tags/nightly"); #else - QUrl url(m_baseUrl + "/releases/latest"); + const QUrl url(m_baseUrl + "/releases/latest"); #endif - QNetworkRequest request(url); + const QNetworkRequest request(url); auto *reply = m_networkAccessManager->get(request); connect(reply, &QNetworkReply::finished, this, &ProgramUpdater::checkForUpdatesDone); @@ -45,7 +45,7 @@ void ProgramUpdater::checkForUpdatesDone() latest = latest.left(8); #else QString latest = lastRelease["name"].toString().mid(1); - bool isNew = compareVersions(latest, QString(VERSION)) > 0; + const bool isNew = compareVersions(latest, QString(VERSION)) > 0; changelog = lastRelease["body"].toString(); #endif @@ -69,7 +69,7 @@ void ProgramUpdater::downloadUpdate() QUrl url(lastAsset["browser_download_url"].toString()); m_updateFilename = url.fileName(); - QNetworkRequest request(url); + const QNetworkRequest request(url); log(QStringLiteral("Downloading installer from \"%1\".").arg(url.toString())); m_downloadReply = m_networkAccessManager->get(request); @@ -83,7 +83,7 @@ void ProgramUpdater::downloadDone() if (!redirection.isEmpty()) { log(QStringLiteral("Installer download redirected to \"%1\".").arg(redirection.toString())); - QNetworkRequest request(redirection); + const QNetworkRequest request(redirection); m_downloadReply = m_networkAccessManager->get(request); connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress); connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone); diff --git a/lib/src/updater/source-updater.cpp b/lib/src/updater/source-updater.cpp index 47fd027ee..05549d1f4 100644 --- a/lib/src/updater/source-updater.cpp +++ b/lib/src/updater/source-updater.cpp @@ -15,8 +15,8 @@ SourceUpdater::SourceUpdater(const QString &source, const QString &directory, co void SourceUpdater::checkForUpdates() const { - QUrl url(m_baseUrl + m_source + "/model.xml"); - QNetworkRequest request(url); + const QUrl url(m_baseUrl + m_source + "/model.xml"); + const QNetworkRequest request(url); auto *reply = m_networkAccessManager->get(request); connect(reply, &QNetworkReply::finished, this, &SourceUpdater::checkForUpdatesDone); diff --git a/lib/src/updater/source-updater.h b/lib/src/updater/source-updater.h index c6246ec10..f7f0453da 100644 --- a/lib/src/updater/source-updater.h +++ b/lib/src/updater/source-updater.h @@ -1,6 +1,7 @@ #ifndef SOURCE_UPDATER_H #define SOURCE_UPDATER_H +#include #include #include "updater/updater.h" diff --git a/lib/src/updater/updater.cpp b/lib/src/updater/updater.cpp index 923f7783a..15205bc02 100644 --- a/lib/src/updater/updater.cpp +++ b/lib/src/updater/updater.cpp @@ -16,7 +16,7 @@ int Updater::compareVersions(QString a, QString b) { int aSub = 0; char aSubType = ' '; - int aPos = a.indexOf(QRegularExpression("[a-z]")); + const int aPos = a.indexOf(QRegularExpression("[a-z]")); if (aPos != -1) { aSubType = a[aPos].toLatin1(); @@ -26,7 +26,7 @@ int Updater::compareVersions(QString a, QString b) int bSub = 0; char bSubType = ' '; - int bPos = b.indexOf(QRegularExpression("[a-z]")); + const int bPos = b.indexOf(QRegularExpression("[a-z]")); if (bPos != -1) { bSubType = b[bPos].toLatin1(); @@ -42,8 +42,8 @@ int Updater::compareVersions(QString a, QString b) for (int i = 0; i < aSem.count(); ++i) { - int aPart = aSem[i].toInt(); - int bPart = bSem[i].toInt(); + const int aPart = aSem[i].toInt(); + const int bPart = bSem[i].toInt(); if (aPart > bPart) return 1; From c3233b7cba68bda5cafdbfcc306cd814b4d24a63 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 17 Jun 2018 01:35:36 +0200 Subject: [PATCH 004/112] Stop leaking memory in a few places --- gui/src/aboutwindow.cpp | 3 ++- gui/src/main/main.cpp | 1 + lib/src/models/site.cpp | 6 +++++- lib/src/updater/program-updater.cpp | 1 + lib/src/updater/source-updater.cpp | 1 + 5 files changed, 10 insertions(+), 2 deletions(-) diff --git a/gui/src/aboutwindow.cpp b/gui/src/aboutwindow.cpp index d15b86b0d..e4b2e0754 100644 --- a/gui/src/aboutwindow.cpp +++ b/gui/src/aboutwindow.cpp @@ -5,6 +5,7 @@ AboutWindow::AboutWindow(const QString &version, QWidget *parent) : QDialog(parent), ui(new Ui::AboutWindow), m_updater() { + setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); ui->labelCurrent->setText(version); @@ -22,6 +23,6 @@ AboutWindow::~AboutWindow() void AboutWindow::finished(const QString &newVersion, bool available) { - QString msg = available ? tr("A new version is available: %1").arg(newVersion) : tr("Grabber is up to date"); + const QString msg = available ? tr("A new version is available: %1").arg(newVersion) : tr("Grabber is up to date"); ui->labelMessage->setText("

" + msg + "

"); } diff --git a/gui/src/main/main.cpp b/gui/src/main/main.cpp index 6dfcbd46a..3e22e86af 100644 --- a/gui/src/main/main.cpp +++ b/gui/src/main/main.cpp @@ -207,6 +207,7 @@ int main(int argc, char *argv[]) updateDialog->checkForUpdates(); el->exec(); el->deleteLater(); + updateDialog->deleteLater(); if (shouldQuit) return 0; diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index 4f8ced906..adc110f04 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -31,7 +31,7 @@ Site::Site(const QString &url, Source *source) - : m_type(source->getName()), m_url(url), m_source(source), m_settings(nullptr), m_manager(nullptr), m_cookieJar(nullptr), m_loggedIn(LoginStatus::Unknown), m_autoLogin(true) + : m_type(source->getName()), m_url(url), m_source(source), m_settings(nullptr), m_manager(nullptr), m_cookieJar(nullptr), m_tagDatabase(nullptr), m_login(nullptr), m_loggedIn(LoginStatus::Unknown), m_autoLogin(true) { // Create the access manager and get its slots m_manager = new CustomNetworkAccessManager(this); @@ -100,6 +100,8 @@ void Site::loadConfig() // Auth information const QString type = m_settings->value("login/type", "url").toString(); + if (m_login != nullptr) + m_login->deleteLater(); if (type == "url") m_login = new UrlLogin(this, m_manager, m_settings); else if (type == "oauth2") @@ -131,6 +133,8 @@ void Site::loadConfig() resetCookieJar(); // Tag database + if (m_tagDatabase != nullptr) + { delete m_tagDatabase; } m_tagDatabase = TagDatabaseFactory::Create(siteDir); m_tagDatabase->loadTypes(); } diff --git a/lib/src/updater/program-updater.cpp b/lib/src/updater/program-updater.cpp index 07cbfdd89..75a9bca50 100644 --- a/lib/src/updater/program-updater.cpp +++ b/lib/src/updater/program-updater.cpp @@ -51,6 +51,7 @@ void ProgramUpdater::checkForUpdatesDone() m_newVersion = latest; emit finished(latest, isNew, changelog); + reply->deleteLater(); } diff --git a/lib/src/updater/source-updater.cpp b/lib/src/updater/source-updater.cpp index 05549d1f4..944068da2 100644 --- a/lib/src/updater/source-updater.cpp +++ b/lib/src/updater/source-updater.cpp @@ -45,4 +45,5 @@ void SourceUpdater::checkForUpdatesDone() } emit finished(m_source, isNew); + reply->deleteLater(); } From 70dbc5be33eb027004dcc7e5cb8263aa72a5bd15 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 17 Jun 2018 13:31:55 +0200 Subject: [PATCH 005/112] Replace 'unknown' tag type by boolean --- gui/src/mainwindow.cpp | 2 +- gui/src/tabs/search-tab.cpp | 2 +- lib/src/flyweight-cache.h | 37 +++++++++++++++++++++++ lib/src/models/api/html-api.cpp | 2 +- lib/src/models/api/javascript-api.cpp | 2 +- lib/src/models/api/json-api.cpp | 2 +- lib/src/models/api/xml-api.cpp | 2 +- lib/src/models/image.cpp | 2 +- lib/src/tags/tag-type-factory.h | 12 ++++++++ lib/src/tags/tag-type.cpp | 14 ++++++--- lib/src/tags/tag-type.h | 2 ++ lib/src/tags/tag.cpp | 7 ++--- tests/src/integration/derpibooru-test.cpp | 4 +-- tests/src/tags/tag-test.cpp | 2 +- 14 files changed, 73 insertions(+), 19 deletions(-) create mode 100644 lib/src/flyweight-cache.h create mode 100644 lib/src/tags/tag-type-factory.h diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index bd28a9a66..017a137ab 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -1623,7 +1623,7 @@ void mainWindow::_getAll() bool hasUnknownTag = false; for (const Tag &tag : img->tags()) { - if (tag.type().name() == "unknown") + if (tag.type().isUnknown()) { hasUnknownTag = true; break; diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index b03d086b7..5d04822c1 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -605,7 +605,7 @@ double getImageKnownTagProportion(const QSharedPointer &img) int known = 0; for (const Tag &tag : img->tags()) { - if (tag.type().name() != QLatin1String("unknown")) + if (!tag.type().isUnknown()) known++; } diff --git a/lib/src/flyweight-cache.h b/lib/src/flyweight-cache.h new file mode 100644 index 000000000..705601e23 --- /dev/null +++ b/lib/src/flyweight-cache.h @@ -0,0 +1,37 @@ +#ifndef FLYWEIGHT_CACHE_H +#define FLYWEIGHT_CACHE_H + +#include + + +template +class FlyweightCache +{ + public: + static QSharedPointer Get(const K &key); + + private: + static QMap> Map; +}; + + +template +QMap> FlyweightCache::Map; + +template +QSharedPointer FlyweightCache::Get(const K &key) +{ + auto it = Map.find(key); + if (it != Map.end()) + { + return QSharedPointer(it.value()); + } + + const QSharedPointer shared(new T(key)); + const QWeakPointer weak(shared); + Map.insert(key, weak); + + return shared; +} + +#endif // FLYWEIGHT_CACHE_H diff --git a/lib/src/models/api/html-api.cpp b/lib/src/models/api/html-api.cpp index 787ac0431..2f2f6674d 100644 --- a/lib/src/models/api/html-api.cpp +++ b/lib/src/models/api/html-api.cpp @@ -148,7 +148,7 @@ ParsedTags HtmlApi::parseTags(const QString &source, Site *site) const int typeId = d.contains("typeId") ? d["typeId"].toInt() : -1; QString ttype = d["type"]; - TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); + TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); ret.tags.append(Tag(id, name, tagType, count)); } diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index 7cb790dd1..0d496151c 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -161,7 +161,7 @@ QList JavascriptApi::makeTags(const QJSValue &tags, Site *site) const if (tag.hasProperty("typeId") && !tag.property("typeId").isUndefined()) { typeId = tag.property("typeId").toInt(); } - const TagType tagType = !type.isEmpty() ? TagType(type) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); + const TagType tagType = !type.isEmpty() ? TagType(type) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); ret.append(Tag(id, text, tagType, count)); } diff --git a/lib/src/models/api/json-api.cpp b/lib/src/models/api/json-api.cpp index 6225788ee..f21713fc8 100644 --- a/lib/src/models/api/json-api.cpp +++ b/lib/src/models/api/json-api.cpp @@ -244,7 +244,7 @@ ParsedTags JsonApi::parseTags(const QString &source, Site *site) const typeId = sc.value("type").toInt(); } - const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); + const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); ret.tags.append(Tag(id, name, tagType, count)); } diff --git a/lib/src/models/api/xml-api.cpp b/lib/src/models/api/xml-api.cpp index 95dc975a7..94afadf99 100644 --- a/lib/src/models/api/xml-api.cpp +++ b/lib/src/models/api/xml-api.cpp @@ -153,7 +153,7 @@ ParsedTags XmlApi::parseTags(const QString &source, Site *site) const typeId = node.namedItem("type").toElement().text().toInt(); } - const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType("unknown")); + const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); ret.tags.append(Tag(id, name, tagType, count)); } diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 7995a28a9..d0492b6f0 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -203,7 +203,7 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* m_parentSite->tagDatabase()->load(); QStringList unknownTags; for (Tag const &tag : qAsConst(m_tags)) - if (tag.type().name() == "unknown") + if (tag.type().isUnknown()) unknownTags.append(tag.text()); QMap dbTypes = m_parentSite->tagDatabase()->getTagTypes(unknownTags); for (Tag &tag : m_tags) diff --git a/lib/src/tags/tag-type-factory.h b/lib/src/tags/tag-type-factory.h new file mode 100644 index 000000000..df8929dab --- /dev/null +++ b/lib/src/tags/tag-type-factory.h @@ -0,0 +1,12 @@ +#ifndef TAG_TYPE_FACTORY_H +#define TAG_TYPE_FACTORY_H + +#include "flyweight-cache.h" + + +class TagType; + +class TagTypeFactory : public FlyweightCache +{}; + +#endif // TAG_TYPE_FACTORY_H diff --git a/lib/src/tags/tag-type.cpp b/lib/src/tags/tag-type.cpp index 9306b4f7a..44bb5a850 100644 --- a/lib/src/tags/tag-type.cpp +++ b/lib/src/tags/tag-type.cpp @@ -3,12 +3,17 @@ TagType::TagType() - : TagType("unknown") + : m_isUnknown(true), m_name("unknown") {} TagType::TagType(const QString &name) - : m_name(name) + : m_isUnknown(name.isEmpty() || name == "unknown"), m_name(name) {} +bool TagType::isUnknown() const +{ + return m_isUnknown; +} + const QString &TagType::name() const { return m_name; @@ -27,10 +32,11 @@ int TagType::number() const { "photo_set", 6 }, }; - return shortTypes.contains(m_name) ? shortTypes[m_name] : -1; + return !m_isUnknown && shortTypes.contains(m_name) ? shortTypes[m_name] : -1; } bool operator==(const TagType &a, const TagType &b) { - return a.name() == b.name(); + return (a.isUnknown() && b.isUnknown()) + || a.name() == b.name(); } diff --git a/lib/src/tags/tag-type.h b/lib/src/tags/tag-type.h index ae38ca273..a71df2bfd 100644 --- a/lib/src/tags/tag-type.h +++ b/lib/src/tags/tag-type.h @@ -10,10 +10,12 @@ class TagType public: TagType(); explicit TagType(const QString &name); + bool isUnknown() const; const QString &name() const; int number() const; private: + bool m_isUnknown; QString m_name; }; diff --git a/lib/src/tags/tag.cpp b/lib/src/tags/tag.cpp index 558ba3d66..6527dfa97 100644 --- a/lib/src/tags/tag.cpp +++ b/lib/src/tags/tag.cpp @@ -15,7 +15,7 @@ QMap stringListToMap(const QStringList &list) } Tag::Tag() - : m_type(TagType(QStringLiteral("unknown"))), m_count(0) + : m_type(TagType()), m_count(0) { } Tag::Tag(const QString &text, const QString &type, int count, const QStringList &related) @@ -89,8 +89,6 @@ Tag Tag::FromCapture(const QRegularExpressionMatch &match, const QStringList &gr static QStringList types = QStringList() << "general" << "artist" << "unknown" << "copyright" << "character" << "species" << "meta"; type = Tag::GetType(data.value("type").trimmed(), stringListToMap(types)); } - if (type.isEmpty()) - { type = "unknown"; } // Count int count = 0; @@ -198,7 +196,6 @@ bool sortTagsByCount(const Tag &s1, const Tag &s2) bool operator==(const Tag &t1, const Tag &t2) { - const QLatin1String unknown("unknown"); return QString::compare(t1.text(), t2.text(), Qt::CaseInsensitive) == 0 - && (t1.type() == t2.type() || t1.type().name() == unknown || t2.type().name() == unknown); + && (t1.type() == t2.type() || t1.type().isUnknown() || t2.type().isUnknown()); } diff --git a/tests/src/integration/derpibooru-test.cpp b/tests/src/integration/derpibooru-test.cpp index a5b21cfb4..a6bb4586c 100644 --- a/tests/src/integration/derpibooru-test.cpp +++ b/tests/src/integration/derpibooru-test.cpp @@ -50,7 +50,7 @@ void DerpibooruTest::testHtmlTags() QCOMPARE(tags[1].text(), QString("solo")); QCOMPARE(tags[1].count(), 599506); - QCOMPARE(tags[1].type().name(), QString("unknown")); + QCOMPARE(tags[1].type().isUnknown(), true); } void DerpibooruTest::testJsonTags() @@ -61,7 +61,7 @@ void DerpibooruTest::testJsonTags() QCOMPARE(tags[1].text(), QString("solo")); QCOMPARE(tags[1].count(), 599506); - QCOMPARE(tags[1].type().name(), QString("unknown")); + QCOMPARE(tags[1].type().isUnknown(), true); } diff --git a/tests/src/tags/tag-test.cpp b/tests/src/tags/tag-test.cpp index 852185638..216802bda 100644 --- a/tests/src/tags/tag-test.cpp +++ b/tests/src/tags/tag-test.cpp @@ -67,7 +67,7 @@ void TagTest::testTypeArtistEnding() } void TagTest::testTypePrefix() { - Tag tag("artist:tag_text", "unknown", 123, QStringList() << "related1" << "related2" << "related3"); + Tag tag("artist:tag_text", "", 123, QStringList() << "related1" << "related2" << "related3"); QCOMPARE(tag.type().name(), QString("artist")); QCOMPARE(tag.text(), QString("tag_text")); From ba51a56b57069f2d74476d798b93e04ed0b0b98e Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 00:42:18 +0200 Subject: [PATCH 006/112] Restore mac build script --- build-mac.sh | 272 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 253 insertions(+), 19 deletions(-) mode change 100644 => 100755 build-mac.sh diff --git a/build-mac.sh b/build-mac.sh old mode 100644 new mode 100755 index ccd35442f..cf07dd46b --- a/build-mac.sh +++ b/build-mac.sh @@ -1,19 +1,253 @@ -#!/usr/bin/env sh - -# Install required packages -ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" -brew install qt5 --with-docs --with-developer --with-d-bus --with-mysql -brew install gcc cmake - -# Build the project in the build directory -mkdir build -cd build -cmake .. -make -j8 -cd .. - -# Move the built binary to the release folder with its config -mv "build/gui/Grabber" "release/" -touch "release/settings.ini" - -echo "Grabber has been compiled in the release directory. To run it, type './release/Grabber'" +#!/usr/bin/env bash +#####################{{{1 +# Variables +##################### +srcDir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +oldApp="${HOME}/Applications/Grabber.app/Contents/MacOS" +appDir="${srcDir}/gui/build/release/Grabber.app/Contents/MacOS" +logfile="$(mktemp -t $(basename $0))" +[[ $? -ne 0 ]] && echo -e "${logfile}" && exit 1 + +#####################{{{1 +# Build Environment Validation +##################### + +# Is Homebrew Installed? {{{2 +export BREW_BIN="$(which brew)" +if [[ -z "${BREW_BIN}" ]] +then + echo "Homebrew not found. Installing with the following command: " + echo ' ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"' + read -p 'Do you agree? [y|N]' AGREE + case "${AGREE}" in + [yY]|[yY][eE]|[yY][eE][sS]) #{{{3 + ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" + export BREW_BIN=$(which brew) + ;; + *) #{{{3 + echo "You must type 'yes' to accept. Aborting."; exit 1 + ;; #}}}3 + esac +fi + +#Is cmake installed? {{{2 +which cmake > /dev/null 2>&1 +if [[ $? -ne 0 ]] +then + echo "cmake(1) is required to build imgbrd-grabber. Installing with brew..." + ${BREW_BIN} install cmake + which cmake > /dev/null 2>&1 + [[ $? -ne 0 ]] && echo "Failed to install cmake. Aborting." && exit 1 +fi + +#Is gcc installed? {{{2 +which gcc > /dev/null 2>&1 +if [[ $? -ne 0 ]] +then + echo "gcc(1) is required to build imgbrd-grabber. Installing with brew..." + ${BREW_BIN} install gcc + which gcc > /dev/null 2>&1 + [[ $? -ne 0 ]] && echo "Failed to install gcc. Aborting." && exit 1 +fi + +# Is Qt installed? {{{2 +QT_BIN_ROOT="$(${BREW_BIN} --prefix)/opt/qt/bin" +if [[ ! -e "${QT_BIN_ROOT}" ]] +then + echo "Qt5 build binaries not found at '${QT_BIN_ROOT}'. Installing with homebrew." + echo "Qt5 can be installed with mysql integration. This requires qt5 to be compiled from scratch and takes a VERY long time." + read -p 'Do you want to compile Qt5 with mysql (can take 1hr or more to finish) [y|N|abort]' AGREE + case "${AGREE}" in + [yY]|[yY][eE]|[yY][eE][sS]) #{{{3 + echo "Compiling qt from source code with mysql. This can take one hour or more to complete..." + "${BREW_BIN}" install qt --with-docs --with-mysql + QT_BIN_ROOT="$(${BREW_BIN} --prefix)/opt/qt/bin" + ;; + [aA]|[aA][bB]|[aA][bB][oO]|[aA][bB][oO][rR]|[aA][bB][oO][rR][tT]) #{{{3 + echo "User requested abort." + exit 1 + ;; + *) #{{{3 + "${BREW_BIN}" install qt + QT_BIN_ROOT="$(${BREW_BIN} --prefix)/opt/qt/bin" + ;; #}}}3 + esac + "${QT_BIN_ROOT}/qmake" -v >/dev/null 2>&1 + ERR=$? + [[ $ERR -ne 0 ]] && echo "Failed to install Qt. Aborting." && exit 1 +fi + +# Are the Qt build binaries found in our Path variable? {{{2 +echo "${PATH}"|grep "${QT_BIN_ROOT}" >/dev/null 2>&1 +ERR=$? +if [[ $ERR -ne 0 ]] +then + echo "QT build binaries not found in path. Adding '${QT_BIN_ROOT}' to path." + export PATH="${QT_BIN_ROOT}:${PATH}" +fi + +# We use the app JQ to parse brews package details. Is it installed? {{{2 +JQ_PATH="$(which jq)" +ERR=$? +if [[ $ERR -ne 0 ]] +then + echo "The program jq(1) is used to parse Brew package information but was not found. Installing..." + "${BREW_BIN}" install jq + JQ_PATH="$(which jq)" + ERR=$? + [[ $ERR -ne 0 ]] && echo "Failed to install jq. Aborting." && exit 1 +fi + +# Is OpenSSL installed? {{{2 +export OPENSSL_ROOT_DIR="$("${BREW_BIN}" info --json=v1 openssl|"${JQ_PATH}" -r '.[0].bottle.stable.cellar,.[0].name,.[0].versions.stable'|tr '\n' '/')" +export OPENSSL_INCLUDE_DIR="${OPENSSL_ROOT_DIR}/lib" +if [[ ! -e "${OPENSSL_ROOT_DIR}" ]] +then + echo "A local version of OpenSSL is required to build against. Installing. (This will not overwrite the systems OpenSSL installation)" + "${BREW_BIN}" install openssl + export OPENSSL_ROOT_DIR="$("${BREW_BIN}" info --json=v1 openssl|"${JQ_PATH}" -r '.[0].bottle.stable.cellar,.[0].name,.[0].versions.stable'|tr '\n' '/')" + export OPENSSL_INCLUDE_DIR="${OPENSSL_ROOT_DIR}/lib" + + if [[ ! -e "${OPENSSL_INCLUDE_DIR}" ]] + then + echo "Failed to install openssl, or was unable to find the includes directory at '${OPENSSL_INCLUDE_DIR}'. Aborting." + exit 1 + fi +fi + +# Is the imgbrd-grabber repo checked out to the current directory? +if [[ ! -e "${srcDir}/.git" ]] +then + APP_NAME="$(basename $0 2>/dev/null )" + ERR=$? + TEMPDIR="$(mktemp -d -t ${APP_NAME}.tmpdir 2>/dev/null )" + ERR=$(( $ERR + $? )) + git clone https://github.com/Bionus/imgbrd-grabber.git "${TEMPDIR}" + ERR=$(( $ERR + $? )) + cp -r "${TEMPDIR}/" "${srcDir}/" + ERR=$(( $ERR + $? )) + if [[ $ERR -ne 0 ]] + then + echo "Failed to clone down the git repository of imgbrd-grabber. Cannot compile most recent version. Aborting." + exit 1 + fi + rm -rf "${TEMPDIR}" +else + git pull + ERR=$? + if [[ $ERR -ne 0 ]] + then + echo "Failed to pull updates to the git repository of imgbrd-grabber. Continuing, but you may not be compiling the latest release..." + fi +fi + +#####################{{{1 +# Main +##################### + +#Clean the build environment {{{2 +if [[ -e "${srcDir}/build" ]] +then + rm -rf "${srcDir}/build" + mkdir "${srcDir}/build" +else + mkdir "${srcDir}/build" +fi + +#Create the template directory structure for a MacOS App {{{2 +mkdir -p "${appDir}" + +#Commence Building {{{2 +echo "Building imgbrd-grabber. Build output can be found at:" +echo +echo " ${logfile}" +echo +cd "${srcDir}/build" +cmake .. -DOPENSSL_ROOT_DIR="${OPENSSL_ROOT_DIR}" -DOPENSSL_LIBRARIES="${OPENSSL_INCLUDE_DIR}" > "${logfile}" 2>&1 +ERR=$? +make -j8 > "${logfile}" 2>&1 +ERR=$(( $ERR + $? )) +cd .. + +if [[ $ERR -ne 0 ]] +then + echo + echo "Failed to build imgbrd-grabber." + echo "Last 40 lines of the log file follow." + tail -n 40 "${logfile}" + echo + exit 1 +fi +#Pack up the MacOS Application {{{2 +\cp "${srcDir}/build/gui/Grabber" "${appDir}" +\cp -r "${srcDir}"/release/* "${appDir}" +\touch "${appDir}/settings.ini" + +#Copy imgbrd-grabber configs from previous builds and inject into new App {{{2 +if [[ -e "${HOME}/Applications/Grabber.app" ]] +then + echo "Old build has been found at '${HOME}/Applications/Grabber.app'. Migrating configs into new build..." + \cp "${oldApp}"/*.txt "${appDir}" >/dev/null 2>&1 + \cp "${oldApp}"/*.ini "${appDir}" >/dev/null 2>&1 + \cp "${oldApp}"/*.log "${appDir}" >/dev/null 2>&1 + \cp "${oldApp}"/*.igl "${appDir}" >/dev/null 2>&1 + \cp -r "${oldApp}/thumbs" "${appDir}" >/dev/null 2>&1 +fi + +#Clean out any build of imgbrd-grabber that still exists from a previous execution of this script {{{2 +if [[ -e "${srcDir}/TEMP-Grabber.app" ]] +then + rm -rf "${srcDir}/TEMP-Grabber.app" +fi +mv "${srcDir}/gui/build/release/Grabber.app" "${srcDir}/TEMP-Grabber.app" + +#Decide if we are supposed to move the App to ${HOME}/Applications {{{2 +echo "Finished Compiling updated version of imgbrd-grabber. Application is now at '${srcDir}/TEMP-Grabber.app'" +read -p "Would you like to copy this to '${HOME}/Applications/Grabber.app'? [Y|n]" AGREE +case "${AGREE}" in + [nN]|[nN][oO]) #{{{3 + echo "Will not move application from '${srcDir}/TEMP-Grabber.app' to ~/Applications/Grabber.app" + echo "WARNING - This application will be destroyed the next time ${0} executes!" + mv "${srcDir}/TEMP-Grabber.app/Contents/MacOS/Grabber" "${srcDir}/TEMP-Grabber.app/Contents/MacOS/TEMP-Grabber" >/dev/null 2>&1 + APP_PATH="${srcDir}/TEMP-Grabber.app" + ;; + *) #{{{3 + if [[ -e ${HOME}/Applications/Grabber.app ]] #{{{4 + then + echo "A copy of imgbrd-grabber already exists at '${HOME}/Applications/Grabber.app'" + read -p "Overwrite '${HOME}/Applications/Grabber.app'? [y|N]" AGREE + case "${AGREE}" in + [yY]|[yY][eE]|[yY][eE][sS]) #{{{5 + rm -rf ${HOME}/Applications/Grabber.app >/dev/null 2>&1 + ERR=$? + [[ $ERR -ne 0 ]] && echo "Unable to delete '${HOME}/Applications/Grabber.app'. Aborting." && exit 1 + mv "${srcDir}/TEMP-Grabber.app" "${HOME}/Applications/Grabber.app" >/dev/null 2>&1 + APP_PATH="${HOME}/Applications/Grabber.app" + ;; + *) #{{{5 + echo "Will not move application from '${srcDir}/TEMP-Grabber.app' to ~/Applications/Grabber.app" + echo "WARNING - This application will be destroyed the next time ${0} executes!" + mv "${srcDir}/TEMP-Grabber.app/Contents/MacOS/Grabber" "${srcDir}/TEMP-Grabber.app/Contents/MacOS/TEMP-Grabber" >/dev/null 2>&1 + APP_PATH="${srcDir}/TEMP-Grabber.app" + ;; #}}}5 + esac + else #{{{4 + mv "${srcDir}/TEMP-Grabber.app" "${HOME}/Applications/Grabber.app" >/dev/null 2>&1 + APP_PATH="${HOME}/Applications/Grabber.app" + fi #}}}4 + ;; #}}}3 +esac + +#Launch the finished app? {{{2 +echo "${APP_PATH}" +read -p 'Would you like to launch the app now? [Y|n]' AGREE +case "${AGREE}" in + [yY]|[yY][eE]|[yY][eE][sS]|'') #{{{3 + \open "${APP_PATH}" + ;; + *) #{{{3 + echo "Finished Application can be found at '${APP_PATH}'" + ;; #}}}3 +esac #}}}2 +#}}}1 +# vim:ts=4:sw=4:tw=0:noexpandtab:autoindent:foldmethod=marker:foldcolumn=4 From a4174fe609f695adae6a045392fc7d09a8879c84 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 00:43:29 +0200 Subject: [PATCH 007/112] Various style fixes --- lib/src/downloader/downloader.cpp | 2 +- lib/src/downloader/file-downloader.cpp | 2 +- lib/src/downloader/image-downloader.cpp | 4 ++-- lib/src/downloader/image-downloader.h | 1 + lib/src/models/filename.cpp | 10 +++++----- lib/src/models/site.cpp | 6 +++--- lib/src/models/source.cpp | 6 +++--- lib/src/updater/program-updater.cpp | 7 +++---- lib/src/updater/updater.h | 3 +-- tests/src/downloader/image-downloader-test.h | 2 +- 10 files changed, 21 insertions(+), 22 deletions(-) diff --git a/lib/src/downloader/downloader.cpp b/lib/src/downloader/downloader.cpp index 29eee646c..6eff45db5 100644 --- a/lib/src/downloader/downloader.cpp +++ b/lib/src/downloader/downloader.cpp @@ -32,7 +32,7 @@ void Downloader::clear() } Downloader::Downloader(Profile *profile, const QStringList &tags, const QStringList &postFiltering, const QList &sources, int page, int max, int perPage, const QString &location, const QString &filename, const QString &user, const QString &password, bool blacklist, const QList &blacklistedTags, bool noDuplicates, int tagsMin, const QString &tagsFormat, Downloader *previous) - : m_profile(profile), m_lastPage(nullptr), m_tags(tags), m_postFiltering(postFiltering), m_sites(sources), m_page(page), m_max(max), m_perPage(perPage), m_waiting(0), m_ignored(0), m_duplicates(0), m_tagsMin(tagsMin), m_location(location), m_filename(filename), m_user(user), m_password(password), m_blacklist(blacklist), m_noDuplicates(noDuplicates), m_tagsFormat(tagsFormat), m_blacklistedTags(blacklistedTags), m_quit(false), m_previous(previous), m_cancelled(false) + : m_profile(profile), m_lastPage(nullptr), m_tags(tags), m_postFiltering(postFiltering), m_sites(sources), m_page(page), m_max(max), m_perPage(perPage), m_waiting(0), m_ignored(0), m_duplicates(0), m_tagsMin(tagsMin), m_location(location), m_filename(filename), m_user(user), m_password(password), m_blacklist(blacklist), m_noDuplicates(noDuplicates), m_tagsFormat(tagsFormat), m_blacklistedTags(blacklistedTags), m_cancelled(false), m_quit(false), m_previous(previous) { } void Downloader::setQuit(bool quit) diff --git a/lib/src/downloader/file-downloader.cpp b/lib/src/downloader/file-downloader.cpp index 559ff1704..ece7de1a2 100644 --- a/lib/src/downloader/file-downloader.cpp +++ b/lib/src/downloader/file-downloader.cpp @@ -6,7 +6,7 @@ FileDownloader::FileDownloader(QObject *parent) - : QObject(parent), m_reply(Q_NULLPTR) + : QObject(parent), m_reply(Q_NULLPTR), m_writeError(false) {} bool FileDownloader::start(QNetworkReply *reply, const QString &path) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 2ff4df27d..a382b3435 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -12,11 +12,11 @@ ImageDownloader::ImageDownloader(QSharedPointer img, const QString &filename, const QString &path, int count, bool addMd5, bool startCommands, QObject *parent, bool loadTags, bool rotate) - : QObject(parent), m_fileDownloader(this), m_image(img), m_filename(filename), m_path(path), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) + : QObject(parent), m_image(img), m_fileDownloader(this), m_filename(filename), m_path(path), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) {} ImageDownloader::ImageDownloader(QSharedPointer img, const QStringList &paths, int count, bool addMd5, bool startCommands, QObject *parent, bool rotate) - : QObject(parent), m_fileDownloader(this), m_image(img), m_paths(paths), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) + : QObject(parent), m_image(img), m_fileDownloader(this), m_loadTags(false), m_paths(paths), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) {} void ImageDownloader::save() diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index 30d5a5ba5..af6d97c07 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -3,6 +3,7 @@ #include #include "downloader/file-downloader.h" +#include "loader/downloadable.h" #include "models/image.h" diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index 7ffb98e9e..73599e24e 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -345,8 +345,8 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin { const int mid = QDir::toNativeSeparators(cFilename).lastIndexOf(QDir::separator()); QDir dir(folder + (mid >= 0 ? QDir::separator() + cFilename.left(mid) : QString())); - QString cRight = mid >= 0 ? cFilename.right(cFilename.length() - mid - 1) : cFilename; - QString filter = QString(cRight).replace(hasNum, "*"); + const QString cRight = mid >= 0 ? cFilename.right(cFilename.length() - mid - 1) : cFilename; + const QString filter = QString(cRight).replace(hasNum, "*"); QFileInfoList files = dir.entryInfoList(QStringList() << filter, QDir::Files, QDir::NoSort); // Sort files naturally @@ -358,9 +358,9 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin int num = 1; if (!files.isEmpty()) { - QString last = files.last().fileName(); - int pos = cRight.indexOf(hasNum); - int len = last.length() - cRight.length() + 5; + const QString last = files.last().fileName(); + const int pos = cRight.indexOf(hasNum); + const int len = last.length() - cRight.length() + 5; num = last.midRef(pos, len).toInt() + 1; } cFilename.replace(hasNum, optionedValue(num, "num", numOptions, settings, namespaces)); diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index adc110f04..00277e88e 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -275,7 +275,7 @@ void Site::getAsync(QueryType type, const QUrl &url, const std::functionmakeRequest(url, page, ref, img); - qint64 sinceLastRequest = m_lastRequest.msecsTo(QDateTime::currentDateTime()); + const qint64 sinceLastRequest = m_lastRequest.msecsTo(QDateTime::currentDateTime()); const QString key = (type == QueryType::Retry ? "retry" : (type == QueryType::List ? "page" : (type == QueryType::Img ? "image" : (type == QueryType::Thumb ? "thumbnail" : "details")))); const int def = (type == QueryType::Retry ? 60 : 0); @@ -394,8 +394,8 @@ QUrl Site::fixUrl(const QString &url, const QUrl &old) const { return QUrl(protocol + ":" + url); } if (url.startsWith("/")) { - QString baseUrl = m_url.mid(m_url.indexOf('/')); - QString right = url.startsWith(baseUrl) ? url.mid(baseUrl.length()) : url; + const QString baseUrl = m_url.mid(m_url.indexOf('/')); + const QString right = url.startsWith(baseUrl) ? url.mid(baseUrl.length()) : url; return QUrl(protocol + "://" + m_url + right); } diff --git a/lib/src/models/source.cpp b/lib/src/models/source.cpp index 351d55dc0..926b0e495 100644 --- a/lib/src/models/source.cpp +++ b/lib/src/models/source.cpp @@ -74,7 +74,7 @@ Source::Source(Profile *profile, const QString &dir) { log(QStringLiteral("Error parsing XML file: %1 (%2 - %3).").arg(errorMsg, QString::number(errorLine), QString::number(errorColumn)), Logger::Error); } else { - QDomElement docElem = doc.documentElement(); + const QDomElement docElem = doc.documentElement(); QMap details = domToMap(docElem); // Tag format mapper @@ -93,7 +93,7 @@ Source::Source(Profile *profile, const QString &dir) { log(QStringLiteral("Using Javascript model for %1").arg(m_diskName), Logger::Debug); - QString src = "(function() { var window = {}; " + js.readAll().replace("export var source = ", "return ") + " })()"; + const QString src = "(function() { var window = {}; " + js.readAll().replace("export var source = ", "return ") + " })()"; m_jsSource = jsEngine()->evaluate(src, js.fileName()); if (m_jsSource.isError()) @@ -103,7 +103,7 @@ Source::Source(Profile *profile, const QString &dir) m_name = m_jsSource.property("name").toString(); // Get the list of APIs for this Source - QJSValue apis = m_jsSource.property("apis"); + const QJSValue apis = m_jsSource.property("apis"); QJSValueIterator it(apis); while (it.hasNext()) { diff --git a/lib/src/updater/program-updater.cpp b/lib/src/updater/program-updater.cpp index 75a9bca50..0b26ea427 100644 --- a/lib/src/updater/program-updater.cpp +++ b/lib/src/updater/program-updater.cpp @@ -3,7 +3,6 @@ #include #include #include -#include "custom-network-access-manager.h" #include "logger.h" #include "vendor/json.h" @@ -37,16 +36,16 @@ void ProgramUpdater::checkForUpdatesDone() QVariant json = Json::parse(m_source); QMap lastRelease = json.toMap(); - QString changelog; #if defined NIGHTLY QString latest = lastRelease["target_commitish"].toString(); QString current = QString(NIGHTLY_COMMIT); bool isNew = !current.isEmpty() && latest != current; latest = latest.left(8); + QString changelog; #else - QString latest = lastRelease["name"].toString().mid(1); + const QString latest = lastRelease["name"].toString().mid(1); const bool isNew = compareVersions(latest, QString(VERSION)) > 0; - changelog = lastRelease["body"].toString(); + const QString changelog = lastRelease["body"].toString(); #endif m_newVersion = latest; diff --git a/lib/src/updater/updater.h b/lib/src/updater/updater.h index 89614015b..f97a8f73f 100644 --- a/lib/src/updater/updater.h +++ b/lib/src/updater/updater.h @@ -2,10 +2,9 @@ #define UPDATER_H #include +#include "custom-network-access-manager.h" -class CustomNetworkAccessManager; - class Updater : public QObject { Q_OBJECT diff --git a/tests/src/downloader/image-downloader-test.h b/tests/src/downloader/image-downloader-test.h index 747fb14d2..d2f946e88 100644 --- a/tests/src/downloader/image-downloader-test.h +++ b/tests/src/downloader/image-downloader-test.h @@ -2,7 +2,7 @@ #define IMAGE_DOWNLOADER_TEST_H #include "downloader/image-downloader.h" -#include +#include "models/source.h" #include "test-suite.h" From b5c7612d3a4f924a7ed42e321e84a08883ee3662 Mon Sep 17 00:00:00 2001 From: chrissly90 Date: Thu, 21 Jun 2018 08:52:27 +0200 Subject: [PATCH 008/112] Fix gcc compile errors on MAC OS and Debian 9 --- tests/src/models/filename-test.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/src/models/filename-test.cpp b/tests/src/models/filename-test.cpp index ecde29498..e0a973cc6 100644 --- a/tests/src/models/filename-test.cpp +++ b/tests/src/models/filename-test.cpp @@ -670,11 +670,11 @@ void FilenameTest::testNeedTemporaryFile() void FilenameTest::testNeedExactTags() { - QCOMPARE(Filename("%md5%.%ext%").needExactTags(false), 0); + QCOMPARE(Filename("%md5%.%ext%").needExactTags(NULL), 0); QCOMPARE(Filename("%md5%.%ext%").needExactTags(m_site), 0); - QCOMPARE(Filename("javascript:md5 + '.' + ext").needExactTags(false), 2); - QCOMPARE(Filename("%character% %md5%.%ext%").needExactTags(false), 1); - QCOMPARE(Filename("%all:includenamespace% %md5%.%ext%").needExactTags(false), 1); + QCOMPARE(Filename("javascript:md5 + '.' + ext").needExactTags(NULL), 2); + QCOMPARE(Filename("%character% %md5%.%ext%").needExactTags(NULL), 1); + QCOMPARE(Filename("%all:includenamespace% %md5%.%ext%").needExactTags(NULL), 1); Filename filename("%filename%.%ext%"); QCOMPARE(filename.needExactTags(), 0); From c5c4ec140c147c68d0d181204a1edd7ba9bc2d11 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 00:43:50 +0200 Subject: [PATCH 009/112] Fix multiple tag conditional filenames (fix #1310) --- lib/src/models/filename.cpp | 5 ++++- tests/src/models/filename-test.cpp | 13 ++++++++++++- tests/src/models/filename-test.h | 1 + 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index 73599e24e..0cafa42f6 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -175,6 +175,9 @@ void Filename::setJavaScriptVariables(QJSEngine &engine, QSettings *settings, co bool Filename::matchConditionalFilename(QString cond, QSettings *settings, const QMap &tokens) const { + if (cond.isEmpty()) + return false; + // Javascript conditions if (cond.startsWith("javascript:")) { @@ -197,7 +200,7 @@ bool Filename::matchConditionalFilename(QString cond, QSettings *settings, const const QStringList options = cond.split(' '); const QStringList matches = PostFilter::filter(tokens, options); - return matches.isEmpty(); + return matches.count() < options.count(); } QList> Filename::expandTokens(const QString &filename, QMap tokens, QSettings *settings) const diff --git a/tests/src/models/filename-test.cpp b/tests/src/models/filename-test.cpp index e0a973cc6..01615a9b8 100644 --- a/tests/src/models/filename-test.cpp +++ b/tests/src/models/filename-test.cpp @@ -542,13 +542,24 @@ void FilenameTest::testConditionalsTag() { m_settings->setValue("Filenames/0_fn", "%md5%.%ext%"); m_settings->setValue("Filenames/0_dir", QDir::homePath()); - m_settings->setValue("Filenames/0_cond", "tag4 tag7"); + m_settings->setValue("Filenames/0_cond", "tag7"); m_settings->setValue("Filenames/1_fn", "%id% %md5%.%ext%"); m_settings->setValue("Filenames/1_dir", QDir::homePath()); m_settings->setValue("Filenames/1_cond", "character1"); assertPath("%artist%/%copyright%/%character%/%md5%.%ext%", "7331 1bc29b36f623ba82aaf6724fd3b16718.jpg"); } +void FilenameTest::testConditionalsMultipleTags() +{ + m_settings->setValue("Filenames/0_fn", "%md5%.%ext%"); + m_settings->setValue("Filenames/0_dir", QDir::homePath()); + m_settings->setValue("Filenames/0_cond", "tag7"); + m_settings->setValue("Filenames/1_fn", "%id% %md5%.%ext%"); + m_settings->setValue("Filenames/1_dir", QDir::homePath()); + m_settings->setValue("Filenames/1_cond", "tag1 tag8"); + + assertPath("%artist%/%copyright%/%character%/%md5%.%ext%", "7331 1bc29b36f623ba82aaf6724fd3b16718.jpg"); +} void FilenameTest::testConditionalsToken() { m_settings->setValue("Filenames/0_fn", "%md5%.%ext%"); diff --git a/tests/src/models/filename-test.h b/tests/src/models/filename-test.h index 0fe276f91..67d861f9c 100644 --- a/tests/src/models/filename-test.h +++ b/tests/src/models/filename-test.h @@ -70,6 +70,7 @@ class FilenameTest : public TestSuite void testIsValid(); void testUseShorterCopyright(); void testConditionalsTag(); + void testConditionalsMultipleTags(); void testConditionalsToken(); void testConditionalsMeta(); void testConditionalsCustom(); From 5c30343d0897d39ee9987e400488682b401fb16b Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 01:54:44 +0200 Subject: [PATCH 010/112] Un-reference Token.value --- lib/src/loader/token.cpp | 2 +- lib/src/loader/token.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/src/loader/token.cpp b/lib/src/loader/token.cpp index 2be23584c..b2e922032 100644 --- a/lib/src/loader/token.cpp +++ b/lib/src/loader/token.cpp @@ -12,7 +12,7 @@ Token::Token(const QVariant &value, const QString &whatToDoDefault, const QStrin {} -const QVariant &Token::value() const +QVariant Token::value() const { return m_value; } QString Token::toString() const diff --git a/lib/src/loader/token.h b/lib/src/loader/token.h index 0f25b305a..fdc95d29a 100644 --- a/lib/src/loader/token.h +++ b/lib/src/loader/token.h @@ -11,7 +11,7 @@ class Token explicit Token(const QVariant &value, const QVariant &def = QVariant()); explicit Token(const QVariant &value, const QString &whatToDoDefault, const QString &emptyDefault, const QString &multipleDefault); - const QVariant &value() const; + QVariant value() const; template T value() const { return m_value.value(); } QString toString() const; From f0d0a94377a74c8ad5e5866f32f9750968378355 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 02:08:02 +0200 Subject: [PATCH 011/112] Fix empty TagType name --- lib/src/tags/tag-type.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/tags/tag-type.cpp b/lib/src/tags/tag-type.cpp index 44bb5a850..6a3856af5 100644 --- a/lib/src/tags/tag-type.cpp +++ b/lib/src/tags/tag-type.cpp @@ -6,7 +6,7 @@ TagType::TagType() : m_isUnknown(true), m_name("unknown") {} TagType::TagType(const QString &name) - : m_isUnknown(name.isEmpty() || name == "unknown"), m_name(name) + : m_isUnknown(name.isEmpty() || name == "unknown"), m_name(name.isEmpty() ? "unknown" : name) {} bool TagType::isUnknown() const From a6975845c1f9e0f132b8f08e0a21fa6c2b9a0b46 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 03:21:57 +0200 Subject: [PATCH 012/112] Fix build --- gui/src/settings/filenamewindow.cpp | 1 + gui/src/tag-context-menu.cpp | 1 + lib/src/functions.cpp | 1 + lib/src/tags/tag.h | 1 + 4 files changed, 4 insertions(+) diff --git a/gui/src/settings/filenamewindow.cpp b/gui/src/settings/filenamewindow.cpp index d17963437..01ad9195a 100644 --- a/gui/src/settings/filenamewindow.cpp +++ b/gui/src/settings/filenamewindow.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include "models/filename.h" #include "models/image.h" diff --git a/gui/src/tag-context-menu.cpp b/gui/src/tag-context-menu.cpp index 58e278505..5f2ee17df 100644 --- a/gui/src/tag-context-menu.cpp +++ b/gui/src/tag-context-menu.cpp @@ -3,6 +3,7 @@ #include #include #include +#include "functions.h" #include "models/profile.h" diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index bca5b25c6..cab25ea11 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #ifdef Q_OS_WIN #include #else diff --git a/lib/src/tags/tag.h b/lib/src/tags/tag.h index 4d33ad34a..d2235c094 100644 --- a/lib/src/tags/tag.h +++ b/lib/src/tags/tag.h @@ -4,6 +4,7 @@ #include #include #include +#include #include "tags/tag-type.h" From 508ab3e0493d104585c6e2678fdae61e200edab1 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 03:37:21 +0200 Subject: [PATCH 013/112] Add explicit destructors to TagDatabase classes --- lib/src/tags/tag-database-in-memory.cpp | 3 +++ lib/src/tags/tag-database-in-memory.h | 1 + lib/src/tags/tag-database-sqlite.cpp | 3 +++ lib/src/tags/tag-database-sqlite.h | 1 + lib/src/tags/tag-database.cpp | 3 +++ lib/src/tags/tag-database.h | 1 + 6 files changed, 12 insertions(+) diff --git a/lib/src/tags/tag-database-in-memory.cpp b/lib/src/tags/tag-database-in-memory.cpp index c47bf268e..601ac66e9 100644 --- a/lib/src/tags/tag-database-in-memory.cpp +++ b/lib/src/tags/tag-database-in-memory.cpp @@ -8,6 +8,9 @@ TagDatabaseInMemory::TagDatabaseInMemory(const QString &typeFile, const QString : TagDatabase(typeFile), m_tagFile(tagFile) {} +TagDatabaseInMemory::~TagDatabaseInMemory() +{} + bool TagDatabaseInMemory::load() { // Don't reload databases diff --git a/lib/src/tags/tag-database-in-memory.h b/lib/src/tags/tag-database-in-memory.h index 2b1cca9c8..f1bf48323 100644 --- a/lib/src/tags/tag-database-in-memory.h +++ b/lib/src/tags/tag-database-in-memory.h @@ -9,6 +9,7 @@ class TagDatabaseInMemory : public TagDatabase { public: TagDatabaseInMemory(const QString &typeFile, const QString &tagFile); + ~TagDatabaseInMemory() override; bool load() override; bool save() override; void setTags(const QList &tags) override; diff --git a/lib/src/tags/tag-database-sqlite.cpp b/lib/src/tags/tag-database-sqlite.cpp index dc8fa33ea..e0a42cb89 100644 --- a/lib/src/tags/tag-database-sqlite.cpp +++ b/lib/src/tags/tag-database-sqlite.cpp @@ -13,6 +13,9 @@ TagDatabaseSqlite::TagDatabaseSqlite(const QString &typeFile, const QString &tag : TagDatabase(typeFile), m_tagFile(tagFile), m_count(-1) {} +TagDatabaseSqlite::~TagDatabaseSqlite() +{} + bool TagDatabaseSqlite::load() { // Don't reload databases diff --git a/lib/src/tags/tag-database-sqlite.h b/lib/src/tags/tag-database-sqlite.h index 32df0db33..c4e58da87 100644 --- a/lib/src/tags/tag-database-sqlite.h +++ b/lib/src/tags/tag-database-sqlite.h @@ -11,6 +11,7 @@ class TagDatabaseSqlite : public TagDatabase { public: TagDatabaseSqlite(const QString &typeFile, const QString &tagFile); + ~TagDatabaseSqlite() override; bool load() override; bool save() override; void setTags(const QList &tags) override; diff --git a/lib/src/tags/tag-database.cpp b/lib/src/tags/tag-database.cpp index 5ec6e2a06..669588f6d 100644 --- a/lib/src/tags/tag-database.cpp +++ b/lib/src/tags/tag-database.cpp @@ -9,6 +9,9 @@ TagDatabase::TagDatabase(const QString &typeFile) : m_typeFile(typeFile) {} +TagDatabase::~TagDatabase() +{} + bool TagDatabase::load() { loadTypes(); diff --git a/lib/src/tags/tag-database.h b/lib/src/tags/tag-database.h index a8d52099f..3612c74f3 100644 --- a/lib/src/tags/tag-database.h +++ b/lib/src/tags/tag-database.h @@ -11,6 +11,7 @@ class Tag; class TagDatabase { public: + virtual ~TagDatabase(); void loadTypes(); virtual bool load(); virtual bool save() = 0; From 031712cf348d04878c23a00c179c357922d8ebe4 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 15:05:00 +0200 Subject: [PATCH 014/112] Fix sankaku rating tag count not detected (fix #1312) --- release/sites/Sankaku/model.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release/sites/Sankaku/model.ts b/release/sites/Sankaku/model.ts index ee1292f7b..d71509168 100644 --- a/release/sites/Sankaku/model.ts +++ b/release/sites/Sankaku/model.ts @@ -80,7 +80,7 @@ export const source: ISource = { } }, parse: (src: string): IParsedSearch => { - const searchImageCounts = Grabber.regexMatches('class="?tag-count"? title="Post Count: (?[0-9,]+)"', src); + const searchImageCounts = Grabber.regexMatches('class="?tag-(?:count|type-none)"? title="Post Count: (?[0-9,]+)"', src); const lastPage = Grabber.regexToConst("page", '\\s*(?[0-9,]+)\\s*\\s*>>\\s*', src); return { tags: Grabber.regexToTags('
  • ]*tag-type-(?[^">]+)(?:|"[^>]*)>.*?]*>(?[^<\\?]+).*?(?\\d+).*?
  • ', src), From 5d3ef0f34f187b63b3f9d9d1795a9419dd8e6f38 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 23 Jun 2018 15:39:31 +0200 Subject: [PATCH 015/112] Fix Zerochan always loading sample images (fix #1317) --- release/sites/Zerochan/model.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/release/sites/Zerochan/model.ts b/release/sites/Zerochan/model.ts index ff97af4cc..cc94db8fc 100644 --- a/release/sites/Zerochan/model.ts +++ b/release/sites/Zerochan/model.ts @@ -1,13 +1,14 @@ function completeImage(img: IImage): IImage { if (!img["file_url"] || img["file_url"].length < 5) { - img["file_url"] = img["preview_url"] - .replace(".240.", ".full.") - .replace(".600.", ".full.") - .replace("/240/", "/full/") - .replace("/600/", "/full/"); + img["file_url"] = img["preview_url"]; } - img["file_url"] = img["file_url"].replace(/\/s\d+\.zerochan/, "/static.zerochan"); + img["file_url"] = img["file_url"] + .replace(/\/s\d+\.zerochan/, "/static.zerochan") + .replace(".240.", ".full.") + .replace(".600.", ".full.") + .replace("/240/", "/full/") + .replace("/600/", "/full/"); return img; } From 2928cf38b75ef3ba87c8353b4ab04a9f937e52cc Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 24 Jun 2018 01:24:54 +0200 Subject: [PATCH 016/112] Fix Grabber JS helper on older Qt versions --- release/sites/helper.ts | 52 ++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/release/sites/helper.ts b/release/sites/helper.ts index 31ff1ec36..f690e3f99 100644 --- a/release/sites/helper.ts +++ b/release/sites/helper.ts @@ -1,19 +1,23 @@ -Grabber.makeArray = (val: any): any[] => { +function addHelper(name: string, value: any): void { + Object.defineProperty(Grabber, name, { value }); +} + +addHelper("makeArray", (val: any): any[] => { if (!Array.isArray(val)) { return [ val ]; } return val; -}; +}); -Grabber.mapObject = (obj: any, fn: (v: any) => any): any => { +addHelper("mapObject", (obj: any, fn: (v: any) => any): any => { const ret: any = {}; for (const k in obj) { ret[k] = fn(obj[k]); } return ret; -}; +}); -Grabber.typedXML = (val: any) => { +addHelper("typedXML", (val: any) => { if (val && typeof val === "object" && ("#text" in val || "@attributes" in val)) { const txt = val["#text"]; @@ -47,9 +51,9 @@ Grabber.typedXML = (val: any) => { } return val; -}; +}); -Grabber.mapFields = (data: any, map: any): any => { +addHelper("mapFields", (data: any, map: any): any => { const result: any = {}; if (typeof data !== "object") { return result; @@ -59,9 +63,9 @@ Grabber.mapFields = (data: any, map: any): any => { result[to] = from in data && data[from] !== null ? data[from] : undefined; } return result; -}; +}); -Grabber.countToInt = (str: string): number => { +addHelper("countToInt", (str: string): number => { if (!str) { return 0; } @@ -74,9 +78,9 @@ Grabber.countToInt = (str: string): number => { count = parseFloat(normalized); } return Math.round(count); -}; +}); -Grabber.loginUrl = (fields: any, values: any): string => { +addHelper("loginUrl", (fields: any, values: any): string => { let res = ""; for (const field of fields) { const val = values[field.key]; @@ -85,9 +89,9 @@ Grabber.loginUrl = (fields: any, values: any): string => { } } return res; -}; +}); -Grabber.fixPageUrl = (url: string, page: number, previous: any): string => { +addHelper("fixPageUrl", (url: string, page: number, previous: any): string => { url = url.replace("{page}", String(page)); if (previous) { url = url.replace("{min}", previous.minId); @@ -98,9 +102,9 @@ Grabber.fixPageUrl = (url: string, page: number, previous: any): string => { url = url.replace("{max+1}", previous.maxId + 1); } return url; -}; +}); -Grabber.pageUrl = (page: number, previous: any, limit: number, ifBelow: string, ifPrev: string, ifNext: string): string => { +addHelper("pageUrl", (page: number, previous: any, limit: number, ifBelow: string, ifPrev: string, ifNext: string): string => { if (page <= limit || limit < 0) { return Grabber.fixPageUrl(ifBelow, page, previous); } @@ -111,9 +115,9 @@ Grabber.pageUrl = (page: number, previous: any, limit: number, ifBelow: string, return Grabber.fixPageUrl(ifNext, page, previous); } throw new Error("You need valid previous page information to browse that far"); -}; +}); -Grabber.regexToImages = (regexp: string, src: string): IImage[] => { +addHelper("regexToImages", (regexp: string, src: string): IImage[] => { const images: IImage[] = []; const matches = Grabber.regexMatches(regexp, src); for (const match of matches) { @@ -126,9 +130,9 @@ Grabber.regexToImages = (regexp: string, src: string): IImage[] => { images.push(match); } return images; -}; +}); -Grabber.regexToTags = (regexp: string, src: string): ITag[] => { +addHelper("regexToTags", (regexp: string, src: string): ITag[] => { const tags: ITag[] = []; const uniques: { [key: string]: boolean } = {}; @@ -144,21 +148,21 @@ Grabber.regexToTags = (regexp: string, src: string): ITag[] => { uniques[match["name"]] = true; } return tags; -}; +}); -Grabber.regexToPools = (regexp: string, src: string): IPool[] => { +addHelper("regexToPools", (regexp: string, src: string): IPool[] => { const pools: IPool[] = []; const matches = Grabber.regexMatches(regexp, src); for (const match of matches) { pools.push(match); } return pools; -}; +}); -Grabber.regexToConst = (key: string, regexp: string, src: string): string => { +addHelper("regexToConst", (key: string, regexp: string, src: string): string => { const matches = Grabber.regexMatches(regexp, src); for (const match of matches) { return match[key]; } return undefined; -}; +}); From a078a3eeb2da37040c21d0ecdbcc9fb27c14738b Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 24 Jun 2018 12:13:40 +0200 Subject: [PATCH 017/112] Pass site baseUrl in JS api opts parameter --- lib/src/models/api/javascript-api.cpp | 2 ++ lib/src/models/site.cpp | 7 +++++++ lib/src/models/site.h | 1 + 3 files changed, 10 insertions(+) diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index 0d496151c..c74fd152d 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -94,6 +94,7 @@ PageUrl JavascriptApi::pageUrl(const QString &search, int page, int limit, int l QJSValue opts = m_source.engine()->newObject(); opts.setProperty("limit", limit); + opts.setProperty("baseUrl", site->baseUrl()); opts.setProperty("loggedIn", site->isLoggedIn(false, true)); QJSValue auth = m_source.engine()->newObject(); MixedSettings *settings = site->settings(); @@ -276,6 +277,7 @@ PageUrl JavascriptApi::tagsUrl(int page, int limit, Site *site) const QJSValue opts = m_source.engine()->newObject(); opts.setProperty("limit", limit); + opts.setProperty("baseUrl", site->baseUrl()); opts.setProperty("loggedIn", site->isLoggedIn(false, true)); QJSValue auth = m_source.engine()->newObject(); MixedSettings *settings = site->settings(); diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index 00277e88e..1d6d678a2 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -342,6 +342,13 @@ void Site::syncSettings() { m_settings->sync(); } MixedSettings *Site::settings() const { return m_settings; } TagDatabase *Site::tagDatabase() const { return m_tagDatabase; } +QString Site::baseUrl() const +{ + const bool ssl = m_settings->value("ssl", false).toBool(); + const QString protocol = (ssl ? QStringLiteral("https") : QStringLiteral("http")); + return protocol + "://" + m_url; +} + const QString &Site::name() const { return m_name; } const QString &Site::url() const { return m_url; } const QString &Site::type() const { return m_type; } diff --git a/lib/src/models/site.h b/lib/src/models/site.h index e2f9d5de1..1234b21cd 100644 --- a/lib/src/models/site.h +++ b/lib/src/models/site.h @@ -53,6 +53,7 @@ class Site : public QObject void loadConfig(); const QString &type() const; const QString &name() const; + QString baseUrl() const; const QString &url() const; const QList &cookies() const; QVariant setting(const QString &key, const QVariant &def = QVariant()); From 4798eccb0cd0ad2a21eee982d0a4234d41d7e153 Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 25 Jun 2018 19:53:52 +0200 Subject: [PATCH 018/112] Fix JSON API url for Sankaku (issue #1250) --- release/sites/Sankaku/chan.sankakucomplex.com/defaults.ini | 2 +- release/sites/Sankaku/idol.sankakucomplex.com/defaults.ini | 2 +- release/sites/Sankaku/model.ts | 5 ++++- release/sites/Sankaku/sites.txt | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/release/sites/Sankaku/chan.sankakucomplex.com/defaults.ini b/release/sites/Sankaku/chan.sankakucomplex.com/defaults.ini index c0e4f3d77..f780f9889 100644 --- a/release/sites/Sankaku/chan.sankakucomplex.com/defaults.ini +++ b/release/sites/Sankaku/chan.sankakucomplex.com/defaults.ini @@ -4,7 +4,7 @@ referer_preview=page referer_image=none name=chan.sankakucomplex.com ssl=true -headers="@Variant(\0\0\0\b\0\0\0\x2\0\0\0\x14\0U\0s\0\x65\0r\0-\0\x41\0g\0\x65\0n\0t\0\0\0\n\0\0\0\x46\0S\0\x43\0\x43\0h\0\x61\0n\0n\0\x65\0l\0\x41\0p\0p\0/\0\x32\0.\0\x30\0.\0\x31\0 \0(\0\x41\0n\0\x64\0r\0o\0i\0\x64\0;\0 \0\x62\0l\0\x61\0\x63\0k\0)\0\0\0\x1e\0\x41\0\x63\0\x63\0\x65\0p\0t\0-\0L\0\x61\0n\0g\0u\0\x61\0g\0\x65\0\0\0\n\0\0\0\x1c\0\x65\0n\0-\0U\0S\0,\0\x65\0n\0;\0q\0=\0\x30\0.\0\x38)" +headers="@Variant(\0\0\0\b\0\0\0\x1\0\0\0\x14\0U\0s\0\x65\0r\0-\0\x41\0g\0\x65\0n\0t\0\0\0\n\0\0\0\xe4\0M\0o\0z\0i\0l\0l\0\x61\0/\0\x35\0.\0\x30\0 \0(\0W\0i\0n\0\x64\0o\0w\0s\0 \0N\0T\0 \0\x31\0\x30\0.\0\x30\0;\0 \0W\0i\0n\0\x36\0\x34\0;\0 \0x\0\x36\0\x34\0)\0 \0\x41\0p\0p\0l\0\x65\0W\0\x65\0\x62\0K\0i\0t\0/\0\x35\0\x33\0\x37\0.\0\x33\0\x36\0 \0(\0K\0H\0T\0M\0L\0,\0 \0l\0i\0k\0\x65\0 \0G\0\x65\0\x63\0k\0o\0)\0 \0\x43\0h\0r\0o\0m\0\x65\0/\0\x36\0\x37\0.\0\x30\0.\0\x33\0\x33\0\x39\0\x36\0.\0\x38\0\x37\0 \0S\0\x61\0\x66\0\x61\0r\0i\0/\0\x35\0\x33\0\x37\0.\0\x33\0\x36)" [sources] usedefault=false diff --git a/release/sites/Sankaku/idol.sankakucomplex.com/defaults.ini b/release/sites/Sankaku/idol.sankakucomplex.com/defaults.ini index ffabff17e..1990dc26f 100644 --- a/release/sites/Sankaku/idol.sankakucomplex.com/defaults.ini +++ b/release/sites/Sankaku/idol.sankakucomplex.com/defaults.ini @@ -4,7 +4,7 @@ referer_preview=page referer_image=none name=idol.sankakucomplex.com ssl=true -headers="@Variant(\0\0\0\b\0\0\0\x2\0\0\0\x14\0U\0s\0\x65\0r\0-\0\x41\0g\0\x65\0n\0t\0\0\0\n\0\0\0\x46\0S\0\x43\0\x43\0h\0\x61\0n\0n\0\x65\0l\0\x41\0p\0p\0/\0\x32\0.\0\x30\0.\0\x31\0 \0(\0\x41\0n\0\x64\0r\0o\0i\0\x64\0;\0 \0\x62\0l\0\x61\0\x63\0k\0)\0\0\0\x1e\0\x41\0\x63\0\x63\0\x65\0p\0t\0-\0L\0\x61\0n\0g\0u\0\x61\0g\0\x65\0\0\0\n\0\0\0\x1c\0\x65\0n\0-\0U\0S\0,\0\x65\0n\0;\0q\0=\0\x30\0.\0\x38)" +headers="@Variant(\0\0\0\b\0\0\0\x1\0\0\0\x14\0U\0s\0\x65\0r\0-\0\x41\0g\0\x65\0n\0t\0\0\0\n\0\0\0\xe4\0M\0o\0z\0i\0l\0l\0\x61\0/\0\x35\0.\0\x30\0 \0(\0W\0i\0n\0\x64\0o\0w\0s\0 \0N\0T\0 \0\x31\0\x30\0.\0\x30\0;\0 \0W\0i\0n\0\x36\0\x34\0;\0 \0x\0\x36\0\x34\0)\0 \0\x41\0p\0p\0l\0\x65\0W\0\x65\0\x62\0K\0i\0t\0/\0\x35\0\x33\0\x37\0.\0\x33\0\x36\0 \0(\0K\0H\0T\0M\0L\0,\0 \0l\0i\0k\0\x65\0 \0G\0\x65\0\x63\0k\0o\0)\0 \0\x43\0h\0r\0o\0m\0\x65\0/\0\x36\0\x37\0.\0\x30\0.\0\x33\0\x33\0\x39\0\x36\0.\0\x38\0\x37\0 \0S\0\x61\0\x66\0\x61\0r\0i\0/\0\x35\0\x33\0\x37\0.\0\x33\0\x36)" [sources] usedefault=false diff --git a/release/sites/Sankaku/model.ts b/release/sites/Sankaku/model.ts index d71509168..2c5c0191b 100644 --- a/release/sites/Sankaku/model.ts +++ b/release/sites/Sankaku/model.ts @@ -48,8 +48,11 @@ export const source: ISource = { maxLimit: 200, search: { url: (query: any, opts: any, previous: any): string => { + const baseUrl = opts.baseUrl + .replace("//chan.", "//capi-beta.") + .replace("//idol.", "//iapi."); const loginPart = Grabber.loginUrl(auth.url.fields, opts["auth"]); - return "/post/index.json?" + loginPart + "page=" + query.page + "&limit=" + opts.limit + "&tags=" + query.search; + return baseUrl + "/post/index.json?" + loginPart + "page=" + query.page + "&limit=" + opts.limit + "&tags=" + query.search; }, parse: (src: string): IParsedSearch => { const data = JSON.parse(src); diff --git a/release/sites/Sankaku/sites.txt b/release/sites/Sankaku/sites.txt index d637465cb..f2155c465 100644 --- a/release/sites/Sankaku/sites.txt +++ b/release/sites/Sankaku/sites.txt @@ -1 +1,2 @@ -chan.sankakucomplex.com \ No newline at end of file +chan.sankakucomplex.com +idol.sankakucomplex.com \ No newline at end of file From 29355c592c42f8052bb1f25a0c3802e7e8ef3aea Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 00:01:36 +0200 Subject: [PATCH 019/112] Fix default preset name disappearing when adding presets --- gui/src/sources/sourceswindow.cpp | 28 ++++++++++++++++------------ gui/src/sources/sourceswindow.h | 1 + gui/src/sources/sourceswindow.ui | 8 +------- 3 files changed, 18 insertions(+), 19 deletions(-) diff --git a/gui/src/sources/sourceswindow.cpp b/gui/src/sources/sourceswindow.cpp index 831fe505b..4b2cf4d10 100644 --- a/gui/src/sources/sourceswindow.cpp +++ b/gui/src/sources/sourceswindow.cpp @@ -46,14 +46,9 @@ sourcesWindow::sourcesWindow(Profile *profile, const QList &selected, QWi connect(ui->checkBox, &QCheckBox::clicked, this, &sourcesWindow::checkClicked); checkUpdate(); - // Set default preset font italic - QFont font = ui->comboPresets->itemData(0, Qt::FontRole).value(); - font.setItalic(true); - ui->comboPresets->setItemData(0, font, Qt::FontRole); - // Presets m_presets = loadPresets(m_profile->getSettings()); - ui->comboPresets->addItems(m_presets.keys()); + showPresets(); // Check for updates in the model files checkForUpdates(); @@ -392,6 +387,19 @@ QList sourcesWindow::selected() const return selected; } +void sourcesWindow::showPresets() +{ + // Reset combo box and re-add items + ui->comboPresets->clear(); + ui->comboPresets->addItem(tr("- No preset selected -")); + ui->comboPresets->addItems(m_presets.keys()); + + // Set default preset font italic + QFont font = ui->comboPresets->itemData(0, Qt::FontRole).value(); + font.setItalic(true); + ui->comboPresets->setItemData(0, font, Qt::FontRole); +} + void sourcesWindow::addPreset() { bool ok; @@ -406,9 +414,7 @@ void sourcesWindow::addPreset() sel.append(site->url()); m_presets.insert(name, sel); - ui->comboPresets->clear(); - ui->comboPresets->addItem(QString()); - ui->comboPresets->addItems(m_presets.keys()); + showPresets(); ui->comboPresets->setCurrentText(name); } @@ -429,9 +435,7 @@ void sourcesWindow::editPreset() m_presets.insert(newName, m_presets[oldName]); m_presets.remove(oldName); - ui->comboPresets->clear(); - ui->comboPresets->addItem(QString()); - ui->comboPresets->addItems(m_presets.keys()); + showPresets(); ui->comboPresets->setCurrentText(newName); } diff --git a/gui/src/sources/sourceswindow.h b/gui/src/sources/sourceswindow.h index 4087a989c..b06138a24 100644 --- a/gui/src/sources/sourceswindow.h +++ b/gui/src/sources/sourceswindow.h @@ -49,6 +49,7 @@ class sourcesWindow : public QDialog // Presets QMap loadPresets(QSettings *settings) const; void savePresets(QSettings *settings) const; + void showPresets(); void addPreset(); void deletePreset(); void editPreset(); diff --git a/gui/src/sources/sourceswindow.ui b/gui/src/sources/sourceswindow.ui index f081047bd..ca458aae2 100644 --- a/gui/src/sources/sourceswindow.ui +++ b/gui/src/sources/sourceswindow.ui @@ -55,13 +55,7 @@ - - - - - No preset selected - - - - + From 7c85d7511e13d6866c432acab5a7f50dcfa2e10d Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 17:55:50 +0200 Subject: [PATCH 020/112] Add support for 'lazy' tokens to reduce their overhead --- lib/src/loader/token.cpp | 17 +++++++++++++-- lib/src/loader/token.h | 5 ++++- tests/src/loader/token-test.cpp | 38 +++++++++++++++++++++++++++++++++ tests/src/loader/token-test.h | 18 ++++++++++++++++ 4 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 tests/src/loader/token-test.cpp create mode 100644 tests/src/loader/token-test.h diff --git a/lib/src/loader/token.cpp b/lib/src/loader/token.cpp index b2e922032..3670dcf88 100644 --- a/lib/src/loader/token.cpp +++ b/lib/src/loader/token.cpp @@ -11,12 +11,25 @@ Token::Token(const QVariant &value, const QString &whatToDoDefault, const QStrin : m_value(value), m_whatToDoDefault(whatToDoDefault), m_emptyDefault(emptyDefault), m_multipleDefault(multipleDefault) {} +Token::Token(std::function func, bool cacheResult) + : m_func(std::move(func)), m_cacheResult(cacheResult) +{} + QVariant Token::value() const -{ return m_value; } +{ + if (m_func == nullptr || m_value.isValid()) + { return m_value; } + + QVariant val = m_func(); + if (m_cacheResult) + { m_value = val; } + + return val; +} QString Token::toString() const -{ return m_value.toString(); } +{ return value().toString(); } const QString &Token::whatToDoDefault() const diff --git a/lib/src/loader/token.h b/lib/src/loader/token.h index fdc95d29a..24575d5fd 100644 --- a/lib/src/loader/token.h +++ b/lib/src/loader/token.h @@ -10,6 +10,7 @@ class Token Token() = default; explicit Token(const QVariant &value, const QVariant &def = QVariant()); explicit Token(const QVariant &value, const QString &whatToDoDefault, const QString &emptyDefault, const QString &multipleDefault); + explicit Token(std::function func, bool cacheResult = true); QVariant value() const; template T value() const { return m_value.value(); } @@ -20,10 +21,12 @@ class Token const QString &multipleDefault() const; private: - QVariant m_value; + mutable QVariant m_value; QString m_whatToDoDefault; QString m_emptyDefault; QString m_multipleDefault; + std::function m_func = nullptr; + bool m_cacheResult; }; bool operator==(const Token &lhs, const Token &rhs); diff --git a/tests/src/loader/token-test.cpp b/tests/src/loader/token-test.cpp new file mode 100644 index 000000000..bdfea9663 --- /dev/null +++ b/tests/src/loader/token-test.cpp @@ -0,0 +1,38 @@ +#include "token-test.h" +#include + + +void TokenTest::testLazyNotCalled() +{ + int callCount = 0; + Token token([&callCount]() { return ++callCount; }); + + QCOMPARE(callCount, 0); +} + +void TokenTest::testLazyWithCaching() +{ + int callCount = 0; + Token token([&callCount]() { return ++callCount; }, true); + + token.value(); + int val = token.value().toInt(); + + QCOMPARE(callCount, 1); + QCOMPARE(val, 1); +} + +void TokenTest::testLazyWithoutCaching() +{ + int callCount = 0; + Token token([&callCount]() { return ++callCount; }, false); + + token.value(); + int val = token.value().toInt(); + + QCOMPARE(callCount, 2); + QCOMPARE(val, 2); +} + + +static TokenTest instance; diff --git a/tests/src/loader/token-test.h b/tests/src/loader/token-test.h new file mode 100644 index 000000000..376c0eec7 --- /dev/null +++ b/tests/src/loader/token-test.h @@ -0,0 +1,18 @@ +#ifndef TOKEN_TEST_H +#define TOKEN_TEST_H + +#include "loader/token.h" +#include "test-suite.h" + + +class TokenTest : public TestSuite +{ + Q_OBJECT + + private slots: + void testLazyNotCalled(); + void testLazyWithCaching(); + void testLazyWithoutCaching(); +}; + +#endif // TOKEN_TEST_H From 9fcaffcc73e07b68075b57444fcb3b4038c55b67 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 18:10:05 +0200 Subject: [PATCH 021/112] Add 'grabber' meta-tag for post-filtering (fix #1325) --- lib/src/loader/downloadable.cpp | 28 ++++++++++++++++++++++++++++ lib/src/models/post-filter.cpp | 16 ++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/lib/src/loader/downloadable.cpp b/lib/src/loader/downloadable.cpp index b579f7c19..e343d2146 100644 --- a/lib/src/loader/downloadable.cpp +++ b/lib/src/loader/downloadable.cpp @@ -1,5 +1,6 @@ #include "loader/downloadable.h" #include "functions.h" +#include "models/filename.h" #include "models/profile.h" @@ -30,6 +31,33 @@ const QMap &Downloadable::tokens(Profile *profile) const { tokens.insert(it.key(), Token(it.value())); } } + // Use a lazy token for Grabber meta-tags as it can be expensive to calculate + tokens.insert("grabber", Token([profile, tokens]() { + QString pth = profile->getSettings()->value("Save/path").toString(); + Filename filename(profile->getSettings()->value("Save/filename").toString()); + QStringList paths = filename.path(tokens, profile, pth); + bool alreadyExists = false; + for (const QString &path : paths) + { + if (QFile::exists(path)) + { + alreadyExists = true; + break; + } + } + bool inMd5List = !profile->md5Action(tokens["md5"].value().toString()).second.isEmpty(); + + // Generate corresponding combination + QStringList metas; + if (alreadyExists) + { metas.append("alreadyExists"); } + if (inMd5List) + { metas.append("inMd5List"); } + if (alreadyExists || inMd5List) + { metas.append("downloaded"); } + return metas; + })); + m_tokens = tokens; } diff --git a/lib/src/models/post-filter.cpp b/lib/src/models/post-filter.cpp index 3d1555cda..1460c5a0a 100644 --- a/lib/src/models/post-filter.cpp +++ b/lib/src/models/post-filter.cpp @@ -40,6 +40,22 @@ QString PostFilter::match(const QMap &tokens, QString filter, bo { const QString type = filter.section(':', 0, 0).toLower(); filter = filter.section(':', 1).toLower(); + + // Grabber specials + if (type == QStringLiteral("grabber")) + { + const QStringList &vals = tokens[type].value().toStringList(); + bool cond = vals.contains(filter, Qt::CaseInsensitive); + + if (!cond && !invert) + { return QObject::tr("image is not \"%1\"").arg(filter); } + if (cond && invert) + { return QObject::tr("image is \"%1\"").arg(filter); } + + return QString(); + } + + // Meta tokens if (!tokens.contains(type)) { QStringList keys = tokens.keys(); From 423fe4bead8ef605828ea31efcbe8b6beafdadaa Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 18:38:20 +0200 Subject: [PATCH 022/112] Don't trust calculated count from tags for image count (issue #1329) --- lib/src/models/page-api.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 03a426c26..813cbdd6d 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -209,6 +209,16 @@ void PageApi::parseActual() if (!page.wiki.isEmpty()) { m_wiki = page.wiki; } + // Complete image count information from tag count information + if (m_imagesCount < 1) + { + for (const Tag &tag : qAsConst(m_tags)) + { + if (tag.text() == m_search.join(" ")) + { setImageCount(tag.count(), false); } + } + } + // Complete missing tag information from images' tags if necessary if (m_tags.isEmpty()) { @@ -229,16 +239,6 @@ void PageApi::parseActual() } } - // Complete image count information from tag count information - if (m_imagesCount < 1) - { - for (const Tag &tag : qAsConst(m_tags)) - { - if (tag.text() == m_search.join(" ")) - { setImageCount(tag.count(), false); } - } - } - // Remove first n images (according to site settings) int skip = m_site->setting("ignore/always", 0).toInt(); if (false && m_isAltPage) // FIXME(Bionus): broken since move to Api class From 189eab58c70d036daab892b241bf9ea7e5fe2bf5 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 19:36:06 +0200 Subject: [PATCH 023/112] Calculate 'max image count' when parsing page tags (issue #1331) --- lib/src/models/page-api.cpp | 31 +++++++++++++++++++++++++++++-- lib/src/models/page-api.h | 5 ++++- lib/src/models/page.cpp | 20 ++++++++++++++++++++ lib/src/models/page.h | 2 ++ 4 files changed, 55 insertions(+), 3 deletions(-) diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 813cbdd6d..647c2de54 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -18,6 +18,7 @@ PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, const : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(tags), m_postFiltering(postFiltering), m_errors(QStringList()), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(nullptr), m_replyTags(nullptr) { m_imagesCount = -1; + m_maxImagesCount = -1; m_pagesCount = -1; m_imagesCountSafe = false; m_pagesCountSafe = false; @@ -94,6 +95,7 @@ void PageApi::load(bool rateLimit, bool force) m_loaded = false; m_pageImageCount = 0; /*m_imagesCount = -1; + m_maxImagesCount = -1; m_pagesCount = -1;*/ m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply *reply) { @@ -212,10 +214,22 @@ void PageApi::parseActual() // Complete image count information from tag count information if (m_imagesCount < 1) { + int found = 0; + int min = -1; for (const Tag &tag : qAsConst(m_tags)) { - if (tag.text() == m_search.join(" ")) - { setImageCount(tag.count(), false); } + if (m_search.contains(tag.text())) + { + found++; + if (min == -1 || min > tag.count()) + { min = tag.count(); } + } + } + if (m_search.count() == found) + { + if (m_search.count() == 1) + { setImageCount(min, false); } + setImageMaxCount(min); } } @@ -328,6 +342,8 @@ int PageApi::imagesCount(bool guess) const return m_imagesCount; } +int PageApi::maxImagesCount() const +{ return m_maxImagesCount; } bool PageApi::isPageCountSure() const { return m_pagesCountSafe; } int PageApi::pagesCount(bool guess) const { @@ -346,6 +362,15 @@ int PageApi::pagesCount(bool guess) const return m_pagesCount; } +int PageApi::maxPagesCount() const +{ + if (m_maxImagesCount < 0) + return -1; + + const int forcedLimit = m_api->forcedLimit(); + const int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; + return qCeil(static_cast(m_maxImagesCount) / perPage); +} qulonglong PageApi::maxId() const { @@ -379,6 +404,8 @@ void PageApi::setImageCount(int count, bool sure) } } } +void PageApi::setImageMaxCount(int maxCount) +{ m_maxImagesCount = maxCount; } void PageApi::setPageCount(int count, bool sure) { diff --git a/lib/src/models/page-api.h b/lib/src/models/page-api.h index 026b3c096..02e3cab45 100644 --- a/lib/src/models/page-api.h +++ b/lib/src/models/page-api.h @@ -28,7 +28,9 @@ class PageApi : public QObject bool isImageCountSure() const; bool isPageCountSure() const; int imagesCount(bool guess = true) const; + int maxImagesCount() const; int pagesCount(bool guess = true) const; + int maxPagesCount() const; const QUrl &url() const; const QString &source() const; const QString &wiki() const; @@ -61,6 +63,7 @@ class PageApi : public QObject void updateUrls(); void parseActual(); void setImageCount(int count, bool sure); + void setImageMaxCount(int maxCount); void setPageCount(int count, bool sure); private: @@ -77,7 +80,7 @@ class PageApi : public QObject QList> m_images; QList m_tags; QNetworkReply *m_reply, *m_replyTags; - int m_imagesCount, m_pagesCount, m_pageImageCount; + int m_imagesCount, m_maxImagesCount, m_pagesCount, m_pageImageCount; bool m_imagesCountSafe, m_pagesCountSafe; bool m_loaded = false; }; diff --git a/lib/src/models/page.cpp b/lib/src/models/page.cpp index 3d33585b2..85d698b69 100644 --- a/lib/src/models/page.cpp +++ b/lib/src/models/page.cpp @@ -189,6 +189,16 @@ int Page::imagesCount(bool guess) const } return m_pageApis[m_currentApi]->imagesCount(guess); } +int Page::maxImagesCount() const +{ + if (m_regexApi >= 0 && !m_pageApis[m_currentApi]->isImageCountSure()) + { + const int count = m_pageApis[m_regexApi]->maxImagesCount(); + if (count >= 0) + return count; + } + return m_pageApis[m_currentApi]->maxImagesCount(); +} int Page::pagesCount(bool guess) const { if (m_regexApi >= 0 && !m_pageApis[m_currentApi]->isPageCountSure()) @@ -199,6 +209,16 @@ int Page::pagesCount(bool guess) const } return m_pageApis[m_currentApi]->pagesCount(guess); } +int Page::maxPagesCount() const +{ + if (m_regexApi >= 0 && !m_pageApis[m_currentApi]->isPageCountSure()) + { + const int count = m_pageApis[m_regexApi]->maxPagesCount(); + if (count >= 0) + return count; + } + return m_pageApis[m_currentApi]->maxPagesCount(); +} qulonglong Page::maxId() const { diff --git a/lib/src/models/page.h b/lib/src/models/page.h index 7748410fc..45509b251 100644 --- a/lib/src/models/page.h +++ b/lib/src/models/page.h @@ -27,7 +27,9 @@ class Page : public QObject const QList> &images() const; Site *site() const; int imagesCount(bool guess = true) const; + int maxImagesCount() const; int pagesCount(bool guess = true) const; + int maxPagesCount() const; const QUrl &url() const; const QUrl &friendlyUrl() const; bool hasSource() const; From f9e0fbe0d6363b7e21b1396bd6a8f8fb1d05d768 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 19:38:16 +0200 Subject: [PATCH 024/112] Use 'max image count' in display and batch downloads (fix #1331) --- gui/src/tabs/favorites-tab.cpp | 2 +- gui/src/tabs/pool-tab.cpp | 2 +- gui/src/tabs/search-tab.cpp | 15 +++++++++++---- gui/src/tabs/tag-tab.cpp | 2 +- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/gui/src/tabs/favorites-tab.cpp b/gui/src/tabs/favorites-tab.cpp index 2f97bda55..d99138fe2 100644 --- a/gui/src/tabs/favorites-tab.cpp +++ b/gui/src/tabs/favorites-tab.cpp @@ -272,7 +272,7 @@ void favoritesTab::getAll() const int highLimit = page->highLimit(); const int currentCount = page->images().count(); - const int imageCount = page->imagesCount(); + const int imageCount = page->imagesCount() >= 0 ? page->imagesCount() : page->maxImagesCount(); const int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); const int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; if ((perPage == 0 && total == 0) || (currentCount == 0 && imageCount <= 0)) diff --git a/gui/src/tabs/pool-tab.cpp b/gui/src/tabs/pool-tab.cpp index 7e8a67a86..d09b10c9a 100644 --- a/gui/src/tabs/pool-tab.cpp +++ b/gui/src/tabs/pool-tab.cpp @@ -155,7 +155,7 @@ void poolTab::getAll() const int highLimit = page->highLimit(); const int currentCount = page->images().count(); - const int imageCount = page->imagesCount(); + const int imageCount = page->imagesCount() >= 0 ? page->imagesCount() : page->maxImagesCount(); const int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); const int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; if ((perPage == 0 && total == 0) || (currentCount == 0 && imageCount <= 0)) diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index 5d04822c1..749bc94f5 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -757,7 +757,8 @@ void searchTab::setMergedLabelText(QLabel *txt, const QListsetText(QString(links + " - Page %1 of %2 (%3 of max %4)").arg(page).arg(maxPage).arg(imgs.count()).arg(sumImages)); + const QString countLabel = tr("Page %1 of %2 (%3 of %4)").arg(page).arg(maxPage).arg(imgs.count()).arg(tr("max %1").arg(sumImages)); + txt->setText(QString(links + " - " + countLabel)); } void searchTab::setPageLabelText(QLabel *txt, Page *page, const QList> &imgs, const QString &noResultsMessage) { @@ -793,10 +794,16 @@ void searchTab::setPageLabelText(QLabel *txt, Page *page, const QList 0 ? (page->pagesCount(false) == -1 ? "~" : QString()) + QString::number(pageCount) : "?"; - const QString imageCountStr = imageCount > 0 ? (page->imagesCount(false) == -1 ? "~" : QString()) + QString::number(imageCount) : "?"; const QString pageLabel = firstPage != lastPage ? QString("%1-%2").arg(firstPage).arg(lastPage) : QString::number(lastPage); - txt->setText("url().toString().toHtmlEscaped()+"\">"+page->site()->name()+" - "+tr("Page %1 of %2 (%3 of %4)").arg(pageLabel, pageCountStr).arg(totalCount).arg(imageCountStr)); + const QString pageCountStr = pageCount > 0 + ? (page->pagesCount(false) == -1 ? "~" : QString()) + QString::number(pageCount) + : (page->maxPagesCount() == -1 ? "?" : QString::number(page->maxPagesCount())); + const QString imageCountStr = imageCount > 0 + ? (page->imagesCount(false) == -1 ? "~" : QString()) + QString::number(imageCount) + : (page->maxImagesCount() == -1 ? "?" : tr("max %1").arg(page->maxImagesCount())); + + const QString countLabel = tr("Page %1 of %2 (%3 of %4)").arg(pageLabel, pageCountStr).arg(totalCount).arg(imageCountStr); + txt->setText("url().toString().toHtmlEscaped()+"\">"+page->site()->name()+" - " + countLabel); } /*if (page->search().join(" ") != m_search->toPlainText() && m_settings->value("showtagwarning", true).toBool()) diff --git a/gui/src/tabs/tag-tab.cpp b/gui/src/tabs/tag-tab.cpp index a5e98e68b..410db9787 100644 --- a/gui/src/tabs/tag-tab.cpp +++ b/gui/src/tabs/tag-tab.cpp @@ -210,7 +210,7 @@ void tagTab::getAll() const int highLimit = page->highLimit(); const int currentCount = page->images().count(); - const int imageCount = page->imagesCount(); + const int imageCount = page->imagesCount() >= 0 ? page->imagesCount() : page->maxImagesCount(); const int total = imageCount > 0 ? qMax(currentCount, imageCount) : (highLimit > 0 ? highLimit : currentCount); const int perPage = highLimit > 0 ? (imageCount > 0 ? qMin(highLimit, imageCount) : highLimit) : currentCount; if ((perPage == 0 && total == 0) || (currentCount == 0 && imageCount <= 0)) From f66c511abda093036508b64a5eaf903187d9d7d4 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 20:26:19 +0200 Subject: [PATCH 025/112] Fix Danbooru parsing with '+' and '-' tag links (fix #1331) --- release/sites/Danbooru (2.0)/model.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release/sites/Danbooru (2.0)/model.ts b/release/sites/Danbooru (2.0)/model.ts index 6ad503dac..66f85e2a6 100644 --- a/release/sites/Danbooru (2.0)/model.ts +++ b/release/sites/Danbooru (2.0)/model.ts @@ -257,7 +257,7 @@ export const source: ISource = { }, parse: (src: string): IParsedSearch => { return { - tags: Grabber.regexToTags('
  • (?:\\s*\\?)?\\s*]*href="[^"]+"[^>]*>(?[^<]+)\\s*(?[^<]+)\\s*
  • ', src), + tags: Grabber.regexToTags('
  • (?:\\s*\\?)?(?:\\s*]* class="search-inc-tag">[^<]+\\s*]* class="search-exl-tag">[^<]+)?\\s*]*href="[^"]+"[^>]*>(?[^<]+)\\s*(?[^<]+)\\s*
  • ', src), images: Grabber.regexToImages(']* id="[^"]*" class="[^"]*"\\s+data-id="(?[^"]*)"\\s+data-has-sound="[^"]*"\\s+data-tags="(?[^"]*)"\\s+data-pools="(?[^"]*)"(?:\\s+data-uploader="(?[^"]*)")?\\s+data-approver-id="(?[^"]*)"\\s+data-rating="(?[^"]*)"\\s+data-width="(?[^"]*)"\\s+data-height="(?[^"]*)"\\s+data-flags="(?[^"]*)"\\s+data-parent-id="(?[^"]*)"\\s+data-has-children="(?[^"]*)"\\s+data-score="(?[^"]*)"\\s+data-views="[^"]*"\\s+data-fav-count="(?[^"]*)"\\s+data-pixiv-id="[^"]*"\\s+data-file-ext="(?[^"]*)"\\s+data-source="(?[^"]*)"\\s+data-top-tagger="[^"]*"\\s+data-uploader-id="[^"]*"\\s+data-normalized-source="[^"]*"\\s+data-is-favorited="[^"]*"\\s+data-md5="(?[^"]*)"\\s+data-file-url="(?[^"]*)"\\s+data-large-file-url="(?[^"]*)"\\s+data-preview-file-url="(?[^"]*)"', src).map(completeImage), wiki: Grabber.regexToConst("wiki", '
    ]+)>(?.+?)
    ', src), pageCount: Grabber.regexToConst("page", ">(?\\d+)<(?:a|span)[^>]*>>><", src), From 212509ffb3e359f0c33a324174fe80f737db6da0 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 8 Jul 2018 21:03:53 +0200 Subject: [PATCH 026/112] Add a few const --- lib/src/login/oauth2-login.cpp | 10 +++++----- lib/src/models/api/javascript-api.cpp | 2 +- lib/src/models/api/javascript-console-helper.cpp | 10 +++++----- lib/src/models/api/javascript-console-helper.h | 10 +++++----- lib/src/models/api/javascript-grabber-helper.cpp | 4 ++-- lib/src/models/filename.cpp | 6 +++--- lib/src/models/post-filter.cpp | 2 +- lib/src/models/profile.cpp | 6 +++--- lib/src/models/profile.h | 6 +++--- lib/src/models/site.cpp | 6 +++--- lib/src/models/site.h | 6 +++--- lib/src/models/source-guesser.cpp | 2 +- 12 files changed, 35 insertions(+), 35 deletions(-) diff --git a/lib/src/login/oauth2-login.cpp b/lib/src/login/oauth2-login.cpp index 8619019e1..49ee0c32f 100644 --- a/lib/src/login/oauth2-login.cpp +++ b/lib/src/login/oauth2-login.cpp @@ -19,16 +19,16 @@ bool OAuth2Login::isTestable() const void OAuth2Login::login() { // Get user application credentials - QString consumerKey = m_settings->value("auth/consumerKey").toString(); - QString consumerSecret = m_settings->value("auth/consumerSecret").toString(); - QByteArray bearerCredentials = QUrl::toPercentEncoding(consumerKey) + ":" + QUrl::toPercentEncoding(consumerSecret); - QByteArray base64BearerCredentials = bearerCredentials.toBase64(); + const QString consumerKey = m_settings->value("auth/consumerKey").toString(); + const QString consumerSecret = m_settings->value("auth/consumerSecret").toString(); + const QByteArray bearerCredentials = QUrl::toPercentEncoding(consumerKey) + ":" + QUrl::toPercentEncoding(consumerSecret); + const QByteArray base64BearerCredentials = bearerCredentials.toBase64(); // Create request QNetworkRequest request(m_site->fixUrl(m_settings->value("login/oauth2/tokenUrl").toString())); request.setRawHeader("Authorization", "Basic " + base64BearerCredentials); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded;charset=UTF-8"); - QString body = QStringLiteral("grant_type=client_credentials"); + const QString body = QStringLiteral("grant_type=client_credentials"); // Post request and wait for a reply m_tokenReply = m_manager->post(request, body.toUtf8()); diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index c74fd152d..54656cf6e 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -227,7 +227,7 @@ ParsedPage JavascriptApi::parsePage(Page *parentPage, const QString &source, int if (!d.isEmpty()) { - int id = d["id"].toInt(); + const int id = d["id"].toInt(); QSharedPointer img = parseImage(parentPage, d, id + first, tags, false); if (!img.isNull()) { ret.images.append(img); } diff --git a/lib/src/models/api/javascript-console-helper.cpp b/lib/src/models/api/javascript-console-helper.cpp index aec2b9335..d91540693 100644 --- a/lib/src/models/api/javascript-console-helper.cpp +++ b/lib/src/models/api/javascript-console-helper.cpp @@ -8,27 +8,27 @@ JavascriptConsoleHelper::JavascriptConsoleHelper(const QString &prefix, QObject {} -void JavascriptConsoleHelper::debug(const QString &msg) +void JavascriptConsoleHelper::debug(const QString &msg) const { LOG(m_prefix + msg, Logger::Debug); } -void JavascriptConsoleHelper::error(const QString &msg) +void JavascriptConsoleHelper::error(const QString &msg) const { LOG(m_prefix + msg, Logger::Error); } -void JavascriptConsoleHelper::info(const QString &msg) +void JavascriptConsoleHelper::info(const QString &msg) const { LOG(m_prefix + msg, Logger::Info); } -void JavascriptConsoleHelper::log(const QString &msg) +void JavascriptConsoleHelper::log(const QString &msg) const { LOG(m_prefix + msg, Logger::Info); } -void JavascriptConsoleHelper::warn(const QString &msg) +void JavascriptConsoleHelper::warn(const QString &msg) const { LOG(m_prefix + msg, Logger::Warning); } diff --git a/lib/src/models/api/javascript-console-helper.h b/lib/src/models/api/javascript-console-helper.h index a357cb6ab..5d0717944 100644 --- a/lib/src/models/api/javascript-console-helper.h +++ b/lib/src/models/api/javascript-console-helper.h @@ -11,11 +11,11 @@ class JavascriptConsoleHelper : public QObject public: explicit JavascriptConsoleHelper(const QString &prefix, QObject *parent = Q_NULLPTR); - Q_INVOKABLE void debug(const QString &msg); - Q_INVOKABLE void error(const QString &msg); - Q_INVOKABLE void info(const QString &msg); - Q_INVOKABLE void log(const QString &msg); - Q_INVOKABLE void warn(const QString &msg); + Q_INVOKABLE void debug(const QString &msg) const; + Q_INVOKABLE void error(const QString &msg) const; + Q_INVOKABLE void info(const QString &msg) const; + Q_INVOKABLE void log(const QString &msg) const; + Q_INVOKABLE void warn(const QString &msg) const; private: QString m_prefix; diff --git a/lib/src/models/api/javascript-grabber-helper.cpp b/lib/src/models/api/javascript-grabber-helper.cpp index 84b697482..0df522733 100644 --- a/lib/src/models/api/javascript-grabber-helper.cpp +++ b/lib/src/models/api/javascript-grabber-helper.cpp @@ -33,7 +33,7 @@ QJSValue JavascriptGrabberHelper::regexMatches(const QString ®ex, const QStri if (val.isEmpty()) continue; - int underscorePos = group.lastIndexOf('_'); + const int underscorePos = group.lastIndexOf('_'); bool ok; group.midRef(underscorePos + 1).toInt(&ok); if (underscorePos != -1 && ok) @@ -100,7 +100,7 @@ QJSValue JavascriptGrabberHelper::_parseXMLRec(const QDomNode &node) const prop = newProp; } - quint32 length = prop.property(QStringLiteral("length")).toUInt(); + const quint32 length = prop.property(QStringLiteral("length")).toUInt(); prop.setProperty(length, _parseXMLRec(item)); } } diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index 0cafa42f6..c96ec2407 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -373,7 +373,7 @@ QStringList Filename::path(QMap tokens, Profile *profile, QStrin } } - int cnt = fns.count(); + const int cnt = fns.count(); for (int i = 0; i < cnt; ++i) { if (shouldFixFilename) @@ -429,7 +429,7 @@ QString Filename::optionedValue(const QVariant &val, const QString &key, const Q QStringList opts = ops.split(QRegularExpression("(? &tokens, QString filter, bo if (type == QStringLiteral("grabber")) { const QStringList &vals = tokens[type].value().toStringList(); - bool cond = vals.contains(filter, Qt::CaseInsensitive); + const bool cond = vals.contains(filter, Qt::CaseInsensitive); if (!cond && !invert) { return QObject::tr("image is not \"%1\"").arg(filter); } diff --git a/lib/src/models/profile.cpp b/lib/src/models/profile.cpp index 727c6a0b2..1b1ca290d 100644 --- a/lib/src/models/profile.cpp +++ b/lib/src/models/profile.cpp @@ -210,7 +210,7 @@ void Profile::sync() if (m_settings != nullptr) m_settings->sync(); } -void Profile::syncFavorites() +void Profile::syncFavorites() const { QFile fileFavorites(m_path + "/favorites.json"); if (fileFavorites.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) @@ -235,7 +235,7 @@ void Profile::syncFavorites() fileFavorites.close(); } } -void Profile::syncKeptForLater() +void Profile::syncKeptForLater() const { QFile fileKfl(m_path + "/viewitlater.txt"); if (fileKfl.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) @@ -244,7 +244,7 @@ void Profile::syncKeptForLater() fileKfl.close(); } } -void Profile::syncIgnored() +void Profile::syncIgnored() const { QFile fileIgnored(m_path + "/ignore.txt"); if (fileIgnored.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) diff --git a/lib/src/models/profile.h b/lib/src/models/profile.h index f2c53173c..d097069b7 100644 --- a/lib/src/models/profile.h +++ b/lib/src/models/profile.h @@ -71,9 +71,9 @@ class Profile : public QObject QList getFilteredSites(const QStringList &urls) const; private: - void syncFavorites(); - void syncKeptForLater(); - void syncIgnored(); + void syncFavorites() const; + void syncKeptForLater() const; + void syncIgnored() const; signals: void favoritesChanged(); diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index 1d6d678a2..6cb19c26d 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -336,9 +336,9 @@ void Site::finishedTags() emit finishedLoadingTags(tags); } -QVariant Site::setting(const QString &key, const QVariant &def) { return m_settings->value(key, def); } -void Site::setSetting(const QString &key, const QVariant &value, const QVariant &def) { m_settings->setValue(key, value, def); } -void Site::syncSettings() { m_settings->sync(); } +QVariant Site::setting(const QString &key, const QVariant &def) const { return m_settings->value(key, def); } +void Site::setSetting(const QString &key, const QVariant &value, const QVariant &def) const { m_settings->setValue(key, value, def); } +void Site::syncSettings() const { m_settings->sync(); } MixedSettings *Site::settings() const { return m_settings; } TagDatabase *Site::tagDatabase() const { return m_tagDatabase; } diff --git a/lib/src/models/site.h b/lib/src/models/site.h index 1234b21cd..61be279fe 100644 --- a/lib/src/models/site.h +++ b/lib/src/models/site.h @@ -56,9 +56,9 @@ class Site : public QObject QString baseUrl() const; const QString &url() const; const QList &cookies() const; - QVariant setting(const QString &key, const QVariant &def = QVariant()); - void setSetting(const QString &key, const QVariant &value, const QVariant &def); - void syncSettings(); + QVariant setting(const QString &key, const QVariant &def = QVariant()) const; + void setSetting(const QString &key, const QVariant &value, const QVariant &def) const; + void syncSettings() const; MixedSettings *settings() const; TagDatabase *tagDatabase() const; QNetworkRequest makeRequest(QUrl url, Page *page = nullptr, const QString &referer = "", Image *img = nullptr); diff --git a/lib/src/models/source-guesser.cpp b/lib/src/models/source-guesser.cpp index 3c0f800db..511f36298 100644 --- a/lib/src/models/source-guesser.cpp +++ b/lib/src/models/source-guesser.cpp @@ -29,7 +29,7 @@ Source *SourceGuesser::start() Api *api = source->getApis().first(); if (api->canLoadCheck()) { - QString checkUrl = api->checkUrl().url; + const QString checkUrl = api->checkUrl().url; if (!m_cache.contains(checkUrl)) { QUrl getUrl(m_url + checkUrl); From 619cf2701dc72fa6663a12eebad23957ea713799 Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 9 Jul 2018 00:35:03 +0200 Subject: [PATCH 027/112] Fix a bunch of clang tidy errors --- e2e/src/main.cpp | 4 +- gui/src/aboutwindow.cpp | 2 +- gui/src/batch/adduniquewindow.cpp | 4 +- gui/src/batch/adduniquewindow.h | 2 +- gui/src/favoritewindow.cpp | 7 ++- gui/src/favoritewindow.h | 3 +- gui/src/image-context-menu.cpp | 2 +- gui/src/mainwindow.cpp | 12 ++--- gui/src/settings/optionswindow.cpp | 6 +-- gui/src/settings/web-service-window.cpp | 2 +- gui/src/sources/sourceswindow.cpp | 2 +- gui/src/tabs/favorites-tab.cpp | 2 +- gui/src/tabs/search-tab.cpp | 20 ++++---- gui/src/tabs/search-tab.h | 12 ++--- gui/src/theme-loader.cpp | 4 +- gui/src/theme-loader.h | 2 +- gui/src/ui/QAffiche.cpp | 2 +- gui/src/ui/QBouton.cpp | 20 ++++---- gui/src/ui/QBouton.h | 2 +- gui/src/ui/fixed-size-grid-layout.cpp | 9 ++-- gui/src/ui/qclosabletabwidget.cpp | 6 +-- .../utils/blacklist-fix/blacklist-fix-2.cpp | 4 +- gui/src/utils/blacklist-fix/blacklist-fix-2.h | 2 +- .../utils/empty-dirs-fix/empty-dirs-fix-1.cpp | 2 +- .../rename-existing/rename-existing-2.cpp | 4 +- .../utils/rename-existing/rename-existing-2.h | 2 +- gui/src/viewer/details-window.cpp | 2 +- gui/src/viewer/details-window.h | 2 +- gui/src/viewer/zoom-window.cpp | 12 ++--- gui/src/viewer/zoom-window.h | 8 ++-- lib/src/commands/commands.cpp | 4 +- lib/src/commands/sql-worker.cpp | 4 +- lib/src/commands/sql-worker.h | 2 +- lib/src/custom-network-access-manager.cpp | 8 ++-- lib/src/downloader/download-query-group.cpp | 8 ++-- lib/src/downloader/download-query-group.h | 4 +- lib/src/downloader/download-query.cpp | 4 +- lib/src/downloader/download-query.h | 2 +- lib/src/downloader/downloader.cpp | 8 ++-- lib/src/downloader/downloader.h | 4 +- lib/src/downloader/image-downloader.cpp | 8 ++-- lib/src/downloader/image-downloader.h | 4 +- lib/src/functions.cpp | 48 +++++++++---------- lib/src/functions.h | 12 ++--- lib/src/language-loader.cpp | 4 +- lib/src/language-loader.h | 2 +- lib/src/loader/downloadable-downloader.cpp | 2 +- lib/src/loader/downloadable.cpp | 4 +- lib/src/loader/loader-query.cpp | 4 +- lib/src/loader/loader-query.h | 2 +- lib/src/loader/token.cpp | 9 ++-- lib/src/loader/token.h | 4 +- lib/src/logger.cpp | 2 +- lib/src/logger.h | 2 +- lib/src/login/http-get-login.cpp | 8 ++-- lib/src/login/http-login.cpp | 12 +++-- lib/src/login/http-login.h | 2 +- lib/src/login/http-post-login.cpp | 4 +- lib/src/login/url-login.cpp | 8 +++- lib/src/mixed-settings.cpp | 4 +- lib/src/mixed-settings.h | 2 +- lib/src/models/api/api.cpp | 4 +- lib/src/models/api/api.h | 2 +- lib/src/models/api/html-api.cpp | 19 ++++---- .../models/api/javascript-console-helper.cpp | 4 +- .../models/api/javascript-console-helper.h | 2 +- lib/src/models/favorite.cpp | 12 ++--- lib/src/models/favorite.h | 6 +-- lib/src/models/filename.cpp | 8 ++-- lib/src/models/filename.h | 4 +- lib/src/models/image.cpp | 14 +++--- lib/src/models/image.h | 1 - lib/src/models/monitor.cpp | 4 +- lib/src/models/monitor.h | 2 +- lib/src/models/page-api.cpp | 7 ++- lib/src/models/page-api.h | 4 +- lib/src/models/page.h | 2 +- lib/src/models/pool.cpp | 4 +- lib/src/models/pool.h | 2 +- lib/src/models/profile.cpp | 10 ++-- lib/src/models/profile.h | 4 +- lib/src/models/site.cpp | 9 ++-- lib/src/models/site.h | 2 +- lib/src/models/source-guesser.cpp | 8 ++-- lib/src/models/source-guesser.h | 2 +- lib/src/models/source.cpp | 2 +- .../reverse-search/reverse-search-engine.cpp | 4 +- .../reverse-search/reverse-search-engine.h | 2 +- lib/src/tags/tag-database-in-memory.cpp | 7 +-- lib/src/tags/tag-database-in-memory.h | 4 +- lib/src/tags/tag-database-sqlite.cpp | 7 +-- lib/src/tags/tag-database-sqlite.h | 4 +- lib/src/tags/tag-database.cpp | 7 +-- lib/src/tags/tag-database.h | 4 +- lib/src/tags/tag-name-format.cpp | 7 +-- lib/src/tags/tag-name-format.h | 4 +- lib/src/tags/tag-name.cpp | 7 +-- lib/src/tags/tag-name.h | 4 +- lib/src/tags/tag-stylist.cpp | 5 -- lib/src/tags/tag.cpp | 8 ++-- lib/src/tags/tag.h | 2 +- lib/src/updater/program-updater.cpp | 4 +- lib/src/updater/program-updater.h | 2 +- lib/src/updater/source-updater.cpp | 4 +- lib/src/updater/source-updater.h | 2 +- 105 files changed, 287 insertions(+), 297 deletions(-) diff --git a/e2e/src/main.cpp b/e2e/src/main.cpp index f83cbf51f..137053199 100644 --- a/e2e/src/main.cpp +++ b/e2e/src/main.cpp @@ -16,7 +16,7 @@ #include "tags/tag.h" -bool opCompare(QString op, int left, int right) +bool opCompare(const QString &op, int left, int right) { if (right == -1) return true; @@ -27,7 +27,7 @@ bool opCompare(QString op, int left, int right) return left == right; } -bool jsonCompare(QVariant value, QJsonValue opt) +bool jsonCompare(const QVariant &value, QJsonValue opt) { QString op = "="; if (opt.isArray()) diff --git a/gui/src/aboutwindow.cpp b/gui/src/aboutwindow.cpp index e4b2e0754..9026819d8 100644 --- a/gui/src/aboutwindow.cpp +++ b/gui/src/aboutwindow.cpp @@ -3,7 +3,7 @@ AboutWindow::AboutWindow(const QString &version, QWidget *parent) - : QDialog(parent), ui(new Ui::AboutWindow), m_updater() + : QDialog(parent), ui(new Ui::AboutWindow) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); diff --git a/gui/src/batch/adduniquewindow.cpp b/gui/src/batch/adduniquewindow.cpp index 943435d44..ccf5bac14 100644 --- a/gui/src/batch/adduniquewindow.cpp +++ b/gui/src/batch/adduniquewindow.cpp @@ -17,7 +17,7 @@ * @param parent The parent window */ AddUniqueWindow::AddUniqueWindow(Site *selected, Profile *profile, QWidget *parent) - : QDialog(parent), ui(new Ui::AddUniqueWindow), m_sites(profile->getSites()), m_profile(profile) + : QDialog(parent), ui(new Ui::AddUniqueWindow), m_page(Q_NULLPTR), m_sites(profile->getSites()), m_close(Q_NULLPTR), m_profile(profile) { ui->setupUi(this); @@ -102,7 +102,7 @@ void AddUniqueWindow::addLoadedImage() { addImage(m_image); } -void AddUniqueWindow::addImage(QSharedPointer img) +void AddUniqueWindow::addImage(const QSharedPointer &img) { emit sendData(DownloadQueryImage(*img, m_sites[ui->comboSites->currentText()], ui->lineFilename->text(), ui->lineFolder->text())); diff --git a/gui/src/batch/adduniquewindow.h b/gui/src/batch/adduniquewindow.h index 57f46baca..88ec2902e 100644 --- a/gui/src/batch/adduniquewindow.h +++ b/gui/src/batch/adduniquewindow.h @@ -29,7 +29,7 @@ class AddUniqueWindow : public QDialog void ok(bool close = true); void replyFinished(Page *p); void addLoadedImage(); - void addImage(QSharedPointer img); + void addImage(const QSharedPointer& img); void on_buttonFolder_clicked(); void on_lineFilename_textChanged(const QString &); diff --git a/gui/src/favoritewindow.cpp b/gui/src/favoritewindow.cpp index 0dd5920bf..ce3fcc881 100644 --- a/gui/src/favoritewindow.cpp +++ b/gui/src/favoritewindow.cpp @@ -1,7 +1,6 @@ #include "favoritewindow.h" #include #include -#include #include #include #include "functions.h" @@ -15,8 +14,8 @@ * @param Favorite The favorite we are setting options for * @param parent The parent window */ -favoriteWindow::favoriteWindow(Profile *profile, const Favorite &favorite, QWidget *parent) - : QDialog(parent), ui(new Ui::favoriteWindow), m_profile(profile), m_favorite(favorite) +favoriteWindow::favoriteWindow(Profile *profile, Favorite favorite, QWidget *parent) + : QDialog(parent), ui(new Ui::favoriteWindow), m_profile(profile), m_favorite(std::move(favorite)) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); @@ -31,7 +30,7 @@ favoriteWindow::favoriteWindow(Profile *profile, const Favorite &favorite, QWidg if (!m_favorite.getMonitors().isEmpty()) { Monitor monitor = m_favorite.getMonitors().first(); - ui->spinMonitoringInterval->setValue(qFloor(monitor.interval() / 60)); + ui->spinMonitoringInterval->setValue(qFloor(monitor.interval() / 60.0)); ui->comboMonitoringSource->setCurrentIndex(sourceKeys.indexOf(monitor.site()->url())); } diff --git a/gui/src/favoritewindow.h b/gui/src/favoritewindow.h index 4e531b557..9fac1258d 100644 --- a/gui/src/favoritewindow.h +++ b/gui/src/favoritewindow.h @@ -1,7 +1,6 @@ #ifndef FAVORITEWINDOW_H #define FAVORITEWINDOW_H -#include #include #include "models/favorite.h" @@ -19,7 +18,7 @@ class favoriteWindow : public QDialog Q_OBJECT public: - favoriteWindow(Profile *profile, const Favorite &favorite, QWidget *parent); + favoriteWindow(Profile *profile, Favorite favorite, QWidget *parent); ~favoriteWindow() override; public slots: diff --git a/gui/src/image-context-menu.cpp b/gui/src/image-context-menu.cpp index d28e4ed47..63d97ae70 100644 --- a/gui/src/image-context-menu.cpp +++ b/gui/src/image-context-menu.cpp @@ -6,7 +6,7 @@ ImageContextMenu::ImageContextMenu(QSettings *settings, QSharedPointer img, mainWindow *mw, QWidget *parent) - : QMenu(parent), m_settings(settings), m_image(img), m_mainWindow(mw) + : QMenu(parent), m_settings(settings), m_image(std::move(img)), m_mainWindow(mw) { // Load reverse search engines ReverseSearchLoader loader(m_settings); diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 017a137ab..6a7b820ac 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -357,7 +357,7 @@ void mainWindow::parseArgs(const QStringList &args, const QMap void mainWindow::initialLoginsFinished() { - Site *site = qobject_cast(sender()); + auto site = qobject_cast(sender()); disconnect(site, &Site::loggedIn, this, &mainWindow::initialLoginsFinished); m_waitForLogin--; @@ -893,13 +893,13 @@ Site* mainWindow::getSelectedSiteOrDefault() void mainWindow::addGroup() { - AddGroupWindow *wAddGroup = new AddGroupWindow(getSelectedSiteOrDefault(), m_profile, this); + auto wAddGroup = new AddGroupWindow(getSelectedSiteOrDefault(), m_profile, this); connect(wAddGroup, &AddGroupWindow::sendData, this, &mainWindow::batchAddGroup); wAddGroup->show(); } void mainWindow::addUnique() { - AddUniqueWindow *wAddUnique = new AddUniqueWindow(getSelectedSiteOrDefault(), m_profile, this); + auto wAddUnique = new AddUniqueWindow(getSelectedSiteOrDefault(), m_profile, this); connect(wAddUnique, SIGNAL(sendData(DownloadQueryImage)), this, SLOT(batchAddUnique(DownloadQueryImage))); wAddUnique->show(); } @@ -1453,7 +1453,7 @@ void mainWindow::getAllGetPages() */ void mainWindow::getAllFinishedPage(Page *page) { - Downloader *d = qobject_cast(sender()); + auto *d = qobject_cast(sender()); int pos = d->getData().toInt(); m_groupBatchs[pos].unk += (m_groupBatchs[pos].unk == "" ? "" : "¤") + QString::number((quintptr)page); @@ -1468,11 +1468,11 @@ void mainWindow::getAllFinishedPage(Page *page) */ void mainWindow::getAllFinishedImages(const QList> &images) { - Downloader *downloader = qobject_cast(sender()); + auto *downloader = qobject_cast(sender()); m_downloaders.removeAll(downloader); m_getAllIgnoredPre += downloader->ignoredCount(); - int row = downloader->getData().toInt(); + const int row = downloader->getData().toInt(); for (const auto &img : images) { diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index 08342d447..7ecfa530b 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -69,9 +69,9 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) m_filenamesFilenames = QList(); for (auto it = filenames.begin(); it != filenames.end(); ++it) { - QLineEdit *leCondition = new QLineEdit(it.key()); - QLineEdit *leFilename = new QLineEdit(it.value().first); - QLineEdit *leFolder = new QLineEdit(it.value().second); + auto leCondition = new QLineEdit(it.key()); + auto leFilename = new QLineEdit(it.value().first); + auto leFolder = new QLineEdit(it.value().second); m_filenamesConditions.append(leCondition); m_filenamesFilenames.append(leFilename); diff --git a/gui/src/settings/web-service-window.cpp b/gui/src/settings/web-service-window.cpp index cd311480b..488cef73b 100644 --- a/gui/src/settings/web-service-window.cpp +++ b/gui/src/settings/web-service-window.cpp @@ -7,7 +7,7 @@ WebServiceWindow::WebServiceWindow(const ReverseSearchEngine *webService, QWidget *parent) - : QDialog(parent), ui(new Ui::WebServiceWindow), m_webService(webService) + : QDialog(parent), ui(new Ui::WebServiceWindow), m_webService(webService), m_faviconReply(Q_NULLPTR) { ui->setupUi(this); diff --git a/gui/src/sources/sourceswindow.cpp b/gui/src/sources/sourceswindow.cpp index 4b2cf4d10..fae95fb59 100644 --- a/gui/src/sources/sourceswindow.cpp +++ b/gui/src/sources/sourceswindow.cpp @@ -22,7 +22,7 @@ * @param parent The parent window */ sourcesWindow::sourcesWindow(Profile *profile, const QList &selected, QWidget *parent) - : QDialog(parent), ui(new Ui::sourcesWindow), m_profile(profile), m_selected(selected), m_sites(profile->getSites()), m_sources(profile->getSources()) + : QDialog(parent), ui(new Ui::sourcesWindow), m_profile(profile), m_selected(selected), m_sites(profile->getSites()), m_sources(profile->getSources()), m_checkForSourceReply(Q_NULLPTR) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); diff --git a/gui/src/tabs/favorites-tab.cpp b/gui/src/tabs/favorites-tab.cpp index d99138fe2..e5f414371 100644 --- a/gui/src/tabs/favorites-tab.cpp +++ b/gui/src/tabs/favorites-tab.cpp @@ -376,7 +376,7 @@ void favoritesTab::favoriteProperties(const QString &name) return; const Favorite fav = m_favorites[index]; - favoriteWindow *fwin = new favoriteWindow(m_profile, fav, this); + auto fwin = new favoriteWindow(m_profile, fav, this); fwin->show(); } diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index 749bc94f5..abd0cffe4 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -253,7 +253,7 @@ void searchTab::clear() // Abort current loadings for (const auto &pages : qAsConst(m_pages)) { - for (auto page : pages) + for (const auto &page : pages) { page->abort(); page->abortTags(); @@ -500,7 +500,7 @@ void searchTab::loadImageThumbnail(Page *page, QSharedPointer img, const QNetworkReply *reply = site->get(site->fixUrl(url), page, "preview"); reply->setParent(this); - m_thumbnailsLoading[reply] = img; + m_thumbnailsLoading[reply] = std::move(img); connect(reply, &QNetworkReply::finished, this, &searchTab::finishedLoadingPreview); } @@ -509,7 +509,7 @@ void searchTab::finishedLoadingPreview() if (m_stop) return; - QNetworkReply *reply = qobject_cast(sender()); + auto *reply = qobject_cast(sender()); // Aborted if (reply->error() == QNetworkReply::OperationCanceledError) @@ -881,7 +881,7 @@ QString getImageAlreadyExists(Image *img, Profile *profile) return profile->md5Exists(img->md5()); } -void searchTab::thumbnailContextMenu(int position, QSharedPointer img) +void searchTab::thumbnailContextMenu(int position, const QSharedPointer &img) { QMenu *menu = new ImageContextMenu(m_settings, img, m_parent, this); QAction *first = menu->actions().first(); @@ -997,7 +997,7 @@ void searchTab::contextSaveSelected() } } -void searchTab::addResultsImage(QSharedPointer img, Page *page, bool merge) +void searchTab::addResultsImage(const QSharedPointer &img, Page *page, bool merge) { // Early return if the layout has already been removed Page *layoutKey = merge && m_layouts.contains(nullptr) ? nullptr : page; @@ -1161,7 +1161,7 @@ void searchTab::webZoom(int id) openImage(image); } -void searchTab::openImage(QSharedPointer image) +void searchTab::openImage(const QSharedPointer &image) { if (m_settings->value("Zoom/singleWindow", false).toBool() && m_lastZoomWindow) { @@ -1188,7 +1188,7 @@ void searchTab::mouseReleaseEvent(QMouseEvent *e) } -void searchTab::selectImage(QSharedPointer img) +void searchTab::selectImage(const QSharedPointer &img) { if (!m_selectedImagesPtrs.contains(img)) { @@ -1197,7 +1197,7 @@ void searchTab::selectImage(QSharedPointer img) } } -void searchTab::unselectImage(QSharedPointer img) +void searchTab::unselectImage(const QSharedPointer &img) { if (m_selectedImagesPtrs.contains(img)) { @@ -1207,7 +1207,7 @@ void searchTab::unselectImage(QSharedPointer img) } } -void searchTab::toggleImage(QSharedPointer img) +void searchTab::toggleImage(const QSharedPointer &img) { const bool selected = m_selectedImagesPtrs.contains(img); m_boutons[img.data()]->setChecked(!selected); @@ -1249,7 +1249,7 @@ void searchTab::toggleImage(int id, bool toggle, bool range) void searchTab::openSourcesWindow() { - sourcesWindow *adv = new sourcesWindow(m_profile, m_selectedSources, this); + auto adv = new sourcesWindow(m_profile, m_selectedSources, this); connect(adv, SIGNAL(valid(QList)), this, SLOT(saveSources(QList))); adv->show(); } diff --git a/gui/src/tabs/search-tab.h b/gui/src/tabs/search-tab.h index 250cf34da..79a06f7a4 100644 --- a/gui/src/tabs/search-tab.h +++ b/gui/src/tabs/search-tab.h @@ -64,7 +64,7 @@ class searchTab : public QWidget void loadImageThumbnail(Page *page, QSharedPointer img, const QString &url); QBouton *createImageThumbnail(int position, QSharedPointer img); FixedSizeGridLayout *createImagesLayout(QSettings *settings); - void thumbnailContextMenu(int position, QSharedPointer img); + void thumbnailContextMenu(int position, const QSharedPointer &img); protected slots: void contextSaveImage(int position); @@ -85,7 +85,7 @@ class searchTab : public QWidget void updateCheckboxes(); // Zooms void webZoom(int); - void openImage(QSharedPointer image); + void openImage(const QSharedPointer &image); // Pagination void firstPage(); void previousPage(); @@ -107,7 +107,7 @@ class searchTab : public QWidget virtual void addResultsPage(Page *page, const QList> &imgs, bool merged, const QString &noResultsMessage = nullptr); void setMergedLabelText(QLabel *txt, const QList> &imgs); virtual void setPageLabelText(QLabel *txt, Page *page, const QList> &imgs, const QString &noResultsMessage = nullptr); - void addResultsImage(QSharedPointer img, Page *page, bool merge = false); + void addResultsImage(const QSharedPointer &img, Page *page, bool merge = false); void finishedLoadingPreview(); // Merged QList> mergeResults(int page, const QList > &results); @@ -120,9 +120,9 @@ class searchTab : public QWidget void postLoading(Page *page, const QList > &imgs); void finishedLoadingTags(Page *page); // Image selection - void selectImage(QSharedPointer img); - void unselectImage(QSharedPointer img); - void toggleImage(QSharedPointer img); + void selectImage(const QSharedPointer &img); + void unselectImage(const QSharedPointer &img); + void toggleImage(const QSharedPointer &img); void toggleImage(int id, bool toggle, bool range); // Others void optionsChanged(); diff --git a/gui/src/theme-loader.cpp b/gui/src/theme-loader.cpp index 08f55f9c2..24d03c574 100644 --- a/gui/src/theme-loader.cpp +++ b/gui/src/theme-loader.cpp @@ -3,8 +3,8 @@ #include -ThemeLoader::ThemeLoader(const QString &path) - : m_path(path) +ThemeLoader::ThemeLoader(QString path) + : m_path(std::move(path)) {} QStringList ThemeLoader::getAllThemes() const diff --git a/gui/src/theme-loader.h b/gui/src/theme-loader.h index 8b6d77a9a..7c4ed22e3 100644 --- a/gui/src/theme-loader.h +++ b/gui/src/theme-loader.h @@ -8,7 +8,7 @@ class ThemeLoader { public: - explicit ThemeLoader(const QString &path); + explicit ThemeLoader(QString path); QStringList getAllThemes() const; bool setTheme(const QString &name); diff --git a/gui/src/ui/QAffiche.cpp b/gui/src/ui/QAffiche.cpp index 59b2e6603..ffd23cd3c 100644 --- a/gui/src/ui/QAffiche.cpp +++ b/gui/src/ui/QAffiche.cpp @@ -10,7 +10,7 @@ QAffiche::QAffiche(const QVariant &id, int border, QColor color, QWidget *parent m_pressed = false; m_id = id; m_border = border; - m_color = color; + m_color = std::move(color); setText(QString()); } diff --git a/gui/src/ui/QBouton.cpp b/gui/src/ui/QBouton.cpp index 691c64f1d..9850c3104 100644 --- a/gui/src/ui/QBouton.cpp +++ b/gui/src/ui/QBouton.cpp @@ -4,8 +4,8 @@ #include -QBouton::QBouton(const QVariant &id, bool resizeInsteadOfCropping, bool smartSizeHint, int border, QColor color, QWidget *parent) - : QPushButton(parent), m_id(id), m_resizeInsteadOfCropping(resizeInsteadOfCropping), m_smartSizeHint(smartSizeHint), m_penColor(color), m_border(border), m_center(true), m_progress(0), m_progressMax(0), m_invertToggle(false), m_counter(QString()) +QBouton::QBouton(QVariant id, bool resizeInsteadOfCropping, bool smartSizeHint, int border, QColor color, QWidget *parent) + : QPushButton(parent), m_id(std::move(id)), m_resizeInsteadOfCropping(resizeInsteadOfCropping), m_smartSizeHint(smartSizeHint), m_penColor(std::move(color)), m_border(border), m_center(true), m_progress(0), m_progressMax(0), m_invertToggle(false), m_counter(QString()) { } void QBouton::scale(const QPixmap &image, qreal scale) @@ -119,11 +119,11 @@ void QBouton::paintEvent(QPaintEvent *event) // Draw counter if (!m_counter.isEmpty()) { - int right = qMax(x, 0) + qMin(w, size().width()); - int dim = 10 + 5 * m_counter.length(); - double pad = 2.5; - QRectF notif(right - dim - pad, qMax(y, 0) + pad, dim, 20); - int radius = qFloor(qMin(dim, 20) / 2); + const int right = qMax(x, 0) + qMin(w, size().width()); + const int dim = 10 + 5 * m_counter.length(); + const double pad = 2.5; + const QRectF notif(right - dim - pad, qMax(y, 0) + pad, dim, 20); + const int radius = qFloor(qMin(dim, 20) / 2.0); painter.setRenderHint(QPainter::Antialiasing); @@ -151,9 +151,9 @@ QSize QBouton::getIconSize(int regionWidth, int regionHeight, bool wOnly) const // Calculate ratio to resize by keeping proportions if (m_resizeInsteadOfCropping) { - qreal coef = wOnly - ? qMin(1.0, static_cast(regionWidth) / static_cast(w)) - : qMin(1.0, qMin(static_cast(regionWidth) / static_cast(w), static_cast(regionHeight) / static_cast(h))); + const qreal coef = wOnly + ? qMin(1.0, static_cast(regionWidth) / static_cast(w)) + : qMin(1.0, qMin(static_cast(regionWidth) / static_cast(w), static_cast(regionHeight) / static_cast(h))); w *= coef; h *= coef; } diff --git a/gui/src/ui/QBouton.h b/gui/src/ui/QBouton.h index 0d8567148..f0cb98e93 100644 --- a/gui/src/ui/QBouton.h +++ b/gui/src/ui/QBouton.h @@ -10,7 +10,7 @@ class QBouton : public QPushButton Q_OBJECT public: - explicit QBouton(const QVariant &id = 0, bool resizeInsteadOfCropping = false, bool smartSizeHint = false, int border = 0, QColor color = QColor(), QWidget *parent = Q_NULLPTR); + explicit QBouton(QVariant id = 0, bool resizeInsteadOfCropping = false, bool smartSizeHint = false, int border = 0, QColor color = QColor(), QWidget *parent = Q_NULLPTR); QVariant id(); void mousePressEvent(QMouseEvent *event) override; QSize sizeHint() const override; diff --git a/gui/src/ui/fixed-size-grid-layout.cpp b/gui/src/ui/fixed-size-grid-layout.cpp index 5895dae16..a86e3c3a4 100644 --- a/gui/src/ui/fixed-size-grid-layout.cpp +++ b/gui/src/ui/fixed-size-grid-layout.cpp @@ -163,11 +163,12 @@ int FixedSizeGridLayout::smartSpacing(QStyle::PixelMetric pm) const if (parent->isWidgetType()) { - auto *pw = static_cast(parent); - return pw->style()->pixelMetric(pm, Q_NULLPTR, pw); + auto *pw = dynamic_cast(parent); + if (pw != Q_NULLPTR) + return pw->style()->pixelMetric(pm, Q_NULLPTR, pw); } - return static_cast(parent)->spacing(); + return dynamic_cast(parent)->spacing(); } int FixedSizeGridLayout::widgetSpacing(int spacing, QWidget *widget, Qt::Orientation orientation) const @@ -175,6 +176,6 @@ int FixedSizeGridLayout::widgetSpacing(int spacing, QWidget *widget, Qt::Orienta if (spacing >= 0) return spacing; - QSizePolicy::ControlType controlType = widget->sizePolicy().controlType(); + const QSizePolicy::ControlType controlType = widget->sizePolicy().controlType(); return widget->style()->layoutSpacing(controlType, controlType, orientation); } diff --git a/gui/src/ui/qclosabletabwidget.cpp b/gui/src/ui/qclosabletabwidget.cpp index 14ad80561..efc431268 100644 --- a/gui/src/ui/qclosabletabwidget.cpp +++ b/gui/src/ui/qclosabletabwidget.cpp @@ -13,10 +13,10 @@ bool QClosableTabWidget::eventFilter(QObject *o, QEvent *e) { if (o == tabBar() && e->type() == QEvent::MouseButtonPress) { - auto *mouseEvent = static_cast(e); - if (mouseEvent->button() == Qt::MiddleButton) + auto *mouseEvent = dynamic_cast(e); + if (mouseEvent != Q_NULLPTR && mouseEvent->button() == Qt::MiddleButton) { - int index = tabBar()->tabAt(mouseEvent->pos()); + const int index = tabBar()->tabAt(mouseEvent->pos()); QWidget *w = widget(index); // Non-closable tabs have a maximum width of 16777214 (default: 16777215) diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp index c9cd2208b..611ba38fa 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp +++ b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp @@ -5,8 +5,8 @@ #include "models/post-filter.h" -BlacklistFix2::BlacklistFix2(const QList> &details, const QList &blacklist, QWidget *parent) - : QDialog(parent), ui(new Ui::BlacklistFix2), m_details(details), m_blacklist(blacklist) +BlacklistFix2::BlacklistFix2(QList> details, QList blacklist, QWidget *parent) + : QDialog(parent), ui(new Ui::BlacklistFix2), m_details(std::move(details)), m_blacklist(std::move(blacklist)) { ui->setupUi(this); diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-2.h b/gui/src/utils/blacklist-fix/blacklist-fix-2.h index cb0ccc6e6..d067046ea 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-2.h +++ b/gui/src/utils/blacklist-fix/blacklist-fix-2.h @@ -18,7 +18,7 @@ class BlacklistFix2 : public QDialog Q_OBJECT public: - explicit BlacklistFix2(const QList > &details, const QList &blacklist, QWidget *parent = Q_NULLPTR); + explicit BlacklistFix2(QList> details, QList blacklist, QWidget *parent = Q_NULLPTR); ~BlacklistFix2() override; private slots: diff --git a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp index 767bf7f33..425de421f 100644 --- a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp +++ b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp @@ -33,7 +33,7 @@ void EmptyDirsFix1::next() return; } - EmptyDirsFix2 *edf2 = new EmptyDirsFix2(dirs); + auto *edf2 = new EmptyDirsFix2(dirs); close(); edf2->show(); } diff --git a/gui/src/utils/rename-existing/rename-existing-2.cpp b/gui/src/utils/rename-existing/rename-existing-2.cpp index aa9592ad7..477d209e5 100644 --- a/gui/src/utils/rename-existing/rename-existing-2.cpp +++ b/gui/src/utils/rename-existing/rename-existing-2.cpp @@ -5,8 +5,8 @@ #include "functions.h" -RenameExisting2::RenameExisting2(const QList &details, const QString &folder, QWidget *parent) - : QDialog(parent), ui(new Ui::RenameExisting2), m_details(details), m_folder(folder) +RenameExisting2::RenameExisting2(QList details, QString folder, QWidget *parent) + : QDialog(parent), ui(new Ui::RenameExisting2), m_details(std::move(details)), m_folder(std::move(folder)) { ui->setupUi(this); diff --git a/gui/src/utils/rename-existing/rename-existing-2.h b/gui/src/utils/rename-existing/rename-existing-2.h index 1b0a9b453..1434803f4 100644 --- a/gui/src/utils/rename-existing/rename-existing-2.h +++ b/gui/src/utils/rename-existing/rename-existing-2.h @@ -17,7 +17,7 @@ class RenameExisting2 : public QDialog Q_OBJECT public: - explicit RenameExisting2(const QList &details, const QString &folder, QWidget *parent = Q_NULLPTR); + explicit RenameExisting2(QList details, QString folder, QWidget *parent = Q_NULLPTR); ~RenameExisting2() override; void deleteDir(const QString &path); diff --git a/gui/src/viewer/details-window.cpp b/gui/src/viewer/details-window.cpp index 525cf33a9..7d833b4a5 100644 --- a/gui/src/viewer/details-window.cpp +++ b/gui/src/viewer/details-window.cpp @@ -16,7 +16,7 @@ DetailsWindow::~DetailsWindow() delete ui; } -void DetailsWindow::setImage(QSharedPointer image) +void DetailsWindow::setImage(const QSharedPointer &image) { clearLayout(ui->formLayout); diff --git a/gui/src/viewer/details-window.h b/gui/src/viewer/details-window.h index e72dd1446..d692abbe6 100644 --- a/gui/src/viewer/details-window.h +++ b/gui/src/viewer/details-window.h @@ -20,7 +20,7 @@ class DetailsWindow : public QDialog public: explicit DetailsWindow(Profile *profile, QWidget *parent = Q_NULLPTR); ~DetailsWindow() override; - void setImage(QSharedPointer image); + void setImage(const QSharedPointer &image); private: Ui::DetailsWindow *ui; diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 400f6fb89..6cf2d10d0 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -25,8 +25,8 @@ #include "viewer/details-window.h" -ZoomWindow::ZoomWindow(const QList> &images, QSharedPointer image, Site *site, Profile *profile, mainWindow *parent) - : QWidget(Q_NULLPTR, Qt::Window), m_parent(parent), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()), m_ignore(profile->getIgnored()), m_settings(profile->getSettings()), ui(new Ui::ZoomWindow), m_site(site), m_timeout(300), m_tooBig(false), m_loadedImage(false), m_loadedDetails(false), m_displayImage(QPixmap()), m_displayMovie(nullptr), m_finished(false), m_size(0), m_source(), m_fullScreen(nullptr), m_images(images), m_isFullscreen(false), m_isSlideshowRunning(false), m_imagePath(""), m_labelImageScaled(false) +ZoomWindow::ZoomWindow(QList> images, const QSharedPointer &image, Site *site, Profile *profile, mainWindow *parent) + : QWidget(Q_NULLPTR, Qt::Window), m_parent(parent), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()), m_ignore(profile->getIgnored()), m_settings(profile->getSettings()), ui(new Ui::ZoomWindow), m_site(site), m_timeout(300), m_tooBig(false), m_loadedImage(false), m_loadedDetails(false), m_displayImage(QPixmap()), m_displayMovie(Q_NULLPTR), m_finished(false), m_size(0), m_source(), m_fullScreen(nullptr), m_images(std::move(images)), m_isFullscreen(false), m_isSlideshowRunning(false), m_imagePath(""), m_labelImageScaled(false) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); @@ -341,7 +341,7 @@ void ZoomWindow::contextMenu(QPoint) return; Page page(m_profile, m_site, QList() << m_site, QStringList() << m_link); - TagContextMenu *menu = new TagContextMenu(m_link, m_image->tags(), page.friendlyUrl(), m_profile, true, this); + auto *menu = new TagContextMenu(m_link, m_image->tags(), page.friendlyUrl(), m_profile, true, this); connect(menu, &TagContextMenu::openNewTab, this, &ZoomWindow::openInNewTab); connect(menu, &TagContextMenu::setFavoriteImage, this, &ZoomWindow::setfavorite); menu->exec(QCursor::pos()); @@ -401,7 +401,7 @@ void ZoomWindow::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) ui->progressBarDownload->setMaximum(bytesTotal); ui->progressBarDownload->setValue(bytesReceived); - bool isAnimated = m_image->isVideo() || !m_isAnimated.isEmpty(); + const bool isAnimated = m_image->isVideo() || !m_isAnimated.isEmpty(); if (!isAnimated && (m_imageTime.elapsed() > TIME || (bytesTotal > 0 && bytesReceived / bytesTotal > PERCENT))) { m_imageTime.restart(); @@ -1108,7 +1108,7 @@ void ZoomWindow::urlChanged(const QString &before, const QString &after) } -void ZoomWindow::reuse(const QList> &images, QSharedPointer image, Site *site) +void ZoomWindow::reuse(const QList> &images, const QSharedPointer &image, Site *site) { m_images = images; m_site = site; @@ -1116,7 +1116,7 @@ void ZoomWindow::reuse(const QList> &images, QSharedPointe load(image); } -void ZoomWindow::load(QSharedPointer image) +void ZoomWindow::load(const QSharedPointer &image) { emit clearLoadQueue(); diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index 58c88f247..b0deb2a22 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -39,7 +39,7 @@ class ZoomWindow : public QWidget Delete }; - ZoomWindow(const QList> &images, QSharedPointer image, Site *site, Profile *profile, mainWindow *parent); + ZoomWindow(QList> images, const QSharedPointer &image, Site *site, Profile *profile, mainWindow *parent); ~ZoomWindow() override; void go(); void load(bool force = false); @@ -47,7 +47,7 @@ class ZoomWindow : public QWidget public slots: void update(bool onlySize = false, bool force = false); void replyFinishedDetails(); - void replyFinishedZoom(QNetworkReply::NetworkError error = QNetworkReply::NoError, const QString &errorString = ""); + void replyFinishedZoom(QNetworkReply::NetworkError err = QNetworkReply::NoError, const QString &errorString = ""); void display(const QPixmap &, int); void saveNQuit(); void saveNQuitFav(); @@ -74,7 +74,7 @@ class ZoomWindow : public QWidget void updateWindowTitle(); void showLoadingError(const QString &error); void setButtonState(bool fav, SaveButtonState state); - void reuse(const QList> &images, QSharedPointer image, Site *site); + void reuse(const QList> &images, const QSharedPointer &image, Site *site); // Context menus void imageContextMenu(); @@ -90,7 +90,7 @@ class ZoomWindow : public QWidget void toggleSlideshow(); // Navigation - void load(QSharedPointer image); + void load(const QSharedPointer &image); void next(); void previous(); diff --git a/lib/src/commands/commands.cpp b/lib/src/commands/commands.cpp index a7c00e457..f7c33ab89 100644 --- a/lib/src/commands/commands.cpp +++ b/lib/src/commands/commands.cpp @@ -68,7 +68,7 @@ bool Commands::image(const Image &img, const QString &path) log(QStringLiteral("Execution of \"%1\"").arg(exec)); Logger::getInstance().logCommand(exec); - int code = QProcess::execute(exec); + const int code = QProcess::execute(exec); if (code != 0) log(QStringLiteral("Error executing command (return code: %1)").arg(code)); } @@ -115,7 +115,7 @@ bool Commands::tag(const Image &img, const Tag &tag, bool after) log(QStringLiteral("Execution of \"%1\"").arg(exec)); Logger::getInstance().logCommand(exec); - int code = QProcess::execute(exec); + const int code = QProcess::execute(exec); if (code != 0) log(QStringLiteral("Error executing command (return code: %1)").arg(code)); } diff --git a/lib/src/commands/sql-worker.cpp b/lib/src/commands/sql-worker.cpp index 567e320d8..4a5a97cb1 100644 --- a/lib/src/commands/sql-worker.cpp +++ b/lib/src/commands/sql-worker.cpp @@ -6,8 +6,8 @@ #include "logger.h" -SqlWorker::SqlWorker(const QString &driver, const QString &host, const QString &user, const QString &password, const QString &database, QObject *parent) - : QThread(parent), m_driver(driver), m_host(host), m_user(user), m_password(password), m_database(database) +SqlWorker::SqlWorker(QString driver, QString host, QString user, QString password, QString database, QObject *parent) + : QThread(parent), m_driver(std::move(driver)), m_host(std::move(host)), m_user(std::move(user)), m_password(std::move(password)), m_database(std::move(database)) { m_enabled = (m_driver == QLatin1String("QSQLITE") && !m_database.isEmpty()) || (!m_host.isEmpty() && !m_user.isEmpty() && !m_database.isEmpty()); diff --git a/lib/src/commands/sql-worker.h b/lib/src/commands/sql-worker.h index d36e0d229..13c660e90 100644 --- a/lib/src/commands/sql-worker.h +++ b/lib/src/commands/sql-worker.h @@ -10,7 +10,7 @@ class SqlWorker : public QThread Q_OBJECT public: - SqlWorker(const QString &driver, const QString &host, const QString &user, const QString &password, const QString &database, QObject *parent = Q_NULLPTR); + SqlWorker(QString driver, QString host, QString user, QString password, QString database, QObject *parent = Q_NULLPTR); bool connect(); static QString escape(const QVariant &val); diff --git a/lib/src/custom-network-access-manager.cpp b/lib/src/custom-network-access-manager.cpp index 7477ea34a..33663493d 100644 --- a/lib/src/custom-network-access-manager.cpp +++ b/lib/src/custom-network-access-manager.cpp @@ -18,9 +18,9 @@ QNetworkReply *CustomNetworkAccessManager::get(const QNetworkRequest &request) if (isTestModeEnabled()) { QString md5 = QString(QCryptographicHash::hash(request.url().toString().toLatin1(), QCryptographicHash::Md5).toHex()); - QString filename = request.url().fileName(); - QString ext = filename.contains('.') ? filename.mid(filename.lastIndexOf('.') + 1) : QStringLiteral("html"); - QString host = request.url().host(); + const QString filename = request.url().fileName(); + const QString ext = filename.contains('.') ? filename.mid(filename.lastIndexOf('.') + 1) : QStringLiteral("html"); + const QString host = request.url().host(); QString path = "tests/resources/pages/" + host + "/" + md5 + "." + ext; const bool fromQueue = !CustomNetworkAccessManager::NextFiles.isEmpty(); @@ -92,7 +92,7 @@ QNetworkReply *CustomNetworkAccessManager::get(const QNetworkRequest &request) /** * Log SSL errors in debug mode only. * - * @param qnr The network reply who generated the SSL errors + * @param reply The network reply who generated the SSL errors * @param errors The list of SSL errors that occurred */ void CustomNetworkAccessManager::sslErrorHandler(QNetworkReply *reply, const QList &errors) diff --git a/lib/src/downloader/download-query-group.cpp b/lib/src/downloader/download-query-group.cpp index 3c4188446..8e207f8ab 100644 --- a/lib/src/downloader/download-query-group.cpp +++ b/lib/src/downloader/download-query-group.cpp @@ -3,16 +3,16 @@ #include "models/site.h" -DownloadQueryGroup::DownloadQueryGroup(QSettings *settings, const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, Site *site, const QString &unk) - : DownloadQuery(site), tags(tags), page(page), perpage(perPage), total(total), postFiltering(postFiltering), unk(unk) +DownloadQueryGroup::DownloadQueryGroup(QSettings *settings, QString tags, int page, int perPage, int total, QStringList postFiltering, Site *site, QString unk) + : DownloadQuery(site), tags(std::move(tags)), page(page), perpage(perPage), total(total), postFiltering(std::move(postFiltering)), unk(std::move(unk)) { getBlacklisted = settings->value("downloadblacklist").toBool(); filename = settings->value("Save/filename").toString(); path = settings->value("Save/path").toString(); } -DownloadQueryGroup::DownloadQueryGroup(const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, bool blacklisted, Site *site, const QString &filename, const QString &path, const QString &unk) - : DownloadQuery(site, filename, path), tags(tags), page(page), perpage(perPage), total(total), postFiltering(postFiltering), getBlacklisted(blacklisted), unk(unk) +DownloadQueryGroup::DownloadQueryGroup(QString tags, int page, int perPage, int total, QStringList postFiltering, bool blacklisted, Site *site, const QString &filename, const QString &path, QString unk) + : DownloadQuery(site, filename, path), tags(std::move(tags)), page(page), perpage(perPage), total(total), postFiltering(std::move(postFiltering)), getBlacklisted(blacklisted), unk(std::move(unk)) { } diff --git a/lib/src/downloader/download-query-group.h b/lib/src/downloader/download-query-group.h index 2ec85470a..1dcdd3d12 100644 --- a/lib/src/downloader/download-query-group.h +++ b/lib/src/downloader/download-query-group.h @@ -14,8 +14,8 @@ class DownloadQueryGroup : public DownloadQuery public: // Constructors DownloadQueryGroup() = default; - explicit DownloadQueryGroup(QSettings *settings, const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, Site *site, const QString &unk = QString()); - explicit DownloadQueryGroup(const QString &tags, int page, int perPage, int total, const QStringList &postFiltering, bool getBlacklisted, Site *site, const QString &filename, const QString &path, const QString &unk = QString()); + explicit DownloadQueryGroup(QSettings *settings, QString tags, int page, int perPage, int total, QStringList postFiltering, Site *site, QString unk = QString()); + explicit DownloadQueryGroup(QString tags, int page, int perPage, int total, QStringList postFiltering, bool getBlacklisted, Site *site, const QString &filename, const QString &path, QString unk = QString()); // Serialization QString toString(const QString &separator) const override; diff --git a/lib/src/downloader/download-query.cpp b/lib/src/downloader/download-query.cpp index 1aa78a0ac..c62aab93b 100644 --- a/lib/src/downloader/download-query.cpp +++ b/lib/src/downloader/download-query.cpp @@ -5,6 +5,6 @@ DownloadQuery::DownloadQuery(Site *site) : site(site) {} -DownloadQuery::DownloadQuery(Site *site, const QString &filename, const QString &path) - : site(site), filename(filename), path(path) +DownloadQuery::DownloadQuery(Site *site, QString filename, QString path) + : site(site), filename(std::move(filename)), path(std::move(path)) {} diff --git a/lib/src/downloader/download-query.h b/lib/src/downloader/download-query.h index d58da7570..39e9a23f0 100644 --- a/lib/src/downloader/download-query.h +++ b/lib/src/downloader/download-query.h @@ -13,7 +13,7 @@ class DownloadQuery // Constructors DownloadQuery() = default; explicit DownloadQuery(Site *site); - explicit DownloadQuery(Site *site, const QString &filename, const QString &path); + explicit DownloadQuery(Site *site, QString filename, QString path); // Serialization virtual QString toString(const QString &separator) const = 0; diff --git a/lib/src/downloader/downloader.cpp b/lib/src/downloader/downloader.cpp index 6eff45db5..72035a4e9 100644 --- a/lib/src/downloader/downloader.cpp +++ b/lib/src/downloader/downloader.cpp @@ -31,8 +31,8 @@ void Downloader::clear() m_oPagesT.clear(); } -Downloader::Downloader(Profile *profile, const QStringList &tags, const QStringList &postFiltering, const QList &sources, int page, int max, int perPage, const QString &location, const QString &filename, const QString &user, const QString &password, bool blacklist, const QList &blacklistedTags, bool noDuplicates, int tagsMin, const QString &tagsFormat, Downloader *previous) - : m_profile(profile), m_lastPage(nullptr), m_tags(tags), m_postFiltering(postFiltering), m_sites(sources), m_page(page), m_max(max), m_perPage(perPage), m_waiting(0), m_ignored(0), m_duplicates(0), m_tagsMin(tagsMin), m_location(location), m_filename(filename), m_user(user), m_password(password), m_blacklist(blacklist), m_noDuplicates(noDuplicates), m_tagsFormat(tagsFormat), m_blacklistedTags(blacklistedTags), m_cancelled(false), m_quit(false), m_previous(previous) +Downloader::Downloader(Profile *profile, QStringList tags, QStringList postFiltering, QList sources, int page, int max, int perPage, QString location, QString filename, QString user, QString password, bool blacklist, QList blacklistedTags, bool noDuplicates, int tagsMin, QString tagsFormat, Downloader *previous) + : m_profile(profile), m_lastPage(Q_NULLPTR), m_tags(std::move(tags)), m_postFiltering(std::move(postFiltering)), m_sites(std::move(sources)), m_page(page), m_max(max), m_perPage(perPage), m_waiting(0), m_ignored(0), m_duplicates(0), m_tagsMin(tagsMin), m_location(std::move(location)), m_filename(std::move(filename)), m_user(std::move(user)), m_password(std::move(password)), m_blacklist(blacklist), m_noDuplicates(noDuplicates), m_tagsFormat(std::move(tagsFormat)), m_blacklistedTags(std::move(blacklistedTags)), m_cancelled(false), m_quit(false), m_previous(previous) { } void Downloader::setQuit(bool quit) @@ -230,7 +230,7 @@ void Downloader::loadNext() if (!m_images.isEmpty()) { - QSharedPointer image = m_images.takeFirst(); + const QSharedPointer image = m_images.takeFirst(); log("Loading image '"+image->url()+"'"); auto dwl = new ImageDownloader(image, m_filename, m_location, 0, true, false); connect(dwl, &ImageDownloader::saved, this, &Downloader::finishedLoadingImage); @@ -357,7 +357,7 @@ void Downloader::downloadImages(const QList> &images) loadNext(); } -void Downloader::finishedLoadingImage(QSharedPointer image, const QMap &result) +void Downloader::finishedLoadingImage(const QSharedPointer &image, const QMap &result) { Q_UNUSED(result); diff --git a/lib/src/downloader/downloader.h b/lib/src/downloader/downloader.h index 7311f6e90..bb84fc93c 100644 --- a/lib/src/downloader/downloader.h +++ b/lib/src/downloader/downloader.h @@ -14,7 +14,7 @@ class Downloader : public QObject public: Downloader() = default; ~Downloader() override; - Downloader(Profile *profile, const QStringList &tags, const QStringList &postFiltering, const QList &sources, int page, int max, int perPage, const QString &location, const QString &filename, const QString &user, const QString &password, bool blacklist, const QList &blacklistedTags, bool noDuplicates, int tagsMin, const QString &tagsFormat, Downloader *previous = nullptr); + Downloader(Profile *profile, QStringList tags, QStringList postFiltering, QList sources, int page, int max, int perPage, QString location, QString filename, QString user, QString password, bool blacklist, QList blacklistedTags, bool noDuplicates, int tagsMin, QString tagsFormat, Downloader *previous = nullptr); void setQuit(bool quit); void downloadImages(const QList> &images); void loadNext(); @@ -54,7 +54,7 @@ class Downloader : public QObject void finishedLoadingPageTags(Page *page); void finishedLoadingImages(Page *page); void finishedLoadingUrls(Page *page); - void finishedLoadingImage(QSharedPointer img, const QMap &result); + void finishedLoadingImage(const QSharedPointer &img, const QMap &result); void cancel(); void clear(); diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index a382b3435..53dc514e8 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -11,12 +11,12 @@ #include "models/source.h" -ImageDownloader::ImageDownloader(QSharedPointer img, const QString &filename, const QString &path, int count, bool addMd5, bool startCommands, QObject *parent, bool loadTags, bool rotate) - : QObject(parent), m_image(img), m_fileDownloader(this), m_filename(filename), m_path(path), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) +ImageDownloader::ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent, bool loadTags, bool rotate) + : QObject(parent), m_image(std::move(img)), m_fileDownloader(this), m_filename(std::move(filename)), m_path(std::move(path)), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) {} -ImageDownloader::ImageDownloader(QSharedPointer img, const QStringList &paths, int count, bool addMd5, bool startCommands, QObject *parent, bool rotate) - : QObject(parent), m_image(img), m_fileDownloader(this), m_loadTags(false), m_paths(paths), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) +ImageDownloader::ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent, bool rotate) + : QObject(parent), m_image(std::move(img)), m_fileDownloader(this), m_loadTags(false), m_paths(std::move(paths)), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) {} void ImageDownloader::save() diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index af6d97c07..3fd48c9a2 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -12,8 +12,8 @@ class ImageDownloader : public QObject Q_OBJECT public: - ImageDownloader(QSharedPointer img, const QString &filename, const QString &path, int count, bool addMd5, bool startCommands, QObject *parent = Q_NULLPTR, bool loadTags = false, bool rotate = true); - ImageDownloader(QSharedPointer img, const QStringList &paths, int count, bool addMd5, bool startCommands, QObject *parent = Q_NULLPTR, bool rotate = true); + ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent = Q_NULLPTR, bool loadTags = false, bool rotate = true); + ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent = Q_NULLPTR, bool rotate = true); public slots: void save(); diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index cab25ea11..5bb480642 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -128,7 +128,7 @@ QStringList removeWildards(const QStringList &elements, const QStringList &remov * @param str The date string. * @return The converted date as a QDateTime. */ -QDateTime qDateTimeFromString(QString str) +QDateTime qDateTimeFromString(const QString &str) { QDateTime date; @@ -189,15 +189,15 @@ QDateTime qDateTimeFromString(QString str) return date; } -QString getUnit(double *value) +QString getUnit(double *size) { QStringList units = FILESIZE_UNITS; const int multiplier = FILESIZE_MULTIPLIER; int power = 0; - while (*value >= multiplier && power < units.count() - 1) + while (*size >= multiplier && power < units.count() - 1) { - *value /= 1024; + *size /= 1024; power++; } @@ -208,7 +208,7 @@ QString formatFilesize(double size) { const QString unit = getUnit(&size); const double round = size > 100 ? 1 : (size >= 10 ? 10 : 100); - const double roundedSize = static_cast(static_cast(size * round + 0.5)) / round; + const double roundedSize = qRound(size * round) / round; return QStringLiteral("%1 %2").arg(roundedSize).arg(unit); } @@ -326,10 +326,10 @@ bool setFileCreationDate(const QString &path, const QDateTime &datetime) if (!datetime.isValid()) { return false; } #ifdef Q_OS_WIN - wchar_t *filename = new wchar_t[path.length() + 1]; + auto *filename = new wchar_t[path.length() + 1]; path.toWCharArray(filename); filename[path.length()] = 0; - HANDLE hfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + const HANDLE hfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); delete[] filename; if (hfile == INVALID_HANDLE_VALUE) { @@ -338,7 +338,7 @@ bool setFileCreationDate(const QString &path, const QDateTime &datetime) } else { - LONGLONG ll = Int32x32To64(datetime.toTime_t(), 10000000) + 116444736000000000; + const LONGLONG ll = Int32x32To64(datetime.toTime_t(), 10000000) + 116444736000000000; FILETIME pcreationtime; pcreationtime.dwLowDateTime = (DWORD) ll; pcreationtime.dwHighDateTime = ll >> 32; @@ -458,22 +458,22 @@ bool isUrl(const QString &str) return regexUrl.match(str).hasMatch(); } -QString fixFilename(QString fn, QString path, int maxlength, bool invalidChars) +QString fixFilename(QString filename, QString path, int maxLength, bool invalidChars) { const QString sep = QDir::separator(); - fn = QDir::toNativeSeparators(fn); + filename = QDir::toNativeSeparators(filename); path = QDir::toNativeSeparators(path); - if (!path.endsWith(sep) && !path.isEmpty() && !fn.isEmpty()) + if (!path.endsWith(sep) && !path.isEmpty() && !filename.isEmpty()) path += sep; #ifdef Q_OS_WIN - return fixFilenameWindows(fn, path, maxlength, invalidChars); + return fixFilenameWindows(filename, path, maxLength, invalidChars); #else - return fixFilenameLinux(fn, path, maxlength, invalidChars); + return fixFilenameLinux(filename, path, maxLength, invalidChars); #endif } -QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, bool invalidChars) +QString fixFilenameLinux(const QString &fn, const QString &path, int maxLength, bool invalidChars) { Q_UNUSED(invalidChars); @@ -512,8 +512,8 @@ QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, // A filename cannot exceed a certain length const int extlen = ext.isEmpty() ? 0 : ext.length() + 1; - if (file.length() > maxlength - extlen) - file = file.left(maxlength - extlen).trimmed(); + if (file.length() > maxLength - extlen) + file = file.left(maxLength - extlen).trimmed(); if (file.length() > 255 - extlen) file = file.left(255 - extlen).trimmed(); @@ -539,11 +539,11 @@ QString fixFilenameLinux(const QString &fn, const QString &path, int maxlength, #define MAX_PATH 260 #endif -QString fixFilenameWindows(const QString &fn, const QString &path, int maxlength, bool invalidChars) +QString fixFilenameWindows(const QString &fn, const QString &path, int maxLength, bool invalidChars) { // Fix parameters const QString sep = QStringLiteral("\\"); - maxlength = maxlength == 0 ? MAX_PATH : maxlength; + maxLength = maxLength == 0 ? MAX_PATH : maxLength; QString filename = path + fn; // Drive @@ -590,19 +590,19 @@ QString fixFilenameWindows(const QString &fn, const QString &path, int maxlength part = part.trimmed(); // A part should still allow creating a file - if (part.length() > maxlength - 12) - { part = part.left(qMax(0, maxlength - 12)).trimmed(); } + if (part.length() > maxLength - 12) + { part = part.left(qMax(0, maxLength - 12)).trimmed(); } } // Join parts back QString dirpart = parts.join(sep); - if (dirpart.length() > maxlength - 12) - { dirpart = dirpart.left(qMax(0, maxlength - 12)).trimmed(); } + if (dirpart.length() > maxLength - 12) + { dirpart = dirpart.left(qMax(0, maxLength - 12)).trimmed(); } filename = (dirpart.isEmpty() ? QString() : dirpart + (!fn.isEmpty() ? sep : QString())) + file; // A filename cannot exceed MAX_PATH (-1 for and -3 for drive "C:\") - if (filename.length() > maxlength - 1 - 3 - ext.length() - 1) - { filename = filename.left(qMax(0, maxlength - 1 - 3 - ext.length() - 1)).trimmed(); } + if (filename.length() > maxLength - 1 - 3 - ext.length() - 1) + { filename = filename.left(qMax(0, maxLength - 1 - 3 - ext.length() - 1)).trimmed(); } // Get separation between filename and path int index = -1; diff --git a/lib/src/functions.h b/lib/src/functions.h index a7a8ca980..7ed184eb7 100644 --- a/lib/src/functions.h +++ b/lib/src/functions.h @@ -36,8 +36,8 @@ #endif -QDateTime qDateTimeFromString(QString s); -QString savePath(const QString &s = "", bool exists = false, bool writable = false); +QDateTime qDateTimeFromString(const QString &str); +QString savePath(const QString &file = "", bool exists = false, bool writable = false); bool copyRecursively(QString srcFilePath, QString tgtFilePath); int levenshtein(QString, QString); QString stripTags(QString); @@ -50,13 +50,13 @@ bool isUrl(const QString &str); bool isVariantEmpty(const QVariant &value); QMap multiMatchToMap(const QRegularExpressionMatch &match, const QStringList &groups); -bool setFileCreationDate(const QString &path, const QDateTime &time); +bool setFileCreationDate(const QString &path, const QDateTime &datetime); void shutDown(int timeout = 0); void openTray(); -QString fixFilename(QString filename, QString path = "", int maxlength = 0, bool invalidChars = true); -QString fixFilenameWindows(const QString &filename, const QString &path = "", int maxlength = 0, bool invalidChars = true); -QString fixFilenameLinux(const QString &filename, const QString &path = "", int maxlength = 0, bool invalidChars = true); +QString fixFilename(QString filename, QString path = "", int maxLength = 0, bool invalidChars = true); +QString fixFilenameWindows(const QString &filename, const QString &path = "", int maxLength = 0, bool invalidChars = true); +QString fixFilenameLinux(const QString &filename, const QString &path = "", int maxLength = 0, bool invalidChars = true); QMap domToMap(const QDomElement &); diff --git a/lib/src/language-loader.cpp b/lib/src/language-loader.cpp index e7c07b364..818f88af7 100644 --- a/lib/src/language-loader.cpp +++ b/lib/src/language-loader.cpp @@ -3,8 +3,8 @@ #include -LanguageLoader::LanguageLoader(const QString &path) - : m_path(path) +LanguageLoader::LanguageLoader(QString path) + : m_path(std::move(path)) {} QMap LanguageLoader::getAllLanguages() const diff --git a/lib/src/language-loader.h b/lib/src/language-loader.h index 4a0dd2ce3..fb27b3853 100644 --- a/lib/src/language-loader.h +++ b/lib/src/language-loader.h @@ -8,7 +8,7 @@ class LanguageLoader { public: - explicit LanguageLoader(const QString &path); + explicit LanguageLoader(QString path); QMap getAllLanguages() const; private: diff --git a/lib/src/loader/downloadable-downloader.cpp b/lib/src/loader/downloadable-downloader.cpp index e6789cf4a..c3aaf1aac 100644 --- a/lib/src/loader/downloadable-downloader.cpp +++ b/lib/src/loader/downloadable-downloader.cpp @@ -5,7 +5,7 @@ DownloadableDownloader::DownloadableDownloader(QSharedPointer downloadable, Site *site, int count, bool addMd5, bool startCommands, bool loadTags, QObject *parent) - : QObject(parent), m_downloadable(downloadable), m_site(site), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_loadTags(loadTags) + : QObject(parent), m_downloadable(std::move(downloadable)), m_site(site), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_loadTags(loadTags) {} void DownloadableDownloader::setPath(const Filename &filename, const QString &folder) diff --git a/lib/src/loader/downloadable.cpp b/lib/src/loader/downloadable.cpp index e343d2146..de67a8c03 100644 --- a/lib/src/loader/downloadable.cpp +++ b/lib/src/loader/downloadable.cpp @@ -33,7 +33,7 @@ const QMap &Downloadable::tokens(Profile *profile) const // Use a lazy token for Grabber meta-tags as it can be expensive to calculate tokens.insert("grabber", Token([profile, tokens]() { - QString pth = profile->getSettings()->value("Save/path").toString(); + const QString pth = profile->getSettings()->value("Save/path").toString(); Filename filename(profile->getSettings()->value("Save/filename").toString()); QStringList paths = filename.path(tokens, profile, pth); bool alreadyExists = false; @@ -45,7 +45,7 @@ const QMap &Downloadable::tokens(Profile *profile) const break; } } - bool inMd5List = !profile->md5Action(tokens["md5"].value().toString()).second.isEmpty(); + const bool inMd5List = !profile->md5Action(tokens["md5"].value().toString()).second.isEmpty(); // Generate corresponding combination QStringList metas; diff --git a/lib/src/loader/loader-query.cpp b/lib/src/loader/loader-query.cpp index 027caeb5e..afb377475 100644 --- a/lib/src/loader/loader-query.cpp +++ b/lib/src/loader/loader-query.cpp @@ -9,8 +9,8 @@ #include "models/source.h" -LoaderQuery::LoaderQuery(Site *site, const QMap &options) - : m_site(site), m_options(options), m_finished(false), m_offset(0) +LoaderQuery::LoaderQuery(Site *site, QMap options) + : m_site(site), m_options(std::move(options)), m_finished(false), m_offset(0) {} bool LoaderQuery::start() diff --git a/lib/src/loader/loader-query.h b/lib/src/loader/loader-query.h index 859fd1ade..dd30baa8f 100644 --- a/lib/src/loader/loader-query.h +++ b/lib/src/loader/loader-query.h @@ -10,7 +10,7 @@ class Site; class LoaderQuery { public: - explicit LoaderQuery(Site *site, const QMap &options); + explicit LoaderQuery(Site *site, QMap options); bool start(); LoaderData next(); bool hasNext() const; diff --git a/lib/src/loader/token.cpp b/lib/src/loader/token.cpp index 3670dcf88..a9bb7445d 100644 --- a/lib/src/loader/token.cpp +++ b/lib/src/loader/token.cpp @@ -3,12 +3,11 @@ Token::Token(const QVariant &value, const QVariant &def) -{ - m_value = def.isValid() && (value.isNull() || !value.isValid() || isVariantEmpty(value)) ? def : value; -} + : m_value(def.isValid() && (value.isNull() || !value.isValid() || isVariantEmpty(value)) ? def : value) +{} -Token::Token(const QVariant &value, const QString &whatToDoDefault, const QString &emptyDefault, const QString &multipleDefault) - : m_value(value), m_whatToDoDefault(whatToDoDefault), m_emptyDefault(emptyDefault), m_multipleDefault(multipleDefault) +Token::Token(QVariant value, QString whatToDoDefault, QString emptyDefault, QString multipleDefault) + : m_value(std::move(value)), m_whatToDoDefault(std::move(whatToDoDefault)), m_emptyDefault(std::move(emptyDefault)), m_multipleDefault(std::move(multipleDefault)) {} Token::Token(std::function func, bool cacheResult) diff --git a/lib/src/loader/token.h b/lib/src/loader/token.h index 24575d5fd..b5882fee5 100644 --- a/lib/src/loader/token.h +++ b/lib/src/loader/token.h @@ -9,7 +9,7 @@ class Token public: Token() = default; explicit Token(const QVariant &value, const QVariant &def = QVariant()); - explicit Token(const QVariant &value, const QString &whatToDoDefault, const QString &emptyDefault, const QString &multipleDefault); + explicit Token(QVariant value, QString whatToDoDefault, QString emptyDefault, QString multipleDefault); explicit Token(std::function func, bool cacheResult = true); QVariant value() const; @@ -26,7 +26,7 @@ class Token QString m_emptyDefault; QString m_multipleDefault; std::function m_func = nullptr; - bool m_cacheResult; + bool m_cacheResult = false; }; bool operator==(const Token &lhs, const Token &rhs); diff --git a/lib/src/logger.cpp b/lib/src/logger.cpp index 11d0cb9e8..ef48aec2a 100644 --- a/lib/src/logger.cpp +++ b/lib/src/logger.cpp @@ -86,7 +86,7 @@ void Logger::log(const QString &l, LogLevel level) m_logFile.flush(); // Emit colored HTML log - QString msg = "[" + time.toString(timeFormat) + "][" + levelStr + "] " + l; + const QString msg = "[" + time.toString(timeFormat) + "][" + levelStr + "] " + l; emit newLog(msg); #ifdef QT_DEBUG diff --git a/lib/src/logger.h b/lib/src/logger.h index 18007d1c8..8d1f0d5ad 100644 --- a/lib/src/logger.h +++ b/lib/src/logger.h @@ -39,7 +39,7 @@ class Logger : public QObject void setLogFile(const QString &path); void setLogLevel(LogLevel level); - void log(const QString &, LogLevel type = Info); + void log(const QString &, LogLevel level = Info); void logCommand(const QString &); void logCommandSql(const QString &); void logUpdate(const QString &); diff --git a/lib/src/login/http-get-login.cpp b/lib/src/login/http-get-login.cpp index 18e4b955a..3cb3255b2 100644 --- a/lib/src/login/http-get-login.cpp +++ b/lib/src/login/http-get-login.cpp @@ -8,11 +8,11 @@ HttpGetLogin::HttpGetLogin(Site *site, CustomNetworkAccessManager *manager, Mixe : HttpLogin("get", site, manager, settings) {} -QNetworkReply *HttpGetLogin::getReply(const QString &loginUrl, const QUrlQuery &query) const +QNetworkReply *HttpGetLogin::getReply(const QString &url, const QUrlQuery &query) const { - QUrl url = m_site->fixUrl(loginUrl); - url.setQuery(query); - const QNetworkRequest request(url); + QUrl fixedUrl = m_site->fixUrl(url); + fixedUrl.setQuery(query); + const QNetworkRequest request(fixedUrl); return m_manager->get(request); } diff --git a/lib/src/login/http-login.cpp b/lib/src/login/http-login.cpp index dd1c9a9f3..ef1b50236 100644 --- a/lib/src/login/http-login.cpp +++ b/lib/src/login/http-login.cpp @@ -8,8 +8,8 @@ #include "models/site.h" -HttpLogin::HttpLogin(const QString &type, Site *site, CustomNetworkAccessManager *manager, MixedSettings *settings) - : m_type(type), m_site(site), m_manager(manager), m_settings(settings) +HttpLogin::HttpLogin(QString type, Site *site, CustomNetworkAccessManager *manager, MixedSettings *settings) + : m_type(std::move(type)), m_site(site), m_loginReply(Q_NULLPTR), m_manager(manager), m_settings(settings) {} bool HttpLogin::isTestable() const @@ -32,7 +32,13 @@ void HttpLogin::login() { query.addQueryItem(key, m_settings->value(key).toString()); } m_settings->endGroup(); - QString loginUrl = m_settings->value("login/" + m_type + "/url").toString(); + if (m_loginReply != Q_NULLPTR) + { + m_loginReply->abort(); + m_loginReply->deleteLater(); + } + + const QString loginUrl = m_settings->value("login/" + m_type + "/url").toString(); m_loginReply = getReply(loginUrl, query); connect(m_loginReply, &QNetworkReply::finished, this, &HttpLogin::loginFinished); diff --git a/lib/src/login/http-login.h b/lib/src/login/http-login.h index 17085877a..3f55e93d9 100644 --- a/lib/src/login/http-login.h +++ b/lib/src/login/http-login.h @@ -15,7 +15,7 @@ class HttpLogin : public Login Q_OBJECT public: - explicit HttpLogin(const QString &type, Site *site, CustomNetworkAccessManager *manager, MixedSettings *settings); + explicit HttpLogin(QString type, Site *site, CustomNetworkAccessManager *manager, MixedSettings *settings); bool isTestable() const override; virtual QNetworkReply *getReply(const QString &url, const QUrlQuery &query) const = 0; diff --git a/lib/src/login/http-post-login.cpp b/lib/src/login/http-post-login.cpp index b85c628e3..836468ca8 100644 --- a/lib/src/login/http-post-login.cpp +++ b/lib/src/login/http-post-login.cpp @@ -8,9 +8,9 @@ HttpPostLogin::HttpPostLogin(Site *site, CustomNetworkAccessManager *manager, Mi : HttpLogin("post", site, manager, settings) {} -QNetworkReply *HttpPostLogin::getReply(const QString &loginUrl, const QUrlQuery &query) const +QNetworkReply *HttpPostLogin::getReply(const QString &url, const QUrlQuery &query) const { - QNetworkRequest request(m_site->fixUrl(loginUrl)); + QNetworkRequest request(m_site->fixUrl(url)); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); return m_manager->post(request, query.query(QUrl::FullyEncoded).toUtf8()); diff --git a/lib/src/login/url-login.cpp b/lib/src/login/url-login.cpp index c6c1f27e2..eb50e642f 100644 --- a/lib/src/login/url-login.cpp +++ b/lib/src/login/url-login.cpp @@ -7,7 +7,7 @@ UrlLogin::UrlLogin(Site *site, QNetworkAccessManager *manager, MixedSettings *settings) - : m_site(site), m_manager(manager), m_settings(settings) + : m_site(site), m_manager(manager), m_settings(settings), m_page(Q_NULLPTR) {} bool UrlLogin::isTestable() const @@ -17,6 +17,12 @@ bool UrlLogin::isTestable() const void UrlLogin::login() { + if (m_page != Q_NULLPTR) + { + m_page->abort(); + m_page->deleteLater(); + } + const int maxPageAnonymous = m_settings->value("login/maxPage", 0).toInt(); m_page = new Page(m_site->getSource()->getProfile(), m_site, QList() << m_site, QStringList(), maxPageAnonymous); connect(m_page, &Page::finishedLoading, this, &UrlLogin::loginFinished); diff --git a/lib/src/mixed-settings.cpp b/lib/src/mixed-settings.cpp index 919f2bfdb..697012b07 100644 --- a/lib/src/mixed-settings.cpp +++ b/lib/src/mixed-settings.cpp @@ -2,8 +2,8 @@ #include "functions.h" -MixedSettings::MixedSettings(const QList &settings) - : m_settings(settings) +MixedSettings::MixedSettings(QList settings) + : m_settings(std::move(settings)) {} MixedSettings::~MixedSettings() diff --git a/lib/src/mixed-settings.h b/lib/src/mixed-settings.h index b9b3fd832..6e51664a2 100644 --- a/lib/src/mixed-settings.h +++ b/lib/src/mixed-settings.h @@ -9,7 +9,7 @@ class MixedSettings : public QObject Q_OBJECT public: - explicit MixedSettings(const QList &settings); + explicit MixedSettings(QList settings); ~MixedSettings() override; QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const; diff --git a/lib/src/models/api/api.cpp b/lib/src/models/api/api.cpp index e1f783896..83955a4f7 100644 --- a/lib/src/models/api/api.cpp +++ b/lib/src/models/api/api.cpp @@ -6,8 +6,8 @@ #include "models/source.h" -Api::Api(const QString &name, const QMap &data) - : QObject(), m_name(name), m_data(data) +Api::Api(QString name, QMap data) + : m_name(std::move(name)), m_data(std::move(data)) { QString prefix = "Urls/" + m_name; for (auto it = m_data.begin(); it != m_data.end(); ++it) diff --git a/lib/src/models/api/api.h b/lib/src/models/api/api.h index 6979022b4..138ff9eb2 100644 --- a/lib/src/models/api/api.h +++ b/lib/src/models/api/api.h @@ -50,7 +50,7 @@ class Api : public QObject Q_OBJECT public: - Api(const QString &name, const QMap &data); + Api(QString name, QMap data); // Getters QString getName() const; diff --git a/lib/src/models/api/html-api.cpp b/lib/src/models/api/html-api.cpp index 2f2f6674d..94c11e665 100644 --- a/lib/src/models/api/html-api.cpp +++ b/lib/src/models/api/html-api.cpp @@ -142,13 +142,13 @@ ParsedTags HtmlApi::parseTags(const QString &source, Site *site) const } // Map variables - int id = d.contains("id") ? d["id"].toInt() : 0; - QString name = d["tag"]; - int count = d.contains("count") ? d["count"].toInt() : 0; - int typeId = d.contains("typeId") ? d["typeId"].toInt() : -1; - QString ttype = d["type"]; + const int id = d.contains("id") ? d["id"].toInt() : 0; + const QString name = d["tag"]; + const int count = d.contains("count") ? d["count"].toInt() : 0; + const int typeId = d.contains("typeId") ? d["typeId"].toInt() : -1; + const QString ttype = d["type"]; - TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); + const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); ret.tags.append(Tag(id, name, tagType, count)); } @@ -168,8 +168,11 @@ ParsedDetails HtmlApi::parseDetails(const QString &source, Site *site) const while (matches.hasNext()) { auto match = matches.next(); - QString previous = match.captured(1), id = match.captured(2), name = match.captured(3), next = match.captured(4); - ret.pools.append(Pool(id.toInt(), name, 0, next.toInt(), previous.toInt())); + const int previous = match.captured(1).toInt(); + const int id = match.captured(2).toInt(); + const QString name = match.captured(3); + const int next = match.captured(4).toInt(); + ret.pools.append(Pool(id, name, 0, next, previous)); } } diff --git a/lib/src/models/api/javascript-console-helper.cpp b/lib/src/models/api/javascript-console-helper.cpp index d91540693..eea9d94bb 100644 --- a/lib/src/models/api/javascript-console-helper.cpp +++ b/lib/src/models/api/javascript-console-helper.cpp @@ -3,8 +3,8 @@ #include "logger.h" -JavascriptConsoleHelper::JavascriptConsoleHelper(const QString &prefix, QObject *parent) - : QObject(parent), m_prefix(prefix) +JavascriptConsoleHelper::JavascriptConsoleHelper(QString prefix, QObject *parent) + : QObject(parent), m_prefix(std::move(prefix)) {} diff --git a/lib/src/models/api/javascript-console-helper.h b/lib/src/models/api/javascript-console-helper.h index 5d0717944..2db64a6dc 100644 --- a/lib/src/models/api/javascript-console-helper.h +++ b/lib/src/models/api/javascript-console-helper.h @@ -9,7 +9,7 @@ class JavascriptConsoleHelper : public QObject Q_OBJECT public: - explicit JavascriptConsoleHelper(const QString &prefix, QObject *parent = Q_NULLPTR); + explicit JavascriptConsoleHelper(QString prefix, QObject *parent = Q_NULLPTR); Q_INVOKABLE void debug(const QString &msg) const; Q_INVOKABLE void error(const QString &msg) const; diff --git a/lib/src/models/favorite.cpp b/lib/src/models/favorite.cpp index 7d69ddfa7..63cbe06db 100644 --- a/lib/src/models/favorite.cpp +++ b/lib/src/models/favorite.cpp @@ -3,14 +3,14 @@ #include "functions.h" -Favorite::Favorite(const QString &name) - : Favorite(name, 50, QDateTime::currentDateTime(), QString()) +Favorite::Favorite(QString name) + : Favorite(std::move(name), 50, QDateTime::currentDateTime(), QString()) {} -Favorite::Favorite(const QString &name, int note, const QDateTime &lastViewed, const QString &imagePath) - : Favorite(name, note, lastViewed, QList(), imagePath) +Favorite::Favorite(QString name, int note, QDateTime lastViewed, QString imagePath) + : Favorite(std::move(name), note, std::move(lastViewed), QList(), std::move(imagePath)) {} -Favorite::Favorite(const QString &name, int note, const QDateTime &lastViewed, const QList &monitors, const QString &imagePath) - : m_name(name), m_note(note), m_lastViewed(lastViewed), m_monitors(monitors), m_imagePath(imagePath) +Favorite::Favorite(QString name, int note, QDateTime lastViewed, QList monitors, QString imagePath) + : m_name(std::move(name)), m_note(note), m_lastViewed(std::move(lastViewed)), m_monitors(std::move(monitors)), m_imagePath(std::move(imagePath)) {} void Favorite::setImagePath(const QString &imagePath) diff --git a/lib/src/models/favorite.h b/lib/src/models/favorite.h index abe81826a..a9578f0b0 100644 --- a/lib/src/models/favorite.h +++ b/lib/src/models/favorite.h @@ -11,9 +11,9 @@ class Site; class Favorite { public: - explicit Favorite(const QString &name); - Favorite(const QString &name, int note, const QDateTime &lastViewed, const QString &imagePath = ""); - Favorite(const QString &name, int note, const QDateTime &lastViewed, const QList &monitors, const QString &imagePath = ""); + explicit Favorite(QString name); + Favorite(QString name, int note, QDateTime lastViewed, QString imagePath = ""); + Favorite(QString name, int note, QDateTime lastViewed, QList monitors, QString imagePath = ""); // Getters and setters void setNote(int note); diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index c96ec2407..9da59434d 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -12,8 +12,8 @@ #include "post-filter.h" -Filename::Filename(const QString &format) - : m_format(format) +Filename::Filename(QString format) + : m_format(std::move(format)) { } QString Filename::expandConditionals(const QString &text, const QStringList &tags, const QMap &tokens, QSettings *settings, int depth) const @@ -237,7 +237,7 @@ QList> Filename::expandTokens(const QString &filename, QMap return ret; } -QStringList Filename::path(const Image& img, Profile *profile, const QString &pth, int counter, bool complex, bool maxLength, bool shouldFixFilename, bool getFull, bool keepInvalidTokens) const +QStringList Filename::path(const Image &img, Profile *profile, const QString &pth, int counter, bool complex, bool maxLength, bool shouldFixFilename, bool getFull, bool keepInvalidTokens) const { return path(img.tokens(profile), profile, pth, counter, complex, maxLength, shouldFixFilename, getFull, keepInvalidTokens); } QStringList Filename::path(QMap tokens, Profile *profile, QString folder, int counter, bool complex, bool maxLength, bool shouldFixFilename, bool getFull, bool keepInvalidTokens) const { @@ -454,7 +454,7 @@ QString Filename::optionedValue(const QVariant &val, const QString &key, const Q else if (val.type() == QVariant::StringList) { QStringList vals = val.toStringList(); - QString mainSeparator = settings->value("Save/separator", " ").toString(); + const QString mainSeparator = settings->value("Save/separator", " ").toString(); QString tagSeparator = fixSeparator(settings->value("Save/" + key + "_sep", mainSeparator).toString()); // Namespaces diff --git a/lib/src/models/filename.h b/lib/src/models/filename.h index 1a25e483b..2ce68b8ad 100644 --- a/lib/src/models/filename.h +++ b/lib/src/models/filename.h @@ -17,7 +17,7 @@ class Filename { public: Filename() = default; - explicit Filename(const QString &format); + explicit Filename(QString format); QString getFormat() const; void setFormat(const QString &format); void setEscapeMethod(QString (*)(const QVariant &)); @@ -30,7 +30,7 @@ class Filename * @param complex Whether the filename is complex or not (contains conditionals). * @return The filename of the image, with any token replaced. */ - QStringList path(const Image& img, Profile *settings, const QString &pth = "", int counter = 0, bool complex = true, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false, bool keepInvalidTokens = false) const; + QStringList path(const Image &img, Profile *settings, const QString &pth = "", int counter = 0, bool complex = true, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false, bool keepInvalidTokens = false) const; QStringList path(QMap tokens, Profile *settings, QString folder = "", int counter = 0, bool complex = true, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false, bool keepInvalidTokens = false) const; /** diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index d0492b6f0..6611634e7 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -38,7 +38,7 @@ QString removeCacheUrl(QString url) } Image::Image() - : QObject(), m_profile(nullptr), m_extensionRotator(nullptr) + : m_profile(Q_NULLPTR), m_extensionRotator(Q_NULLPTR) { } // TODO(Bionus): clean up this mess @@ -97,7 +97,7 @@ Image::Image(const Image &other) } Image::Image(Site *site, QMap details, Profile *profile, Page* parent) - : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(nullptr) + : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(Q_NULLPTR) { m_settings = m_profile->getSettings(); @@ -875,11 +875,11 @@ void Image::setUrl(const QString &u) m_url = u; refreshTokens(); } -void Image::setSize(QSize size) { m_size = size; refreshTokens(); } -void Image::setFileSize(int s) { m_fileSize = s; refreshTokens(); } -void Image::setData(const QByteArray &d) +void Image::setSize(QSize size) { m_size = size; refreshTokens(); } +void Image::setFileSize(int size) { m_fileSize = size; refreshTokens(); } +void Image::setData(const QByteArray &data) { - m_data = d; + m_data = data; // Detect file extension from data headers const bool headerDetection = m_settings->value("Save/headerDetection", true).toBool(); @@ -1164,7 +1164,7 @@ QMap Image::generateTokens(Profile *profile) const QMap details; for (const Tag &tag : filteredTags(remove)) { - const QString t = tag.text(); + const QString &t = tag.text(); details[ignore.contains(t, Qt::CaseInsensitive) ? "general" : tag.type().name()].append(t); details["alls"].append(t); diff --git a/lib/src/models/image.h b/lib/src/models/image.h index 02239a897..00063e0cf 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -34,7 +34,6 @@ class Image : public QObject, public Downloadable QString md5() const; const QString &url() const; const QString &rating() const; - QString site() const; const QList &tags() const; QList filteredTags(const QStringList &remove) const; QStringList tagsString() const; diff --git a/lib/src/models/monitor.cpp b/lib/src/models/monitor.cpp index c7ba473d3..262033415 100644 --- a/lib/src/models/monitor.cpp +++ b/lib/src/models/monitor.cpp @@ -3,8 +3,8 @@ #include "models/site.h" -Monitor::Monitor(Site *site, int interval, const QDateTime &lastCheck, int cumulated, bool preciseCumulated) - : m_site(site), m_interval(interval), m_lastCheck(lastCheck), m_cumulated(cumulated), m_preciseCumulated(preciseCumulated) +Monitor::Monitor(Site *site, int interval, QDateTime lastCheck, int cumulated, bool preciseCumulated) + : m_site(site), m_interval(interval), m_lastCheck(std::move(lastCheck)), m_cumulated(cumulated), m_preciseCumulated(preciseCumulated) {} qint64 Monitor::secsToNextCheck() const diff --git a/lib/src/models/monitor.h b/lib/src/models/monitor.h index a436934e1..462beab55 100644 --- a/lib/src/models/monitor.h +++ b/lib/src/models/monitor.h @@ -10,7 +10,7 @@ class Site; class Monitor { public: - Monitor(Site *site, int interval, const QDateTime &lastCheck, int cumulated = 0, bool preciseCumulated = true); + Monitor(Site *site, int interval, QDateTime lastCheck, int cumulated = 0, bool preciseCumulated = true); qint64 secsToNextCheck() const; // Getters and setters diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 647c2de54..bc2c494a0 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -14,8 +14,8 @@ #include "tags/tag.h" -PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, const QStringList &tags, int page, int limit, const QStringList &postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) - : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(tags), m_postFiltering(postFiltering), m_errors(QStringList()), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(nullptr), m_replyTags(nullptr) +PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags, int page, int limit, QStringList postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) + : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(std::move(tags)), m_postFiltering(std::move(postFiltering)), m_errors(QStringList()), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(Q_NULLPTR), m_replyTags(Q_NULLPTR) { m_imagesCount = -1; m_maxImagesCount = -1; @@ -23,7 +23,6 @@ PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, const m_imagesCountSafe = false; m_pagesCountSafe = false; - m_search = tags; m_page = page; m_pool = pool; m_format = m_api->getName(); @@ -110,7 +109,7 @@ void PageApi::abort() m_reply->abort(); } -bool PageApi::addImage(QSharedPointer img) +bool PageApi::addImage(const QSharedPointer &img) { if (img.isNull()) return false; diff --git a/lib/src/models/page-api.h b/lib/src/models/page-api.h index 02e3cab45..944a873ed 100644 --- a/lib/src/models/page-api.h +++ b/lib/src/models/page-api.h @@ -22,7 +22,7 @@ class PageApi : public QObject Error }; - explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, const QStringList &tags = QStringList(), int page = 1, int limit = 25, const QStringList &postFiltering = QStringList(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); + explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags = QStringList(), int page = 1, int limit = 25, QStringList postFiltering = QStringList(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); void setLastPage(Page *page); const QList> &images() const; bool isImageCountSure() const; @@ -59,7 +59,7 @@ class PageApi : public QObject void httpsRedirect(); protected: - bool addImage(QSharedPointer img); + bool addImage(const QSharedPointer &img); void updateUrls(); void parseActual(); void setImageCount(int count, bool sure); diff --git a/lib/src/models/page.h b/lib/src/models/page.h index 45509b251..8a8849aac 100644 --- a/lib/src/models/page.h +++ b/lib/src/models/page.h @@ -70,7 +70,7 @@ class Page : public QObject QList m_pageApis; int m_regexApi; QStringList m_postFiltering, m_errors, m_search; - int m_imagesPerPage, m_lastPage, m_imagesCount, m_pagesCount, m_page, m_blim, m_pool; + int m_imagesPerPage, m_lastPage, m_imagesCount, m_pagesCount, m_page, m_pool; qulonglong m_lastPageMinId, m_lastPageMaxId; bool m_smart; QString m_format, m_website, m_source, m_originalUrl; diff --git a/lib/src/models/pool.cpp b/lib/src/models/pool.cpp index 944a3d29b..0ce862ec7 100644 --- a/lib/src/models/pool.cpp +++ b/lib/src/models/pool.cpp @@ -2,8 +2,8 @@ #include -Pool::Pool(int id, const QString &name, int current, int next, int previous) - : m_id(id), m_name(name), m_current(current), m_next(next), m_previous(previous) +Pool::Pool(int id, QString name, int current, int next, int previous) + : m_id(id), m_name(std::move(name)), m_current(current), m_next(next), m_previous(previous) { } int Pool::id() const { return m_id; } diff --git a/lib/src/models/pool.h b/lib/src/models/pool.h index c172841a8..54e986b93 100644 --- a/lib/src/models/pool.h +++ b/lib/src/models/pool.h @@ -7,7 +7,7 @@ class Pool { public: - explicit Pool(int id, const QString &name, int current, int next = 0, int previous = 0); + explicit Pool(int id, QString name, int current, int next = 0, int previous = 0); // Getters int id() const; diff --git a/lib/src/models/profile.cpp b/lib/src/models/profile.cpp index 1b1ca290d..4181bad05 100644 --- a/lib/src/models/profile.cpp +++ b/lib/src/models/profile.cpp @@ -10,13 +10,13 @@ Profile::Profile() - : m_settings(nullptr), m_commands(nullptr) + : m_settings(Q_NULLPTR), m_commands(Q_NULLPTR) {} -Profile::Profile(QSettings *settings, const QList &favorites, const QStringList &keptForLater, const QString &path) - : m_path(path), m_settings(settings), m_favorites(favorites), m_keptForLater(keptForLater), m_commands(nullptr) +Profile::Profile(QSettings *settings, QList favorites, QStringList keptForLater, QString path) + : m_path(std::move(path)), m_settings(settings), m_favorites(std::move(favorites)), m_keptForLater(std::move(keptForLater)), m_commands(Q_NULLPTR) {} -Profile::Profile(const QString &path) - : m_path(path) +Profile::Profile(QString path) + : m_path(std::move(path)) { m_settings = new QSettings(m_path + "/settings.ini", QSettings::IniFormat); diff --git a/lib/src/models/profile.h b/lib/src/models/profile.h index d097069b7..35ac15ccb 100644 --- a/lib/src/models/profile.h +++ b/lib/src/models/profile.h @@ -16,8 +16,8 @@ class Profile : public QObject public: Profile(); - Profile(QSettings *settings, const QList &favorites, const QStringList &keptForLater = QStringList(), const QString &path = QString()); - explicit Profile(const QString &path); + Profile(QSettings *settings, QList favorites, QStringList keptForLater = QStringList(), QString path = QString()); + explicit Profile(QString path); ~Profile() override; void sync(); diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index 6cb19c26d..d42826432 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -30,8 +30,8 @@ -Site::Site(const QString &url, Source *source) - : m_type(source->getName()), m_url(url), m_source(source), m_settings(nullptr), m_manager(nullptr), m_cookieJar(nullptr), m_tagDatabase(nullptr), m_login(nullptr), m_loggedIn(LoginStatus::Unknown), m_autoLogin(true) +Site::Site(QString url, Source *source) + : m_type(source->getName()), m_url(std::move(url)), m_source(source), m_settings(Q_NULLPTR), m_manager(Q_NULLPTR), m_cookieJar(Q_NULLPTR), m_updateReply(Q_NULLPTR), m_tagsReply(Q_NULLPTR), m_tagDatabase(Q_NULLPTR), m_login(Q_NULLPTR), m_loggedIn(LoginStatus::Unknown), m_autoLogin(true) { // Create the access manager and get its slots m_manager = new CustomNetworkAccessManager(this); @@ -133,8 +133,7 @@ void Site::loadConfig() resetCookieJar(); // Tag database - if (m_tagDatabase != nullptr) - { delete m_tagDatabase; } + delete m_tagDatabase; m_tagDatabase = TagDatabaseFactory::Create(siteDir); m_tagDatabase->loadTypes(); } @@ -386,7 +385,7 @@ void Site::setAutoLogin(bool autoLogin) { m_autoLogin = autoLogin; } QString Site::fixLoginUrl(QString url, const QString &loginPart) const { - return m_login->complementUrl(url, loginPart); + return m_login->complementUrl(std::move(url), loginPart); } QUrl Site::fixUrl(const QString &url, const QUrl &old) const diff --git a/lib/src/models/site.h b/lib/src/models/site.h index 61be279fe..d2d0a314f 100644 --- a/lib/src/models/site.h +++ b/lib/src/models/site.h @@ -48,7 +48,7 @@ class Site : public QObject LoggedIn = 3, }; - Site(const QString &url, Source *source); + Site(QString url, Source *source); ~Site() override; void loadConfig(); const QString &type() const; diff --git a/lib/src/models/source-guesser.cpp b/lib/src/models/source-guesser.cpp index 511f36298..38a03b9e3 100644 --- a/lib/src/models/source-guesser.cpp +++ b/lib/src/models/source-guesser.cpp @@ -10,8 +10,8 @@ #include "models/source.h" -SourceGuesser::SourceGuesser(const QString &url, const QList &sources) - : m_url(url), m_sources(sources) +SourceGuesser::SourceGuesser(QString url, QList sources) + : m_url(std::move(url)), m_sources(std::move(sources)) { m_manager = new CustomNetworkAccessManager(this); } @@ -64,6 +64,6 @@ Source *SourceGuesser::start() } } - emit finished(nullptr); - return nullptr; + emit finished(Q_NULLPTR); + return Q_NULLPTR; } diff --git a/lib/src/models/source-guesser.h b/lib/src/models/source-guesser.h index e3373917c..027b3ad4d 100644 --- a/lib/src/models/source-guesser.h +++ b/lib/src/models/source-guesser.h @@ -15,7 +15,7 @@ class SourceGuesser : public QObject Q_OBJECT public: - SourceGuesser(const QString &url, const QList &sources); + SourceGuesser(QString url, QList sources); Source *start(); signals: diff --git a/lib/src/models/source.cpp b/lib/src/models/source.cpp index 926b0e495..cf1ab4de1 100644 --- a/lib/src/models/source.cpp +++ b/lib/src/models/source.cpp @@ -185,7 +185,7 @@ Source::Source(Profile *profile, const QString &dir) if (line.isEmpty()) continue; - Site *site = new Site(line, this); + auto site = new Site(line, this); m_sites.append(site); } } diff --git a/lib/src/reverse-search/reverse-search-engine.cpp b/lib/src/reverse-search/reverse-search-engine.cpp index 90b0b87a7..8a5888d5d 100644 --- a/lib/src/reverse-search/reverse-search-engine.cpp +++ b/lib/src/reverse-search/reverse-search-engine.cpp @@ -4,8 +4,8 @@ #include "functions.h" -ReverseSearchEngine::ReverseSearchEngine(int id, const QString &icon, const QString &name, const QString &tpl, int order) - : m_id(id), m_icon(loadIcon(icon)), m_name(name), m_tpl(tpl), m_order(order) +ReverseSearchEngine::ReverseSearchEngine(int id, const QString &icon, QString name, QString tpl, int order) + : m_id(id), m_icon(loadIcon(icon)), m_name(std::move(name)), m_tpl(std::move(tpl)), m_order(order) {} QIcon ReverseSearchEngine::loadIcon(const QString &path) const diff --git a/lib/src/reverse-search/reverse-search-engine.h b/lib/src/reverse-search/reverse-search-engine.h index ad9ec2e8d..01dfb759b 100644 --- a/lib/src/reverse-search/reverse-search-engine.h +++ b/lib/src/reverse-search/reverse-search-engine.h @@ -9,7 +9,7 @@ class ReverseSearchEngine { public: ReverseSearchEngine() = default; - ReverseSearchEngine(int id, const QString &icon, const QString &name, const QString &tpl, int order); + ReverseSearchEngine(int id, const QString &icon, QString name, QString tpl, int order); void searchByUrl(const QUrl &url) const; int id() const; diff --git a/lib/src/tags/tag-database-in-memory.cpp b/lib/src/tags/tag-database-in-memory.cpp index 601ac66e9..6f50c2ff0 100644 --- a/lib/src/tags/tag-database-in-memory.cpp +++ b/lib/src/tags/tag-database-in-memory.cpp @@ -4,11 +4,8 @@ #include "tags/tag.h" -TagDatabaseInMemory::TagDatabaseInMemory(const QString &typeFile, const QString &tagFile) - : TagDatabase(typeFile), m_tagFile(tagFile) -{} - -TagDatabaseInMemory::~TagDatabaseInMemory() +TagDatabaseInMemory::TagDatabaseInMemory(const QString &typeFile, QString tagFile) + : TagDatabase(typeFile), m_tagFile(std::move(tagFile)) {} bool TagDatabaseInMemory::load() diff --git a/lib/src/tags/tag-database-in-memory.h b/lib/src/tags/tag-database-in-memory.h index f1bf48323..e0189f3ae 100644 --- a/lib/src/tags/tag-database-in-memory.h +++ b/lib/src/tags/tag-database-in-memory.h @@ -8,8 +8,8 @@ class TagDatabaseInMemory : public TagDatabase { public: - TagDatabaseInMemory(const QString &typeFile, const QString &tagFile); - ~TagDatabaseInMemory() override; + TagDatabaseInMemory(const QString &typeFile, QString tagFile); + ~TagDatabaseInMemory() override = default; bool load() override; bool save() override; void setTags(const QList &tags) override; diff --git a/lib/src/tags/tag-database-sqlite.cpp b/lib/src/tags/tag-database-sqlite.cpp index e0a42cb89..9f550bc89 100644 --- a/lib/src/tags/tag-database-sqlite.cpp +++ b/lib/src/tags/tag-database-sqlite.cpp @@ -9,11 +9,8 @@ #include "tags/tag.h" -TagDatabaseSqlite::TagDatabaseSqlite(const QString &typeFile, const QString &tagFile) - : TagDatabase(typeFile), m_tagFile(tagFile), m_count(-1) -{} - -TagDatabaseSqlite::~TagDatabaseSqlite() +TagDatabaseSqlite::TagDatabaseSqlite(const QString &typeFile, QString tagFile) + : TagDatabase(typeFile), m_tagFile(std::move(tagFile)), m_count(-1) {} bool TagDatabaseSqlite::load() diff --git a/lib/src/tags/tag-database-sqlite.h b/lib/src/tags/tag-database-sqlite.h index c4e58da87..1ae8013df 100644 --- a/lib/src/tags/tag-database-sqlite.h +++ b/lib/src/tags/tag-database-sqlite.h @@ -10,8 +10,8 @@ class TagDatabaseSqlite : public TagDatabase { public: - TagDatabaseSqlite(const QString &typeFile, const QString &tagFile); - ~TagDatabaseSqlite() override; + TagDatabaseSqlite(const QString &typeFile, QString tagFile); + ~TagDatabaseSqlite() override = default; bool load() override; bool save() override; void setTags(const QList &tags) override; diff --git a/lib/src/tags/tag-database.cpp b/lib/src/tags/tag-database.cpp index 669588f6d..523399b13 100644 --- a/lib/src/tags/tag-database.cpp +++ b/lib/src/tags/tag-database.cpp @@ -5,11 +5,8 @@ #include "tag-type.h" -TagDatabase::TagDatabase(const QString &typeFile) - : m_typeFile(typeFile) -{} - -TagDatabase::~TagDatabase() +TagDatabase::TagDatabase(QString typeFile) + : m_typeFile(std::move(typeFile)) {} bool TagDatabase::load() diff --git a/lib/src/tags/tag-database.h b/lib/src/tags/tag-database.h index 3612c74f3..ceed80ead 100644 --- a/lib/src/tags/tag-database.h +++ b/lib/src/tags/tag-database.h @@ -11,7 +11,7 @@ class Tag; class TagDatabase { public: - virtual ~TagDatabase(); + virtual ~TagDatabase() = default; void loadTypes(); virtual bool load(); virtual bool save() = 0; @@ -21,7 +21,7 @@ class TagDatabase const QMap &tagTypes() const; protected: - explicit TagDatabase(const QString &typeFile); + explicit TagDatabase(QString typeFile); protected: QMap m_tagTypes; diff --git a/lib/src/tags/tag-name-format.cpp b/lib/src/tags/tag-name-format.cpp index bf100ca24..c51539d15 100644 --- a/lib/src/tags/tag-name-format.cpp +++ b/lib/src/tags/tag-name-format.cpp @@ -2,11 +2,8 @@ #include -TagNameFormat::TagNameFormat() -{} - -TagNameFormat::TagNameFormat(CaseFormat caseFormat, const QString &wordSeparator) - : m_caseFormat(caseFormat), m_wordSeparator(wordSeparator) +TagNameFormat::TagNameFormat(CaseFormat caseFormat, QString wordSeparator) + : m_caseFormat(caseFormat), m_wordSeparator(std::move(wordSeparator)) {} TagNameFormat &TagNameFormat::Normalized() diff --git a/lib/src/tags/tag-name-format.h b/lib/src/tags/tag-name-format.h index 87a168b4e..7e0ae05ad 100644 --- a/lib/src/tags/tag-name-format.h +++ b/lib/src/tags/tag-name-format.h @@ -16,8 +16,8 @@ class TagNameFormat Caps, // SOME_TAG }; - TagNameFormat(); - TagNameFormat(CaseFormat caseFormat, const QString &wordSeparator); + TagNameFormat() = default; + TagNameFormat(CaseFormat caseFormat, QString wordSeparator); static TagNameFormat &Normalized(); CaseFormat caseFormat() const; QString wordSeparator() const; diff --git a/lib/src/tags/tag-name.cpp b/lib/src/tags/tag-name.cpp index 282de56f7..492eca046 100644 --- a/lib/src/tags/tag-name.cpp +++ b/lib/src/tags/tag-name.cpp @@ -1,11 +1,8 @@ #include "tags/tag-name.h" -TagName::TagName() -{} - -TagName::TagName(const QString &name, const TagNameFormat &format) - : m_name(name), m_format(format) +TagName::TagName(QString name, TagNameFormat format) + : m_name(std::move(name)), m_format(std::move(format)) { m_normalized = normalized(); } diff --git a/lib/src/tags/tag-name.h b/lib/src/tags/tag-name.h index ae02b4f85..4f8087859 100644 --- a/lib/src/tags/tag-name.h +++ b/lib/src/tags/tag-name.h @@ -8,8 +8,8 @@ class TagName { public: - TagName(); - explicit TagName(const QString &name, const TagNameFormat &format = TagNameFormat::Normalized()); + TagName() = default; + explicit TagName(QString name, TagNameFormat format = TagNameFormat::Normalized()); QString normalized() const; QString formatted(const TagNameFormat &format) const; diff --git a/lib/src/tags/tag-stylist.cpp b/lib/src/tags/tag-stylist.cpp index c39270783..3f95918c0 100644 --- a/lib/src/tags/tag-stylist.cpp +++ b/lib/src/tags/tag-stylist.cpp @@ -28,11 +28,6 @@ QStringList TagStylist::stylished(QList tags, bool count, bool noUnderscore return t; } -/** - * Return the colored tag. - * @param favs The list of the user's favorite tags. - * @return The HTML colored tag. - */ QString TagStylist::stylished(const Tag &tag, bool count, bool noUnderscores) const { static const QStringList tlist = QStringList() << "artists" << "circles" << "copyrights" << "characters" << "species" << "metas" << "models" << "generals" << "favorites" << "keptForLater" << "blacklisteds" << "ignoreds" << "favorites"; diff --git a/lib/src/tags/tag.cpp b/lib/src/tags/tag.cpp index 6527dfa97..b54fd7655 100644 --- a/lib/src/tags/tag.cpp +++ b/lib/src/tags/tag.cpp @@ -15,7 +15,7 @@ QMap stringListToMap(const QStringList &list) } Tag::Tag() - : m_type(TagType()), m_count(0) + : m_id(0), m_type(TagType()), m_count(0) { } Tag::Tag(const QString &text, const QString &type, int count, const QStringList &related) @@ -26,8 +26,8 @@ Tag::Tag(const QString &text, const TagType &type, int count, const QStringList : Tag(0, text, type, count, related) { } -Tag::Tag(int id, const QString &text, const TagType &type, int count, const QStringList &related) - : m_id(id), m_type(type), m_count(count), m_related(related) +Tag::Tag(int id, const QString &text, TagType type, int count, QStringList related) + : m_id(id), m_type(std::move(type)), m_count(count), m_related(std::move(related)) { static QStringList weakTypes = QStringList() << QStringLiteral("unknown") << QStringLiteral("origin"); @@ -166,7 +166,7 @@ void Tag::setId(int id) { m_id = id; } void Tag::setText(const QString &text) { m_text = text; } void Tag::setType(const TagType &type) { m_type = type; } void Tag::setCount(int count) { m_count = count; } -void Tag::setRelated(const QStringList &r) { m_related = r; } +void Tag::setRelated(const QStringList &related) { m_related = related; } int Tag::id() const { return m_id; } const QString &Tag::text() const { return m_text; } diff --git a/lib/src/tags/tag.h b/lib/src/tags/tag.h index d2235c094..f81be1948 100644 --- a/lib/src/tags/tag.h +++ b/lib/src/tags/tag.h @@ -14,7 +14,7 @@ class Tag Tag(); explicit Tag(const QString &text, const QString &type = "unknown", int count = 0, const QStringList &related = QStringList()); explicit Tag(const QString &text, const TagType &type, int count = 0, const QStringList &related = QStringList()); - explicit Tag(int id, const QString &text, const TagType &type, int count = 0, const QStringList &related = QStringList()); + explicit Tag(int id, const QString &text, TagType type, int count = 0, QStringList related = QStringList()); static Tag FromCapture(const QRegularExpressionMatch &match, const QStringList &groups); static QList FromRegexp(const QString &rx, const QString &source); static QString GetType(QString type, QMap ids = QMap()); diff --git a/lib/src/updater/program-updater.cpp b/lib/src/updater/program-updater.cpp index 0b26ea427..238ceae6e 100644 --- a/lib/src/updater/program-updater.cpp +++ b/lib/src/updater/program-updater.cpp @@ -11,8 +11,8 @@ ProgramUpdater::ProgramUpdater() : ProgramUpdater(QStringLiteral("https://api.github.com/repos/Bionus/imgbrd-grabber")) { } -ProgramUpdater::ProgramUpdater(const QString &baseUrl) - : m_baseUrl(baseUrl), m_downloadReply(Q_NULLPTR) +ProgramUpdater::ProgramUpdater(QString baseUrl) + : m_baseUrl(std::move(baseUrl)), m_downloadReply(Q_NULLPTR) { } void ProgramUpdater::checkForUpdates() const diff --git a/lib/src/updater/program-updater.h b/lib/src/updater/program-updater.h index d1a8853eb..2d522a700 100644 --- a/lib/src/updater/program-updater.h +++ b/lib/src/updater/program-updater.h @@ -11,7 +11,7 @@ class ProgramUpdater : public Updater public: ProgramUpdater(); - explicit ProgramUpdater(const QString &baseUrl); + explicit ProgramUpdater(QString baseUrl); QUrl latestUrl() const; public slots: diff --git a/lib/src/updater/source-updater.cpp b/lib/src/updater/source-updater.cpp index 944068da2..39b4df764 100644 --- a/lib/src/updater/source-updater.cpp +++ b/lib/src/updater/source-updater.cpp @@ -5,8 +5,8 @@ #include "custom-network-access-manager.h" -SourceUpdater::SourceUpdater(const QString &source, const QString &directory, const QString &baseUrl) - : m_source(source), m_directory(directory), m_baseUrl(baseUrl) +SourceUpdater::SourceUpdater(QString source, QString directory, QString baseUrl) + : m_source(std::move(source)), m_directory(std::move(directory)), m_baseUrl(std::move(baseUrl)) { if (!m_baseUrl.endsWith("/")) m_baseUrl += "/"; diff --git a/lib/src/updater/source-updater.h b/lib/src/updater/source-updater.h index f7f0453da..eddcee07d 100644 --- a/lib/src/updater/source-updater.h +++ b/lib/src/updater/source-updater.h @@ -11,7 +11,7 @@ class SourceUpdater : public Updater Q_OBJECT public: - SourceUpdater(const QString &source, const QString &directory, const QString &baseUrl); + SourceUpdater(QString source, QString directory, QString baseUrl); public slots: void checkForUpdates() const override; From 6d9f36af72a6fad912bd0c0920177721609e0bcd Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 9 Jul 2018 18:39:17 +0200 Subject: [PATCH 028/112] Use html entities decoder instead of dom parser in Tag constructor --- lib/src/functions.cpp | 10 + lib/src/functions.h | 1 + lib/src/tags/tag.cpp | 5 +- lib/src/vendor/html-entities.cpp | 388 +++++++++++++++++++++++++++++++ lib/src/vendor/html-entities.h | 20 ++ 5 files changed, 420 insertions(+), 4 deletions(-) create mode 100644 lib/src/vendor/html-entities.cpp create mode 100644 lib/src/vendor/html-entities.h diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index 5bb480642..ca352eb95 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -21,6 +21,7 @@ #ifdef QT_DEBUG #include #endif +#include "vendor/html-entities.h" /** @@ -820,3 +821,12 @@ QMap multiMatchToMap(const QRegularExpressionMatch &match, con return data; } + +QString decodeHtmlEntities(const QString &html) +{ + QByteArray data = html.toUtf8(); + const char *src = data.constData(); + auto *dest = new char[strlen(src) + 1]; + decode_html_entities_utf8(dest, src); + return QString::fromUtf8(dest); +} diff --git a/lib/src/functions.h b/lib/src/functions.h index 7ed184eb7..e324d1ea9 100644 --- a/lib/src/functions.h +++ b/lib/src/functions.h @@ -72,6 +72,7 @@ void setTestModeEnabled(bool testMode); bool isTestModeEnabled(); QString parseMarkdown(QString str); +QString decodeHtmlEntities(const QString &html); QString qFontToCss(const QFont &font); QFont qFontFromString(const QString &str); diff --git a/lib/src/tags/tag.cpp b/lib/src/tags/tag.cpp index b54fd7655..e1ab4da97 100644 --- a/lib/src/tags/tag.cpp +++ b/lib/src/tags/tag.cpp @@ -1,7 +1,6 @@ #include "tag.h" #include #include -#include #include "functions.h" #include "tag-type.h" @@ -32,9 +31,7 @@ Tag::Tag(int id, const QString &text, TagType type, int count, QStringList relat static QStringList weakTypes = QStringList() << QStringLiteral("unknown") << QStringLiteral("origin"); // Decode HTML entities in the tag text - QTextDocument htmlEncoded; - htmlEncoded.setHtml(text); - m_text = htmlEncoded.toPlainText().replace(' ', '_'); + m_text = decodeHtmlEntities(text).replace(' ', '_'); // Sometimes a type is found with multiple words, only the first is relevant const int typeSpace = m_type.name().indexOf(' '); diff --git a/lib/src/vendor/html-entities.cpp b/lib/src/vendor/html-entities.cpp new file mode 100644 index 000000000..fd3afb0e7 --- /dev/null +++ b/lib/src/vendor/html-entities.cpp @@ -0,0 +1,388 @@ +/* Copyright 2012, 2016 Christoph Gärtner + Distributed under the Boost Software License, Version 1.0 +*/ + +#include "html-entities.h" + +#include +#include +#include +#include + +#define UNICODE_MAX 0x10FFFFul + +static const char *const NAMED_ENTITIES[][2] = { + { "AElig;", "Æ" }, + { "Aacute;", "Á" }, + { "Acirc;", "Â" }, + { "Agrave;", "À" }, + { "Alpha;", "Α" }, + { "Aring;", "Å" }, + { "Atilde;", "Ã" }, + { "Auml;", "Ä" }, + { "Beta;", "Β" }, + { "Ccedil;", "Ç" }, + { "Chi;", "Χ" }, + { "Dagger;", "‡" }, + { "Delta;", "Δ" }, + { "ETH;", "Ð" }, + { "Eacute;", "É" }, + { "Ecirc;", "Ê" }, + { "Egrave;", "È" }, + { "Epsilon;", "Ε" }, + { "Eta;", "Η" }, + { "Euml;", "Ë" }, + { "Gamma;", "Γ" }, + { "Iacute;", "Í" }, + { "Icirc;", "Î" }, + { "Igrave;", "Ì" }, + { "Iota;", "Ι" }, + { "Iuml;", "Ï" }, + { "Kappa;", "Κ" }, + { "Lambda;", "Λ" }, + { "Mu;", "Μ" }, + { "Ntilde;", "Ñ" }, + { "Nu;", "Ν" }, + { "OElig;", "Œ" }, + { "Oacute;", "Ó" }, + { "Ocirc;", "Ô" }, + { "Ograve;", "Ò" }, + { "Omega;", "Ω" }, + { "Omicron;", "Ο" }, + { "Oslash;", "Ø" }, + { "Otilde;", "Õ" }, + { "Ouml;", "Ö" }, + { "Phi;", "Φ" }, + { "Pi;", "Π" }, + { "Prime;", "″" }, + { "Psi;", "Ψ" }, + { "Rho;", "Ρ" }, + { "Scaron;", "Š" }, + { "Sigma;", "Σ" }, + { "THORN;", "Þ" }, + { "Tau;", "Τ" }, + { "Theta;", "Θ" }, + { "Uacute;", "Ú" }, + { "Ucirc;", "Û" }, + { "Ugrave;", "Ù" }, + { "Upsilon;", "Υ" }, + { "Uuml;", "Ü" }, + { "Xi;", "Ξ" }, + { "Yacute;", "Ý" }, + { "Yuml;", "Ÿ" }, + { "Zeta;", "Ζ" }, + { "aacute;", "á" }, + { "acirc;", "â" }, + { "acute;", "´" }, + { "aelig;", "æ" }, + { "agrave;", "à" }, + { "alefsym;", "ℵ" }, + { "alpha;", "α" }, + { "amp;", "&" }, + { "and;", "∧" }, + { "ang;", "∠" }, + { "apos;", "'" }, + { "aring;", "å" }, + { "asymp;", "≈" }, + { "atilde;", "ã" }, + { "auml;", "ä" }, + { "bdquo;", "„" }, + { "beta;", "β" }, + { "brvbar;", "¦" }, + { "bull;", "•" }, + { "cap;", "∩" }, + { "ccedil;", "ç" }, + { "cedil;", "¸" }, + { "cent;", "¢" }, + { "chi;", "χ" }, + { "circ;", "ˆ" }, + { "clubs;", "♣" }, + { "cong;", "≅" }, + { "copy;", "©" }, + { "crarr;", "↵" }, + { "cup;", "∪" }, + { "curren;", "¤" }, + { "dArr;", "⇓" }, + { "dagger;", "†" }, + { "darr;", "↓" }, + { "deg;", "°" }, + { "delta;", "δ" }, + { "diams;", "♦" }, + { "divide;", "÷" }, + { "eacute;", "é" }, + { "ecirc;", "ê" }, + { "egrave;", "è" }, + { "empty;", "∅" }, + { "emsp;", "\xE2\x80\x83" }, + { "ensp;", "\xE2\x80\x82" }, + { "epsilon;", "ε" }, + { "equiv;", "≡" }, + { "eta;", "η" }, + { "eth;", "ð" }, + { "euml;", "ë" }, + { "euro;", "€" }, + { "exist;", "∃" }, + { "fnof;", "ƒ" }, + { "forall;", "∀" }, + { "frac12;", "½" }, + { "frac14;", "¼" }, + { "frac34;", "¾" }, + { "frasl;", "⁄" }, + { "gamma;", "γ" }, + { "ge;", "≥" }, + { "gt;", ">" }, + { "hArr;", "⇔" }, + { "harr;", "↔" }, + { "hearts;", "♥" }, + { "hellip;", "…" }, + { "iacute;", "í" }, + { "icirc;", "î" }, + { "iexcl;", "¡" }, + { "igrave;", "ì" }, + { "image;", "ℑ" }, + { "infin;", "∞" }, + { "int;", "∫" }, + { "iota;", "ι" }, + { "iquest;", "¿" }, + { "isin;", "∈" }, + { "iuml;", "ï" }, + { "kappa;", "κ" }, + { "lArr;", "⇐" }, + { "lambda;", "λ" }, + { "lang;", "〈" }, + { "laquo;", "«" }, + { "larr;", "←" }, + { "lceil;", "⌈" }, + { "ldquo;", "“" }, + { "le;", "≤" }, + { "lfloor;", "⌊" }, + { "lowast;", "∗" }, + { "loz;", "◊" }, + { "lrm;", "\xE2\x80\x8E" }, + { "lsaquo;", "‹" }, + { "lsquo;", "‘" }, + { "lt;", "<" }, + { "macr;", "¯" }, + { "mdash;", "—" }, + { "micro;", "µ" }, + { "middot;", "·" }, + { "minus;", "−" }, + { "mu;", "μ" }, + { "nabla;", "∇" }, + { "nbsp;", "\xC2\xA0" }, + { "ndash;", "–" }, + { "ne;", "≠" }, + { "ni;", "∋" }, + { "not;", "¬" }, + { "notin;", "∉" }, + { "nsub;", "⊄" }, + { "ntilde;", "ñ" }, + { "nu;", "ν" }, + { "oacute;", "ó" }, + { "ocirc;", "ô" }, + { "oelig;", "œ" }, + { "ograve;", "ò" }, + { "oline;", "‾" }, + { "omega;", "ω" }, + { "omicron;", "ο" }, + { "oplus;", "⊕" }, + { "or;", "∨" }, + { "ordf;", "ª" }, + { "ordm;", "º" }, + { "oslash;", "ø" }, + { "otilde;", "õ" }, + { "otimes;", "⊗" }, + { "ouml;", "ö" }, + { "para;", "¶" }, + { "part;", "∂" }, + { "permil;", "‰" }, + { "perp;", "⊥" }, + { "phi;", "φ" }, + { "pi;", "π" }, + { "piv;", "ϖ" }, + { "plusmn;", "±" }, + { "pound;", "£" }, + { "prime;", "′" }, + { "prod;", "∏" }, + { "prop;", "∝" }, + { "psi;", "ψ" }, + { "quot;", "\"" }, + { "rArr;", "⇒" }, + { "radic;", "√" }, + { "rang;", "〉" }, + { "raquo;", "»" }, + { "rarr;", "→" }, + { "rceil;", "⌉" }, + { "rdquo;", "”" }, + { "real;", "ℜ" }, + { "reg;", "®" }, + { "rfloor;", "⌋" }, + { "rho;", "ρ" }, + { "rlm;", "\xE2\x80\x8F" }, + { "rsaquo;", "›" }, + { "rsquo;", "’" }, + { "sbquo;", "‚" }, + { "scaron;", "š" }, + { "sdot;", "⋅" }, + { "sect;", "§" }, + { "shy;", "\xC2\xAD" }, + { "sigma;", "σ" }, + { "sigmaf;", "ς" }, + { "sim;", "∼" }, + { "spades;", "♠" }, + { "sub;", "⊂" }, + { "sube;", "⊆" }, + { "sum;", "∑" }, + { "sup1;", "¹" }, + { "sup2;", "²" }, + { "sup3;", "³" }, + { "sup;", "⊃" }, + { "supe;", "⊇" }, + { "szlig;", "ß" }, + { "tau;", "τ" }, + { "there4;", "∴" }, + { "theta;", "θ" }, + { "thetasym;", "ϑ" }, + { "thinsp;", "\xE2\x80\x89" }, + { "thorn;", "þ" }, + { "tilde;", "˜" }, + { "times;", "×" }, + { "trade;", "™" }, + { "uArr;", "⇑" }, + { "uacute;", "ú" }, + { "uarr;", "↑" }, + { "ucirc;", "û" }, + { "ugrave;", "ù" }, + { "uml;", "¨" }, + { "upsih;", "ϒ" }, + { "upsilon;", "υ" }, + { "uuml;", "ü" }, + { "weierp;", "℘" }, + { "xi;", "ξ" }, + { "yacute;", "ý" }, + { "yen;", "¥" }, + { "yuml;", "ÿ" }, + { "zeta;", "ζ" }, + { "zwj;", "\xE2\x80\x8D" }, + { "zwnj;", "\xE2\x80\x8C" } +}; + +static int cmp(const void *key, const void *value) +{ + return strncmp((const char *)key, *(const char *const *)value, + strlen(*(const char *const *)value)); +} + +static const char *get_named_entity(const char *name) +{ + const char *const *entity = (const char *const *)bsearch(name, + NAMED_ENTITIES, sizeof NAMED_ENTITIES / sizeof *NAMED_ENTITIES, + sizeof *NAMED_ENTITIES, cmp); + + return entity ? entity[1] : NULL; +} + +static size_t putc_utf8(unsigned long cp, char *buffer) +{ + unsigned char *bytes = (unsigned char *)buffer; + + if(cp <= 0x007Ful) + { + bytes[0] = (unsigned char)cp; + return 1; + } + + if(cp <= 0x07FFul) + { + bytes[1] = (unsigned char)((2 << 6) | (cp & 0x3F)); + bytes[0] = (unsigned char)((6 << 5) | (cp >> 6)); + return 2; + } + + if(cp <= 0xFFFFul) + { + bytes[2] = (unsigned char)(( 2 << 6) | ( cp & 0x3F)); + bytes[1] = (unsigned char)(( 2 << 6) | ((cp >> 6) & 0x3F)); + bytes[0] = (unsigned char)((14 << 4) | (cp >> 12)); + return 3; + } + + if(cp <= 0x10FFFFul) + { + bytes[3] = (unsigned char)(( 2 << 6) | ( cp & 0x3F)); + bytes[2] = (unsigned char)(( 2 << 6) | ((cp >> 6) & 0x3F)); + bytes[1] = (unsigned char)(( 2 << 6) | ((cp >> 12) & 0x3F)); + bytes[0] = (unsigned char)((30 << 3) | (cp >> 18)); + return 4; + } + + return 0; +} + +static bool parse_entity( + const char *current, char **to, const char **from) +{ + const char *end = strchr(current, ';'); + if(!end) return 0; + + if(current[1] == '#') + { + char *tail = NULL; + int errno_save = errno; + bool hex = current[2] == 'x' || current[2] == 'X'; + + errno = 0; + unsigned long cp = strtoul( + current + (hex ? 3 : 2), &tail, hex ? 16 : 10); + + bool fail = errno || tail != end || cp > UNICODE_MAX; + errno = errno_save; + if(fail) return 0; + + *to += putc_utf8(cp, *to); + *from = end + 1; + + return 1; + } + else + { + const char *entity = get_named_entity(¤t[1]); + if(!entity) return 0; + + size_t len = strlen(entity); + memcpy(*to, entity, len); + + *to += len; + *from = end + 1; + + return 1; + } +} + +size_t decode_html_entities_utf8(char *dest, const char *src) +{ + if(!src) src = dest; + + char *to = dest; + const char *from = src; + + for(const char *current; (current = strchr(from, '&'));) + { + memmove(to, from, (size_t)(current - from)); + to += current - from; + + if(parse_entity(current, &to, &from)) + continue; + + from = current; + *to++ = *from++; + } + + size_t remaining = strlen(from); + + memmove(to, from, remaining); + to += remaining; + *to = 0; + + return (size_t)(to - dest); +} diff --git a/lib/src/vendor/html-entities.h b/lib/src/vendor/html-entities.h new file mode 100644 index 000000000..0aaf63599 --- /dev/null +++ b/lib/src/vendor/html-entities.h @@ -0,0 +1,20 @@ +/* Copyright 2012 Christoph Gärtner + Distributed under the Boost Software License, Version 1.0 +*/ + +#ifndef DECODE_HTML_ENTITIES_UTF8_ +#define DECODE_HTML_ENTITIES_UTF8_ + +#include + +extern size_t decode_html_entities_utf8(char *dest, const char *src); +/* Takes input from and decodes into , which should be a buffer + large enough to hold characters. + + If is , input will be taken from , decoding + the entities in-place. + + The function returns the length of the decoded string. +*/ + +#endif From 4d81be35ae23b27f3b6b1961e4efc5f0e3e1aa7f Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 9 Jul 2018 19:05:48 +0200 Subject: [PATCH 029/112] Improve performance of the Tag class in a few cases --- lib/src/tags/tag-type.cpp | 10 ++++- lib/src/tags/tag.cpp | 79 ++++++++++++++++++++------------------- 2 files changed, 49 insertions(+), 40 deletions(-) diff --git a/lib/src/tags/tag-type.cpp b/lib/src/tags/tag-type.cpp index 6a3856af5..17c39f41a 100644 --- a/lib/src/tags/tag-type.cpp +++ b/lib/src/tags/tag-type.cpp @@ -7,7 +7,15 @@ TagType::TagType() {} TagType::TagType(const QString &name) : m_isUnknown(name.isEmpty() || name == "unknown"), m_name(name.isEmpty() ? "unknown" : name) -{} +{ + // Sometimes a type is found with multiple words, only the first is relevant + if (!m_isUnknown) + { + const int typeSpace = m_name.indexOf(' '); + if (typeSpace != -1) + { m_name = m_name.left(typeSpace); } + } +} bool TagType::isUnknown() const { diff --git a/lib/src/tags/tag.cpp b/lib/src/tags/tag.cpp index e1ab4da97..5a2fe0648 100644 --- a/lib/src/tags/tag.cpp +++ b/lib/src/tags/tag.cpp @@ -5,14 +5,6 @@ #include "tag-type.h" -QMap stringListToMap(const QStringList &list) -{ - QMap ret; - for (int i = 0; i < list.count(); ++i) - ret.insert(i, list[i]); - return ret; -} - Tag::Tag() : m_id(0), m_type(TagType()), m_count(0) { } @@ -28,42 +20,42 @@ Tag::Tag(const QString &text, const TagType &type, int count, const QStringList Tag::Tag(int id, const QString &text, TagType type, int count, QStringList related) : m_id(id), m_type(std::move(type)), m_count(count), m_related(std::move(related)) { - static QStringList weakTypes = QStringList() << QStringLiteral("unknown") << QStringLiteral("origin"); + static QStringList weakTypes = QStringList() << QStringLiteral("origin"); // Decode HTML entities in the tag text m_text = decodeHtmlEntities(text).replace(' ', '_'); - // Sometimes a type is found with multiple words, only the first is relevant - const int typeSpace = m_type.name().indexOf(' '); - if (typeSpace != -1) - { m_type = TagType(m_type.name().left(typeSpace)); } - - // Some artist names end with " (artist)" so we can guess their type - if (m_text.endsWith(QLatin1String("(artist)")) && weakTypes.contains(m_type.name())) + if (m_type.isUnknown() || weakTypes.contains(m_type.name())) { - m_type = TagType(QStringLiteral("artist")); - m_text = m_text.left(m_text.length() - 9); - } + // Some artist names end with " (artist)" so we can guess their type + if (m_text.endsWith(QLatin1String("(artist)"))) + { + m_type = TagType(QStringLiteral("artist")); + m_text = m_text.left(m_text.length() - 9); + } - const int sepPos = m_text.indexOf(':'); - if (sepPos != -1 && weakTypes.contains(m_type.name())) - { - static QStringList prep = QStringList() - << QStringLiteral("artist") - << QStringLiteral("copyright") - << QStringLiteral("character") - << QStringLiteral("model") - << QStringLiteral("species") - << QStringLiteral("meta") - << QStringLiteral("unknown") - << QStringLiteral("oc"); - - const QString pre = Tag::GetType(m_text.left(sepPos)); - const int prepIndex = prep.indexOf(pre); - if (prepIndex != -1) + const int sepPos = m_text.indexOf(':'); + if (sepPos != -1) { - m_type = TagType(Tag::GetType(prep[prepIndex], stringListToMap(prep))); - m_text = m_text.mid(sepPos + 1); + static QMap prep = + { + { 0, QStringLiteral("artist") }, + { 1, QStringLiteral("copyright") }, + { 2, QStringLiteral("character") }, + { 3, QStringLiteral("model") }, + { 4, QStringLiteral("species") }, + { 5, QStringLiteral("meta") }, + { 6, QStringLiteral("unknown") }, + { 7, QStringLiteral("oc") } + }; + + const QString pre = Tag::GetType(m_text.left(sepPos)); + const int prepIndex = prep.key(pre, -1); + if (prepIndex != -1) + { + m_type = TagType(Tag::GetType(prep[prepIndex], prep)); + m_text = m_text.mid(sepPos + 1); + } } } } @@ -83,8 +75,17 @@ Tag Tag::FromCapture(const QRegularExpressionMatch &match, const QStringList &gr QString type; if (data.contains("type")) { - static QStringList types = QStringList() << "general" << "artist" << "unknown" << "copyright" << "character" << "species" << "meta"; - type = Tag::GetType(data.value("type").trimmed(), stringListToMap(types)); + static QMap types = + { + { 0, "general" }, + { 1, "artist" }, + { 2, "unknown" }, + { 3, "copyright" }, + { 4, "character" }, + { 5, "species" }, + { 6, "generalmeta" }, + }; + type = Tag::GetType(data.value("type").trimmed(), types); } // Count From 2cd06cf9404f697db86935ec2f0a2e7a033736fa Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 9 Jul 2018 22:33:17 +0200 Subject: [PATCH 030/112] Improve performance of Image::setRating --- lib/src/models/image.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 6611634e7..157fd7aca 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -1049,15 +1049,17 @@ void Image::unload() void Image::setRating(const QString &rating) { - QMap assoc; - assoc["s"] = "safe"; - assoc["q"] = "questionable"; - assoc["e"] = "explicit"; + static QMap assoc = + { + { "s", "safe" }, + { "q", "questionable" }, + { "e", "explicit" } + }; + + m_rating = assoc.contains(rating) + ? assoc[rating] + : rating.toLower(); - if (assoc.contains(rating)) - { m_rating = assoc.value(rating); } - else - { m_rating = rating.toLower(); } refreshTokens(); } From ae0716345782dfa06e519d78d0225d1bc1a886f5 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 10 Jul 2018 00:06:42 +0200 Subject: [PATCH 031/112] Optimize TagStylist::stylished method --- lib/src/tags/tag-stylist.cpp | 31 +++++++++++++++++------------ lib/src/tags/tag-stylist.h | 2 +- tests/src/tags/tag-stylist-test.cpp | 12 +++++------ 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/lib/src/tags/tag-stylist.cpp b/lib/src/tags/tag-stylist.cpp index 3f95918c0..93589a741 100644 --- a/lib/src/tags/tag-stylist.cpp +++ b/lib/src/tags/tag-stylist.cpp @@ -20,21 +20,31 @@ QStringList TagStylist::stylished(QList tags, bool count, bool noUnderscore else if (sort == QLatin1String("count")) std::sort(tags.begin(), tags.end(), sortTagsByCount); + // Generate style map + static const QStringList tlist = QStringList() << "artists" << "circles" << "copyrights" << "characters" << "species" << "metas" << "models" << "generals" << "favorites" << "keptForLater" << "blacklisteds" << "ignoreds" << "favorites"; + static const QStringList defaults = QStringList() << "#aa0000" << "#55bbff" << "#aa00aa" << "#00aa00" << "#ee6600" << "#ee6600" << "#0000ee" << "#000000" << "#ffc0cb" << "#000000" << "#000000" << "#999999" << "#ffcccc"; + QMap styles; + for (const QString &key : tlist) + { + QFont font; + font.fromString(m_profile->getSettings()->value("Coloring/Fonts/" + key).toString()); + const QString color = m_profile->getSettings()->value("Coloring/Colors/" + key, defaults.at(tlist.indexOf(key))).toString(); + styles.insert(key, "color:" + color + "; " + qFontToCss(font)); + } + QStringList t; t.reserve(tags.count()); for (const Tag &tag : tags) - t.append(stylished(tag, count, noUnderscores)); + t.append(stylished(tag, styles, count, noUnderscores)); return t; } -QString TagStylist::stylished(const Tag &tag, bool count, bool noUnderscores) const +QString TagStylist::stylished(const Tag &tag, const QMap &styles, bool count, bool noUnderscores) const { - static const QStringList tlist = QStringList() << "artists" << "circles" << "copyrights" << "characters" << "species" << "metas" << "models" << "generals" << "favorites" << "keptForLater" << "blacklisteds" << "ignoreds" << "favorites"; - static const QStringList defaults = QStringList() << "#aa0000" << "#55bbff" << "#aa00aa" << "#00aa00" << "#ee6600" << "#ee6600" << "#0000ee" << "#000000" << "#ffc0cb" << "#000000" << "#000000" << "#999999" << "#ffcccc"; - // Guess the correct tag family - QString key = tlist.contains(tag.type().name()+"s") ? tag.type().name() + "s" : "generals"; + const QString plural = tag.type().name() + "s"; + QString key = styles.contains(plural) ? plural : "generals"; if (m_profile->getBlacklist().contains(QStringList() << tag.text())) key = "blacklisteds"; if (m_profile->getIgnored().contains(tag.text(), Qt::CaseInsensitive)) @@ -46,15 +56,10 @@ QString TagStylist::stylished(const Tag &tag, bool count, bool noUnderscores) co if (fav.getName() == tag.text()) key = "favorites"; - QFont font; - font.fromString(m_profile->getSettings()->value("Coloring/Fonts/" + key).toString()); - const QString color = m_profile->getSettings()->value("Coloring/Colors/" + key, defaults.at(tlist.indexOf(key))).toString(); - const QString style = "color:" + color + "; " + qFontToCss(font); - QString txt = tag.text(); - QString ret = "" + (noUnderscores ? txt.replace('_', ' ') : tag.text()) + ""; + QString ret = QString("%3").arg(tag.text(), styles.value(key), noUnderscores ? txt.replace('_', ' ') : tag.text()); if (count && tag.count() > 0) - ret += " (" + QString("%L1").arg(tag.count()) + ")"; + ret += QString(" (%L1)").arg(tag.count()); return ret; } diff --git a/lib/src/tags/tag-stylist.h b/lib/src/tags/tag-stylist.h index 0d222bf44..ba1ec98f9 100644 --- a/lib/src/tags/tag-stylist.h +++ b/lib/src/tags/tag-stylist.h @@ -14,7 +14,7 @@ class TagStylist public: explicit TagStylist(Profile *profile); QStringList stylished(QList tags, bool count = false, bool noUnderscores = false, const QString &sort = "") const; - QString stylished(const Tag &tag, bool count = false, bool noUnderscores = false) const; + QString stylished(const Tag &tag, const QMap &styles, bool count = false, bool noUnderscores = false) const; private: Profile *m_profile; diff --git a/tests/src/tags/tag-stylist-test.cpp b/tests/src/tags/tag-stylist-test.cpp index a55d1bec3..9a26ecf10 100644 --- a/tests/src/tags/tag-stylist-test.cpp +++ b/tests/src/tags/tag-stylist-test.cpp @@ -26,7 +26,7 @@ void TagStylistTest::testBasic() favorites.append(Favorite("tag_other", 50, QDateTime::currentDateTime())); TagStylist stylist(new Profile(m_settings, favorites)); - QString actual = stylist.stylished(tag); + QString actual = stylist.stylished(QList() << tag).join(""); QString expected = "tag_text"; QCOMPARE(actual, expected); } @@ -40,7 +40,7 @@ void TagStylistTest::testIgnored() pro.addIgnored("tag_text"); TagStylist stylist(&pro); - QString actual = stylist.stylished(tag); + QString actual = stylist.stylished(QList() << tag).join(""); QString expected = "tag_text"; QCOMPARE(actual, expected); } @@ -54,7 +54,7 @@ void TagStylistTest::testBlacklisted() pro.addBlacklistedTag("tag_text"); TagStylist stylist(&pro); - QString actual = stylist.stylished(tag); + QString actual = stylist.stylished(QList() << tag).join(""); QString expected = "tag_text"; QCOMPARE(actual, expected); } @@ -68,7 +68,7 @@ void TagStylistTest::testFavorite() favorites.append(Favorite("tag_text", 50, QDateTime::currentDateTime())); TagStylist stylist(new Profile(m_settings, favorites)); - QString actual = stylist.stylished(tag); + QString actual = stylist.stylished(QList() << tag).join(""); QString expected = "tag_text"; QCOMPARE(actual, expected); } @@ -83,7 +83,7 @@ void TagStylistTest::testKeptForLater() QStringList keptForLater = QStringList() << "tag_text"; TagStylist stylist(new Profile(m_settings, QList(), keptForLater)); - QString actual = stylist.stylished(tag); + QString actual = stylist.stylished(QList() << tag).join(""); QString expected = "tag_text"; QCOMPARE(actual, expected); } @@ -96,7 +96,7 @@ void TagStylistTest::testWithCount() Tag tag("tag_text", "artist", 123, QStringList() << "related1" << "related2" << "related3"); TagStylist stylist(new Profile(m_settings, QList())); - QString actual = stylist.stylished(tag, true); + QString actual = stylist.stylished(QList() << tag, true).join(""); QString expected = "tag_text (123)"; QCOMPARE(actual, expected); } From ac7046fae836e314ccda6173384adf33f53ed4fc Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 10 Jul 2018 01:20:02 +0200 Subject: [PATCH 032/112] Compile blacklist and post-filtering to prevent re-parsing --- e2e/src/main.cpp | 2 +- gui/src/mainwindow.cpp | 4 +- gui/src/settings/optionswindow.cpp | 9 +- gui/src/tabs/search-tab.cpp | 16 +- gui/src/tag-context-menu.cpp | 2 +- .../utils/blacklist-fix/blacklist-fix-1.cpp | 9 +- .../utils/blacklist-fix/blacklist-fix-2.cpp | 6 +- gui/src/utils/blacklist-fix/blacklist-fix-2.h | 6 +- gui/src/viewer/zoom-window.cpp | 6 +- lib/src/downloader/downloader.cpp | 8 +- lib/src/downloader/downloader.h | 5 +- lib/src/loader/loader-query.cpp | 7 +- lib/src/models/filename.cpp | 2 +- lib/src/models/filtering/blacklist.cpp | 102 +++++++ lib/src/models/filtering/blacklist.h | 32 +++ lib/src/models/filtering/filter-factory.cpp | 42 +++ lib/src/models/filtering/filter-factory.h | 15 + lib/src/models/filtering/filter.cpp | 6 + lib/src/models/filtering/filter.h | 20 ++ lib/src/models/filtering/meta-filter.cpp | 145 ++++++++++ lib/src/models/filtering/meta-filter.h | 19 ++ .../models/{ => filtering}/post-filter.cpp | 19 +- lib/src/models/{ => filtering}/post-filter.h | 1 - lib/src/models/filtering/tag-filter.cpp | 41 +++ lib/src/models/filtering/tag-filter.h | 18 ++ lib/src/models/filtering/token-filter.cpp | 28 ++ lib/src/models/filtering/token-filter.h | 18 ++ lib/src/models/image.cpp | 4 +- lib/src/models/page-api.cpp | 2 +- lib/src/models/profile.cpp | 17 +- lib/src/models/profile.h | 7 +- lib/src/tags/tag-stylist.cpp | 2 +- .../integration/integration-test-suite.cpp | 4 +- tests/src/models/filtering/blacklist-test.cpp | 47 +++ tests/src/models/filtering/blacklist-test.h | 17 ++ .../src/models/filtering/meta-filter-test.cpp | 126 ++++++++ tests/src/models/filtering/meta-filter-test.h | 22 ++ .../src/models/filtering/post-filter-test.cpp | 109 +++++++ .../models/{ => filtering}/post-filter-test.h | 9 - .../src/models/filtering/tag-filter-test.cpp | 28 ++ tests/src/models/filtering/tag-filter-test.h | 16 ++ .../models/filtering/token-filter-test.cpp | 65 +++++ .../src/models/filtering/token-filter-test.h | 18 ++ tests/src/models/image-test.cpp | 2 +- tests/src/models/post-filter-test.cpp | 269 ------------------ 45 files changed, 993 insertions(+), 359 deletions(-) create mode 100644 lib/src/models/filtering/blacklist.cpp create mode 100644 lib/src/models/filtering/blacklist.h create mode 100644 lib/src/models/filtering/filter-factory.cpp create mode 100644 lib/src/models/filtering/filter-factory.h create mode 100644 lib/src/models/filtering/filter.cpp create mode 100644 lib/src/models/filtering/filter.h create mode 100644 lib/src/models/filtering/meta-filter.cpp create mode 100644 lib/src/models/filtering/meta-filter.h rename lib/src/models/{ => filtering}/post-filter.cpp (92%) rename lib/src/models/{ => filtering}/post-filter.h (71%) create mode 100644 lib/src/models/filtering/tag-filter.cpp create mode 100644 lib/src/models/filtering/tag-filter.h create mode 100644 lib/src/models/filtering/token-filter.cpp create mode 100644 lib/src/models/filtering/token-filter.h create mode 100644 tests/src/models/filtering/blacklist-test.cpp create mode 100644 tests/src/models/filtering/blacklist-test.h create mode 100644 tests/src/models/filtering/meta-filter-test.cpp create mode 100644 tests/src/models/filtering/meta-filter-test.h create mode 100644 tests/src/models/filtering/post-filter-test.cpp rename tests/src/models/{ => filtering}/post-filter-test.h (68%) create mode 100644 tests/src/models/filtering/tag-filter-test.cpp create mode 100644 tests/src/models/filtering/tag-filter-test.h create mode 100644 tests/src/models/filtering/token-filter-test.cpp create mode 100644 tests/src/models/filtering/token-filter-test.h delete mode 100644 tests/src/models/post-filter-test.cpp diff --git a/e2e/src/main.cpp b/e2e/src/main.cpp index 137053199..54d7ed69a 100644 --- a/e2e/src/main.cpp +++ b/e2e/src/main.cpp @@ -75,7 +75,7 @@ int main(int argc, char *argv[]) auto allSites = profile->getSites(); const auto oldBlacklist = profile->getBlacklist(); - profile->setBlacklistedTags(QList()); + profile->setBlacklistedTags(Blacklist()); const QJsonObject root = input.object(); const QJsonArray rootSearch = root.value("search").toArray(); diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 6a7b820ac..4c0a849f7 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -36,8 +36,8 @@ #include "models/api/api.h" #include "models/favorite.h" #include "models/filename.h" +#include "models/filtering/post-filter.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/profile.h" #include "monitoring-center.h" #include "settings/optionswindow.h" @@ -1688,7 +1688,7 @@ void mainWindow::getAllGetImageIfNotBlacklisted(const BatchDownloadImage &downlo } // Check if image is blacklisted - const QStringList &detected = PostFilter::blacklisted(download.image->tokens(m_profile), m_profile->getBlacklist()); + const QStringList &detected = m_profile->getBlacklist().match(download.image->tokens(m_profile)); if (!detected.isEmpty()) { m_getAllIgnored++; diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index 7ecfa530b..50d66b58c 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -99,10 +99,7 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) settings->endGroup(); // Blacklist - QString blacklist; - for (const QStringList &tags : profile->getBlacklist()) - { blacklist += (blacklist.isEmpty() ? QString() : "\n") + tags.join(' '); } - ui->textBlacklist->setPlainText(blacklist); + ui->textBlacklist->setPlainText(profile->getBlacklist().toString()); ui->checkDownloadBlacklisted->setChecked(settings->value("downloadblacklist", false).toBool()); // Monitoring @@ -873,9 +870,9 @@ void optionsWindow::save() settings->endGroup(); // Blacklist - QList blacklist; + Blacklist blacklist; for (const QString &tags : ui->textBlacklist->toPlainText().split("\n", QString::SkipEmptyParts)) - { blacklist.append(tags.trimmed().split(' ', QString::SkipEmptyParts)); } + { blacklist.add(tags.trimmed().split(' ', QString::SkipEmptyParts)); } m_profile->setBlacklistedTags(blacklist); settings->setValue("downloadblacklist", ui->checkDownloadBlacklisted->isChecked()); diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index abd0cffe4..d5cbe6164 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -15,8 +15,8 @@ #include "models/api/api.h" #include "models/favorite.h" #include "models/filename.h" +#include "models/filtering/post-filter.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/profile.h" #include "models/site.h" #include "sources/sourceswindow.h" @@ -563,11 +563,11 @@ void searchTab::finishedLoadingPreview() img->setPreviewImage(preview); // Download whitelist images on thumbnail view - QList whitelistedTags; - for (const QString &tag : m_settings->value("whitelistedtags").toString().split(" ")) - { whitelistedTags.append(QStringList() << tag); } - QStringList detected = PostFilter::blacklisted(img->tokens(m_profile), m_profile->getBlacklist()); - QStringList whitelisted = PostFilter::blacklisted(img->tokens(m_profile), whitelistedTags); + Blacklist whitelistedTags; + for (const QString &tag : m_settings->value("whitelistedtags").toString().split(" ", QString::SkipEmptyParts)) + { whitelistedTags.add(tag); } + QStringList detected = m_profile->getBlacklist().match(img->tokens(m_profile)); + QStringList whitelisted = whitelistedTags.match(img->tokens(m_profile)); if (!whitelisted.isEmpty() && m_settings->value("whitelist_download", "image").toString() == "page") { bool download = false; @@ -1150,7 +1150,7 @@ void searchTab::webZoom(int id) const QSharedPointer &image = m_images.at(id); - QStringList detected = PostFilter::blacklisted(image->tokens(m_profile), m_profile->getBlacklist()); + QStringList detected = m_profile->getBlacklist().match(image->tokens(m_profile)); if (!detected.isEmpty()) { const int reply = QMessageBox::question(parentWidget(), tr("Blacklist"), tr("%n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway?", "", detected.size()).arg(detected.join(", ")), QMessageBox::Yes | QMessageBox::No); @@ -1433,7 +1433,7 @@ FixedSizeGridLayout *searchTab::createImagesLayout(QSettings *settings) bool searchTab::validateImage(const QSharedPointer &img, QString &error) { - QStringList detected = PostFilter::blacklisted(img->tokens(m_profile), m_profile->getBlacklist()); + QStringList detected = m_profile->getBlacklist().match(img->tokens(m_profile)); if (!detected.isEmpty() && m_settings->value("hideblacklisted", false).toBool()) { error = QStringLiteral("Image #%1 ignored. Reason: %2.").arg(img->id()).arg("\""+detected.join(", ")+"\""); diff --git a/gui/src/tag-context-menu.cpp b/gui/src/tag-context-menu.cpp index 5f2ee17df..072e708c3 100644 --- a/gui/src/tag-context-menu.cpp +++ b/gui/src/tag-context-menu.cpp @@ -27,7 +27,7 @@ TagContextMenu::TagContextMenu(const QString &tag, const QList &allTags, co { addAction(QIcon(":/images/icons/add.png"), tr("Keep for later"), this, SLOT(viewitlater())); } // Blacklist - if (profile->getBlacklist().contains(QStringList() << m_tag)) + if (profile->getBlacklist().contains(m_tag)) { addAction(QIcon(":/images/icons/eye-plus.png"), tr("Don't blacklist"), this, SLOT(unblacklist())); } else { addAction(QIcon(":/images/icons/eye-minus.png"), tr("Blacklist"), this, SLOT(blacklist())); } diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-1.cpp b/gui/src/utils/blacklist-fix/blacklist-fix-1.cpp index 455b72163..ac9cabebf 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-1.cpp +++ b/gui/src/utils/blacklist-fix/blacklist-fix-1.cpp @@ -23,10 +23,7 @@ BlacklistFix1::BlacklistFix1(Profile *profile, QWidget *parent) ui->comboSource->addItems(m_sites.keys()); ui->progressBar->hide(); - QString blacklist; - for (const QStringList &tags : profile->getBlacklist()) - { blacklist += (blacklist.isEmpty() ? QString() : "\n") + tags.join(' '); } - ui->textBlacklist->setPlainText(blacklist); + ui->textBlacklist->setPlainText(profile->getBlacklist().toString()); resize(size().width(), 0); } @@ -150,9 +147,9 @@ void BlacklistFix1::getAll(Page *p) } else { - QList blacklist; + Blacklist blacklist; for (const QString &tags : ui->textBlacklist->toPlainText().split("\n", QString::SkipEmptyParts)) - { blacklist.append(tags.trimmed().split(' ', QString::SkipEmptyParts)); } + { blacklist.add(tags.trimmed().split(' ', QString::SkipEmptyParts)); } BlacklistFix2 *bf2 = new BlacklistFix2(m_getAll.values(), blacklist); close(); diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp index 611ba38fa..dff8a7185 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp +++ b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp @@ -2,10 +2,10 @@ #include #include #include "loader/token.h" -#include "models/post-filter.h" +#include "models/filtering/post-filter.h" -BlacklistFix2::BlacklistFix2(QList> details, QList blacklist, QWidget *parent) +BlacklistFix2::BlacklistFix2(QList> details, Blacklist blacklist, QWidget *parent) : QDialog(parent), ui(new Ui::BlacklistFix2), m_details(std::move(details)), m_blacklist(std::move(blacklist)) { ui->setupUi(this); @@ -20,7 +20,7 @@ BlacklistFix2::BlacklistFix2(QList> details, QList tokens; tokens.insert("allos", Token(tags)); - found = PostFilter::blacklisted(tokens, m_blacklist); + found = m_blacklist.match(tokens); color = found.empty() ? "green" : "red"; } QTableWidgetItem *id = new QTableWidgetItem(QString::number(i+1)); diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-2.h b/gui/src/utils/blacklist-fix/blacklist-fix-2.h index d067046ea..90e37f17d 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-2.h +++ b/gui/src/utils/blacklist-fix/blacklist-fix-2.h @@ -3,7 +3,7 @@ #include #include - +#include "models/filtering/blacklist.h" namespace Ui @@ -18,7 +18,7 @@ class BlacklistFix2 : public QDialog Q_OBJECT public: - explicit BlacklistFix2(QList> details, QList blacklist, QWidget *parent = Q_NULLPTR); + explicit BlacklistFix2(QList> details, Blacklist blacklist, QWidget *parent = Q_NULLPTR); ~BlacklistFix2() override; private slots: @@ -30,7 +30,7 @@ class BlacklistFix2 : public QDialog Ui::BlacklistFix2 *ui; QList> m_details; QList m_previews; - QList m_blacklist; + Blacklist m_blacklist; }; #endif // BLACKLIST_FIX_2_H diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 6cf2d10d0..3e3a895de 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -12,8 +12,8 @@ #include "image-context-menu.h" #include "mainwindow.h" #include "models/filename.h" +#include "models/filtering/post-filter.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/profile.h" #include "models/site.h" #include "settings/optionswindow.h" @@ -131,7 +131,7 @@ void ZoomWindow::go() bool whitelisted = false; if (!m_settings->value("whitelistedtags").toString().isEmpty()) { - QStringList whitelist = m_settings->value("whitelistedtags").toString().split(" "); + QStringList whitelist = m_settings->value("whitelistedtags").toString().split(" ", QString::SkipEmptyParts); for (const Tag &t : m_image->tags()) { if (whitelist.contains(t.text())) @@ -1197,7 +1197,7 @@ int ZoomWindow::firstNonBlacklisted(int direction) index = (index + m_images.count() + direction) % m_images.count(); // Skip blacklisted images - while (!PostFilter::blacklisted(m_images[index]->tokens(m_profile), m_profile->getBlacklist()).isEmpty() && index != first) + while (!m_profile->getBlacklist().match(m_images[index]->tokens(m_profile)).isEmpty() && index != first) { index = (index + m_images.count() + direction) % m_images.count(); } diff --git a/lib/src/downloader/downloader.cpp b/lib/src/downloader/downloader.cpp index 72035a4e9..78dc5d180 100644 --- a/lib/src/downloader/downloader.cpp +++ b/lib/src/downloader/downloader.cpp @@ -6,8 +6,8 @@ #include "downloader/image-downloader.h" #include "functions.h" #include "logger.h" +#include "models/filtering/post-filter.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/site.h" @@ -31,7 +31,7 @@ void Downloader::clear() m_oPagesT.clear(); } -Downloader::Downloader(Profile *profile, QStringList tags, QStringList postFiltering, QList sources, int page, int max, int perPage, QString location, QString filename, QString user, QString password, bool blacklist, QList blacklistedTags, bool noDuplicates, int tagsMin, QString tagsFormat, Downloader *previous) +Downloader::Downloader(Profile *profile, QStringList tags, QStringList postFiltering, QList sources, int page, int max, int perPage, QString location, QString filename, QString user, QString password, bool blacklist, Blacklist blacklistedTags, bool noDuplicates, int tagsMin, QString tagsFormat, Downloader *previous) : m_profile(profile), m_lastPage(Q_NULLPTR), m_tags(std::move(tags)), m_postFiltering(std::move(postFiltering)), m_sites(std::move(sources)), m_page(page), m_max(max), m_perPage(perPage), m_waiting(0), m_ignored(0), m_duplicates(0), m_tagsMin(tagsMin), m_location(std::move(location)), m_filename(std::move(filename)), m_user(std::move(user)), m_password(std::move(password)), m_blacklist(blacklist), m_noDuplicates(noDuplicates), m_tagsFormat(std::move(tagsFormat)), m_blacklistedTags(std::move(blacklistedTags)), m_cancelled(false), m_quit(false), m_previous(previous) { } @@ -319,7 +319,7 @@ void Downloader::finishedLoadingImages(Page *page) // Blacklisted tags if (!m_blacklist) { - if (!PostFilter::blacklisted(img->tokens(m_profile), m_blacklistedTags).empty()) + if (!m_blacklistedTags.match(img->tokens(m_profile)).empty()) { ++m_ignored; continue; @@ -433,7 +433,7 @@ void Downloader::finishedLoadingUrls(Page *page) // Blacklisted tags if (!m_blacklist) { - if (!PostFilter::blacklisted(img->tokens(m_profile), m_blacklistedTags).empty()) + if (!m_blacklistedTags.match(img->tokens(m_profile)).empty()) { ++m_ignored; continue; diff --git a/lib/src/downloader/downloader.h b/lib/src/downloader/downloader.h index bb84fc93c..80c0d4a1a 100644 --- a/lib/src/downloader/downloader.h +++ b/lib/src/downloader/downloader.h @@ -2,6 +2,7 @@ #define DOWNLOADER_H #include +#include "models/filtering/blacklist.h" #include "models/image.h" @@ -14,7 +15,7 @@ class Downloader : public QObject public: Downloader() = default; ~Downloader() override; - Downloader(Profile *profile, QStringList tags, QStringList postFiltering, QList sources, int page, int max, int perPage, QString location, QString filename, QString user, QString password, bool blacklist, QList blacklistedTags, bool noDuplicates, int tagsMin, QString tagsFormat, Downloader *previous = nullptr); + Downloader(Profile *profile, QStringList tags, QStringList postFiltering, QList sources, int page, int max, int perPage, QString location, QString filename, QString user, QString password, bool blacklist, Blacklist blacklistedTags, bool noDuplicates, int tagsMin, QString tagsFormat, Downloader *previous = nullptr); void setQuit(bool quit); void downloadImages(const QList> &images); void loadNext(); @@ -67,7 +68,7 @@ class Downloader : public QObject QString m_location, m_filename, m_user, m_password; bool m_blacklist, m_noDuplicates; QString m_tagsFormat; - QList m_blacklistedTags; + Blacklist m_blacklistedTags; QList m_pages, m_pagesC, m_pagesT, m_oPages, m_oPagesC, m_oPagesT; QList> m_images; diff --git a/lib/src/loader/loader-query.cpp b/lib/src/loader/loader-query.cpp index afb377475..88e4955cc 100644 --- a/lib/src/loader/loader-query.cpp +++ b/lib/src/loader/loader-query.cpp @@ -2,9 +2,10 @@ #include #include #include "loader/loader-data.h" +#include "models/filtering/blacklist.h" +#include "models/filtering/post-filter.h" #include "models/image.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/site.h" #include "models/source.h" @@ -40,7 +41,7 @@ LoaderData LoaderQuery::next() const QStringList postFiltering = m_options["postFiltering"].toStringList(); const bool getBlacklisted = m_options["getBlacklisted"].toBool(); // const QStringList blacklist = m_options["blacklist"].toStringList(); - const QList blacklist; + const Blacklist blacklist; // Load results QEventLoop loop; @@ -55,7 +56,7 @@ LoaderData LoaderQuery::next() for (const QSharedPointer &img : images) { // Skip blacklisted images - if (!getBlacklisted && !PostFilter::blacklisted(img->tokens(profile), blacklist).empty()) + if (!getBlacklisted && !blacklist.match(img->tokens(profile)).empty()) { ret.ignored.append(img); continue; diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index 9da59434d..0df9a13c6 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -6,10 +6,10 @@ #include #include "functions.h" #include "models/api/api.h" +#include "models/filtering/post-filter.h" #include "models/image.h" #include "models/profile.h" #include "models/site.h" -#include "post-filter.h" Filename::Filename(QString format) diff --git a/lib/src/models/filtering/blacklist.cpp b/lib/src/models/filtering/blacklist.cpp new file mode 100644 index 000000000..4e65def52 --- /dev/null +++ b/lib/src/models/filtering/blacklist.cpp @@ -0,0 +1,102 @@ +#include "blacklist.h" +#include "filter.h" +#include "filter-factory.h" + + +Blacklist::Blacklist(const QStringList &tags) +{ + for (const QString &tag : tags) + add(tag); +} + +Blacklist::~Blacklist() +{ + for (const QList &filters : qAsConst(m_filters)) + qDeleteAll(filters); +} + +int Blacklist::indexOf(const QString &tag) const +{ + for (int i = 0; i < m_filters.count(); ++i) + { + const QList &filters = m_filters[i]; + if (filters.count() == 1 && QString::compare(filters[0]->toString(), tag, Qt::CaseInsensitive) == 0) + return i; + } + return -1; +} + +bool Blacklist::contains(const QString &tag) const +{ + return indexOf(tag) != -1; +} + +void Blacklist::add(const QString &tag) +{ + Filter *filter = FilterFactory::build(tag); + if (filter != Q_NULLPTR) + m_filters.append(QList() << filter); +} + +void Blacklist::add(const QStringList &tags) +{ + QList filters; + for (const QString &tag : tags) + { + Filter *filter = FilterFactory::build(tag); + if (filter != Q_NULLPTR) + filters.append(filter); + } + + if (!filters.isEmpty()) + m_filters.append(filters); +} + +bool Blacklist::remove(const QString &tag) +{ + int index = indexOf(tag); + if (index == -1) + return false; + + qDeleteAll(m_filters[index]); + m_filters.removeAt(index); + return true; +} + +QString Blacklist::toString() const +{ + QString ret; + for (const QList &filters : qAsConst(m_filters)) + { + for (int i = 0; i < filters.count(); ++i) + { + if (i != 0) + { ret.append(' '); } + ret.append(filters[i]->toString()); + } + ret.append("\n"); + } + return ret; +} + +QStringList Blacklist::match(const QMap &tokens, bool invert) const +{ + QStringList detected; + for (const QList &filters : qAsConst(m_filters)) + { + bool allDetected = true; + QStringList res; + for (Filter *filter : filters) + { + if (filter->match(tokens, invert).isEmpty()) + { + allDetected = false; + break; + } + res.append(filter->toString()); + } + if (allDetected) + detected.append(res.join(' ')); + } + return detected; +} diff --git a/lib/src/models/filtering/blacklist.h b/lib/src/models/filtering/blacklist.h new file mode 100644 index 000000000..9c6ab5ded --- /dev/null +++ b/lib/src/models/filtering/blacklist.h @@ -0,0 +1,32 @@ +#ifndef BLACKLIST_H +#define BLACKLIST_H + +#include + + +class Filter; +class Token; + +class Blacklist +{ + public: + Blacklist() = default; + explicit Blacklist(const QStringList &tags); + ~Blacklist(); + + bool contains(const QString &tag) const; + void add(const QString &tag); + void add(const QStringList &tags); + bool remove(const QString &tag); + + QString toString() const; + QStringList match(const QMap &tokens, bool invert = true) const; + + protected: + int indexOf(const QString &tag) const; + + private: + QList> m_filters; +}; + +#endif // BLACKLIST_H diff --git a/lib/src/models/filtering/filter-factory.cpp b/lib/src/models/filtering/filter-factory.cpp new file mode 100644 index 000000000..830f66ffc --- /dev/null +++ b/lib/src/models/filtering/filter-factory.cpp @@ -0,0 +1,42 @@ +#include "filter-factory.h" +#include "meta-filter.h" +#include "tag-filter.h" +#include "token-filter.h" + + +Filter *FilterFactory::build(QString filter) +{ + bool invert = false; + + // Invert the filter by prepending '-' + if (filter.startsWith('-')) + { + filter = filter.right(filter.length() - 1); + invert = true; + } + + // Tokens + if (filter.startsWith('%') && filter.endsWith('%')) + { + const QString token = filter.mid(1, filter.length() - 2); + + return new TokenFilter(token, invert); + } + + // Meta-tags + if (filter.contains(":")) + { + const QString type = filter.section(':', 0, 0).toLower(); + const QString val = filter.section(':', 1).toLower(); + + return new MetaFilter(type, val, invert); + } + + // Tags + if (!filter.isEmpty()) + { + return new TagFilter(filter.trimmed(), invert); + } + + return Q_NULLPTR; +} diff --git a/lib/src/models/filtering/filter-factory.h b/lib/src/models/filtering/filter-factory.h new file mode 100644 index 000000000..79e225f81 --- /dev/null +++ b/lib/src/models/filtering/filter-factory.h @@ -0,0 +1,15 @@ +#ifndef FILTER_FACTORY_H +#define FILTER_FACTORY_H + +#include + + +class Filter; + +class FilterFactory +{ + public: + static Filter *build(QString filter); +}; + +#endif // FILTER_FACTORY_H diff --git a/lib/src/models/filtering/filter.cpp b/lib/src/models/filtering/filter.cpp new file mode 100644 index 000000000..35f206296 --- /dev/null +++ b/lib/src/models/filtering/filter.cpp @@ -0,0 +1,6 @@ +#include "filter.h" + + +Filter::Filter(bool invert) + : m_invert(invert) +{} diff --git a/lib/src/models/filtering/filter.h b/lib/src/models/filtering/filter.h new file mode 100644 index 000000000..6bc544931 --- /dev/null +++ b/lib/src/models/filtering/filter.h @@ -0,0 +1,20 @@ +#ifndef FILTER_H +#define FILTER_H + +#include +#include +#include "loader/token.h" + + +class Filter +{ + public: + explicit Filter(bool invert = false); + virtual QString match(const QMap &tokens, bool invert = false) const = 0; + virtual QString toString() const = 0; + + protected: + bool m_invert; +}; + +#endif // FILTER_H diff --git a/lib/src/models/filtering/meta-filter.cpp b/lib/src/models/filtering/meta-filter.cpp new file mode 100644 index 000000000..53d3a0a27 --- /dev/null +++ b/lib/src/models/filtering/meta-filter.cpp @@ -0,0 +1,145 @@ +#include "meta-filter.h" +#include +#include +#include + + +MetaFilter::MetaFilter(QString type, QString val, bool invert) + : Filter(invert), m_type(std::move(type)), m_val(std::move(val)) +{} + +QString MetaFilter::toString() const +{ + return QString(m_invert ? "-" : "") % m_type % ":" % m_val; +} + +static int toDate(const QString &text) +{ + QDateTime date = QDateTime::fromString(text, "yyyy-MM-dd"); + if (date.isValid()) + { return date.toString("yyyyMMdd").toInt(); } + date = QDateTime::fromString(text, "MM/dd/yyyy"); + if (date.isValid()) + { return date.toString("yyyyMMdd").toInt(); } + return 0; +} + +QString MetaFilter::match(const QMap &tokens, bool invert) const +{ + if (m_invert) + { invert = !invert; } + + // Grabber specials + if (m_type == QStringLiteral("grabber")) + { + const QStringList &vals = tokens[m_type].value().toStringList(); + const bool cond = vals.contains(m_val, Qt::CaseInsensitive); + + if (!cond && !invert) + { return QObject::tr("image is not \"%1\"").arg(m_val); } + if (cond && invert) + { return QObject::tr("image is \"%1\"").arg(m_val); } + + return QString(); + } + + // Meta tokens + if (!tokens.contains(m_type)) + { + QStringList keys = tokens.keys(); + return QObject::tr("unknown type \"%1\" (available types: \"%2\")").arg(m_type, keys.join("\", \"")); + } + + const QVariant &token = tokens[m_type].value(); + if (token.type() == QVariant::Int || token.type() == QVariant::DateTime || token.type() == QVariant::ULongLong) + { + int input = 0; + if (token.type() == QVariant::Int) + { input = token.toInt(); } + else if (token.type() == QVariant::DateTime) + { input = token.toDateTime().toString("yyyyMMdd").toInt(); } + else if (token.type() == QVariant::ULongLong) + { input = token.toULongLong(); } + + bool cond; + if (token.type() == QVariant::DateTime) + { + if (m_val.startsWith("..") || m_val.startsWith("<=")) + { cond = input <= toDate(m_val.right(m_val.size()-2)); } + else if (m_val.endsWith("..")) + { cond = input >= toDate(m_val.left(m_val.size()-2)); } + else if (m_val.startsWith(">=")) + { cond = input >= toDate(m_val.right(m_val.size()-2)); } + else if (m_val.startsWith("<")) + { cond = input < toDate(m_val.right(m_val.size()-1)); } + else if (m_val.startsWith(">")) + { cond = input > toDate(m_val.right(m_val.size()-1)); } + else if (m_val.contains("..")) + { cond = input >= toDate(m_val.left(m_val.indexOf(".."))) && input <= toDate(m_val.right(m_val.size()-m_val.indexOf("..")-2)); } + else + { cond = input == toDate(m_val); } + } + else + { + if (m_val.startsWith("..") || m_val.startsWith("<=")) + { cond = input <= m_val.rightRef(m_val.size()-2).toInt(); } + else if (m_val.endsWith("..")) + { cond = input >= m_val.leftRef(m_val.size()-2).toInt(); } + else if (m_val.startsWith(">=")) + { cond = input >= m_val.rightRef(m_val.size()-2).toInt(); } + else if (m_val.startsWith("<")) + { cond = input < m_val.rightRef(m_val.size()-1).toInt(); } + else if (m_val.startsWith(">")) + { cond = input > m_val.rightRef(m_val.size()-1).toInt(); } + else if (m_val.contains("..")) + { cond = input >= m_val.leftRef(m_val.indexOf("..")).toInt() && input <= m_val.rightRef(m_val.size()-m_val.indexOf("..")-2).toInt(); } + else + { cond = input == m_val.toInt(); } + } + + if (!cond && !invert) + { return QObject::tr("image's %1 does not match").arg(m_type); } + if (cond && invert) + { return QObject::tr("image's %1 match").arg(m_type); } + } + else + { + if (m_type == "rating") + { + QMap assoc; + assoc["s"] = "safe"; + assoc["q"] = "questionable"; + assoc["e"] = "explicit"; + + const QString val = assoc.contains(m_val) ? assoc[m_val] : m_val; + + const bool cond = !val.isEmpty() && token.toString().toLower().startsWith(val.at(0)); + if (!cond && !invert) + { return QObject::tr("image is not \"%1\"").arg(val); } + if (cond && invert) + { return QObject::tr("image is \"%1\"").arg(val); } + } + else if (m_type == "source") + { + QRegExp rx(m_val + "*", Qt::CaseInsensitive, QRegExp::Wildcard); + const bool cond = rx.exactMatch(token.toString()); + if (!cond && !invert) + { return QObject::tr("image's source does not starts with \"%1\"").arg(m_val); } + if (cond && invert) + { return QObject::tr("image's source starts with \"%1\"").arg(m_val); } + } + else + { + const QString input = token.toString(); + + const bool cond = input == m_val; + + if (!cond && !invert) + { return QObject::tr("image's %1 does not match").arg(m_type); } + if (cond && invert) + { return QObject::tr("image's %1 match").arg(m_type); } + } + } + + return QString(); +} diff --git a/lib/src/models/filtering/meta-filter.h b/lib/src/models/filtering/meta-filter.h new file mode 100644 index 000000000..2b50bde30 --- /dev/null +++ b/lib/src/models/filtering/meta-filter.h @@ -0,0 +1,19 @@ +#ifndef META_FILTER_H +#define META_FILTER_H + +#include "filter.h" + + +class MetaFilter : public Filter +{ + public: + MetaFilter(QString type, QString val, bool invert = false); + QString match(const QMap &tokens, bool invert = false) const override; + QString toString() const override; + + private: + QString m_type; + QString m_val; +}; + +#endif // META_FILTER_H diff --git a/lib/src/models/post-filter.cpp b/lib/src/models/filtering/post-filter.cpp similarity index 92% rename from lib/src/models/post-filter.cpp rename to lib/src/models/filtering/post-filter.cpp index 9fb16455b..0e436bf1b 100644 --- a/lib/src/models/post-filter.cpp +++ b/lib/src/models/filtering/post-filter.cpp @@ -3,7 +3,7 @@ #include "loader/token.h" -int toDate(const QString &text) +static int toDate(const QString &text) { QDateTime date = QDateTime::fromString(text, "yyyy-MM-dd"); if (date.isValid()) @@ -190,20 +190,3 @@ QStringList PostFilter::filter(const QMap &tokens, const QString } return ret; } - -QStringList PostFilter::blacklisted(const QMap &tokens, const QList &blacklistedTags, bool invert) -{ - QStringList detected; - for (const QStringList &tags : blacklistedTags) - { - bool allDetected = true; - for (const QString &tag : tags) - { - if (match(tokens, tag, invert).isEmpty()) - allDetected = false; - } - if (allDetected) - detected.append(tags.join(' ')); - } - return detected; -} diff --git a/lib/src/models/post-filter.h b/lib/src/models/filtering/post-filter.h similarity index 71% rename from lib/src/models/post-filter.h rename to lib/src/models/filtering/post-filter.h index 516725a70..de44cc9f7 100644 --- a/lib/src/models/post-filter.h +++ b/lib/src/models/filtering/post-filter.h @@ -10,7 +10,6 @@ class PostFilter { public: static QStringList filter(const QMap &tokens, const QStringList &filters); - static QStringList blacklisted(const QMap &tokens, const QList &blacklistedTags, bool invert = true); static QString match(const QMap &tokens, QString filter, bool invert = false); }; diff --git a/lib/src/models/filtering/tag-filter.cpp b/lib/src/models/filtering/tag-filter.cpp new file mode 100644 index 000000000..0b20528c3 --- /dev/null +++ b/lib/src/models/filtering/tag-filter.cpp @@ -0,0 +1,41 @@ +#include "tag-filter.h" +#include +#include +#include "functions.h" + + +TagFilter::TagFilter(QString tag, bool invert) + : Filter(invert), m_tag(std::move(tag)) +{} + +QString TagFilter::toString() const +{ + return QString(m_invert ? "-" : "") % m_tag; +} + +QString TagFilter::match(const QMap &tokens, bool invert) const +{ + if (m_invert) + { invert = !invert; } + + const QStringList &tags = tokens["allos"].value().toStringList(); + + // Check if any tag match the filter (case insensitive plain text with wildcards allowed) + bool cond = false; + for (const QString &tag : tags) + { + QRegExp reg(m_tag, Qt::CaseInsensitive, QRegExp::Wildcard); + if (reg.exactMatch(tag)) + { + cond = true; + break; + } + } + + if (!cond && !invert) + { return QObject::tr("image does not contains \"%1\"").arg(m_tag); } + if (cond && invert) + { return QObject::tr("image contains \"%1\"").arg(m_tag); } + + return QString(); +} diff --git a/lib/src/models/filtering/tag-filter.h b/lib/src/models/filtering/tag-filter.h new file mode 100644 index 000000000..e08598cba --- /dev/null +++ b/lib/src/models/filtering/tag-filter.h @@ -0,0 +1,18 @@ +#ifndef TAG_FILTER_H +#define TAG_FILTER_H + +#include "filter.h" + + +class TagFilter : public Filter +{ + public: + explicit TagFilter(QString tag, bool invert = false); + QString match(const QMap &tokens, bool invert = false) const override; + QString toString() const override; + + private: + QString m_tag; +}; + +#endif // TAG_FILTER_H diff --git a/lib/src/models/filtering/token-filter.cpp b/lib/src/models/filtering/token-filter.cpp new file mode 100644 index 000000000..04ab194a0 --- /dev/null +++ b/lib/src/models/filtering/token-filter.cpp @@ -0,0 +1,28 @@ +#include "token-filter.h" +#include +#include "functions.h" + + +TokenFilter::TokenFilter(QString token, bool invert) + : Filter(invert), m_token(std::move(token)) +{} + +QString TokenFilter::toString() const +{ + return QString(m_invert ? "-" : "") % "%" % m_token % "%"; +} + +QString TokenFilter::match(const QMap &tokens, bool invert) const +{ + if (m_invert) + { invert = !invert; } + + const bool cond = tokens.contains(m_token) && !isVariantEmpty(tokens[m_token].value()); + + if (cond && invert) + { return QObject::tr("image has a \"%1\" token").arg(m_token); } + else if (!cond && !invert) + { return QObject::tr("image does not have a \"%1\" token").arg(m_token); } + + return QString(); +} diff --git a/lib/src/models/filtering/token-filter.h b/lib/src/models/filtering/token-filter.h new file mode 100644 index 000000000..14be6c988 --- /dev/null +++ b/lib/src/models/filtering/token-filter.h @@ -0,0 +1,18 @@ +#ifndef TOKEN_FILTER_H +#define TOKEN_FILTER_H + +#include "filter.h" + + +class TokenFilter : public Filter +{ + public: + explicit TokenFilter(QString token, bool invert = false); + QString match(const QMap &tokens, bool invert = false) const override; + QString toString() const override; + + private: + QString m_token; +}; + +#endif // TOKEN_FILTER_H diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 157fd7aca..de9dcfbf7 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -10,9 +10,9 @@ #include "loader/token.h" #include "models/api/api.h" #include "models/filename.h" +#include "models/filtering/post-filter.h" #include "models/image.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/profile.h" #include "models/site.h" #include "tags/tag-database.h" @@ -910,7 +910,7 @@ void Image::setTags(const QList &tags) QColor Image::color() const { // Blacklisted - QStringList detected = PostFilter::blacklisted(tokens(m_profile), m_profile->getBlacklist()); + QStringList detected = m_profile->getBlacklist().match(tokens(m_profile)); if (!detected.isEmpty()) return QColor(0, 0, 0); diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index bc2c494a0..d38027a71 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -7,8 +7,8 @@ #include "image.h" #include "logger.h" #include "models/api/api.h" +#include "models/filtering/post-filter.h" #include "models/page.h" -#include "models/post-filter.h" #include "models/profile.h" #include "models/site.h" #include "tags/tag.h" diff --git a/lib/src/models/profile.cpp b/lib/src/models/profile.cpp index 4181bad05..0bf5cea09 100644 --- a/lib/src/models/profile.cpp +++ b/lib/src/models/profile.cpp @@ -137,13 +137,13 @@ Profile::Profile(QString path) // Blacklisted tags const QStringList &blacklist = m_settings->value("blacklistedtags").toString().split(' ', QString::SkipEmptyParts); for (const QString &bl : blacklist) - { m_blacklistedTags.append(QStringList() << bl); } + { m_blacklist.add(bl); } QFile fileBlacklist(m_path + "/blacklist.txt"); if (fileBlacklist.open(QFile::ReadOnly | QFile::Text)) { QString line; while (!(line = fileBlacklist.readLine()).isEmpty()) - m_blacklistedTags.append(line.trimmed().split(" ", QString::SkipEmptyParts)); + m_blacklist.add(line.trimmed().split(" ", QString::SkipEmptyParts)); fileBlacklist.close(); } @@ -200,8 +200,7 @@ void Profile::sync() QFile fileBlacklist(m_path + "/blacklist.txt"); if (fileBlacklist.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) { - for (const QStringList &bl : qAsConst(m_blacklistedTags)) - { fileBlacklist.write((bl.join(' ') + "\n").toUtf8()); } + fileBlacklist.write(m_blacklist.toString().toUtf8()); fileBlacklist.close(); } m_settings->remove("blacklistedtags"); @@ -410,21 +409,21 @@ void Profile::removeSite(Site *site) } -void Profile::setBlacklistedTags(const QList &tags) +void Profile::setBlacklistedTags(const Blacklist &blacklist) { - m_blacklistedTags = tags; + m_blacklist = blacklist; emit blacklistChanged(); } void Profile::addBlacklistedTag(const QString &tag) { - m_blacklistedTags.append(QStringList() << tag); + m_blacklist.add(tag); emit blacklistChanged(); } void Profile::removeBlacklistedTag(const QString &tag) { - m_blacklistedTags.removeAll(QStringList() << tag); + m_blacklist.remove(tag); emit blacklistChanged(); } @@ -437,7 +436,7 @@ QStringList &Profile::getIgnored() { return m_ignored; } Commands &Profile::getCommands() { return *m_commands; } QStringList &Profile::getAutoComplete() { return m_autoComplete; } QStringList &Profile::getCustomAutoComplete() { return m_customAutoComplete; } -QList &Profile::getBlacklist() { return m_blacklistedTags; } +Blacklist &Profile::getBlacklist() { return m_blacklist; } const QMap &Profile::getSources() const { return m_sources; } const QMap &Profile::getSites() const { return m_sites; } diff --git a/lib/src/models/profile.h b/lib/src/models/profile.h index 35ac15ccb..9f26e9bc3 100644 --- a/lib/src/models/profile.h +++ b/lib/src/models/profile.h @@ -4,6 +4,7 @@ #include #include #include "models/favorite.h" +#include "models/filtering/blacklist.h" class Commands; @@ -52,7 +53,7 @@ class Profile : public QObject void removeSite(Site *site); // Blacklist management - void setBlacklistedTags(const QList &tags); + void setBlacklistedTags(const Blacklist &blacklist); void addBlacklistedTag(const QString &tag); void removeBlacklistedTag(const QString &tag); @@ -65,7 +66,7 @@ class Profile : public QObject Commands &getCommands(); QStringList &getAutoComplete(); QStringList &getCustomAutoComplete(); - QList &getBlacklist(); + Blacklist &getBlacklist(); const QMap &getSources() const; const QMap &getSites() const; QList getFilteredSites(const QStringList &urls) const; @@ -92,7 +93,7 @@ class Profile : public QObject Commands *m_commands; QStringList m_autoComplete; QStringList m_customAutoComplete; - QList m_blacklistedTags; + Blacklist m_blacklist; QHash m_md5s; QMap m_sources; QMap m_sites; diff --git a/lib/src/tags/tag-stylist.cpp b/lib/src/tags/tag-stylist.cpp index 93589a741..c93d58e8f 100644 --- a/lib/src/tags/tag-stylist.cpp +++ b/lib/src/tags/tag-stylist.cpp @@ -45,7 +45,7 @@ QString TagStylist::stylished(const Tag &tag, const QMap &styl // Guess the correct tag family const QString plural = tag.type().name() + "s"; QString key = styles.contains(plural) ? plural : "generals"; - if (m_profile->getBlacklist().contains(QStringList() << tag.text())) + if (m_profile->getBlacklist().contains(tag.text())) key = "blacklisteds"; if (m_profile->getIgnored().contains(tag.text(), Qt::CaseInsensitive)) key = "ignoreds"; diff --git a/tests/src/integration/integration-test-suite.cpp b/tests/src/integration/integration-test-suite.cpp index 9bb06c5ae..e818cffb0 100755 --- a/tests/src/integration/integration-test-suite.cpp +++ b/tests/src/integration/integration-test-suite.cpp @@ -59,7 +59,7 @@ QList IntegrationTestSuite::getImages(const QString &site, const QString "", "", false, - QList(), + Blacklist(), false, 0, "%tag %count %type"); @@ -128,7 +128,7 @@ QList IntegrationTestSuite::getPageTags(const QString &site, const QString "", "", false, - QList(), + Blacklist(), false, 0, "%tag %count %type"); diff --git a/tests/src/models/filtering/blacklist-test.cpp b/tests/src/models/filtering/blacklist-test.cpp new file mode 100644 index 000000000..7edf3d787 --- /dev/null +++ b/tests/src/models/filtering/blacklist-test.cpp @@ -0,0 +1,47 @@ +#include "blacklist-test.h" +#include +#include "loader/token.h" +#include "models/filtering/blacklist.h" + + +void BlacklistTest::testContains() +{ + Blacklist blacklist(QStringList() << "tag1" << "tag2"); + + QCOMPARE(blacklist.contains("tag1"), true); + QCOMPARE(blacklist.contains("tag2"), true); + QCOMPARE(blacklist.contains("not_found"), false); +} + +void BlacklistTest::testRemove() +{ + Blacklist blacklist(QStringList() << "tag1" << "tag2"); + + // Remove should only work once + QCOMPARE(blacklist.remove("tag2"), true); + QCOMPARE(blacklist.remove("tag2"), false); + + // The list should not contain "tag2" anymore + QCOMPARE(blacklist.contains("tag1"), true); + QCOMPARE(blacklist.contains("tag2"), false); + QCOMPARE(blacklist.contains("not_found"), false); +} + +void BlacklistTest::testMatch() +{ + QMap tokens; + tokens.insert("allos", Token(QStringList() << "tag1" << "tag2" << "tag3" << "artist1" << "copyright1" << "copyright2" << "character1" << "character2" << "model1")); + + // Basic + QCOMPARE(Blacklist(QStringList() << "tag8" << "tag7").match(tokens), QStringList()); + QCOMPARE(Blacklist(QStringList() << "tag1" << "tag7").match(tokens), QStringList() << "tag1"); + QCOMPARE(Blacklist(QStringList() << "character1" << "artist1").match(tokens), QStringList() << "character1" << "artist1"); + + // Invert + QCOMPARE(Blacklist(QStringList() << "tag8" << "tag7").match(tokens, false), QStringList() << "tag8" << "tag7"); + QCOMPARE(Blacklist(QStringList() << "tag1" << "tag7").match(tokens, false), QStringList() << "tag7"); + QCOMPARE(Blacklist(QStringList() << "character1" << "artist1").match(tokens, false), QStringList()); +} + + +static BlacklistTest instance; diff --git a/tests/src/models/filtering/blacklist-test.h b/tests/src/models/filtering/blacklist-test.h new file mode 100644 index 000000000..78e5ad4dc --- /dev/null +++ b/tests/src/models/filtering/blacklist-test.h @@ -0,0 +1,17 @@ +#ifndef BLACKLIST_TEST_H +#define BLACKLIST_TEST_H + +#include "test-suite.h" + + +class BlacklistTest : public TestSuite +{ + Q_OBJECT + + private slots: + void testContains(); + void testRemove(); + void testMatch(); +}; + +#endif // BLACKLIST_TEST_H diff --git a/tests/src/models/filtering/meta-filter-test.cpp b/tests/src/models/filtering/meta-filter-test.cpp new file mode 100644 index 000000000..93c2a76df --- /dev/null +++ b/tests/src/models/filtering/meta-filter-test.cpp @@ -0,0 +1,126 @@ +#include "meta-filter-test.h" +#include +#include "models/filtering/meta-filter.h" +#include "loader/token.h" + + +void MetaFilterTest::testToString() +{ + QCOMPARE(MetaFilter("meta", "val").toString(), QString("meta:val")); + QCOMPARE(MetaFilter("meta", "val", true).toString(), QString("-meta:val")); +} + +void MetaFilterTest::testMatchInvalidToken() +{ + QMap tokens; + tokens.insert("token_1", Token(1)); + tokens.insert("token_2", Token(2)); + + QString expected = "unknown type \"not_found\" (available types: \"token_1\", \"token_2\")"; + + QCOMPARE(MetaFilter("not_found", "val").match(tokens), expected); + QCOMPARE(MetaFilter("not_found", "val", true).match(tokens), expected); +} + +void MetaFilterTest::testMatchGrabber() +{ + QMap tokens; + tokens.insert("grabber", Token(QStringList() << "downloaded")); + + // Basic + QCOMPARE(MetaFilter("grabber", "downloaded").match(tokens), QString()); + QCOMPARE(MetaFilter("grabber", "nok").match(tokens), QString("image is not \"nok\"")); + + // Invert + QCOMPARE(MetaFilter("grabber", "downloaded", true).match(tokens), QString("image is \"downloaded\"")); + QCOMPARE(MetaFilter("grabber", "nok", true).match(tokens), QString()); +} + +void MetaFilterTest::testMatchMathematical() +{ + QMap tokens; + tokens.insert("id", Token(12345)); + + // Basic + QCOMPARE(MetaFilter("id", ">1000").match(tokens), QString()); + QCOMPARE(MetaFilter("id", "<=1000").match(tokens), QString("image's id does not match")); + QCOMPARE(MetaFilter("id", "1000..").match(tokens), QString()); + QCOMPARE(MetaFilter("id", "..1000").match(tokens), QString("image's id does not match")); + QCOMPARE(MetaFilter("id", "10000..20000").match(tokens), QString()); + QCOMPARE(MetaFilter("id", "10").match(tokens), QString("image's id does not match")); + + // Invert + QCOMPARE(MetaFilter("id", ">1000", true).match(tokens), QString("image's id match")); + QCOMPARE(MetaFilter("id", "<=1000", true).match(tokens), QString()); + QCOMPARE(MetaFilter("id", "1000..", true).match(tokens), QString("image's id match")); + QCOMPARE(MetaFilter("id", "..1000", true).match(tokens), QString()); + QCOMPARE(MetaFilter("id", "10000..20000", true).match(tokens), QString("image's id match")); + QCOMPARE(MetaFilter("id", "10", true).match(tokens), QString()); +} + +void MetaFilterTest::testMatchDate() +{ + QMap tokens; + tokens.insert("date", Token(QDateTime(QDate(2016, 8, 18)))); + + QCOMPARE(MetaFilter("date", ">08/16/2016").match(tokens), QString()); + QCOMPARE(MetaFilter("date", ">=2016-08-16").match(tokens), QString()); + QCOMPARE(MetaFilter("date", "<08/20/2016").match(tokens), QString()); + QCOMPARE(MetaFilter("date", "<=2016-08-20").match(tokens), QString()); + QCOMPARE(MetaFilter("date", "..08/20/2016").match(tokens), QString()); + QCOMPARE(MetaFilter("date", "2016-08-16..").match(tokens), QString()); + QCOMPARE(MetaFilter("date", "08/16/2016..2016-08-20").match(tokens), QString()); + QCOMPARE(MetaFilter("date", "2016-08-18").match(tokens), QString()); + + // Invalid date + QCOMPARE(MetaFilter("date", "someday").match(tokens), QString("image's date does not match")); +} + +void MetaFilterTest::testMatchRating() +{ + QMap tokens; + tokens.insert("rating", Token("safe")); + + // Basic + QCOMPARE(MetaFilter("rating", "s").match(tokens), QString()); + QCOMPARE(MetaFilter("rating", "safe").match(tokens), QString()); + QCOMPARE(MetaFilter("rating", "e").match(tokens), QString("image is not \"explicit\"")); + QCOMPARE(MetaFilter("rating", "explicit").match(tokens), QString("image is not \"explicit\"")); + + // Invert + QCOMPARE(MetaFilter("rating", "s", true).match(tokens), QString("image is \"safe\"")); + QCOMPARE(MetaFilter("rating", "safe", true).match(tokens), QString("image is \"safe\"")); + QCOMPARE(MetaFilter("rating", "e", true).match(tokens), QString()); + QCOMPARE(MetaFilter("rating", "explicit", true).match(tokens), QString()); +} + +void MetaFilterTest::testMatchSource() +{ + QMap tokens; + tokens.insert("source", Token("test.com/some/path")); + + // Basic + QCOMPARE(MetaFilter("source", "test.com").match(tokens), QString()); + QCOMPARE(MetaFilter("source", "nok.com").match(tokens), QString("image's source does not starts with \"nok.com\"")); + + // Invert + QCOMPARE(MetaFilter("source", "test.com", true).match(tokens), QString("image's source starts with \"test.com\"")); + QCOMPARE(MetaFilter("source", "nok.com", true).match(tokens), QString()); +} + +void MetaFilterTest::testMatchString() +{ + QMap tokens; + tokens.insert("meta", Token("val")); + + // Basic + QCOMPARE(MetaFilter("meta", "val").match(tokens), QString()); + QCOMPARE(MetaFilter("meta", "nok").match(tokens), QString("image's meta does not match")); + + // Invert + QCOMPARE(MetaFilter("meta", "val", true).match(tokens), QString("image's meta match")); + QCOMPARE(MetaFilter("meta", "nok", true).match(tokens), QString()); +} + + +static MetaFilterTest instance; diff --git a/tests/src/models/filtering/meta-filter-test.h b/tests/src/models/filtering/meta-filter-test.h new file mode 100644 index 000000000..b0149c23d --- /dev/null +++ b/tests/src/models/filtering/meta-filter-test.h @@ -0,0 +1,22 @@ +#ifndef META_FILTER_TEST_H +#define META_FILTER_TEST_H + +#include "test-suite.h" + + +class MetaFilterTest : public TestSuite +{ + Q_OBJECT + + private slots: + void testToString(); + void testMatchInvalidToken(); + void testMatchGrabber(); + void testMatchMathematical(); + void testMatchDate(); + void testMatchRating(); + void testMatchSource(); + void testMatchString(); +}; + +#endif // META_FILTER_TEST_H diff --git a/tests/src/models/filtering/post-filter-test.cpp b/tests/src/models/filtering/post-filter-test.cpp new file mode 100644 index 000000000..ef1ec1219 --- /dev/null +++ b/tests/src/models/filtering/post-filter-test.cpp @@ -0,0 +1,109 @@ +#include "post-filter-test.h" +#include +#include "models/filtering/post-filter.h" +#include "test-suite.h" + + +void PostFilterTest::init() +{ + // Make tmp dir if not already existing + QDir tmp("tests/resources/"); + if (!tmp.exists("tmp")) + tmp.mkdir("tmp"); + + QFile::remove("tests/resources/md5s.txt"); + + m_details["md5"] = "1bc29b36f623ba82aaf6724fd3b16718"; + m_details["ext"] = "jpg"; + m_details["author"] = "superauthor"; + m_details["status"] = "tested"; + m_details["filename"] = ""; + m_details["folder"] = ""; + m_details["search"] = "testing well"; + m_details["id"] = "7331"; + m_details["score"] = "21"; + m_details["parent_id"] = "1337"; + m_details["file_size"] = "1234567"; + m_details["creator_id"] = "1234"; + m_details["has_children"] = "true"; + m_details["has_note"] = "true"; + m_details["has_comments"] = "true"; + m_details["file_url"] = "http://test.com/img/oldfilename.jpg?123456"; + m_details["sample_url"] = "http://test.com/sample/oldfilename.jpg"; + m_details["preview_url"] = "http://test.com/preview/oldfilename.jpg"; + m_details["page_url"] = ""; + m_details["width"] = "800"; + m_details["height"] = "600"; + m_details["source"] = "http://google.com/toto/toto.jpg"; + m_details["tags_general"] = "tag1 tag2 tag3 "; + m_details["tags_artist"] = "artist1 "; + m_details["tags_copyright"] = "copyright1 copyright2 "; + m_details["tags_character"] = "character1 character2 "; + m_details["tags_model"] = "model1 "; + m_details["created_at"] = "1471513944"; + m_details["rating"] = "safe"; + m_details["file_size"] = "358400"; + m_details["file_size"] = "358400"; + + m_profile = new Profile("tests/resources/"); + m_source = new Source(m_profile, "release/sites/Danbooru (2.0)"); + m_site = new Site("danbooru.donmai.us", m_source); + m_img = new Image(m_site, m_details, m_profile); +} + +void PostFilterTest::cleanup() +{ + m_profile->deleteLater(); + m_source->deleteLater(); + m_site->deleteLater(); + m_img->deleteLater(); +} + + +void PostFilterTest::testFilterNumeric() +{ + auto tokens = m_img->tokens(m_profile); + + QStringList filters; + + // No match + filters = PostFilter::filter(tokens, QStringList() << "id:<=10000" << "width:>100" << "date:<2017-01-01"); + QCOMPARE(filters, QStringList()); + + // All match + filters = PostFilter::filter(tokens, QStringList() << "id:>10000" << "width:<=100" << "date:>=2017-01-01"); + QCOMPARE(filters, QStringList() << "image's id does not match" << "image's width does not match" << "image's date does not match"); +} + +void PostFilterTest::testFilterSpecial() +{ + auto tokens = m_img->tokens(m_profile); + + QStringList filters; + + // No match + filters = PostFilter::filter(tokens, QStringList() << "rating:s" << "rating:safe" << "source:http://google.com"); + QCOMPARE(filters, QStringList()); + + // All match + filters = PostFilter::filter(tokens, QStringList() << "rating:e" << "rating:explicit" << "source:http://test.com"); + QCOMPARE(filters, QStringList() << "image is not \"explicit\"" << "image is not \"explicit\"" << "image's source does not starts with \"http://test.com\""); +} + +void PostFilterTest::testFilterInvert() +{ + auto tokens = m_img->tokens(m_profile); + + QStringList filters; + + // No match + filters = PostFilter::filter(tokens, QStringList() << "-id:>10000" << "-width:<=100" << "-date:>=2017-01-01"); + QCOMPARE(filters, QStringList()); + + // All match + filters = PostFilter::filter(tokens, QStringList() << "-id:<=10000" << "-width:>100" << "-date:<2017-01-01"); + QCOMPARE(filters, QStringList() << "image's id match" << "image's width match" << "image's date match"); +} + + +static PostFilterTest instance; diff --git a/tests/src/models/post-filter-test.h b/tests/src/models/filtering/post-filter-test.h similarity index 68% rename from tests/src/models/post-filter-test.h rename to tests/src/models/filtering/post-filter-test.h index 8d00499a9..df2c5868a 100644 --- a/tests/src/models/post-filter-test.h +++ b/tests/src/models/filtering/post-filter-test.h @@ -15,16 +15,7 @@ class PostFilterTest : public TestSuite void init(); void cleanup(); - void testBlacklisted(); - void testMatchToken(); - void testMatchTag(); - void testMatchUnknown(); - void testMatchMathematical(); - void testMatchDate(); - void testMatchRating(); - void testMatchSource(); void testFilterNumeric(); - void testFilterString(); void testFilterSpecial(); void testFilterInvert(); diff --git a/tests/src/models/filtering/tag-filter-test.cpp b/tests/src/models/filtering/tag-filter-test.cpp new file mode 100644 index 000000000..5f888c318 --- /dev/null +++ b/tests/src/models/filtering/tag-filter-test.cpp @@ -0,0 +1,28 @@ +#include "tag-filter-test.h" +#include +#include "models/filtering/tag-filter.h" +#include "loader/token.h" + + +void TagFilterTest::testToString() +{ + QCOMPARE(TagFilter("test").toString(), QString("test")); + QCOMPARE(TagFilter("test", true).toString(), QString("-test")); +} + +void TagFilterTest::testMatch() +{ + QMap tokens; + tokens.insert("allos", Token(QStringList() << "ok" << "ok2")); + + // Basic + QCOMPARE(TagFilter("ok").match(tokens), QString()); + QCOMPARE(TagFilter("nok").match(tokens), QString("image does not contains \"nok\"")); + + // Invert + QCOMPARE(TagFilter("ok", true).match(tokens), QString("image contains \"ok\"")); + QCOMPARE(TagFilter("nok", true).match(tokens), QString()); +} + + +static TagFilterTest instance; diff --git a/tests/src/models/filtering/tag-filter-test.h b/tests/src/models/filtering/tag-filter-test.h new file mode 100644 index 000000000..bf6d585c1 --- /dev/null +++ b/tests/src/models/filtering/tag-filter-test.h @@ -0,0 +1,16 @@ +#ifndef TAG_FILTER_TEST_H +#define TAG_FILTER_TEST_H + +#include "test-suite.h" + + +class TagFilterTest : public TestSuite +{ + Q_OBJECT + + private slots: + void testToString(); + void testMatch(); +}; + +#endif // TAG_FILTER_TEST_H diff --git a/tests/src/models/filtering/token-filter-test.cpp b/tests/src/models/filtering/token-filter-test.cpp new file mode 100644 index 000000000..332dfd6bd --- /dev/null +++ b/tests/src/models/filtering/token-filter-test.cpp @@ -0,0 +1,65 @@ +#include "token-filter-test.h" +#include +#include "models/filtering/token-filter.h" +#include "loader/token.h" + + +void TokenFilterTest::testToString() +{ + QCOMPARE(TokenFilter("test").toString(), QString("%test%")); + QCOMPARE(TokenFilter("test", true).toString(), QString("-%test%")); +} + +void TokenFilterTest::testMatchInt() +{ + QMap tokens; + tokens.insert("ok", Token(1)); + tokens.insert("nok", Token(QVariant(0))); + + // Basic + QCOMPARE(TokenFilter("ok").match(tokens), QString()); + QCOMPARE(TokenFilter("nok").match(tokens), QString("image does not have a \"nok\" token")); + QCOMPARE(TokenFilter("not_found").match(tokens), QString("image does not have a \"not_found\" token")); + + // Invert + QCOMPARE(TokenFilter("ok", true).match(tokens), QString("image has a \"ok\" token")); + QCOMPARE(TokenFilter("nok", true).match(tokens), QString()); + QCOMPARE(TokenFilter("not_found", true).match(tokens), QString()); +} + +void TokenFilterTest::testMatchString() +{ + QMap tokens; + tokens.insert("ok", Token("ok")); + tokens.insert("nok", Token("")); + + // Basic + QCOMPARE(TokenFilter("ok").match(tokens), QString()); + QCOMPARE(TokenFilter("nok").match(tokens), QString("image does not have a \"nok\" token")); + QCOMPARE(TokenFilter("not_found").match(tokens), QString("image does not have a \"not_found\" token")); + + // Invert + QCOMPARE(TokenFilter("ok", true).match(tokens), QString("image has a \"ok\" token")); + QCOMPARE(TokenFilter("nok", true).match(tokens), QString()); + QCOMPARE(TokenFilter("not_found", true).match(tokens), QString()); +} + +void TokenFilterTest::testMatchStringList() +{ + QMap tokens; + tokens.insert("ok", Token(QStringList() << "ok")); + tokens.insert("nok", Token(QStringList())); + + // Basic + QCOMPARE(TokenFilter("ok").match(tokens), QString()); + QCOMPARE(TokenFilter("nok").match(tokens), QString("image does not have a \"nok\" token")); + QCOMPARE(TokenFilter("not_found").match(tokens), QString("image does not have a \"not_found\" token")); + + // Invert + QCOMPARE(TokenFilter("ok", true).match(tokens), QString("image has a \"ok\" token")); + QCOMPARE(TokenFilter("nok", true).match(tokens), QString()); + QCOMPARE(TokenFilter("not_found", true).match(tokens), QString()); +} + + +static TokenFilterTest instance; diff --git a/tests/src/models/filtering/token-filter-test.h b/tests/src/models/filtering/token-filter-test.h new file mode 100644 index 000000000..a33ed3ec2 --- /dev/null +++ b/tests/src/models/filtering/token-filter-test.h @@ -0,0 +1,18 @@ +#ifndef TOKEN_FILTER_TEST_H +#define TOKEN_FILTER_TEST_H + +#include "test-suite.h" + + +class TokenFilterTest : public TestSuite +{ + Q_OBJECT + + private slots: + void testToString(); + void testMatchInt(); + void testMatchString(); + void testMatchStringList(); +}; + +#endif // TOKEN_FILTER_TEST_H diff --git a/tests/src/models/image-test.cpp b/tests/src/models/image-test.cpp index 89a633a88..f39f459ae 100644 --- a/tests/src/models/image-test.cpp +++ b/tests/src/models/image-test.cpp @@ -155,7 +155,7 @@ void ImageTest::testStylishedTags() QCOMPARE(tags[1], QString("character1")); QCOMPARE(tags[7], QString("tag2"));*/ - m_profile->setBlacklistedTags(QList() << (QStringList() << "character1") << (QStringList() << "tag1")); + m_profile->setBlacklistedTags(Blacklist(QStringList() << "character1" << "tag1")); m_profile->getIgnored() = QStringList() << "copyright1" << "tag2"; tags = m_img->stylishedTags(m_profile); diff --git a/tests/src/models/post-filter-test.cpp b/tests/src/models/post-filter-test.cpp deleted file mode 100644 index c872e3736..000000000 --- a/tests/src/models/post-filter-test.cpp +++ /dev/null @@ -1,269 +0,0 @@ -#include "post-filter-test.h" -#include -#include "models/post-filter.h" -#include "test-suite.h" - - -void PostFilterTest::init() -{ - // Make tmp dir if not already existing - QDir tmp("tests/resources/"); - if (!tmp.exists("tmp")) - tmp.mkdir("tmp"); - - QFile::remove("tests/resources/md5s.txt"); - - m_details["md5"] = "1bc29b36f623ba82aaf6724fd3b16718"; - m_details["ext"] = "jpg"; - m_details["author"] = "superauthor"; - m_details["status"] = "tested"; - m_details["filename"] = ""; - m_details["folder"] = ""; - m_details["search"] = "testing well"; - m_details["id"] = "7331"; - m_details["score"] = "21"; - m_details["parent_id"] = "1337"; - m_details["file_size"] = "1234567"; - m_details["creator_id"] = "1234"; - m_details["has_children"] = "true"; - m_details["has_note"] = "true"; - m_details["has_comments"] = "true"; - m_details["file_url"] = "http://test.com/img/oldfilename.jpg?123456"; - m_details["sample_url"] = "http://test.com/sample/oldfilename.jpg"; - m_details["preview_url"] = "http://test.com/preview/oldfilename.jpg"; - m_details["page_url"] = ""; - m_details["width"] = "800"; - m_details["height"] = "600"; - m_details["source"] = "http://google.com/toto/toto.jpg"; - m_details["tags_general"] = "tag1 tag2 tag3 "; - m_details["tags_artist"] = "artist1 "; - m_details["tags_copyright"] = "copyright1 copyright2 "; - m_details["tags_character"] = "character1 character2 "; - m_details["tags_model"] = "model1 "; - m_details["created_at"] = "1471513944"; - m_details["rating"] = "safe"; - m_details["file_size"] = "358400"; - m_details["file_size"] = "358400"; - - m_profile = new Profile("tests/resources/"); - m_source = new Source(m_profile, "release/sites/Danbooru (2.0)"); - m_site = new Site("danbooru.donmai.us", m_source); - m_img = new Image(m_site, m_details, m_profile); -} - -void PostFilterTest::cleanup() -{ - m_profile->deleteLater(); - m_source->deleteLater(); - m_site->deleteLater(); - m_img->deleteLater(); -} - - -QList makeBlacklist(const QStringList &tags) -{ - QList blacklist; - for (const QString &tag : tags) - { blacklist.append(QStringList() << tag); } - return blacklist; -} - -void PostFilterTest::testBlacklisted() -{ - auto tokens = m_img->tokens(m_profile); - - // Basic - QCOMPARE(PostFilter::blacklisted(tokens, makeBlacklist(QStringList() << "tag8" << "tag7")), QStringList()); - QCOMPARE(PostFilter::blacklisted(tokens, makeBlacklist(QStringList() << "tag1" << "tag7")), QStringList() << "tag1"); - QCOMPARE(PostFilter::blacklisted(tokens, makeBlacklist(QStringList() << "character1" << "artist1")), QStringList() << "character1" << "artist1"); - - // Invert - QCOMPARE(PostFilter::blacklisted(tokens, makeBlacklist(QStringList() << "tag8" << "tag7"), false), QStringList() << "tag8" << "tag7"); - QCOMPARE(PostFilter::blacklisted(tokens, makeBlacklist(QStringList() << "tag1" << "tag7"), false), QStringList() << "tag7"); - QCOMPARE(PostFilter::blacklisted(tokens, makeBlacklist(QStringList() << "character1" << "artist1"), false), QStringList()); -} - -void PostFilterTest::testMatchToken() -{ - auto tokens = m_img->tokens(m_profile); - - // Basic - QCOMPARE(PostFilter::match(tokens, "%copyright%"), QString()); - QCOMPARE(PostFilter::match(tokens, "%toto%"), QString("image does not have a \"toto\" token")); - - // Minus - QCOMPARE(PostFilter::match(tokens, "-%copyright%"), QString("image has a \"copyright\" token")); - QCOMPARE(PostFilter::match(tokens, "-%toto%"), QString()); - - // Invert - QCOMPARE(PostFilter::match(tokens, "%copyright%", true), QString("image has a \"copyright\" token")); - QCOMPARE(PostFilter::match(tokens, "%toto%", true), QString()); - - // Invert minus - QCOMPARE(PostFilter::match(tokens, "-%copyright%", true), QString()); - QCOMPARE(PostFilter::match(tokens, "-%toto%", true), QString("image does not have a \"toto\" token")); -} - -void PostFilterTest::testMatchTag() -{ - auto tokens = m_img->tokens(m_profile); - - // Basic - QCOMPARE(PostFilter::match(tokens, "tag1"), QString()); - QCOMPARE(PostFilter::match(tokens, "character1"), QString()); - QCOMPARE(PostFilter::match(tokens, "tag7"), QString("image does not contains \"tag7\"")); - - // Minus - QCOMPARE(PostFilter::match(tokens, "-tag1"), QString("image contains \"tag1\"")); - QCOMPARE(PostFilter::match(tokens, "-character1"), QString("image contains \"character1\"")); - QCOMPARE(PostFilter::match(tokens, "-tag7"), QString()); - - // Invert - QCOMPARE(PostFilter::match(tokens, "tag1", true), QString("image contains \"tag1\"")); - QCOMPARE(PostFilter::match(tokens, "character1", true), QString("image contains \"character1\"")); - QCOMPARE(PostFilter::match(tokens, "tag7", true), QString()); - - // Invert minus - QCOMPARE(PostFilter::match(tokens, "-tag1", true), QString()); - QCOMPARE(PostFilter::match(tokens, "-character1", true), QString()); - QCOMPARE(PostFilter::match(tokens, "-tag7", true), QString("image does not contains \"tag7\"")); -} - -void PostFilterTest::testMatchUnknown() -{ - auto tokens = m_img->tokens(m_profile); - - QCOMPARE(PostFilter::match(tokens, "toto:test").startsWith("unknown type \"toto\""), true); -} - -void PostFilterTest::testMatchMathematical() -{ - auto tokens = m_img->tokens(m_profile); - - // Basic - QCOMPARE(PostFilter::match(tokens, "id:>1000"), QString()); - QCOMPARE(PostFilter::match(tokens, "id:<=1000"), QString("image's id does not match")); - QCOMPARE(PostFilter::match(tokens, "id:>=0", true), QString("image's id match")); - - // Other types - QCOMPARE(PostFilter::match(tokens, "width:..1000"), QString()); - QCOMPARE(PostFilter::match(tokens, "height:500.."), QString()); - QCOMPARE(PostFilter::match(tokens, "score:10..30"), QString()); - QCOMPARE(PostFilter::match(tokens, "mpixels:<1000000"), QString()); - QCOMPARE(PostFilter::match(tokens, "filesize:358400"), QString()); -} - -void PostFilterTest::testMatchDate() -{ - auto tokens = m_img->tokens(m_profile); - - QCOMPARE(PostFilter::match(tokens, "date:>08/16/2016"), QString()); - QCOMPARE(PostFilter::match(tokens, "date:>=2016-08-16"), QString()); - QCOMPARE(PostFilter::match(tokens, "date:<08/20/2016"), QString()); - QCOMPARE(PostFilter::match(tokens, "date:<=2016-08-20"), QString()); - QCOMPARE(PostFilter::match(tokens, "date:..08/20/2016"), QString()); - QCOMPARE(PostFilter::match(tokens, "date:2016-08-16.."), QString()); - QCOMPARE(PostFilter::match(tokens, "date:08/16/2016..2016-08-20"), QString()); - QCOMPARE(PostFilter::match(tokens, "date:2016-08-18"), QString()); - - // Invalid date - QCOMPARE(PostFilter::match(tokens, "date:someday"), QString("image's date does not match")); -} - -void PostFilterTest::testMatchRating() -{ - auto tokens = m_img->tokens(m_profile); - - // Basic - QCOMPARE(PostFilter::match(tokens, "rating:safe"), QString()); - QCOMPARE(PostFilter::match(tokens, "rating:explicit"), QString("image is not \"explicit\"")); - - // Short versions - QCOMPARE(PostFilter::match(tokens, "rating:s"), QString()); - QCOMPARE(PostFilter::match(tokens, "rating:e"), QString("image is not \"explicit\"")); - - // Invert - QCOMPARE(PostFilter::match(tokens, "rating:safe", true), QString("image is \"safe\"")); - QCOMPARE(PostFilter::match(tokens, "rating:explicit", true), QString()); -} - -void PostFilterTest::testMatchSource() -{ - auto tokens = m_img->tokens(m_profile); - - // Full - QCOMPARE(PostFilter::match(tokens, "source:http://google.com/toto/toto.jpg"), QString()); - QCOMPARE(PostFilter::match(tokens, "source:http://test.fr/toto/toto.jpg"), QString("image's source does not starts with \"http://test.fr/toto/toto.jpg\"")); - - // Short - QCOMPARE(PostFilter::match(tokens, "source:http://google.com"), QString()); - QCOMPARE(PostFilter::match(tokens, "source:http://test.fr"), QString("image's source does not starts with \"http://test.fr\"")); - - // Invert - QCOMPARE(PostFilter::match(tokens, "source:http://google.com", true), QString("image's source starts with \"http://google.com\"")); - QCOMPARE(PostFilter::match(tokens, "source:http://test.fr", true), QString()); -} - -void PostFilterTest::testFilterNumeric() -{ - auto tokens = m_img->tokens(m_profile); - - QStringList filters; - - // No match - filters = PostFilter::filter(tokens, QStringList() << "id:<=10000" << "width:>100" << "date:<2017-01-01"); - QCOMPARE(filters, QStringList()); - - // All match - filters = PostFilter::filter(tokens, QStringList() << "id:>10000" << "width:<=100" << "date:>=2017-01-01"); - QCOMPARE(filters, QStringList() << "image's id does not match" << "image's width does not match" << "image's date does not match"); -} -void PostFilterTest::testFilterString() -{ - auto tokens = m_img->tokens(m_profile); - - QStringList filters; - - // No match - filters = PostFilter::filter(tokens, QStringList() << "filetype:jpg"); - QCOMPARE(filters, QStringList()); - - // All match - filters = PostFilter::filter(tokens, QStringList() << "filetype:png"); - QCOMPARE(filters, QStringList() << "image's filetype does not match"); - - // Invert - filters = PostFilter::filter(tokens, QStringList() << "-filetype:jpg"); - QCOMPARE(filters, QStringList() << "image's filetype match"); -} -void PostFilterTest::testFilterSpecial() -{ - auto tokens = m_img->tokens(m_profile); - - QStringList filters; - - // No match - filters = PostFilter::filter(tokens, QStringList() << "rating:s" << "rating:safe" << "source:http://google.com"); - QCOMPARE(filters, QStringList()); - - // All match - filters = PostFilter::filter(tokens, QStringList() << "rating:e" << "rating:explicit" << "source:http://test.com"); - QCOMPARE(filters, QStringList() << "image is not \"explicit\"" << "image is not \"explicit\"" << "image's source does not starts with \"http://test.com\""); -} -void PostFilterTest::testFilterInvert() -{ - auto tokens = m_img->tokens(m_profile); - - QStringList filters; - - // No match - filters = PostFilter::filter(tokens, QStringList() << "-id:>10000" << "-width:<=100" << "-date:>=2017-01-01"); - QCOMPARE(filters, QStringList()); - - // All match - filters = PostFilter::filter(tokens, QStringList() << "-id:<=10000" << "-width:>100" << "-date:<2017-01-01"); - QCOMPARE(filters, QStringList() << "image's id match" << "image's width match" << "image's date match"); -} - - -static PostFilterTest instance; From 6cf2bf0ae6e9b109e06d09578c376ba3d8d0930d Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 10 Jul 2018 15:36:49 +0200 Subject: [PATCH 033/112] Make PostFilter non-static --- lib/src/models/filename.cpp | 6 +- lib/src/models/filtering/post-filter.cpp | 191 ++---------------- lib/src/models/filtering/post-filter.h | 11 +- lib/src/models/page-api.cpp | 6 +- lib/src/models/page-api.h | 6 +- .../src/models/filtering/post-filter-test.cpp | 12 +- 6 files changed, 43 insertions(+), 189 deletions(-) diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index 0df9a13c6..7c48c2f6f 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -197,10 +197,10 @@ bool Filename::matchConditionalFilename(QString cond, QSettings *settings, const return result.toBool(); } - const QStringList options = cond.split(' '); - const QStringList matches = PostFilter::filter(tokens, options); + const PostFilter filter(cond.split(' ')); + const QStringList matches = filter.match(tokens); - return matches.count() < options.count(); + return matches.count() < filter.count(); } QList> Filename::expandTokens(const QString &filename, QMap tokens, QSettings *settings) const diff --git a/lib/src/models/filtering/post-filter.cpp b/lib/src/models/filtering/post-filter.cpp index 0e436bf1b..2fd6b3756 100644 --- a/lib/src/models/filtering/post-filter.cpp +++ b/lib/src/models/filtering/post-filter.cpp @@ -1,190 +1,35 @@ #include "post-filter.h" #include "functions.h" -#include "loader/token.h" +#include "filter.h" +#include "filter-factory.h" -static int toDate(const QString &text) +PostFilter::PostFilter(const QStringList &filters) { - QDateTime date = QDateTime::fromString(text, "yyyy-MM-dd"); - if (date.isValid()) - { return date.toString("yyyyMMdd").toInt(); } - date = QDateTime::fromString(text, "MM/dd/yyyy"); - if (date.isValid()) - { return date.toString("yyyyMMdd").toInt(); } - return 0; -} - -QString PostFilter::match(const QMap &tokens, QString filter, bool invert) -{ - // Invert the filter by prepending '-' - if (filter.startsWith('-')) - { - filter = filter.right(filter.length() - 1); - invert = !invert; - } - - // Tokens - if (filter.startsWith('%') && filter.endsWith('%')) - { - const QString key = filter.mid(1, filter.length() - 2); - const bool cond = tokens.contains(key) && !isVariantEmpty(tokens[key].value()); - - if (cond && invert) - { return QObject::tr("image has a \"%1\" token").arg(key); } - else if (!cond && !invert) - { return QObject::tr("image does not have a \"%1\" token").arg(key); } - } - - // Meta-tags - else if (filter.contains(":")) + for (const QString &filter : filters) { - const QString type = filter.section(':', 0, 0).toLower(); - filter = filter.section(':', 1).toLower(); - - // Grabber specials - if (type == QStringLiteral("grabber")) - { - const QStringList &vals = tokens[type].value().toStringList(); - const bool cond = vals.contains(filter, Qt::CaseInsensitive); - - if (!cond && !invert) - { return QObject::tr("image is not \"%1\"").arg(filter); } - if (cond && invert) - { return QObject::tr("image is \"%1\"").arg(filter); } - - return QString(); - } - - // Meta tokens - if (!tokens.contains(type)) - { - QStringList keys = tokens.keys(); - return QObject::tr("unknown type \"%1\" (available types: \"%2\")").arg(type, keys.join("\", \"")); - } - - const QVariant &token = tokens[type].value(); - if (token.type() == QVariant::Int || token.type() == QVariant::DateTime || token.type() == QVariant::ULongLong) - { - int input = 0; - if (token.type() == QVariant::Int) - { input = token.toInt(); } - else if (token.type() == QVariant::DateTime) - { input = token.toDateTime().toString("yyyyMMdd").toInt(); } - else if (token.type() == QVariant::ULongLong) - { input = token.toULongLong(); } - - bool cond; - if (token.type() == QVariant::DateTime) - { - if (filter.startsWith("..") || filter.startsWith("<=")) - { cond = input <= toDate(filter.right(filter.size()-2)); } - else if (filter.endsWith("..")) - { cond = input >= toDate(filter.left(filter.size()-2)); } - else if (filter.startsWith(">=")) - { cond = input >= toDate(filter.right(filter.size()-2)); } - else if (filter.startsWith("<")) - { cond = input < toDate(filter.right(filter.size()-1)); } - else if (filter.startsWith(">")) - { cond = input > toDate(filter.right(filter.size()-1)); } - else if (filter.contains("..")) - { cond = input >= toDate(filter.left(filter.indexOf(".."))) && input <= toDate(filter.right(filter.size()-filter.indexOf("..")-2)); } - else - { cond = input == toDate(filter); } - } - else - { - if (filter.startsWith("..") || filter.startsWith("<=")) - { cond = input <= filter.rightRef(filter.size()-2).toInt(); } - else if (filter.endsWith("..")) - { cond = input >= filter.leftRef(filter.size()-2).toInt(); } - else if (filter.startsWith(">=")) - { cond = input >= filter.rightRef(filter.size()-2).toInt(); } - else if (filter.startsWith("<")) - { cond = input < filter.rightRef(filter.size()-1).toInt(); } - else if (filter.startsWith(">")) - { cond = input > filter.rightRef(filter.size()-1).toInt(); } - else if (filter.contains("..")) - { cond = input >= filter.leftRef(filter.indexOf("..")).toInt() && input <= filter.rightRef(filter.size()-filter.indexOf("..")-2).toInt(); } - else - { cond = input == filter.toInt(); } - } - - if (!cond && !invert) - { return QObject::tr("image's %1 does not match").arg(type); } - if (cond && invert) - { return QObject::tr("image's %1 match").arg(type); } - } - else - { - if (type == "rating") - { - QMap assoc; - assoc["s"] = "safe"; - assoc["q"] = "questionable"; - assoc["e"] = "explicit"; - - if (assoc.contains(filter)) - filter = assoc[filter]; - - const bool cond = !filter.isEmpty() && token.toString().toLower().startsWith(filter.at(0)); - if (!cond && !invert) - { return QObject::tr("image is not \"%1\"").arg(filter); } - if (cond && invert) - { return QObject::tr("image is \"%1\"").arg(filter); } - } - else if (type == "source") - { - QRegExp rx(filter + "*", Qt::CaseInsensitive, QRegExp::Wildcard); - const bool cond = rx.exactMatch(token.toString()); - if (!cond && !invert) - { return QObject::tr("image's source does not starts with \"%1\"").arg(filter); } - if (cond && invert) - { return QObject::tr("image's source starts with \"%1\"").arg(filter); } - } - else - { - const QString input = token.toString(); - - const bool cond = input == filter; - - if (!cond && !invert) - { return QObject::tr("image's %1 does not match").arg(type); } - if (cond && invert) - { return QObject::tr("image's %1 match").arg(type); } - } - } + Filter *fil = FilterFactory::build(filter); + if (fil != Q_NULLPTR) + m_filters.append(fil); } - else if (!filter.isEmpty()) - { - QStringList tags = tokens["allos"].value().toStringList(); - - // Check if any tag match the filter (case insensitive plain text with wildcards allowed) - bool cond = false; - for (const QString &tag : tags) - { - QRegExp reg(filter.trimmed(), Qt::CaseInsensitive, QRegExp::Wildcard); - if (reg.exactMatch(tag)) - { - cond = true; - break; - } - } +} - if (!cond && !invert) - { return QObject::tr("image does not contains \"%1\"").arg(filter); } - if (cond && invert) - { return QObject::tr("image contains \"%1\"").arg(filter); } - } +PostFilter::~PostFilter() +{ + qDeleteAll(m_filters); +} - return QString(); +int PostFilter::count() const +{ + return m_filters.count(); } -QStringList PostFilter::filter(const QMap &tokens, const QStringList &filters) +QStringList PostFilter::match(const QMap &tokens) const { QStringList ret; - for (const QString &filter : filters) + for (Filter *filter : m_filters) { - QString err = match(tokens, filter); + QString err = filter->match(tokens); if (!err.isEmpty()) ret.append(err); } diff --git a/lib/src/models/filtering/post-filter.h b/lib/src/models/filtering/post-filter.h index de44cc9f7..b92b72314 100644 --- a/lib/src/models/filtering/post-filter.h +++ b/lib/src/models/filtering/post-filter.h @@ -1,16 +1,23 @@ #ifndef POST_FILTER_H #define POST_FILTER_H +#include #include +class Filter; class Token; class PostFilter { public: - static QStringList filter(const QMap &tokens, const QStringList &filters); - static QString match(const QMap &tokens, QString filter, bool invert = false); + explicit PostFilter(const QStringList &filters = QStringList()); + ~PostFilter(); + int count() const; + QStringList match(const QMap &tokens) const; + + private: + QList m_filters; }; #endif // POST_FILTER_H diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index d38027a71..77a5614bd 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -14,8 +14,8 @@ #include "tags/tag.h" -PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags, int page, int limit, QStringList postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) - : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(std::move(tags)), m_postFiltering(std::move(postFiltering)), m_errors(QStringList()), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(Q_NULLPTR), m_replyTags(Q_NULLPTR) +PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags, int page, int limit, const QStringList &postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) + : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(std::move(tags)), m_errors(QStringList()), m_postFiltering(PostFilter(postFiltering)), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(Q_NULLPTR), m_replyTags(Q_NULLPTR) { m_imagesCount = -1; m_maxImagesCount = -1; @@ -116,7 +116,7 @@ bool PageApi::addImage(const QSharedPointer &img) m_pageImageCount++; - QStringList filters = PostFilter::filter(img->tokens(m_profile), m_postFiltering); + QStringList filters = m_postFiltering.match(img->tokens(m_profile)); if (!filters.isEmpty()) { img->deleteLater(); diff --git a/lib/src/models/page-api.h b/lib/src/models/page-api.h index 944a873ed..3296a08df 100644 --- a/lib/src/models/page-api.h +++ b/lib/src/models/page-api.h @@ -1,6 +1,7 @@ #ifndef PAGE_API_H #define PAGE_API_H +#include "models/filtering/post-filter.h" #include "models/image.h" #include "tags/tag.h" @@ -22,7 +23,7 @@ class PageApi : public QObject Error }; - explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags = QStringList(), int page = 1, int limit = 25, QStringList postFiltering = QStringList(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); + explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags = QStringList(), int page = 1, int limit = 25, const QStringList &postFiltering = QStringList(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); void setLastPage(Page *page); const QList> &images() const; bool isImageCountSure() const; @@ -71,7 +72,8 @@ class PageApi : public QObject Profile *m_profile; Site *m_site; Api *m_api; - QStringList m_search, m_postFiltering, m_errors; + QStringList m_search, m_errors; + PostFilter m_postFiltering; int m_imagesPerPage, m_lastPage, m_page, m_blim, m_pool; qulonglong m_lastPageMinId, m_lastPageMaxId; bool m_smart, m_isAltPage; diff --git a/tests/src/models/filtering/post-filter-test.cpp b/tests/src/models/filtering/post-filter-test.cpp index ef1ec1219..e5ae839f9 100644 --- a/tests/src/models/filtering/post-filter-test.cpp +++ b/tests/src/models/filtering/post-filter-test.cpp @@ -67,11 +67,11 @@ void PostFilterTest::testFilterNumeric() QStringList filters; // No match - filters = PostFilter::filter(tokens, QStringList() << "id:<=10000" << "width:>100" << "date:<2017-01-01"); + filters = PostFilter(QStringList() << "id:<=10000" << "width:>100" << "date:<2017-01-01").match(tokens); QCOMPARE(filters, QStringList()); // All match - filters = PostFilter::filter(tokens, QStringList() << "id:>10000" << "width:<=100" << "date:>=2017-01-01"); + filters = PostFilter(QStringList() << "id:>10000" << "width:<=100" << "date:>=2017-01-01").match(tokens); QCOMPARE(filters, QStringList() << "image's id does not match" << "image's width does not match" << "image's date does not match"); } @@ -82,11 +82,11 @@ void PostFilterTest::testFilterSpecial() QStringList filters; // No match - filters = PostFilter::filter(tokens, QStringList() << "rating:s" << "rating:safe" << "source:http://google.com"); + filters = PostFilter(QStringList() << "rating:s" << "rating:safe" << "source:http://google.com").match(tokens); QCOMPARE(filters, QStringList()); // All match - filters = PostFilter::filter(tokens, QStringList() << "rating:e" << "rating:explicit" << "source:http://test.com"); + filters = PostFilter(QStringList() << "rating:e" << "rating:explicit" << "source:http://test.com").match(tokens); QCOMPARE(filters, QStringList() << "image is not \"explicit\"" << "image is not \"explicit\"" << "image's source does not starts with \"http://test.com\""); } @@ -97,11 +97,11 @@ void PostFilterTest::testFilterInvert() QStringList filters; // No match - filters = PostFilter::filter(tokens, QStringList() << "-id:>10000" << "-width:<=100" << "-date:>=2017-01-01"); + filters = PostFilter(QStringList() << "-id:>10000" << "-width:<=100" << "-date:>=2017-01-01").match(tokens); QCOMPARE(filters, QStringList()); // All match - filters = PostFilter::filter(tokens, QStringList() << "-id:<=10000" << "-width:>100" << "-date:<2017-01-01"); + filters = PostFilter(QStringList() << "-id:<=10000" << "-width:>100" << "-date:<2017-01-01").match(tokens); QCOMPARE(filters, QStringList() << "image's id match" << "image's width match" << "image's date match"); } From dd819673060b640d57ea24bf98388c9bc3e0a4a4 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 10 Jul 2018 16:39:10 +0200 Subject: [PATCH 034/112] Use smart pointers in PostFilter and Blacklist class to fix copying --- lib/src/models/filtering/blacklist.cpp | 27 +++++++++--------------- lib/src/models/filtering/blacklist.h | 4 ++-- lib/src/models/filtering/post-filter.cpp | 11 +++------- lib/src/models/filtering/post-filter.h | 4 ++-- 4 files changed, 17 insertions(+), 29 deletions(-) diff --git a/lib/src/models/filtering/blacklist.cpp b/lib/src/models/filtering/blacklist.cpp index 4e65def52..97e33b640 100644 --- a/lib/src/models/filtering/blacklist.cpp +++ b/lib/src/models/filtering/blacklist.cpp @@ -9,17 +9,11 @@ Blacklist::Blacklist(const QStringList &tags) add(tag); } -Blacklist::~Blacklist() -{ - for (const QList &filters : qAsConst(m_filters)) - qDeleteAll(filters); -} - int Blacklist::indexOf(const QString &tag) const { for (int i = 0; i < m_filters.count(); ++i) { - const QList &filters = m_filters[i]; + const auto &filters = m_filters[i]; if (filters.count() == 1 && QString::compare(filters[0]->toString(), tag, Qt::CaseInsensitive) == 0) return i; } @@ -33,18 +27,18 @@ bool Blacklist::contains(const QString &tag) const void Blacklist::add(const QString &tag) { - Filter *filter = FilterFactory::build(tag); - if (filter != Q_NULLPTR) - m_filters.append(QList() << filter); + auto filter = QSharedPointer(FilterFactory::build(tag)); + if (!filter.isNull()) + m_filters.append(QList>() << filter); } void Blacklist::add(const QStringList &tags) { - QList filters; + QList> filters; for (const QString &tag : tags) { - Filter *filter = FilterFactory::build(tag); - if (filter != Q_NULLPTR) + auto filter = QSharedPointer(FilterFactory::build(tag)); + if (!filter.isNull()) filters.append(filter); } @@ -58,7 +52,6 @@ bool Blacklist::remove(const QString &tag) if (index == -1) return false; - qDeleteAll(m_filters[index]); m_filters.removeAt(index); return true; } @@ -66,7 +59,7 @@ bool Blacklist::remove(const QString &tag) QString Blacklist::toString() const { QString ret; - for (const QList &filters : qAsConst(m_filters)) + for (const auto &filters : qAsConst(m_filters)) { for (int i = 0; i < filters.count(); ++i) { @@ -82,11 +75,11 @@ QString Blacklist::toString() const QStringList Blacklist::match(const QMap &tokens, bool invert) const { QStringList detected; - for (const QList &filters : qAsConst(m_filters)) + for (const auto &filters : qAsConst(m_filters)) { bool allDetected = true; QStringList res; - for (Filter *filter : filters) + for (const auto &filter : filters) { if (filter->match(tokens, invert).isEmpty()) { diff --git a/lib/src/models/filtering/blacklist.h b/lib/src/models/filtering/blacklist.h index 9c6ab5ded..b1dc234a7 100644 --- a/lib/src/models/filtering/blacklist.h +++ b/lib/src/models/filtering/blacklist.h @@ -2,6 +2,7 @@ #define BLACKLIST_H #include +#include class Filter; @@ -12,7 +13,6 @@ class Blacklist public: Blacklist() = default; explicit Blacklist(const QStringList &tags); - ~Blacklist(); bool contains(const QString &tag) const; void add(const QString &tag); @@ -26,7 +26,7 @@ class Blacklist int indexOf(const QString &tag) const; private: - QList> m_filters; + QList>> m_filters; }; #endif // BLACKLIST_H diff --git a/lib/src/models/filtering/post-filter.cpp b/lib/src/models/filtering/post-filter.cpp index 2fd6b3756..d3e12a191 100644 --- a/lib/src/models/filtering/post-filter.cpp +++ b/lib/src/models/filtering/post-filter.cpp @@ -8,17 +8,12 @@ PostFilter::PostFilter(const QStringList &filters) { for (const QString &filter : filters) { - Filter *fil = FilterFactory::build(filter); - if (fil != Q_NULLPTR) + auto fil = QSharedPointer(FilterFactory::build(filter)); + if (!fil.isNull()) m_filters.append(fil); } } -PostFilter::~PostFilter() -{ - qDeleteAll(m_filters); -} - int PostFilter::count() const { return m_filters.count(); @@ -27,7 +22,7 @@ int PostFilter::count() const QStringList PostFilter::match(const QMap &tokens) const { QStringList ret; - for (Filter *filter : m_filters) + for (const auto &filter : m_filters) { QString err = filter->match(tokens); if (!err.isEmpty()) diff --git a/lib/src/models/filtering/post-filter.h b/lib/src/models/filtering/post-filter.h index b92b72314..f926aef3b 100644 --- a/lib/src/models/filtering/post-filter.h +++ b/lib/src/models/filtering/post-filter.h @@ -2,6 +2,7 @@ #define POST_FILTER_H #include +#include #include @@ -12,12 +13,11 @@ class PostFilter { public: explicit PostFilter(const QStringList &filters = QStringList()); - ~PostFilter(); int count() const; QStringList match(const QMap &tokens) const; private: - QList m_filters; + QList> m_filters; }; #endif // POST_FILTER_H From b557a153533faaa51e5db3b21ed732e0370463c8 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 10 Jul 2018 17:07:23 +0200 Subject: [PATCH 035/112] Move PostFilter construction to the Page class --- lib/src/models/page-api.cpp | 4 ++-- lib/src/models/page-api.h | 2 +- lib/src/models/page.cpp | 5 +++-- lib/src/models/page.h | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 77a5614bd..8251e4be1 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -14,8 +14,8 @@ #include "tags/tag.h" -PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags, int page, int limit, const QStringList &postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) - : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(std::move(tags)), m_errors(QStringList()), m_postFiltering(PostFilter(postFiltering)), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(Q_NULLPTR), m_replyTags(Q_NULLPTR) +PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags, int page, int limit, PostFilter postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) + : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(std::move(tags)), m_errors(QStringList()), m_postFiltering(std::move(postFiltering)), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(Q_NULLPTR), m_replyTags(Q_NULLPTR) { m_imagesCount = -1; m_maxImagesCount = -1; diff --git a/lib/src/models/page-api.h b/lib/src/models/page-api.h index 3296a08df..5f3c4b948 100644 --- a/lib/src/models/page-api.h +++ b/lib/src/models/page-api.h @@ -23,7 +23,7 @@ class PageApi : public QObject Error }; - explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags = QStringList(), int page = 1, int limit = 25, const QStringList &postFiltering = QStringList(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); + explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags = QStringList(), int page = 1, int limit = 25, PostFilter postFiltering = PostFilter(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); void setLastPage(Page *page); const QList> &images() const; bool isImageCountSure() const; diff --git a/lib/src/models/page.cpp b/lib/src/models/page.cpp index 85d698b69..14bf29e98 100644 --- a/lib/src/models/page.cpp +++ b/lib/src/models/page.cpp @@ -7,7 +7,7 @@ Page::Page(Profile *profile, Site *site, const QList &sites, QStringList tags, int page, int limit, const QStringList &postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) - : QObject(parent), m_site(site), m_regexApi(-1), m_postFiltering(postFiltering), m_errors(QStringList()), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart) + : QObject(parent), m_site(site), m_regexApi(-1), m_errors(QStringList()), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart) { m_website = m_site->url(); m_imagesCount = -1; @@ -37,11 +37,12 @@ Page::Page(Profile *profile, Site *site, const QList &sites, QStringList m_search = tags; // Generate pages + PostFilter postFilter(postFiltering); m_siteApis = m_site->getLoggedInApis(); m_pageApis.reserve(m_siteApis.count()); for (Api *api : qAsConst(m_siteApis)) { - auto *pageApi = new PageApi(this, profile, m_site, api, m_search, page, limit, postFiltering, smart, parent, pool, lastPage, lastPageMinId, lastPageMaxId); + auto *pageApi = new PageApi(this, profile, m_site, api, m_search, page, limit, postFilter, smart, parent, pool, lastPage, lastPageMinId, lastPageMaxId); if (m_pageApis.count() == 0) { connect(pageApi, &PageApi::httpsRedirect, this, &Page::httpsRedirectSlot); } m_pageApis.append(pageApi); diff --git a/lib/src/models/page.h b/lib/src/models/page.h index 8a8849aac..b6dae2ed9 100644 --- a/lib/src/models/page.h +++ b/lib/src/models/page.h @@ -69,7 +69,7 @@ class Page : public QObject QList m_siteApis; QList m_pageApis; int m_regexApi; - QStringList m_postFiltering, m_errors, m_search; + QStringList m_errors, m_search; int m_imagesPerPage, m_lastPage, m_imagesCount, m_pagesCount, m_page, m_pool; qulonglong m_lastPageMinId, m_lastPageMaxId; bool m_smart; From e520ee2216280bd0d5d2cdcfd17ce2d243d2fe70 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 10 Jul 2018 17:10:51 +0200 Subject: [PATCH 036/112] Fix Travis Blacklist build --- lib/src/models/filtering/blacklist.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/src/models/filtering/blacklist.cpp b/lib/src/models/filtering/blacklist.cpp index 97e33b640..19b119b53 100644 --- a/lib/src/models/filtering/blacklist.cpp +++ b/lib/src/models/filtering/blacklist.cpp @@ -1,6 +1,7 @@ #include "blacklist.h" #include "filter.h" #include "filter-factory.h" +#include "functions.h" Blacklist::Blacklist(const QStringList &tags) @@ -79,7 +80,7 @@ QStringList Blacklist::match(const QMap &tokens, bool invert) co { bool allDetected = true; QStringList res; - for (const auto &filter : filters) + for (const QSharedPointer &filter : filters) { if (filter->match(tokens, invert).isEmpty()) { From ee85c2b71159c36c7d49f07577d5b524a99cd3b4 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 10 Jul 2018 23:48:07 +0200 Subject: [PATCH 037/112] Optimize TagFilter by caching regexp --- lib/src/models/filtering/tag-filter.cpp | 9 ++++++--- lib/src/models/filtering/tag-filter.h | 3 +++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/src/models/filtering/tag-filter.cpp b/lib/src/models/filtering/tag-filter.cpp index 0b20528c3..af159d2e6 100644 --- a/lib/src/models/filtering/tag-filter.cpp +++ b/lib/src/models/filtering/tag-filter.cpp @@ -6,7 +6,10 @@ TagFilter::TagFilter(QString tag, bool invert) : Filter(invert), m_tag(std::move(tag)) -{} +{ + if (m_tag.contains('*')) + { m_regexp.reset(new QRegExp(m_tag, Qt::CaseInsensitive, QRegExp::Wildcard)); } +} QString TagFilter::toString() const { @@ -24,8 +27,8 @@ QString TagFilter::match(const QMap &tokens, bool invert) const bool cond = false; for (const QString &tag : tags) { - QRegExp reg(m_tag, Qt::CaseInsensitive, QRegExp::Wildcard); - if (reg.exactMatch(tag)) + bool match = m_regexp.isNull() ? tag == m_tag : m_regexp->exactMatch(tag); + if (match) { cond = true; break; diff --git a/lib/src/models/filtering/tag-filter.h b/lib/src/models/filtering/tag-filter.h index e08598cba..2eb173eae 100644 --- a/lib/src/models/filtering/tag-filter.h +++ b/lib/src/models/filtering/tag-filter.h @@ -2,6 +2,8 @@ #define TAG_FILTER_H #include "filter.h" +#include +#include class TagFilter : public Filter @@ -13,6 +15,7 @@ class TagFilter : public Filter private: QString m_tag; + QScopedPointer m_regexp; }; #endif // TAG_FILTER_H From bb666a7de2e06cbf26b6def81dd4c1cdbc865e55 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 09:58:44 +0200 Subject: [PATCH 038/112] Add equality operator to filter classes --- lib/src/models/filtering/filter.cpp | 5 +++++ lib/src/models/filtering/filter.h | 3 +++ lib/src/models/filtering/meta-filter.cpp | 9 +++++++++ lib/src/models/filtering/meta-filter.h | 1 + lib/src/models/filtering/tag-filter.cpp | 9 +++++++++ lib/src/models/filtering/tag-filter.h | 1 + lib/src/models/filtering/token-filter.cpp | 9 +++++++++ lib/src/models/filtering/token-filter.h | 1 + 8 files changed, 38 insertions(+) diff --git a/lib/src/models/filtering/filter.cpp b/lib/src/models/filtering/filter.cpp index 35f206296..2751a1c1a 100644 --- a/lib/src/models/filtering/filter.cpp +++ b/lib/src/models/filtering/filter.cpp @@ -4,3 +4,8 @@ Filter::Filter(bool invert) : m_invert(invert) {} + +bool Filter::operator==(const Filter &rhs) +{ + return m_invert == rhs.m_invert && compare(rhs); +} diff --git a/lib/src/models/filtering/filter.h b/lib/src/models/filtering/filter.h index 6bc544931..6f2acc288 100644 --- a/lib/src/models/filtering/filter.h +++ b/lib/src/models/filtering/filter.h @@ -13,6 +13,9 @@ class Filter virtual QString match(const QMap &tokens, bool invert = false) const = 0; virtual QString toString() const = 0; + bool operator==(const Filter &rhs); + virtual bool compare(const Filter& rhs) const = 0; + protected: bool m_invert; }; diff --git a/lib/src/models/filtering/meta-filter.cpp b/lib/src/models/filtering/meta-filter.cpp index 53d3a0a27..f457089bf 100644 --- a/lib/src/models/filtering/meta-filter.cpp +++ b/lib/src/models/filtering/meta-filter.cpp @@ -13,6 +13,15 @@ QString MetaFilter::toString() const return QString(m_invert ? "-" : "") % m_type % ":" % m_val; } +bool MetaFilter::compare(const Filter& rhs) const +{ + auto other = dynamic_cast(&rhs); + if (other == Q_NULLPTR) + return false; + + return m_type == other->m_type && m_val == other->m_val; +} + static int toDate(const QString &text) { QDateTime date = QDateTime::fromString(text, "yyyy-MM-dd"); diff --git a/lib/src/models/filtering/meta-filter.h b/lib/src/models/filtering/meta-filter.h index 2b50bde30..e78a37ad2 100644 --- a/lib/src/models/filtering/meta-filter.h +++ b/lib/src/models/filtering/meta-filter.h @@ -10,6 +10,7 @@ class MetaFilter : public Filter MetaFilter(QString type, QString val, bool invert = false); QString match(const QMap &tokens, bool invert = false) const override; QString toString() const override; + bool compare(const Filter& rhs) const override; private: QString m_type; diff --git a/lib/src/models/filtering/tag-filter.cpp b/lib/src/models/filtering/tag-filter.cpp index af159d2e6..41becddd8 100644 --- a/lib/src/models/filtering/tag-filter.cpp +++ b/lib/src/models/filtering/tag-filter.cpp @@ -16,6 +16,15 @@ QString TagFilter::toString() const return QString(m_invert ? "-" : "") % m_tag; } +bool TagFilter::compare(const Filter& rhs) const +{ + auto other = dynamic_cast(&rhs); + if (other == Q_NULLPTR) + return false; + + return m_tag == other->m_tag; +} + QString TagFilter::match(const QMap &tokens, bool invert) const { if (m_invert) diff --git a/lib/src/models/filtering/tag-filter.h b/lib/src/models/filtering/tag-filter.h index 2eb173eae..ac941c1ff 100644 --- a/lib/src/models/filtering/tag-filter.h +++ b/lib/src/models/filtering/tag-filter.h @@ -12,6 +12,7 @@ class TagFilter : public Filter explicit TagFilter(QString tag, bool invert = false); QString match(const QMap &tokens, bool invert = false) const override; QString toString() const override; + bool compare(const Filter& rhs) const override; private: QString m_tag; diff --git a/lib/src/models/filtering/token-filter.cpp b/lib/src/models/filtering/token-filter.cpp index 04ab194a0..25b1995a0 100644 --- a/lib/src/models/filtering/token-filter.cpp +++ b/lib/src/models/filtering/token-filter.cpp @@ -12,6 +12,15 @@ QString TokenFilter::toString() const return QString(m_invert ? "-" : "") % "%" % m_token % "%"; } +bool TokenFilter::compare(const Filter& rhs) const +{ + auto other = dynamic_cast(&rhs); + if (other == Q_NULLPTR) + return false; + + return m_token == other->m_token; +} + QString TokenFilter::match(const QMap &tokens, bool invert) const { if (m_invert) diff --git a/lib/src/models/filtering/token-filter.h b/lib/src/models/filtering/token-filter.h index 14be6c988..3a6994d21 100644 --- a/lib/src/models/filtering/token-filter.h +++ b/lib/src/models/filtering/token-filter.h @@ -10,6 +10,7 @@ class TokenFilter : public Filter explicit TokenFilter(QString token, bool invert = false); QString match(const QMap &tokens, bool invert = false) const override; QString toString() const override; + bool compare(const Filter& rhs) const override; private: QString m_token; From 0e8ffe9d630a0b89a883a55916b57a108d0d3ae5 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 17:55:49 +0200 Subject: [PATCH 039/112] Fix a bunch of clang-tidy warnings --- e2e/src/main.cpp | 3 - e2e/viewer/index.html | 2 +- e2e/viewer/md.html | 4 +- e2e/viewer/style.css | 1 + gui/src/batch/addgroupwindow.cpp | 4 - gui/src/batch/adduniquewindow.cpp | 9 - gui/src/favoritewindow.cpp | 2 +- gui/src/mainwindow.cpp | 24 +- gui/src/mainwindow.h | 6 +- gui/src/settings/filenamewindow.cpp | 2 +- gui/src/settings/filenamewindow.h | 2 +- gui/src/settings/optionswindow.cpp | 14 +- gui/src/settings/startwindow.cpp | 5 - gui/src/sources/sourceswindow.cpp | 7 - gui/src/tabs/pool-tab.cpp | 2 +- gui/src/tabs/search-tab.cpp | 10 +- gui/src/tabs/search-tab.h | 5 +- gui/src/tabs/tabs-loader.cpp | 6 +- gui/src/tag-context-menu.cpp | 7 +- gui/src/tag-context-menu.h | 2 +- gui/src/ui/QBouton.cpp | 34 +- gui/src/ui/QBouton.h | 2 +- gui/src/ui/fixed-size-grid-layout.cpp | 11 +- gui/src/ui/textedit.cpp | 43 +- gui/src/ui/textedit.h | 2 +- gui/src/ui/verticalscrollarea.h | 2 +- .../utils/blacklist-fix/blacklist-fix-2.cpp | 2 +- .../utils/empty-dirs-fix/empty-dirs-fix-2.cpp | 2 +- gui/src/utils/md5-fix/md5-fix.cpp | 4 +- .../rename-existing/rename-existing-1.cpp | 12 +- .../rename-existing/rename-existing-2.cpp | 14 +- gui/src/viewer/details-window.cpp | 2 +- gui/src/viewer/zoom-window.cpp | 91 +- gui/src/viewer/zoom-window.h | 2 +- lib/src/downloader/download-query-group.cpp | 4 +- lib/src/downloader/download-query.h | 1 + lib/src/downloader/downloader.h | 2 +- lib/src/downloader/extension-rotator.cpp | 5 - lib/src/downloader/extension-rotator.h | 1 - lib/src/functions.cpp | 6 +- lib/src/functions.cpp~RF155d15f.TMP | 832 ++++++++++++++++++ lib/src/functions.h | 4 +- lib/src/loader/downloadable.h | 1 + lib/src/loader/loader-data.h | 4 +- lib/src/login/http-login.h | 1 + lib/src/login/oauth2-login.cpp | 2 +- lib/src/models/api/api.cpp | 17 +- lib/src/models/api/api.h | 2 +- lib/src/models/filename.h | 19 +- lib/src/models/filtering/blacklist.cpp | 2 +- lib/src/models/filtering/filter.cpp | 2 +- lib/src/models/filtering/filter.h | 3 +- lib/src/models/filtering/meta-filter.cpp | 4 +- lib/src/models/filtering/tag-filter.cpp | 4 +- lib/src/models/filtering/token-filter.cpp | 2 +- lib/src/models/image.cpp | 23 +- lib/src/models/site.cpp | 9 - lib/src/models/site.h | 6 +- lib/src/secure-file.cpp | 2 +- lib/src/tags/tag-name-format.h | 2 +- lib/src/tags/tag-stylist.cpp | 2 +- 61 files changed, 1034 insertions(+), 268 deletions(-) create mode 100644 lib/src/functions.cpp~RF155d15f.TMP diff --git a/e2e/src/main.cpp b/e2e/src/main.cpp index 54d7ed69a..6ee37fa7a 100644 --- a/e2e/src/main.cpp +++ b/e2e/src/main.cpp @@ -56,9 +56,6 @@ int main(int argc, char *argv[]) parser.addOption(outputOption); parser.process(app); - parser.value(inputOption); - parser.value(outputOption); - Logger::getInstance().setLogLevel(Logger::Warning); QFile f(parser.value(inputOption)); diff --git a/e2e/viewer/index.html b/e2e/viewer/index.html index 513001f59..bde6ecd07 100644 --- a/e2e/viewer/index.html +++ b/e2e/viewer/index.html @@ -23,7 +23,7 @@

    Source status

    var html = ""; for (var source in data) { var sites = data[source]; - if (Object.keys(sites).length == 0) { + if (Object.keys(sites).length === 0) { continue; } diff --git a/e2e/viewer/md.html b/e2e/viewer/md.html index eab71ec55..f94fe1bcb 100644 --- a/e2e/viewer/md.html +++ b/e2e/viewer/md.html @@ -26,7 +26,7 @@ html += "Last check on the " + dateStr + " at " + timeStr + ".\n"; for (var source in data) { var sites = data[source]; - if (Object.keys(sites).length == 0) { + if (Object.keys(sites).length === 0) { continue; } @@ -59,7 +59,7 @@ var assoc = { error: "x", warning: "warning", - ok: "heavy_check_mark", + ok: "heavy_check_mark" }; html += " :" + assoc[state.status] + ":" + (state.message && state.message.length > 0 ? " ?" : "") + " |"; } diff --git a/e2e/viewer/style.css b/e2e/viewer/style.css index 139ab7c0e..aae922f80 100644 --- a/e2e/viewer/style.css +++ b/e2e/viewer/style.css @@ -10,6 +10,7 @@ body { background-color: #fff; margin: auto; } + h1 { margin-bottom: 10px; font-size: 2em; diff --git a/gui/src/batch/addgroupwindow.cpp b/gui/src/batch/addgroupwindow.cpp index b5c92cba9..1f9058438 100644 --- a/gui/src/batch/addgroupwindow.cpp +++ b/gui/src/batch/addgroupwindow.cpp @@ -7,10 +7,6 @@ #include "ui/textedit.h" -/** - * Constructor of the AddGroupWindow class, generating its window. - * @param parent The parent window - */ AddGroupWindow::AddGroupWindow(Site *selected, Profile *profile, QWidget *parent) : QDialog(parent), ui(new Ui::AddGroupWindow), m_sites(profile->getSites()), m_settings(profile->getSettings()) { diff --git a/gui/src/batch/adduniquewindow.cpp b/gui/src/batch/adduniquewindow.cpp index ccf5bac14..6eb323ec6 100644 --- a/gui/src/batch/adduniquewindow.cpp +++ b/gui/src/batch/adduniquewindow.cpp @@ -11,11 +11,6 @@ #include "models/site.h" -/** - * Constructor of the AddUniqueWindow class, generating its window. - * @param favorites List of favorites tags, needed for coloration - * @param parent The parent window - */ AddUniqueWindow::AddUniqueWindow(Site *selected, Profile *profile, QWidget *parent) : QDialog(parent), ui(new Ui::AddUniqueWindow), m_page(Q_NULLPTR), m_sites(profile->getSites()), m_close(Q_NULLPTR), m_profile(profile) { @@ -81,10 +76,6 @@ void AddUniqueWindow::ok(bool close) } } -/** - * Signal triggered when the search is finished. - * @param r The QNetworkReply associated with the search - */ void AddUniqueWindow::replyFinished(Page *p) { if (p->images().isEmpty()) diff --git a/gui/src/favoritewindow.cpp b/gui/src/favoritewindow.cpp index ce3fcc881..fd719bbd3 100644 --- a/gui/src/favoritewindow.cpp +++ b/gui/src/favoritewindow.cpp @@ -11,7 +11,7 @@ /** * Constructor of the favoriteWindow class, completing its window. * @param profile The current user profile - * @param Favorite The favorite we are setting options for + * @param favorite The favorite we are setting options for * @param parent The parent window */ favoriteWindow::favoriteWindow(Profile *profile, Favorite favorite, QWidget *parent) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 4c0a849f7..a86aef7cb 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -1133,13 +1133,13 @@ void mainWindow::optionsClosed() } } -void mainWindow::setSource(const QString &source) +void mainWindow::setSource(const QString &site) { - if (!m_profile->getSites().contains(source)) + if (!m_profile->getSites().contains(site)) return; m_selectedSites.clear(); - m_selectedSites.append(m_profile->getSites().value(source)); + m_selectedSites.append(m_profile->getSites().value(site)); if (m_tabs.isEmpty()) return; @@ -1733,9 +1733,9 @@ void mainWindow::imageUrlChanged(const QString &before, const QString &after) m_downloadTime.insert(after, m_downloadTime[before]); m_downloadTime.remove(before); } -void mainWindow::getAllProgress(QSharedPointer img, qint64 bytesReceived, qint64 bytesTotal) +void mainWindow::getAllProgress(const QSharedPointer &img, qint64 bytesReceived, qint64 bytesTotal) { - QString url = img->url(); + const QString url = img->url(); if (img->fileSize() == 0) { img->setFileSize(bytesTotal); @@ -1748,15 +1748,15 @@ void mainWindow::getAllProgress(QSharedPointer img, qint64 bytesReceived, if (m_downloadTimeLast[url].elapsed() >= 1000) { m_downloadTimeLast[url].restart(); - int elapsed = m_downloadTime[url].elapsed(); - double speed = elapsed != 0 ? (bytesReceived * 1000) / elapsed : 0; + const int elapsed = m_downloadTime[url].elapsed(); + const double speed = elapsed != 0 ? (bytesReceived * 1000) / elapsed : 0; m_progressDialog->speedImage(url, speed); } int percent = 0; if (bytesTotal> 0) { - qreal pct = static_cast(bytesReceived) / static_cast(bytesTotal); + const qreal pct = static_cast(bytesReceived) / static_cast(bytesTotal); percent = qFloor(pct * 100); } @@ -1868,7 +1868,7 @@ void mainWindow::getAllGetImage(const BatchDownloadImage &download, int siteId) m_getAllImageDownloaders[img] = imgDownloader; } -void mainWindow::getAllGetImageSaved(QSharedPointer img, QMap result) +void mainWindow::getAllGetImageSaved(const QSharedPointer &img, QMap result) { // Delete ImageDownloader to prevent leaks m_getAllImageDownloaders[img]->deleteLater(); @@ -1888,7 +1888,7 @@ void mainWindow::getAllGetImageSaved(QSharedPointer img, QMap img, QMappause(); - bool isDriveFull = false; + bool isDriveFull; QString drive; #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) QDir destinationDir = QFileInfo(path).absoluteDir(); @@ -1914,6 +1914,8 @@ void mainWindow::getAllGetImageSaved(QSharedPointer img, QMap > &images); void getAllImages(); void getAllGetImage(const BatchDownloadImage &download, int siteId); - void getAllGetImageSaved(QSharedPointer img, QMap result); + void getAllGetImageSaved(const QSharedPointer &img, QMap result); void getAllPerformTags(); - void getAllProgress(QSharedPointer img, qint64, qint64); + void getAllProgress(const QSharedPointer &img, qint64 bytesReceived, qint64 bytesTotal); void getAllCancel(); void getAllPause(); void getAllSkip(); @@ -157,7 +157,7 @@ class mainWindow : public QMainWindow void dropEvent(QDropEvent* event) override; protected: - int getRowForSite(int site_id); + int getRowForSite(int siteId); void getAllGetImageIfNotBlacklisted(const BatchDownloadImage &download, int siteId); void getAllImageOk(const BatchDownloadImage &download, int siteId, bool retry = false); Site* getSelectedSiteOrDefault(); diff --git a/gui/src/settings/filenamewindow.cpp b/gui/src/settings/filenamewindow.cpp index 01ad9195a..8905c073d 100644 --- a/gui/src/settings/filenamewindow.cpp +++ b/gui/src/settings/filenamewindow.cpp @@ -107,7 +107,7 @@ void FilenameWindow::on_buttonHelpJavascript_clicked() QDesktopServices::openUrl(QUrl(QString(PROJECT_GITHUB_URL) + "/wiki/Filename#javascript")); } -QString FilenameWindow::format() +QString FilenameWindow::format() const { if (ui->radioJavascript->isChecked()) { diff --git a/gui/src/settings/filenamewindow.h b/gui/src/settings/filenamewindow.h index fbd05d509..d6e75f60f 100644 --- a/gui/src/settings/filenamewindow.h +++ b/gui/src/settings/filenamewindow.h @@ -27,7 +27,7 @@ class FilenameWindow : public QDialog public: explicit FilenameWindow(Profile *profile, QString value = "", QWidget *parent = Q_NULLPTR); ~FilenameWindow() override; - QString format(); + QString format() const; public slots: void on_lineClassic_textChanged(QString); diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index 50d66b58c..ddc7bdc1e 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -419,7 +419,7 @@ void optionsWindow::showLogFiles(QSettings *settings) connect(mapperRemoveLogFile, SIGNAL(mapped(int)), this, SLOT(removeLogFile(int))); for (auto it = logFiles.begin(); it != logFiles.end(); ++it) { - int i = it.key(); + const int i = it.key(); auto logFile = it.value(); auto *label = new QLabel(logFile["name"].toString()); @@ -584,7 +584,7 @@ void optionsWindow::removeWebService(int id) void optionsWindow::setWebService(ReverseSearchEngine rse, const QByteArray &favicon) { - bool isNew = rse.id() < 0; + const bool isNew = rse.id() < 0; // Generate new ID for new web services if (isNew) @@ -679,7 +679,7 @@ void optionsWindow::setColor(QLineEdit *lineEdit, bool button) void optionsWindow::setFont(QLineEdit *lineEdit) { bool ok = false; - QFont police = QFontDialog::getFont(&ok, lineEdit->font(), this, tr("Choose a font")); + const QFont police = QFontDialog::getFont(&ok, lineEdit->font(), this, tr("Choose a font")); if (ok) { lineEdit->setFont(police); } @@ -1042,7 +1042,7 @@ void optionsWindow::save() settings->endGroup(); // Themes - QString theme = ui->comboTheme->currentText(); + const QString theme = ui->comboTheme->currentText(); ThemeLoader themeLoader(savePath("themes/", true)); if (themeLoader.setTheme(theme)) { settings->setValue("theme", theme); } @@ -1144,8 +1144,8 @@ void optionsWindow::save() if (!useSystem) { - QNetworkProxy::ProxyType type = settings->value("Proxy/type", "http") == "http" ? QNetworkProxy::HttpProxy : QNetworkProxy::Socks5Proxy; - QNetworkProxy proxy(type, settings->value("Proxy/hostName").toString(), settings->value("Proxy/port").toInt()); + const QNetworkProxy::ProxyType type = settings->value("Proxy/type", "http") == "http" ? QNetworkProxy::HttpProxy : QNetworkProxy::Socks5Proxy; + const QNetworkProxy proxy(type, settings->value("Proxy/hostName").toString(), settings->value("Proxy/port").toInt()); QNetworkProxy::setApplicationProxy(proxy); log(QStringLiteral("Enabling application proxy on host \"%1\" and port %2.").arg(settings->value("Proxy/hostName").toString()).arg(settings->value("Proxy/port").toInt())); } @@ -1158,7 +1158,7 @@ void optionsWindow::save() log(QStringLiteral("Disabling application proxy.")); } - QString lang = ui->comboLanguages->currentData().toString(); + const QString lang = ui->comboLanguages->currentData().toString(); if (settings->value("language", "English").toString() != lang) { settings->setValue("language", lang); diff --git a/gui/src/settings/startwindow.cpp b/gui/src/settings/startwindow.cpp index 97e13630b..3a2e018a1 100644 --- a/gui/src/settings/startwindow.cpp +++ b/gui/src/settings/startwindow.cpp @@ -11,11 +11,6 @@ #include "settings/optionswindow.h" -/** - * Constructor of the startWindow class, completing its window. - * - * @param parent The parent window - */ startWindow::startWindow(Profile *profile, QWidget *parent) : QDialog(parent), ui(new Ui::startWindow), m_profile(profile) { diff --git a/gui/src/sources/sourceswindow.cpp b/gui/src/sources/sourceswindow.cpp index fae95fb59..44f1032a0 100644 --- a/gui/src/sources/sourceswindow.cpp +++ b/gui/src/sources/sourceswindow.cpp @@ -2,7 +2,6 @@ #include #include #include -#include #include #include "custom-network-access-manager.h" #include "functions.h" @@ -15,12 +14,6 @@ #include "ui/QBouton.h" -/** - * Constructor of the sourcesWindow, generating checkboxes and delete buttons - * @param selected Bool list of currently selected websites, in the alphabetical order - * @param sites QStringList of sites names - * @param parent The parent window - */ sourcesWindow::sourcesWindow(Profile *profile, const QList &selected, QWidget *parent) : QDialog(parent), ui(new Ui::sourcesWindow), m_profile(profile), m_selected(selected), m_sites(profile->getSites()), m_sources(profile->getSources()), m_checkForSourceReply(Q_NULLPTR) { diff --git a/gui/src/tabs/pool-tab.cpp b/gui/src/tabs/pool-tab.cpp index d09b10c9a..6144a9714 100644 --- a/gui/src/tabs/pool-tab.cpp +++ b/gui/src/tabs/pool-tab.cpp @@ -197,7 +197,7 @@ void poolTab::setSite(const QString &site) void poolTab::focusSearch() { - ui->spinPool->focusWidget(); + ui->spinPool->setFocus(); } QString poolTab::tags() const diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index d5cbe6164..62faa0d84 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -826,7 +826,7 @@ void searchTab::setPageLabelText(QLabel *txt, Page *page, const QList img) +QBouton *searchTab::createImageThumbnail(int position, const QSharedPointer &img) { const QColor &color = img->color(); @@ -1024,11 +1024,9 @@ void searchTab::addResultsImage(const QSharedPointer &img, Page *page, bo } // Calculate relative position compared to validated images - int relativePosition = 0; - if (merge) - { relativePosition = absolutePosition; } - else - { relativePosition = m_validImages[page].indexOf(img); } + int relativePosition = merge + ? absolutePosition + : m_validImages[page].indexOf(img); QBouton *button = createImageThumbnail(absolutePosition, img); m_boutons.insert(img.data(), button); diff --git a/gui/src/tabs/search-tab.h b/gui/src/tabs/search-tab.h index 79a06f7a4..ed8fbce54 100644 --- a/gui/src/tabs/search-tab.h +++ b/gui/src/tabs/search-tab.h @@ -57,12 +57,11 @@ class searchTab : public QWidget void setSelectedSources(QSettings *settings); void setTagsFromPages(const QMap > > &pages); void addHistory(const QString &tags, int page, int ipp, int cols); - QStringList reasonsToFail(Page *page, const QStringList &complete = QStringList(), QString *meant = nullptr); + QStringList reasonsToFail(Page *page, const QStringList &completion = QStringList(), QString *meant = Q_NULLPTR); void clear(); TextEdit *createAutocomplete(); - void loadImageThumbnails(Page *page, const QList> &imgs); void loadImageThumbnail(Page *page, QSharedPointer img, const QString &url); - QBouton *createImageThumbnail(int position, QSharedPointer img); + QBouton *createImageThumbnail(int position, const QSharedPointer &img); FixedSizeGridLayout *createImagesLayout(QSettings *settings); void thumbnailContextMenu(int position, const QSharedPointer &img); diff --git a/gui/src/tabs/tabs-loader.cpp b/gui/src/tabs/tabs-loader.cpp index 38931770a..2d1ffaec0 100644 --- a/gui/src/tabs/tabs-loader.cpp +++ b/gui/src/tabs/tabs-loader.cpp @@ -15,7 +15,7 @@ bool TabsLoader::load(const QString &path, QList &allTabs, int ¤tTab, Profile *profile, mainWindow *parent) { QSettings *settings = profile->getSettings(); - bool preload = settings->value("preloadAllTabs", false).toBool(); + const bool preload = settings->value("preloadAllTabs", false).toBool(); QFile f(path); if (!f.open(QFile::ReadOnly)) @@ -69,11 +69,11 @@ bool TabsLoader::load(const QString &path, QList &allTabs, int &curr } // Other versions are JSON-based - QByteArray data = f.readAll(); + const QByteArray data = f.readAll(); QJsonDocument loadDoc = QJsonDocument::fromJson(data); QJsonObject object = loadDoc.object(); - int version = object["version"].toInt(); + const int version = object["version"].toInt(); switch (version) { case 2: diff --git a/gui/src/tag-context-menu.cpp b/gui/src/tag-context-menu.cpp index 072e708c3..0ec815d78 100644 --- a/gui/src/tag-context-menu.cpp +++ b/gui/src/tag-context-menu.cpp @@ -7,8 +7,8 @@ #include "models/profile.h" -TagContextMenu::TagContextMenu(const QString &tag, const QList &allTags, const QUrl &browserUrl, Profile *profile, bool setImage, QWidget *parent) - : QMenu(parent), m_tag(tag), m_allTags(allTags), m_browserUrl(browserUrl), m_profile(profile) +TagContextMenu::TagContextMenu(QString tag, QList allTags, QUrl browserUrl, Profile *profile, bool setImage, QWidget *parent) + : QMenu(parent), m_tag(std::move(tag)), m_allTags(std::move(allTags)), m_browserUrl(std::move(browserUrl)), m_profile(profile) { // Favorites if (profile->getFavorites().contains(Favorite(m_tag))) @@ -100,8 +100,7 @@ void TagContextMenu::openInNewTab() } void TagContextMenu::openInNewWindow() { - QProcess myProcess; - myProcess.startDetached(qApp->arguments().at(0), QStringList(m_tag)); + QProcess::startDetached(qApp->arguments().at(0), QStringList(m_tag)); } void TagContextMenu::openInBrowser() { diff --git a/gui/src/tag-context-menu.h b/gui/src/tag-context-menu.h index 4e170a30d..74b8a7032 100644 --- a/gui/src/tag-context-menu.h +++ b/gui/src/tag-context-menu.h @@ -14,7 +14,7 @@ class TagContextMenu : public QMenu Q_OBJECT public: - TagContextMenu(const QString &tag, const QList &allTags, const QUrl &browserUrl, Profile *profile, bool setImage = false, QWidget *parent = Q_NULLPTR); + TagContextMenu(QString tag, QList allTags, QUrl browserUrl, Profile *profile, bool setImage = false, QWidget *parent = Q_NULLPTR); protected slots: void favorite(); diff --git a/gui/src/ui/QBouton.cpp b/gui/src/ui/QBouton.cpp index 9850c3104..e443e80d3 100644 --- a/gui/src/ui/QBouton.cpp +++ b/gui/src/ui/QBouton.cpp @@ -25,7 +25,7 @@ void QBouton::scale(const QPixmap &image, qreal scale) resize(size); } -QVariant QBouton::id() +QVariant QBouton::id() const { return m_id; } void QBouton::setId(const QVariant &id) { m_id = id; } @@ -53,9 +53,9 @@ void QBouton::paintEvent(QPaintEvent *event) } QPainter painter(this); - QRect region = m_smartSizeHint ? contentsRect() : event->rect(); - QSize iconSize = getIconSize(region.width(), region.height()); - int p = m_border; + const QRect region = m_smartSizeHint ? contentsRect() : event->rect(); + const QSize iconSize = getIconSize(region.width(), region.height()); + const int p = m_border; int x = region.x(); int y = region.y(); int w = iconSize.width() + 2*p; @@ -73,7 +73,7 @@ void QBouton::paintEvent(QPaintEvent *event) } // Draw image - QIcon::Mode mode = this->isChecked() ? QIcon::Selected : QIcon::Normal; + const QIcon::Mode mode = this->isChecked() ? QIcon::Selected : QIcon::Normal; if (w > h) { icon().paint(&painter, x+p, y+p, w-2*p, w-2*p, Qt::AlignLeft | Qt::AlignTop, mode); @@ -91,10 +91,10 @@ void QBouton::paintEvent(QPaintEvent *event) // Draw progress if (m_progressMax > 0 && m_progress > 0 && m_progress != m_progressMax) { - int lineHeight = 6; - int a = p + lineHeight/2; + const int lineHeight = 6; + const int a = p + lineHeight/2; - qreal ratio = static_cast(m_progress) / m_progressMax; + const qreal ratio = static_cast(m_progress) / m_progressMax; QPoint p1(qMax(x, 0) + a, qMax(y, 0) + a); QPoint p2(qFloor(p1.x() + (iconSize.width() - a) * ratio), p1.y()); @@ -130,7 +130,7 @@ void QBouton::paintEvent(QPaintEvent *event) QPainterPath path; path.addRoundedRect(notif, radius, radius); - QPen pen(Qt::black, 1); + const QPen pen(Qt::black, 1); painter.setPen(pen); painter.fillPath(path, QColor(255, 0, 0)); painter.drawPath(path); @@ -158,7 +158,7 @@ QSize QBouton::getIconSize(int regionWidth, int regionHeight, bool wOnly) const h *= coef; } - return QSize(w, h); + return { w, h }; } void QBouton::resizeEvent(QResizeEvent *event) @@ -182,11 +182,11 @@ QSize QBouton::sizeHint() const void QBouton::mousePressEvent(QMouseEvent *event) { // Ignore clicks outside the thumbnail - QSize imgSize = sizeHint(); - QSize size = this->size(); - int wMargin = (size.width() - imgSize.width()) / 2; - int hMargin = (size.height() - imgSize.height()) / 2; - QPoint pos = event->pos(); + const QSize imgSize = sizeHint(); + const QSize size = this->size(); + const int wMargin = (size.width() - imgSize.width()) / 2; + const int hMargin = (size.height() - imgSize.height()) / 2; + const QPoint pos = event->pos(); if (pos.x() < wMargin || pos.y() < hMargin || pos.x() > imgSize.width() + wMargin @@ -195,11 +195,11 @@ void QBouton::mousePressEvent(QMouseEvent *event) if (event->button() == Qt::LeftButton) { - bool ctrlPressed = event->modifiers() & Qt::ControlModifier; + const bool ctrlPressed = event->modifiers() & Qt::ControlModifier; if (ctrlPressed != m_invertToggle) { this->toggle(); - bool range = event->modifiers() & Qt::ShiftModifier; + const bool range = event->modifiers() & Qt::ShiftModifier; emit this->toggled(m_id, this->isChecked(), range); emit this->toggled(m_id.toString(), this->isChecked(), range); emit this->toggled(m_id.toInt(), this->isChecked(), range); diff --git a/gui/src/ui/QBouton.h b/gui/src/ui/QBouton.h index f0cb98e93..f2ce2ad98 100644 --- a/gui/src/ui/QBouton.h +++ b/gui/src/ui/QBouton.h @@ -11,7 +11,7 @@ class QBouton : public QPushButton public: explicit QBouton(QVariant id = 0, bool resizeInsteadOfCropping = false, bool smartSizeHint = false, int border = 0, QColor color = QColor(), QWidget *parent = Q_NULLPTR); - QVariant id(); + QVariant id() const; void mousePressEvent(QMouseEvent *event) override; QSize sizeHint() const override; void resizeEvent(QResizeEvent *event) override; diff --git a/gui/src/ui/fixed-size-grid-layout.cpp b/gui/src/ui/fixed-size-grid-layout.cpp index a86e3c3a4..2d3346d21 100644 --- a/gui/src/ui/fixed-size-grid-layout.cpp +++ b/gui/src/ui/fixed-size-grid-layout.cpp @@ -3,11 +3,11 @@ FixedSizeGridLayout::FixedSizeGridLayout(QWidget *parent, int hSpacing, int vSpacing) - : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) + : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing), m_fixedWidth(150) {} FixedSizeGridLayout::FixedSizeGridLayout(int hSpacing, int vSpacing) - : m_hSpace(hSpacing), m_vSpace(vSpacing) + : m_hSpace(hSpacing), m_vSpace(vSpacing), m_fixedWidth(150) {} FixedSizeGridLayout::~FixedSizeGridLayout() @@ -92,8 +92,7 @@ bool FixedSizeGridLayout::hasHeightForWidth() const int FixedSizeGridLayout::heightForWidth(int width) const { - int height = doLayout(QRect(0, 0, width, 0), true); - return height; + return doLayout(QRect(0, 0, width, 0), true); } QSize FixedSizeGridLayout::minimumSize() const @@ -133,8 +132,8 @@ int FixedSizeGridLayout::doLayout(QRect rect, bool testOnly) const int spaceX = widgetSpacing(horizontalSpacing(), item->widget(), Qt::Horizontal); int spaceY = widgetSpacing(verticalSpacing(), item->widget(), Qt::Vertical); - int nbElements = qMax(1, (w + spaceX) / (m_fixedWidth + spaceX)); - int totalSpace = w - (m_fixedWidth * nbElements); + const int nbElements = qMax(1, (w + spaceX) / (m_fixedWidth + spaceX)); + const int totalSpace = w - (m_fixedWidth * nbElements); spaceX = qMax(spaceX, totalSpace / qMax(1, nbElements - 1)); int nextX = x + item->sizeHint().width() + spaceX; diff --git a/gui/src/ui/textedit.cpp b/gui/src/ui/textedit.cpp index 2a78ca22f..ace8d22f9 100644 --- a/gui/src/ui/textedit.cpp +++ b/gui/src/ui/textedit.cpp @@ -7,7 +7,6 @@ #include #include #include "functions.h" -#include "logger.h" #include "models/profile.h" @@ -27,9 +26,9 @@ TextEdit::TextEdit(Profile *profile, QWidget *parent) QSize TextEdit::sizeHint() const { QFontMetrics fm(font()); - int h = qMax(fm.height(), 14) + 4; - int w = fm.width(QLatin1Char('x')) * 17 + 4; - QStyleOptionFrameV2 opt; + const int h = qMax(fm.height(), 14) + 4; + const int w = fm.width(QLatin1Char('x')) * 17 + 4; + QStyleOptionFrame opt; opt.initFrom(this); return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).expandedTo(QApplication::globalStrut()), this)); } @@ -53,16 +52,16 @@ void TextEdit::doColor() // Color favorite tags QFont fontFavorites; fontFavorites.fromString(m_profile->getSettings()->value("Coloring/Fonts/favorites").toString()); - QString colorFavorites = m_profile->getSettings()->value("Coloring/Colors/favorites", "#ffc0cb").toString(); - QString styleFavorites = "color:" + colorFavorites + "; " + qFontToCss(fontFavorites); + const QString colorFavorites = m_profile->getSettings()->value("Coloring/Colors/favorites", "#ffc0cb").toString(); + const QString styleFavorites = "color:" + colorFavorites + "; " + qFontToCss(fontFavorites); for (const Favorite &fav : m_favorites) txt.replace(" "+fav.getName()+" ", " "+fav.getName()+" "); // Color kept for later tags QFont fontKeptForLater; fontKeptForLater.fromString(m_profile->getSettings()->value("Coloring/Fonts/keptForLater").toString()); - QString colorKeptForLater = m_profile->getSettings()->value("Coloring/Colors/keptForLater", "#000000").toString(); - QString styleKeptForLater = "color:" + colorKeptForLater + "; " + qFontToCss(fontKeptForLater); + const QString colorKeptForLater = m_profile->getSettings()->value("Coloring/Colors/keptForLater", "#000000").toString(); + const QString styleKeptForLater = "color:" + colorKeptForLater + "; " + qFontToCss(fontKeptForLater); for (const QString &tag : m_viewItLater) txt.replace(" "+tag+" ", " "+tag+" "); @@ -81,22 +80,22 @@ void TextEdit::doColor() // Replace spaces to not be trimmed by the HTML renderer txt = txt.mid(1, txt.length() - 2); int depth = 0; - for (int i = 0; i < txt.length(); ++i) + for (QChar &ch : txt) { - if (txt[i] == ' ' && depth == 0) - txt[i] = QChar(29); - else if (txt[i] == '<') + if (ch == ' ' && depth == 0) + ch = QChar(29); + else if (ch == '<') depth++; - else if (txt[i] == '>') + else if (ch == '>') depth--; } txt.replace(QChar(29), " "); // Setup cursor QTextCursor crsr = textCursor(); - int pos = crsr.columnNumber(); - int start = crsr.selectionStart(); - int end = crsr.selectionEnd(); + const int pos = crsr.columnNumber(); + const int start = crsr.selectionStart(); + const int end = crsr.selectionEnd(); setHtml(txt); //If the cursor is at the right side of (if any) selected text @@ -151,7 +150,7 @@ void TextEdit::insertCompletion(const QString& completion) return; QTextCursor tc = textCursor(); - int extra = completion.length() - c->completionPrefix().length(); + const int extra = completion.length() - c->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); @@ -162,9 +161,9 @@ QString TextEdit::textUnderCursor() const { QTextCursor tc = textCursor(); QString txt = ' ' + toPlainText() + ' '; - int pos = tc.position(); - int i2 = txt.indexOf(' ', pos); - int i1 = txt.lastIndexOf(' ', i2 - 1) + 1; + const int pos = tc.position(); + const int i2 = txt.indexOf(' ', pos); + const int i1 = txt.lastIndexOf(' ', i2 - 1) + 1; return txt.mid(i1, i2 - i1); } @@ -204,7 +203,7 @@ void TextEdit::keyPressEvent(QKeyEvent *e) } } - bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Space); // CTRL+Space + const bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Space); // CTRL+Space if (!c || !isShortcut) // do not process the shortcut when we have a completer { if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) @@ -221,7 +220,7 @@ void TextEdit::keyPressEvent(QKeyEvent *e) return; static QString eow(" "); - bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; + const bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 || eow.contains(e->text().right(1)))) diff --git a/gui/src/ui/textedit.h b/gui/src/ui/textedit.h index 54f362a15..983752a8d 100644 --- a/gui/src/ui/textedit.h +++ b/gui/src/ui/textedit.h @@ -14,7 +14,7 @@ class TextEdit : public QTextEdit public: explicit TextEdit(Profile *profile, QWidget *parent = Q_NULLPTR); - void setCompleter(QCompleter *c); + void setCompleter(QCompleter *completer); QCompleter *completer() const; QSize sizeHint() const override; void doColor(); diff --git a/gui/src/ui/verticalscrollarea.h b/gui/src/ui/verticalscrollarea.h index ba84af940..f249056b1 100644 --- a/gui/src/ui/verticalscrollarea.h +++ b/gui/src/ui/verticalscrollarea.h @@ -14,7 +14,7 @@ class VerticalScrollArea : public QScrollArea explicit VerticalScrollArea(QWidget *parent = Q_NULLPTR); void resizeEvent(QResizeEvent *event) override; void setScrollEnabled(bool enabled); - void wheelEvent(QWheelEvent* event) override; + void wheelEvent(QWheelEvent* e) override; protected: void updateWidgetSize(); diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp index dff8a7185..e87aa7340 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp +++ b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp @@ -61,7 +61,7 @@ void BlacklistFix2::on_buttonOk_clicked() { // Delete selected images QList selected = ui->tableWidget->selectedItems(); - int count = selected.size(); + const int count = selected.size(); QSet toDelete = QSet(); for (int i = 0; i < count; i++) { toDelete.insert(selected.at(i)->row()); } diff --git a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.cpp b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.cpp index 8dda48a75..26a541ce0 100644 --- a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.cpp +++ b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.cpp @@ -42,7 +42,7 @@ void EmptyDirsFix2::deleteSel() return; } - int response = QMessageBox::question(this, tr("Empty folders fixer"), tr("You are about to delete %n folder. Are you sure you want to continue?", "", folders.size()), QMessageBox::Yes | QMessageBox::No); + const int response = QMessageBox::question(this, tr("Empty folders fixer"), tr("You are about to delete %n folder. Are you sure you want to continue?", "", folders.size()), QMessageBox::Yes | QMessageBox::No); if (response == QMessageBox::Yes) { for (int i = 0; i < folders.size(); i++) diff --git a/gui/src/utils/md5-fix/md5-fix.cpp b/gui/src/utils/md5-fix/md5-fix.cpp index 173bd7788..c4d8ca448 100644 --- a/gui/src/utils/md5-fix/md5-fix.cpp +++ b/gui/src/utils/md5-fix/md5-fix.cpp @@ -75,8 +75,8 @@ void md5Fix::on_buttonStart_clicked() // Parse all files for (const auto &file : files) { - QString fileName = file.first; - QString path = dir.absoluteFilePath(fileName); + const QString fileName = file.first; + const QString path = dir.absoluteFilePath(fileName); QString md5; if (ui->radioForce->isChecked()) diff --git a/gui/src/utils/rename-existing/rename-existing-1.cpp b/gui/src/utils/rename-existing/rename-existing-1.cpp index dcbf46eaa..0e0ba3835 100644 --- a/gui/src/utils/rename-existing/rename-existing-1.cpp +++ b/gui/src/utils/rename-existing/rename-existing-1.cpp @@ -14,7 +14,7 @@ RenameExisting1::RenameExisting1(Profile *profile, QWidget *parent) - : QDialog(parent), ui(new Ui::RenameExisting1), m_profile(profile), m_sites(profile->getSites()) + : QDialog(parent), ui(new Ui::RenameExisting1), m_profile(profile), m_sites(profile->getSites()), m_needDetails(false) { ui->setupUi(this); @@ -74,8 +74,8 @@ void RenameExisting1::on_buttonContinue_clicked() // Parse all files for (const auto &file : files) { - QString fileName = file.first; - QString path = dir.absoluteFilePath(fileName); + const QString fileName = file.first; + const QString path = dir.absoluteFilePath(fileName); QString md5; if (ui->radioForce->isChecked()) @@ -127,7 +127,7 @@ void RenameExisting1::on_buttonContinue_clicked() m_filename.setFormat(ui->lineFilenameDestination->text()); m_needDetails = m_filename.needExactTags(m_sites.value(ui->comboSource->currentText())); - int response = QMessageBox::question(this, tr("Rename existing images"), tr("You are about to download information from %n image(s). Are you sure you want to continue?", "", m_details.size()), QMessageBox::Yes | QMessageBox::No); + const int response = QMessageBox::question(this, tr("Rename existing images"), tr("You are about to download information from %n image(s). Are you sure you want to continue?", "", m_details.size()), QMessageBox::Yes | QMessageBox::No); if (response == QMessageBox::Yes) { // Show progress bar @@ -147,7 +147,7 @@ void RenameExisting1::getAll(Page *p) { if (!p->images().isEmpty()) { - QSharedPointer img = p->images().at(0); + const QSharedPointer img = p->images().at(0); if (m_needDetails) { @@ -181,7 +181,7 @@ void RenameExisting1::loadNext() { if (!m_details.isEmpty()) { - RenameExistingFile det = m_details.takeFirst(); + const RenameExistingFile det = m_details.takeFirst(); m_getAll.insert(det.md5, det); Page *page = new Page(m_profile, m_sites.value(ui->comboSource->currentText()), m_sites.values(), QStringList("md5:" + det.md5), 1, 1); diff --git a/gui/src/utils/rename-existing/rename-existing-2.cpp b/gui/src/utils/rename-existing/rename-existing-2.cpp index 477d209e5..2ebaf8d71 100644 --- a/gui/src/utils/rename-existing/rename-existing-2.cpp +++ b/gui/src/utils/rename-existing/rename-existing-2.cpp @@ -10,13 +10,13 @@ RenameExisting2::RenameExisting2(QList details, QString fold { ui->setupUi(this); - bool thumbnails = details.count() < 50; + const bool showThumbnails = details.count() < 50; int i = 0; ui->tableWidget->setRowCount(m_details.size()); for (const RenameExistingFile &image : m_details) { - if (thumbnails) + if (showThumbnails) { QLabel *preview = new QLabel(); preview->setPixmap(QPixmap(image.path).scaledToHeight(50, Qt::SmoothTransformation)); @@ -35,7 +35,7 @@ RenameExisting2::RenameExisting2(QList details, QString fold headerView->setSectionResizeMode(1, QHeaderView::Stretch); headerView->setSectionResizeMode(2, QHeaderView::Stretch); - if (!thumbnails) + if (!showThumbnails) ui->tableWidget->removeColumn(0); } @@ -60,7 +60,7 @@ void RenameExisting2::deleteDir(const QString &path) { directory.removeRecursively(); - QString parent = path.left(path.lastIndexOf(QDir::separator())); + const QString parent = path.left(path.lastIndexOf(QDir::separator())); deleteDir(parent); } } @@ -71,7 +71,7 @@ void RenameExisting2::on_buttonOk_clicked() for (const RenameExistingFile &image : m_details) { // Create hierarchy - QString path = image.newPath.left(image.newPath.lastIndexOf(QDir::separator())); + const QString path = image.newPath.left(image.newPath.lastIndexOf(QDir::separator())); QDir directory(path); if (!directory.exists()) { @@ -84,12 +84,12 @@ void RenameExisting2::on_buttonOk_clicked() QFile::rename(image.path, image.newPath); for (const QString &child : image.children) { - QString newPath = QString(child).replace(image.path, image.newPath); + const QString newPath = QString(child).replace(image.path, image.newPath); QFile::rename(child, newPath); } // Delete old path if necessary - QString oldDir = image.path.left(image.path.lastIndexOf(QDir::separator())); + const QString oldDir = image.path.left(image.path.lastIndexOf(QDir::separator())); deleteDir(oldDir); } diff --git a/gui/src/viewer/details-window.cpp b/gui/src/viewer/details-window.cpp index 7d833b4a5..6c9e8c394 100644 --- a/gui/src/viewer/details-window.cpp +++ b/gui/src/viewer/details-window.cpp @@ -28,7 +28,7 @@ void DetailsWindow::setImage(const QSharedPointer &image) } else { - auto label = new QLabel(QString("%1").arg(row.first), this); + const auto label = new QLabel(QString("%1").arg(row.first), this); auto field = new QLabel(row.second, this); field->setWordWrap(true); field->setOpenExternalLinks(true); diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 3e3a895de..9b1a66e9c 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -26,7 +26,7 @@ ZoomWindow::ZoomWindow(QList> images, const QSharedPointer &image, Site *site, Profile *profile, mainWindow *parent) - : QWidget(Q_NULLPTR, Qt::Window), m_parent(parent), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()), m_ignore(profile->getIgnored()), m_settings(profile->getSettings()), ui(new Ui::ZoomWindow), m_site(site), m_timeout(300), m_tooBig(false), m_loadedImage(false), m_loadedDetails(false), m_displayImage(QPixmap()), m_displayMovie(Q_NULLPTR), m_finished(false), m_size(0), m_source(), m_fullScreen(nullptr), m_images(std::move(images)), m_isFullscreen(false), m_isSlideshowRunning(false), m_imagePath(""), m_labelImageScaled(false) + : QWidget(Q_NULLPTR, Qt::Window), m_parent(parent), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()), m_ignore(profile->getIgnored()), m_settings(profile->getSettings()), ui(new Ui::ZoomWindow), m_site(site), m_timeout(300), m_tooBig(false), m_loadedImage(false), m_loadedDetails(false), m_finished(false), m_size(0), m_fullScreen(nullptr), m_isFullscreen(false), m_isSlideshowRunning(false), m_images(std::move(images)), m_displayImage(QPixmap()), m_displayMovie(Q_NULLPTR), m_labelImageScaled(false) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); @@ -303,23 +303,24 @@ void ZoomWindow::openSaveDir(bool fav) } else { - QString path = m_settings->value("Save/path"+QString(fav ? "_favorites" : "")).toString().replace("\\", "/"), fn = m_settings->value("Save/filename"+QString(fav ? "_favorites" : "")).toString(); + QString path = m_settings->value("Save/path" + QString(fav ? "_favorites" : "")).toString().replace("\\", "/"); + const QString fn = m_settings->value("Save/filename" + QString(fav ? "_favorites" : "")).toString(); if (path.right(1) == "/") { path = path.left(path.length()-1); } path = QDir::toNativeSeparators(path); - QStringList files = m_image->path(fn, path); - QString file = files.empty() ? QString() : files.at(0); - QString pth = file.section(QDir::separator(), 0, -2); - QString url = path + QDir::separator() + pth; + const QStringList files = m_image->path(fn, path); + const QString file = files.empty() ? QString() : files.at(0); + const QString pth = file.section(QDir::separator(), 0, -2); + const QString url = path + QDir::separator() + pth; QDir dir(url); if (dir.exists()) { showInGraphicalShell(url); } else { - int reply = QMessageBox::question(this, tr("Folder does not exist"), tr("The save folder does not exist yet. Create it?"), QMessageBox::Yes | QMessageBox::No); + const int reply = QMessageBox::question(this, tr("Folder does not exist"), tr("The save folder does not exist yet. Create it?"), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { QDir rootDir(path); @@ -357,7 +358,7 @@ void ZoomWindow::setfavorite() return; Favorite fav(m_link); - int pos = m_favorites.indexOf(fav); + const int pos = m_favorites.indexOf(fav); if (pos >= 0) { m_favorites[pos].setImage(m_displayImage); @@ -394,7 +395,7 @@ void ZoomWindow::load(bool force) m_image->loadImage(true, force); } -#define PERCENT 0.05f +#define PERCENT 0.05 #define TIME 500 void ZoomWindow::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { @@ -402,7 +403,7 @@ void ZoomWindow::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) ui->progressBarDownload->setValue(bytesReceived); const bool isAnimated = m_image->isVideo() || !m_isAnimated.isEmpty(); - if (!isAnimated && (m_imageTime.elapsed() > TIME || (bytesTotal > 0 && bytesReceived / bytesTotal > PERCENT))) + if (!isAnimated && (m_imageTime.elapsed() > TIME || (bytesTotal > 0 && static_cast(bytesReceived) / bytesTotal > PERCENT))) { m_imageTime.restart(); emit loadImage(m_image->data()); @@ -446,8 +447,8 @@ void ZoomWindow::replyFinishedDetails() m_isAnimated = m_image->isAnimated(); - QString path1 = m_settings->value("Save/path").toString().replace("\\", "/"); - QStringList pth1s = m_image->path(m_settings->value("Save/filename").toString(), path1, 0, true, false, true, true, true); + const QString path1 = m_settings->value("Save/path").toString().replace("\\", "/"); + const QStringList pth1s = m_image->path(m_settings->value("Save/filename").toString(), path1, 0, true, false, true, true, true); QString source1; bool file1notexists = false; for (const QString &pth1 : pth1s) @@ -459,8 +460,8 @@ void ZoomWindow::replyFinishedDetails() file1notexists = true; } - QString path2 = m_settings->value("Save/path_favorites").toString().replace("\\", "/"); - QStringList pth2s = m_image->path(m_settings->value("Save/filename_favorites").toString(), path2, 0, true, false, true, true, true); + const QString path2 = m_settings->value("Save/path_favorites").toString().replace("\\", "/"); + const QStringList pth2s = m_image->path(m_settings->value("Save/filename_favorites").toString(), path2, 0, true, false, true, true, true); QString source2; bool file2notexists = false; for (const QString &pth2 : pth2s) @@ -482,12 +483,12 @@ void ZoomWindow::replyFinishedDetails() log(QStringLiteral("Image loaded from the file %1").arg(m_source)); // Update save button state - SaveButtonState md5State = !md5Exists.isEmpty() ? SaveButtonState::ExistsMd5 : SaveButtonState::Save; + const SaveButtonState md5State = !md5Exists.isEmpty() ? SaveButtonState::ExistsMd5 : SaveButtonState::Save; setButtonState(false, !file1notexists ? SaveButtonState::ExistsDisk : md5State); setButtonState(true, !file2notexists ? SaveButtonState::ExistsDisk : md5State); // Fix extension when it should be guessed - QString fext = m_source.section('.', -1); + const QString fext = m_source.section('.', -1); m_url = m_url.section('.', 0, -2) + "." + fext; m_image->setFileExtension(fext); @@ -511,7 +512,7 @@ void ZoomWindow::replyFinishedDetails() void ZoomWindow::colore() { QStringList t = TagStylist(m_profile).stylished(m_image->tags(), m_settings->value("Zoom/showTagCount", false).toBool(), false, m_settings->value("Zoom/tagOrder", "type").toString()); - QString tags = t.join(' '); + const QString tags = t.join(' '); if (ui->widgetLeft->isHidden()) { m_labelTagsTop->setText(tags); } @@ -642,7 +643,7 @@ void ZoomWindow::pendingUpdate() // If the image is loaded but we need their tags and we don't have them, we wait if (m_mustSave != 6) { - bool fav = (m_mustSave == 3 || m_mustSave == 4); + const bool fav = (m_mustSave == 3 || m_mustSave == 4); Filename fn(m_settings->value("Save/path" + QString(fav ? "_favorites" : "")).toString()); if (!m_loadedDetails && fn.needExactTags(m_site)) @@ -687,7 +688,7 @@ void ZoomWindow::draw() if (m_image->isVideo()) return; - QString fn = m_url.section('/', -1).section('?', 0, 0).toLower(); + const QString fn = m_url.section('/', -1).section('?', 0, 0).toLower(); // We need a filename to display animations, so we get it if we're not already loading from a file QString filename; @@ -763,10 +764,10 @@ void ZoomWindow::update(bool onlySize, bool force) if (m_displayImage.isNull()) return; - bool needScaling = (m_displayImage.width() > m_labelImage->width() || m_displayImage.height() > m_labelImage->height()); + const bool needScaling = (m_displayImage.width() > m_labelImage->width() || m_displayImage.height() > m_labelImage->height()); if (needScaling && (onlySize || m_loadedImage || force)) { - Qt::TransformationMode mode = onlySize ? Qt::FastTransformation : Qt::SmoothTransformation; + const Qt::TransformationMode mode = onlySize ? Qt::FastTransformation : Qt::SmoothTransformation; m_labelImage->setImage(m_displayImage.scaled(m_labelImage->width(), m_labelImage->height(), Qt::KeepAspectRatio, mode)); m_labelImageScaled = true; } @@ -781,11 +782,11 @@ void ZoomWindow::update(bool onlySize, bool force) Qt::Alignment ZoomWindow::getAlignments(const QString &type) { - QString vertical = m_settings->value(type + "V", "center").toString(); - QString horizontal = m_settings->value(type + "H", "left").toString(); + const QString vertical = m_settings->value(type + "V", "center").toString(); + const QString horizontal = m_settings->value(type + "H", "left").toString(); - Qt::Alignment vAlign = vertical == "top" ? Qt::AlignTop : (vertical == "bottom" ? Qt::AlignBottom : Qt::AlignVCenter); - Qt::Alignment hAlign = horizontal == "left" ? Qt::AlignLeft : (horizontal == "right" ? Qt::AlignRight : Qt::AlignHCenter); + const Qt::Alignment vAlign = vertical == "top" ? Qt::AlignTop : (vertical == "bottom" ? Qt::AlignBottom : Qt::AlignVCenter); + const Qt::Alignment hAlign = horizontal == "left" ? Qt::AlignLeft : (horizontal == "right" ? Qt::AlignRight : Qt::AlignHCenter); return vAlign | hAlign; } @@ -817,7 +818,7 @@ void ZoomWindow::saveNQuitFav() void ZoomWindow::saveImage(bool fav) { - SaveButtonState state = fav ? m_saveButonStateFav : m_saveButonState; + const SaveButtonState state = fav ? m_saveButonStateFav : m_saveButonState; switch (state) { case SaveButtonState::Save: @@ -882,7 +883,7 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) for (auto it = results.begin(); it != results.end(); ++it) { - Image::SaveResult res = it.value(); + const Image::SaveResult res = it.value(); paths.append(it.key()); m_imagePath = it.key(); @@ -912,7 +913,6 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) default: error(this, tr("Error saving image.")); return QStringList(); - break; } } @@ -925,10 +925,10 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) void ZoomWindow::saveImageAs() { - Filename format(m_settings->value("Save/filename").toString()); - QStringList filenames = format.path(*m_image, m_profile); - QString filename = filenames.first().section(QDir::separator(), -1); - QString lastDir = m_settings->value("Zoom/lastDir", "").toString(); + const Filename format(m_settings->value("Save/filename").toString()); + const QStringList filenames = format.path(*m_image, m_profile); + const QString filename = filenames.first().section(QDir::separator(), -1); + const QString lastDir = m_settings->value("Zoom/lastDir", "").toString(); QString path = QFileDialog::getSaveFileName(this, tr("Save image"), QDir::toNativeSeparators(lastDir + "/" + filename), "Images (*.png *.gif *.jpg *.jpeg)"); if (!path.isEmpty()) @@ -956,7 +956,6 @@ void ZoomWindow::fullScreen() if (!m_loadedImage && m_displayMovie == nullptr) return; - QWidget *widget; m_fullScreen = new QAffiche(QVariant(), 0, QColor(), this); m_fullScreen->setStyleSheet("background-color: black"); m_fullScreen->setAlignment(Qt::AlignCenter); @@ -968,7 +967,7 @@ void ZoomWindow::fullScreen() m_fullScreen->showFullScreen(); connect(m_fullScreen, SIGNAL(doubleClicked()), this, SLOT(unfullScreen())); - widget = m_fullScreen; + QWidget *widget = m_fullScreen; m_isFullscreen = true; prepareNextSlide(); @@ -1005,16 +1004,16 @@ void ZoomWindow::prepareNextSlide() return; // If the slideshow is disabled - int interval = m_settings->value("slideshow", 0).toInt(); + const int interval = m_settings->value("slideshow", 0).toInt(); if (interval <= 0) return; // We make sure to wait to see the whole displayed item - qint64 additionalInterval = 0; - if (!m_isAnimated.isEmpty()) - additionalInterval = m_displayMovie->nextFrameDelay() * m_displayMovie->frameCount(); + const qint64 additionalInterval = !m_isAnimated.isEmpty() + ? m_displayMovie->nextFrameDelay() * m_displayMovie->frameCount() + : 0; - qint64 totalInterval = interval * 1000 + additionalInterval; + const qint64 totalInterval = interval * 1000 + additionalInterval; m_slideshow.start(totalInterval); m_isSlideshowRunning = true; } @@ -1074,7 +1073,7 @@ void ZoomWindow::showThumbnail() if (size.width() > maxSize.width() || size.height() > maxSize.height()) { size.scale(maxSize, Qt::KeepAspectRatio); } - QPixmap base = m_image->previewImage(); + const QPixmap &base = m_image->previewImage(); QPixmap overlay = QPixmap(":/images/play-overlay.png"); QPixmap result(size.width(), size.height()); result.fill(Qt::transparent); @@ -1137,11 +1136,11 @@ void ZoomWindow::load(const QSharedPointer &image) { showThumbnail(); } // Preload gallery images - int preload = m_settings->value("preload", 0).toInt(); + const int preload = m_settings->value("preload", 0).toInt(); if (preload > 0) { QSet preloaded; - int index = m_images.indexOf(m_image); + const int index = m_images.indexOf(m_image); for (int i = index - preload; i <= index + preload; ++i) { int pos = (i + m_images.count()) % m_images.count(); @@ -1193,7 +1192,7 @@ void ZoomWindow::updateWindowTitle() int ZoomWindow::firstNonBlacklisted(int direction) { int index = m_images.indexOf(m_image); - int first = index; + const int first = index; index = (index + m_images.count() + direction) % m_images.count(); // Skip blacklisted images @@ -1210,7 +1209,7 @@ void ZoomWindow::next() m_image->abortTags(); m_image->abortImage(); - int index = firstNonBlacklisted(+1); + const int index = firstNonBlacklisted(+1); load(m_images[index]); } @@ -1219,7 +1218,7 @@ void ZoomWindow::previous() m_image->abortTags(); m_image->abortImage(); - int index = firstNonBlacklisted(-1); + const int index = firstNonBlacklisted(-1); load(m_images[index]); } @@ -1271,7 +1270,7 @@ void ZoomWindow::wheelEvent(QWheelEvent *e) e->ignore(); m_lastWheelEvent.start(); - int angle = e->angleDelta().y(); + const int angle = e->angleDelta().y(); if (angle <= -120) // Scroll down { next(); diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index b0deb2a22..3d8ec358b 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -72,7 +72,7 @@ class ZoomWindow : public QWidget void updateButtonPlus(); void openFile(bool now = false); void updateWindowTitle(); - void showLoadingError(const QString &error); + void showLoadingError(const QString &message); void setButtonState(bool fav, SaveButtonState state); void reuse(const QList> &images, const QSharedPointer &image, Site *site); diff --git a/lib/src/downloader/download-query-group.cpp b/lib/src/downloader/download-query-group.cpp index 8e207f8ab..d29e6bc29 100644 --- a/lib/src/downloader/download-query-group.cpp +++ b/lib/src/downloader/download-query-group.cpp @@ -11,8 +11,8 @@ DownloadQueryGroup::DownloadQueryGroup(QSettings *settings, QString tags, int pa path = settings->value("Save/path").toString(); } -DownloadQueryGroup::DownloadQueryGroup(QString tags, int page, int perPage, int total, QStringList postFiltering, bool blacklisted, Site *site, const QString &filename, const QString &path, QString unk) - : DownloadQuery(site, filename, path), tags(std::move(tags)), page(page), perpage(perPage), total(total), postFiltering(std::move(postFiltering)), getBlacklisted(blacklisted), unk(std::move(unk)) +DownloadQueryGroup::DownloadQueryGroup(QString tags, int page, int perPage, int total, QStringList postFiltering, bool getBlacklisted, Site *site, const QString &filename, const QString &path, QString unk) + : DownloadQuery(site, filename, path), tags(std::move(tags)), page(page), perpage(perPage), total(total), postFiltering(std::move(postFiltering)), getBlacklisted(getBlacklisted), unk(std::move(unk)) { } diff --git a/lib/src/downloader/download-query.h b/lib/src/downloader/download-query.h index 39e9a23f0..adad96aa2 100644 --- a/lib/src/downloader/download-query.h +++ b/lib/src/downloader/download-query.h @@ -12,6 +12,7 @@ class DownloadQuery public: // Constructors DownloadQuery() = default; + virtual ~DownloadQuery() = default; explicit DownloadQuery(Site *site); explicit DownloadQuery(Site *site, QString filename, QString path); diff --git a/lib/src/downloader/downloader.h b/lib/src/downloader/downloader.h index 80c0d4a1a..d9096b280 100644 --- a/lib/src/downloader/downloader.h +++ b/lib/src/downloader/downloader.h @@ -55,7 +55,7 @@ class Downloader : public QObject void finishedLoadingPageTags(Page *page); void finishedLoadingImages(Page *page); void finishedLoadingUrls(Page *page); - void finishedLoadingImage(const QSharedPointer &img, const QMap &result); + void finishedLoadingImage(const QSharedPointer &image, const QMap &result); void cancel(); void clear(); diff --git a/lib/src/downloader/extension-rotator.cpp b/lib/src/downloader/extension-rotator.cpp index b3a780f68..6f9864576 100644 --- a/lib/src/downloader/extension-rotator.cpp +++ b/lib/src/downloader/extension-rotator.cpp @@ -21,11 +21,6 @@ ExtensionRotator::ExtensionRotator(const QString &initialExtension, const QStrin m_next = index + 1; } -ExtensionRotator::~ExtensionRotator() -{ - m_extensions.clear(); -} - QString ExtensionRotator::next() { // Always return an empty string for empty lists diff --git a/lib/src/downloader/extension-rotator.h b/lib/src/downloader/extension-rotator.h index 6582254dc..79c0e2ae5 100644 --- a/lib/src/downloader/extension-rotator.h +++ b/lib/src/downloader/extension-rotator.h @@ -14,7 +14,6 @@ class ExtensionRotator : public QObject ExtensionRotator() = default; explicit ExtensionRotator(const ExtensionRotator &other); explicit ExtensionRotator(const QString &initialExtension, const QStringList &extensions, QObject *parent = Q_NULLPTR); - ~ExtensionRotator(); QString next(); private: diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index ca352eb95..3ddf4751c 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -330,7 +330,7 @@ bool setFileCreationDate(const QString &path, const QDateTime &datetime) auto *filename = new wchar_t[path.length() + 1]; path.toWCharArray(filename); filename[path.length()] = 0; - const HANDLE hfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE hfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); delete[] filename; if (hfile == INVALID_HANDLE_VALUE) { @@ -341,7 +341,7 @@ bool setFileCreationDate(const QString &path, const QDateTime &datetime) { const LONGLONG ll = Int32x32To64(datetime.toTime_t(), 10000000) + 116444736000000000; FILETIME pcreationtime; - pcreationtime.dwLowDateTime = (DWORD) ll; + pcreationtime.dwLowDateTime = static_cast(ll); pcreationtime.dwHighDateTime = ll >> 32; if (!SetFileTime(hfile, &pcreationtime, NULL, &pcreationtime)) @@ -699,7 +699,7 @@ QString parseMarkdown(QString str) // Issue links static const QRegularExpression issueLinks("(issue|fix) #(\\d+)"); - str.replace(issueLinks, "\\1 #\\2"); + str.replace(issueLinks, "\1 #\2)"); // Line breaks to HTML str.replace("\n", "
    "); diff --git a/lib/src/functions.cpp~RF155d15f.TMP b/lib/src/functions.cpp~RF155d15f.TMP new file mode 100644 index 000000000..5b130a079 --- /dev/null +++ b/lib/src/functions.cpp~RF155d15f.TMP @@ -0,0 +1,832 @@ +#include "functions.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef Q_OS_WIN + #include +#else + #include +#endif +#ifdef QT_DEBUG + #include +#endif +#include "vendor/html-entities.h" + + +/** + * Load custom tokens from settings. + * @return The map with token names as keys and token tags as values. + */ +QMap getCustoms(QSettings *settings) +{ + QMap tokens; + settings->beginGroup(QStringLiteral("Save/Customs")); + QStringList keys = settings->childKeys(); + for (int i = 0; i < keys.size(); i++) + { tokens.insert(keys.at(i), settings->value(keys.at(i)).toString().split(' ')); } + settings->endGroup(); + return tokens; +} + +/** + * Load multiple filenames from settings. + * @return The map with token names as keys and token tags as values. + */ +QMap> getFilenames(QSettings *settings) +{ + QMap> tokens; + + settings->beginGroup(QStringLiteral("Filenames")); + const int count = settings->childKeys().count() / 3; + for (int i = 0; i < count; i++) + { + if (settings->contains(QString::number(i) + "_cond")) + { + QPair pair; + pair.first = settings->value(QString::number(i) + "_fn").toString(); + pair.second = settings->value(QString::number(i) + "_dir").toString(); + tokens.insert(settings->value(QString::number(i) + "_cond").toString(), pair); + } + } + settings->endGroup(); + + return tokens; +} + +QMap> getExternalLogFiles(QSettings *settings) +{ + QMap> ret; + + settings->beginGroup(QStringLiteral("LogFiles")); + for (const QString &group : settings->childGroups()) + { + settings->beginGroup(group); + QMap logSettings; + for (const QString &key : settings->childKeys()) + { logSettings.insert(key, settings->value(key)); } + ret.insert(group.toInt(), logSettings); + settings->endGroup(); + } + settings->endGroup(); + + return ret; +} +QStringList getExternalLogFilesSuffixes(QSettings *settings) +{ + QStringList suffixes; + + auto logFiles = getExternalLogFiles(settings); + for (auto it = logFiles.begin(); it != logFiles.end(); ++it) + { + const QMap &logFile = it.value(); + if (logFile["locationType"].toInt() == 2) + { suffixes.append(logFile["suffix"].toString()); } + } + + return suffixes; +} + +QStringList removeWildards(const QStringList &elements, const QStringList &remove) +{ + QStringList tags; + + QRegExp reg; + reg.setCaseSensitivity(Qt::CaseInsensitive); + reg.setPatternSyntax(QRegExp::Wildcard); + for (const QString &tag : elements) + { + bool removed = false; + for (const QString &rem : remove) + { + reg.setPattern(rem); + if (reg.exactMatch(tag)) + { + removed = true; + break; + } + } + + if (!removed) + tags.append(tag); + } + + return tags; +} + +/** + * Convert a danbooru-like date (Sat May 14 17:38:04 -0400 2011) to a valid QDateTime. + * @param str The date string. + * @return The converted date as a QDateTime. + */ +QDateTime qDateTimeFromString(const QString &str) +{ + QDateTime date; + + const uint toInt = str.toUInt(); + if (toInt != 0) + { + date.setTime_t(toInt); + } + else if (str.length() == 19) + { + date = QDateTime::fromString(str, QStringLiteral("yyyy/MM/dd HH:mm:ss")); + if (!date.isValid()) + date = QDateTime::fromString(str, QStringLiteral("yyyy-MM-dd HH:mm:ss")); + date.setTimeSpec(Qt::UTC); + } + else if (str.length() == 16) + { + date = QDateTime::fromString(str, QStringLiteral("yyyy/MM/dd HH:mm")); + if (!date.isValid()) + date = QDateTime::fromString(str, QStringLiteral("yyyy-MM-dd HH:mm")); + date.setTimeSpec(Qt::UTC); + } + else if (str[0].isDigit()) + { + qreal decay = 0; + + date = QDateTime::fromString(str.left(19), QStringLiteral("yyyy-MM-dd'T'HH:mm:ss")); + if (!date.isValid()) + date = QDateTime::fromString(str.left(19), QStringLiteral("yyyy/MM/dd HH:mm:ss")); + else + decay = str.right(6).remove(':').toDouble() / 100; + date.setOffsetFromUtc(qFloor(3600 * decay)); + } + else + { + QLocale myLoc(QLocale::English); + date = myLoc.toDateTime(str, QStringLiteral("ddd MMM dd HH:mm:ss yyyy")); + if (!date.isValid()) + date = myLoc.toDateTime(str, QStringLiteral("ddd MMM d HH:mm:ss yyyy")); + if (date.isValid()) + { + date.setTimeSpec(Qt::UTC); + return date; + } + + QStringList months = QStringList() << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec"; + const int year = str.midRef(26, 4).toInt(); + const int month = months.indexOf(str.mid(4, 3)) + 1; + const int day = str.midRef(8, 2).toInt(); + const qreal decay = str.midRef(20, 5).toDouble() / 100; + + const QTime time = QTime::fromString(str.mid(11, 8), QStringLiteral("HH:mm:ss")); + date.setDate(QDate(year, month, day)); + date.setTime(time); + date.setOffsetFromUtc(qFloor(3600 * decay)); + } + + return date; +} + +QString getUnit(double *size) +{ + QStringList units = FILESIZE_UNITS; + const int multiplier = FILESIZE_MULTIPLIER; + + int power = 0; + while (*size >= multiplier && power < units.count() - 1) + { + *size /= 1024; + power++; + } + + return units[power]; +} + +QString formatFilesize(double size) +{ + const QString unit = getUnit(&size); + const double round = size > 100 ? 1 : (size >= 10 ? 10 : 100); + const double roundedSize = qRound(size * round) / round; + return QStringLiteral("%1 %2").arg(roundedSize).arg(unit); +} + +bool validSavePath(const QString &file, bool writable) +{ + QString nativeFile = QDir::toNativeSeparators(file); + QFileInfo info(nativeFile); + const bool isWritable = info.isWritable() && !nativeFile.startsWith(QLatin1String("C:\\Program Files")); + return info.exists() && (!writable || isWritable); +} + +/** + * Return the path to a specified file in the config folder (since program files is not writable). + * @param file The file. + * @param exists If the file must already exist beforehand. + * @return The absolute path to the file. + */ +QString savePath(const QString &file, bool exists, bool writable) +{ + const QString &check = exists ? file : QStringLiteral("settings.ini"); + + if (isTestModeEnabled()) + { + if (QDir(QDir::currentPath()+"/tests/resources/").exists()) + { return QDir::toNativeSeparators(QDir::currentPath()+"/tests/resources/"+file); } + } + + if (validSavePath(qApp->applicationDirPath()+"/"+check, writable)) + { return QDir::toNativeSeparators(qApp->applicationDirPath()+"/"+file); } + if (validSavePath(QDir::currentPath()+"/"+check, writable)) + { return QDir::toNativeSeparators(QDir::currentPath()+"/"+file); } + if (validSavePath(QDir::homePath()+"/Grabber/"+check, writable)) + { return QDir::toNativeSeparators(QDir::homePath()+"/Grabber/"+file); } + #ifdef __linux__ + if (validSavePath(QDir::homePath()+"/.Grabber/"+check, writable)) + { return QDir::toNativeSeparators(QDir::homePath()+"/.Grabber/"+file); } + if (validSavePath(QString(PREFIX)+"/share/Grabber/"+check, writable)) + { return QDir::toNativeSeparators(QString(PREFIX)+"/share/Grabber/"+file); } + #endif + + QString dir; + #if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)) + dir = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); + #else + dir = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation); + #ifdef __linux__ + dir += QLatin1Char('/') + QCoreApplication::organizationName(); + dir += QLatin1Char('/') + QCoreApplication::applicationName(); + #endif + #endif + return QDir::toNativeSeparators(dir + QLatin1Char('/') + file); +} + +bool copyRecursively(QString srcFilePath, QString tgtFilePath) +{ + // Trim directory names of their trailing slashes + if (srcFilePath.endsWith(QDir::separator())) + srcFilePath.chop(1); + if (tgtFilePath.endsWith(QDir::separator())) + tgtFilePath.chop(1); + + // Directly copy files using Qt function + if (!QFileInfo(srcFilePath).isDir()) + return QFile(srcFilePath).copy(tgtFilePath); + + // Try to create the target directory + QDir targetDir(tgtFilePath); + targetDir.cdUp(); + if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName())) + return false; + + QDir sourceDir(srcFilePath); + QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System); + for (const QString &fileName : fileNames) + { + const QString newSrcFilePath = srcFilePath + QDir::separator() + fileName; + const QString newTgtFilePath = tgtFilePath + QDir::separator() + fileName; + if (!copyRecursively(newSrcFilePath, newTgtFilePath)) + return false; + } + + return true; +} + +/** + * Return the levenshtein distance between two strings. + * @param s1 First string. + * @param s2 Second string. + * @return The levenshtein distance between s1 and s2. + */ +int levenshtein(QString s1, QString s2) +{ + const int len1 = s1.size(), len2 = s2.size(); + QVector> d(len1 + 1, QVector(len2 + 1)); + + d[0][0] = 0; + for (int i = 1; i <= len1; ++i) d[i][0] = i; + for (int i = 1; i <= len2; ++i) d[0][i] = i; + + for (int i = 1; i <= len1; ++i) + { + for (int j = 1; j <= len2; ++j) + { + const int a = qMin(d[i - 1][j] + 1, d[i][j - 1] + 1); + const int b = d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1); + d[i][j] = qMin(a, b); + } + } + + return d[len1][len2]; +} + +bool setFileCreationDate(const QString &path, const QDateTime &datetime) +{ + if (!datetime.isValid()) + { return false; } + #ifdef Q_OS_WIN + auto *filename = new wchar_t[path.length() + 1]; + path.toWCharArray(filename); + filename[path.length()] = 0; + HANDLE hfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + delete[] filename; + if (hfile == INVALID_HANDLE_VALUE) + { + log(QStringLiteral("Unable to open file to set creation date (%1): %2").arg(GetLastError()).arg(path), Logger::Error); + return false; + } + else + { + const LONGLONG ll = Int32x32To64(datetime.toTime_t(), 10000000) + 116444736000000000; + FILETIME pcreationtime; + pcreationtime.dwLowDateTime = (DWORD) ll; + pcreationtime.dwHighDateTime = ll >> 32; + + if (!SetFileTime(hfile, &pcreationtime, NULL, &pcreationtime)) + { + log(QStringLiteral("Unable to change the file creation date (%1): %2").arg(GetLastError()).arg(path), Logger::Error); + return false; + } + } + CloseHandle(hfile); + #else + struct utimbuf timebuffer; + timebuffer.modtime = datetime.toTime_t(); + const char *filename = path.toStdString().c_str(); + if ((utime(filename, &timebuffer)) < 0) + { + // log(QStringLiteral("Unable to change the file creation date (%1): %2").arg(errno).arg(path), Logger::Error); + return false; + } + #endif + return true; +} + +/** + * Converts a DOM elemet to a map. + * @param dom The DOM element to convert. + * @return A QString map with names (joined with a slash if necessary) as keys and texts as values. + */ +QMap domToMap(const QDomElement &dom) +{ + QMap details; + for (QDomNode n = dom.firstChild(); !n.isNull(); n = n.nextSibling()) + { + const auto type = n.firstChild().nodeType(); + if (type == QDomNode::TextNode || type == QDomNode::CDATASectionNode) + { details[n.nodeName()] = n.firstChild().nodeValue(); } + else + { + QMap r = domToMap(n.toElement()); + QStringList k = r.keys(); + for (int i = 0; i < r.count(); i++) + { details[n.nodeName()+"/"+k.at(i)] = r.value(k.at(i)); } + } + } + return details; +} + +/** + * Removes HTML from a string. + * @param str The string to remove HTML from. + * @return The string without html. + */ +QString stripTags(QString str) +{ + static QRegularExpression strip(QStringLiteral("<[^>]*>")); + return str.remove(strip); +} + +/** + * Shut down computer after a certain period of time. + * @param timeout Time before shutdown in seconds. + */ +void shutDown(int timeout) +{ + #if defined(Q_OS_WIN) + QProcess::startDetached("shutdown -s -f -t " + QString::number(timeout)); + #else + QProcess::startDetached("shutdown " + QString::number(timeout)); + #endif +} + +/** + * Opens CD tray. + */ +void openTray() +{ + #if defined(Q_OS_WIN) + QProcess::startDetached(QStringLiteral("CDR.exe open")); + #else + QProcess::startDetached(QStringLiteral("eject cdrom")); + #endif +} + +QString getExtension(const QUrl &url) +{ return getExtension(url.toString()); } +QString getExtension(const QString &url) +{ + QString ext; + const int pPos = url.lastIndexOf('.'); + if (pPos != -1 && pPos > url.indexOf('/', 7)) + { + ext = url.right(url.length() - pPos - 1); + if (ext.contains('?')) + ext = ext.section('?', 0, -2); + } + return ext; +} + +QString setExtension(QString url, const QString &extension) +{ + const int pPos = url.lastIndexOf('.'); + if (pPos != -1 && pPos > url.indexOf('/', 7)) + { + const int qPos = url.indexOf('?', pPos); + if (qPos != -1) + url.replace(pPos + 1, qPos - pPos - 1, extension); + else + url = url.left(pPos) + "." + extension; + } + return url; +} + +bool isUrl(const QString &str) +{ + static QRegularExpression regexUrl(QStringLiteral("^https?://[^\\s/$.?#].[^\\s]*$")); + return regexUrl.match(str).hasMatch(); +} + +QString fixFilename(QString filename, QString path, int maxLength, bool invalidChars) +{ + const QString sep = QDir::separator(); + filename = QDir::toNativeSeparators(filename); + path = QDir::toNativeSeparators(path); + if (!path.endsWith(sep) && !path.isEmpty() && !filename.isEmpty()) + path += sep; + + #ifdef Q_OS_WIN + return fixFilenameWindows(filename, path, maxLength, invalidChars); + #else + return fixFilenameLinux(filename, path, maxLength, invalidChars); + #endif +} + +QString fixFilenameLinux(const QString &fn, const QString &path, int maxLength, bool invalidChars) +{ + Q_UNUSED(invalidChars); + + // Fix parameters + const QString sep = QStringLiteral("/"); + QString filename = path + fn; + + // Divide filename + QStringList parts = filename.split(sep); + QString file, ext; + if (!fn.isEmpty()) + { + file = parts.takeLast();; + const int lastDot = file.lastIndexOf('.'); + if (lastDot != -1) + { + ext = file.right(file.length() - lastDot - 1); + file = file.left(lastDot); + } + } + + // Fix directories + for (QString &part : parts) + { + // A part cannot start or finish with a space + part = part.trimmed(); + + // Trim part + if (part.length() > 255) + part = part.left(255).trimmed(); + } + + // Join parts back + QString dirpart = parts.join(sep); + filename = (dirpart.isEmpty() ? QString() : dirpart + (!fn.isEmpty() ? sep : QString())) + file; + + // A filename cannot exceed a certain length + const int extlen = ext.isEmpty() ? 0 : ext.length() + 1; + if (file.length() > maxLength - extlen) + file = file.left(maxLength - extlen).trimmed(); + if (file.length() > 255 - extlen) + file = file.left(255 - extlen).trimmed(); + + // Get separation between filename and path + int index = -1; + const int pathGroups = path.count(sep); + for (int i = 0; i < pathGroups; ++i) + index = filename.indexOf(sep, index + 1); + + // Put extension and drive back + filename = filename + (!ext.isEmpty() ? "." + ext : QString()); + if (!fn.isEmpty()) + filename = filename.right(filename.length() - index - 1); + + QFileInfo fi(filename); + QString suffix = fi.suffix(); + filename = (fi.path() != "." ? fi.path() + "/" : QString()) + fi.completeBaseName().left(245) + (suffix.isEmpty() ? QString() : "." + fi.suffix()); + + return filename; +} + +#ifndef MAX_PATH + #define MAX_PATH 260 +#endif + +QString fixFilenameWindows(const QString &fn, const QString &path, int maxLength, bool invalidChars) +{ + // Fix parameters + const QString sep = QStringLiteral("\\"); + maxLength = maxLength == 0 ? MAX_PATH : maxLength; + QString filename = path + fn; + + // Drive + QString drive; + if (filename.mid(1, 2) == QLatin1String(":\\")) + { + drive = filename.left(3); + filename = filename.right(filename.length() - 3); + } + + // Forbidden characters + if (invalidChars) + { filename.replace('<', '_').replace('>', '_').replace(':', '_').remove('"').replace('/', '_').replace('|', '_').remove('?').replace('*', '_'); } + + // Fobidden directories or filenames + static const QStringList forbidden = QStringList() << "CON" << "PRN" << "AUX" << "NUL" << "COM1" << "COM2" << "COM3" << "COM4" << "COM5" << "COM6" << "COM7" << "COM8" << "COM9" << "LPT1" << "LPT2" << "LPT3" << "LPT4" << "LPT5" << "LPT6" << "LPT7" << "LPT8" << "LPT9"; + + // Divide filename + QStringList parts = filename.split(sep); + QString file, ext; + if (!fn.isEmpty()) + { + file = parts.takeLast(); + const int lastDot = file.lastIndexOf('.'); + if (lastDot != -1) + { + ext = file.right(file.length() - lastDot - 1); + file = file.left(lastDot); + } + } + + // Fix directories + for (QString &part : parts) + { + // A part cannot be one in the forbidden list + if (invalidChars && forbidden.contains(part)) + { part = part + "!"; } + + // A part cannot finish by a period + if (invalidChars && part.endsWith('.')) + { part = part.left(part.length() - 1).trimmed(); } + + // A part cannot start or finish with a space + part = part.trimmed(); + + // A part should still allow creating a file + if (part.length() > maxLength - 12) + { part = part.left(qMax(0, maxLength - 12)).trimmed(); } + } + + // Join parts back + QString dirpart = parts.join(sep); + if (dirpart.length() > maxLength - 12) + { dirpart = dirpart.left(qMax(0, maxLength - 12)).trimmed(); } + filename = (dirpart.isEmpty() ? QString() : dirpart + (!fn.isEmpty() ? sep : QString())) + file; + + // A filename cannot exceed MAX_PATH (-1 for and -3 for drive "C:\") + if (filename.length() > maxLength - 1 - 3 - ext.length() - 1) + { filename = filename.left(qMax(0, maxLength - 1 - 3 - ext.length() - 1)).trimmed(); } + + // Get separation between filename and path + int index = -1; + const int pathGroups = path.count(sep); + for (int i = 0; i < pathGroups - (!drive.isEmpty() ? 1 : 0); ++i) + { index = filename.indexOf(sep, index + 1); } + index += drive.length(); + + // Put extension and drive back + filename = drive + filename + (!ext.isEmpty() ? "." + ext : QString()); + if (!fn.isEmpty()) + { filename = filename.right(filename.length() - index - 1); } + + return filename; +} + + +QString getExtensionFromHeader(const QByteArray &data12) +{ + const QByteArray data8 = data12.left(8); + const QByteArray data48 = data12.mid(4, 8); + const QByteArray data6 = data12.left(6); + const QByteArray data4 = data12.left(4); + const QByteArray data3 = data12.left(3); + const QByteArray data2 = data12.left(2); + + // GIF + if (data6 == "GIF87a" || data6 == "GIF89a") + return QStringLiteral("gif"); + + // PNG + if (data8 == "\211PNG\r\n\032\n") + return QStringLiteral("png"); + + // JPG + if (data3 == "\255\216\255") + return QStringLiteral("jpg"); + + // BMP + if (data2 == "BM") + return QStringLiteral("bmp"); + + // WEBM + if (data4 == "\026\069\223\163") + return QStringLiteral("webm"); + + // MP4 + if (data48 == "ftyp3gp5" || data48 == "ftypMSNV" || data48 == "ftypisom") + return QStringLiteral("mp4"); + + // SWF + if (data3 == "FWS" || data3 == "CWS" || data3 == "ZWS") + return QStringLiteral("swf"); + + // FLV + if (data4 == "FLV\001") + return QStringLiteral("flv"); + + // ICO + if (data4 == QByteArray("\000\000\001\000", 4)) + return QStringLiteral("ico"); + + return QString(); +} + + +bool testModeEnabled = false; +void setTestModeEnabled(bool testMode) +{ + testModeEnabled = testMode; +} +bool isTestModeEnabled() +{ + return testModeEnabled; +} + + +QString parseMarkdown(QString str) +{ + // Windows EOL + str.replace("\\r\\n", "\\n"); + + // Headers + static const QRegularExpression header(QStringLiteral("^(#+)([^#].*)$"), QRegularExpression::MultilineOption); + auto matches = header.globalMatch(str); + while (matches.hasNext()) + { + auto match = matches.next(); + const int level = qMax(1, qMin(6, match.captured(1).length())); + const QString result = "" + match.captured(2).trimmed() + ""; + str.replace(match.captured(0), result); + } + + // Issue links + static const QRegularExpression issueLinks("(issue|fix) #(\\d+)"); + str.replace(issueLinks, "\\1 #\\2"); + + // Line breaks to HTML + str.replace("\n", "
    "); + + return str; +} + + +/** + * Converts a QFont to a CSS string. + * @param font The font to convert. + * @return The CSS font. + */ +QString qFontToCss(const QFont &font) +{ + QString style; + switch (font.style()) + { + case QFont::StyleNormal: style = "normal"; break; + case QFont::StyleItalic: style = "italic"; break; + case QFont::StyleOblique: style = "oblique"; break; + } + + QString size; + if (font.pixelSize() == -1) + { size = QString::number(font.pointSize())+"pt"; } + else + { size = QString::number(font.pixelSize())+"px"; } + + // Should be "font.weight() * 8 + 100", but linux doesn't handle weight the same way windows do + const QString weight = QString::number(font.weight() * 8); + + QStringList decorations; + if (font.strikeOut()) { decorations.append("line-through"); } + if (font.underline()) { decorations.append("underline"); } + + return "font-family:'"+font.family()+"'; font-size:"+size+"; font-style:"+style+"; font-weight:"+weight+"; text-decoration:"+(decorations.isEmpty() ? "none" : decorations.join(" "))+";"; +} + +QFont qFontFromString(const QString &str) +{ + QFont font; + font.fromString(str); + if (font.family().isEmpty()) + { font.setFamily(font.defaultFamily()); } + return font; +} + +bool isFileParentWithSuffix(const QString &fileName, const QString &parent, const QStringList &suffixes) +{ + for (const QString &suffix : suffixes) + if (fileName == parent + suffix) + return true; + return false; +} +QList> listFilesFromDirectory(const QDir &dir, const QStringList &suffixes) +{ + auto files = QList>(); + + QDirIterator it(dir, QDirIterator::Subdirectories); + while (it.hasNext()) + { + it.next(); + + if (it.fileInfo().isDir()) + continue; + + QString path = it.filePath(); + const QString fileName = path.right(path.length() - dir.absolutePath().length() - 1); + + if (!files.isEmpty()) + { + const QString &previous = files.last().first; + if (isFileParentWithSuffix(fileName, previous, suffixes)) + { + files.last().second.append(fileName); + continue; + } + } + + files.append(QPair(fileName, QStringList())); + } + + return files; +} + +bool isVariantEmpty(const QVariant &value) +{ + switch (value.type()) + { + case QVariant::Type::Int: return value.toInt() == 0; + case QVariant::Type::List: return value.toList().isEmpty(); + case QVariant::Type::Map: return value.toMap().isEmpty(); + case QVariant::Type::String: return value.toString().isEmpty(); + case QVariant::Type::StringList: return value.toStringList().isEmpty(); + default: return false; + } +} + +QMap multiMatchToMap(const QRegularExpressionMatch &match, const QStringList &groups) +{ + QMap data; + for (QString group : groups) + { + if (group.isEmpty()) + continue; + + QString val = match.captured(group); + if (val.isEmpty()) + continue; + + const int underscorePos = group.lastIndexOf('_'); + bool ok; + group.midRef(underscorePos + 1).toInt(&ok); + if (underscorePos != -1 && ok) + { group = group.left(underscorePos); } + data[group] = val; + } + + return data; +} + +QString decodeHtmlEntities(const QString &html) +{ + QByteArray data = html.toUtf8(); + const char *src = data.constData(); + auto *dest = new char[strlen(src) + 1]; + decode_html_entities_utf8(dest, src); + return QString::fromUtf8(dest); +} diff --git a/lib/src/functions.h b/lib/src/functions.h index e324d1ea9..17d1d026c 100644 --- a/lib/src/functions.h +++ b/lib/src/functions.h @@ -55,8 +55,8 @@ void shutDown(int timeout = 0); void openTray(); QString fixFilename(QString filename, QString path = "", int maxLength = 0, bool invalidChars = true); -QString fixFilenameWindows(const QString &filename, const QString &path = "", int maxLength = 0, bool invalidChars = true); -QString fixFilenameLinux(const QString &filename, const QString &path = "", int maxLength = 0, bool invalidChars = true); +QString fixFilenameWindows(const QString &fn, const QString &path = "", int maxLength = 0, bool invalidChars = true); +QString fixFilenameLinux(const QString &fn, const QString &path = "", int maxLength = 0, bool invalidChars = true); QMap domToMap(const QDomElement &); diff --git a/lib/src/loader/downloadable.h b/lib/src/loader/downloadable.h index 46e41332b..072b6e29d 100644 --- a/lib/src/loader/downloadable.h +++ b/lib/src/loader/downloadable.h @@ -35,6 +35,7 @@ class Downloadable Full }; + virtual ~Downloadable() = default; virtual void preload(const Filename &filename) = 0; virtual QString url(Size size) const = 0; virtual QStringList paths(const Filename &filename, const QString &folder, int count) const = 0; diff --git a/lib/src/loader/loader-data.h b/lib/src/loader/loader-data.h index 694d37690..858831833 100644 --- a/lib/src/loader/loader-data.h +++ b/lib/src/loader/loader-data.h @@ -9,8 +9,8 @@ struct LoaderData { // Progress indicators - int position; - int max; + int position = -1; + int max = -1; // Results QList> ignored; diff --git a/lib/src/login/http-login.h b/lib/src/login/http-login.h index 3f55e93d9..97fce1bb8 100644 --- a/lib/src/login/http-login.h +++ b/lib/src/login/http-login.h @@ -16,6 +16,7 @@ class HttpLogin : public Login public: explicit HttpLogin(QString type, Site *site, CustomNetworkAccessManager *manager, MixedSettings *settings); + virtual ~HttpLogin() = default; bool isTestable() const override; virtual QNetworkReply *getReply(const QString &url, const QUrlQuery &query) const = 0; diff --git a/lib/src/login/oauth2-login.cpp b/lib/src/login/oauth2-login.cpp index 49ee0c32f..892d3a9de 100644 --- a/lib/src/login/oauth2-login.cpp +++ b/lib/src/login/oauth2-login.cpp @@ -8,7 +8,7 @@ OAuth2Login::OAuth2Login(Site *site, QNetworkAccessManager *manager, MixedSettings *settings) - : m_site(site), m_manager(manager), m_settings(settings) + : m_site(site), m_manager(manager), m_settings(settings), m_tokenReply(nullptr) {} bool OAuth2Login::isTestable() const diff --git a/lib/src/models/api/api.cpp b/lib/src/models/api/api.cpp index 83955a4f7..3c8334b0c 100644 --- a/lib/src/models/api/api.cpp +++ b/lib/src/models/api/api.cpp @@ -28,15 +28,16 @@ bool Api::contains(const QString &key) const { return m_data.contains(key); } QString Api::value(const QString &key) const { return m_data.value(key); } -PageUrl Api::pageUrl(const QString &tt, int page, int limit, int lastPage, int lastPageMinId, int lastPageMaxId, Site *site) const +PageUrl Api::pageUrl(const QString &search, int page, int limit, int lastPage, int lastPageMinId, int lastPageMaxId, Site *site) const { PageUrl ret; QString url; - QString search = tt; + QString srch = search; // Default tag is none is given - if (m_data.contains("DefaultTag") && search.isEmpty()) - { search = m_data.value("DefaultTag"); } + if (m_data.contains("DefaultTag") && srch.isEmpty()) + { + srch = m_data.value("DefaultTag"); } // Find page number const int forced = forcedLimit(); @@ -48,7 +49,7 @@ PageUrl Api::pageUrl(const QString &tt, int page, int limit, int lastPage, int l if (m_data.contains("Urls/Pools")) { QRegularExpression poolRx("pool:(\\d+)"); - auto match = poolRx.match(search); + auto match = poolRx.match(srch); if (match.hasMatch()) { url = m_data.value("Urls/Pools"); @@ -59,14 +60,14 @@ PageUrl Api::pageUrl(const QString &tt, int page, int limit, int lastPage, int l // Home URL for empty searches if (url.isEmpty()) { - if (search.isEmpty() && m_data.contains("Urls/Home")) + if (srch.isEmpty() && m_data.contains("Urls/Home")) { url = m_data.value("Urls/Home"); } else { url = m_data.value("Urls/Tags"); } } // Return an error if we are trying to do a search on a non-compatible API - if (!search.isEmpty() && !url.contains("{tags}")) + if (!srch.isEmpty() && !url.contains("{tags}")) { ret.error = tr("Tag search is impossible with the chosen source (%1).").arg(m_name); return ret; @@ -94,7 +95,7 @@ PageUrl Api::pageUrl(const QString &tt, int page, int limit, int lastPage, int l } // Basic replaces - url.replace("{tags}", QUrl::toPercentEncoding(search)); + url.replace("{tags}", QUrl::toPercentEncoding(srch)); url.replace("{limit}", QString::number(limit)); // Previous page replaces diff --git a/lib/src/models/api/api.h b/lib/src/models/api/api.h index 138ff9eb2..bf263fe31 100644 --- a/lib/src/models/api/api.h +++ b/lib/src/models/api/api.h @@ -40,7 +40,7 @@ struct ParsedDetails struct ParsedCheck { QString error; - bool ok; + bool ok = false; }; class Site; diff --git a/lib/src/models/filename.h b/lib/src/models/filename.h index 2ce68b8ad..3699371de 100644 --- a/lib/src/models/filename.h +++ b/lib/src/models/filename.h @@ -22,25 +22,10 @@ class Filename void setFormat(const QString &format); void setEscapeMethod(QString (*)(const QVariant &)); - /** - * Return the filename of the image according to the user's settings. - * @param fn The user's filename. - * @param pth The user's root save path. - * @param counter Current image count (used for batch downloads). - * @param complex Whether the filename is complex or not (contains conditionals). - * @return The filename of the image, with any token replaced. - */ - QStringList path(const Image &img, Profile *settings, const QString &pth = "", int counter = 0, bool complex = true, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false, bool keepInvalidTokens = false) const; - QStringList path(QMap tokens, Profile *settings, QString folder = "", int counter = 0, bool complex = true, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false, bool keepInvalidTokens = false) const; + QStringList path(const Image &img, Profile *profile, const QString &pth = "", int counter = 0, bool complex = true, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false, bool keepInvalidTokens = false) const; + QStringList path(QMap tokens, Profile *profile, QString folder = "", int counter = 0, bool complex = true, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false, bool keepInvalidTokens = false) const; - /** - * Check filename format's validity. - * @param error The format to be validated. - * @return Whether the filename is valid or not. - * @todo Return a constant instead of a QString. - */ bool isValid(Profile *profile = nullptr, QString *error = nullptr) const; - bool needTemporaryFile(const QMap &tokens) const; int needExactTags(Site *site, const QString &api = "") const; diff --git a/lib/src/models/filtering/blacklist.cpp b/lib/src/models/filtering/blacklist.cpp index 19b119b53..5b68bdcee 100644 --- a/lib/src/models/filtering/blacklist.cpp +++ b/lib/src/models/filtering/blacklist.cpp @@ -49,7 +49,7 @@ void Blacklist::add(const QStringList &tags) bool Blacklist::remove(const QString &tag) { - int index = indexOf(tag); + const int index = indexOf(tag); if (index == -1) return false; diff --git a/lib/src/models/filtering/filter.cpp b/lib/src/models/filtering/filter.cpp index 2751a1c1a..a489b795e 100644 --- a/lib/src/models/filtering/filter.cpp +++ b/lib/src/models/filtering/filter.cpp @@ -5,7 +5,7 @@ Filter::Filter(bool invert) : m_invert(invert) {} -bool Filter::operator==(const Filter &rhs) +bool Filter::operator==(const Filter &rhs) const { return m_invert == rhs.m_invert && compare(rhs); } diff --git a/lib/src/models/filtering/filter.h b/lib/src/models/filtering/filter.h index 6f2acc288..95ead6b5e 100644 --- a/lib/src/models/filtering/filter.h +++ b/lib/src/models/filtering/filter.h @@ -10,10 +10,11 @@ class Filter { public: explicit Filter(bool invert = false); + virtual ~Filter() = default; virtual QString match(const QMap &tokens, bool invert = false) const = 0; virtual QString toString() const = 0; - bool operator==(const Filter &rhs); + bool operator==(const Filter &rhs) const; virtual bool compare(const Filter& rhs) const = 0; protected: diff --git a/lib/src/models/filtering/meta-filter.cpp b/lib/src/models/filtering/meta-filter.cpp index f457089bf..b20f3d4a7 100644 --- a/lib/src/models/filtering/meta-filter.cpp +++ b/lib/src/models/filtering/meta-filter.cpp @@ -15,7 +15,7 @@ QString MetaFilter::toString() const bool MetaFilter::compare(const Filter& rhs) const { - auto other = dynamic_cast(&rhs); + const auto other = dynamic_cast(&rhs); if (other == Q_NULLPTR) return false; @@ -56,7 +56,7 @@ QString MetaFilter::match(const QMap &tokens, bool invert) const if (!tokens.contains(m_type)) { QStringList keys = tokens.keys(); - return QObject::tr("unknown type \"%1\" (available types: \"%2\")").arg(m_type, keys.join("\", \"")); + return QObject::tr(R"(unknown type "%1" (available types: "%2"))").arg(m_type, keys.join("\", \"")); } const QVariant &token = tokens[m_type].value(); diff --git a/lib/src/models/filtering/tag-filter.cpp b/lib/src/models/filtering/tag-filter.cpp index 41becddd8..64cc0d948 100644 --- a/lib/src/models/filtering/tag-filter.cpp +++ b/lib/src/models/filtering/tag-filter.cpp @@ -18,7 +18,7 @@ QString TagFilter::toString() const bool TagFilter::compare(const Filter& rhs) const { - auto other = dynamic_cast(&rhs); + const auto other = dynamic_cast(&rhs); if (other == Q_NULLPTR) return false; @@ -36,7 +36,7 @@ QString TagFilter::match(const QMap &tokens, bool invert) const bool cond = false; for (const QString &tag : tags) { - bool match = m_regexp.isNull() ? tag == m_tag : m_regexp->exactMatch(tag); + const bool match = m_regexp.isNull() ? tag == m_tag : m_regexp->exactMatch(tag); if (match) { cond = true; diff --git a/lib/src/models/filtering/token-filter.cpp b/lib/src/models/filtering/token-filter.cpp index 25b1995a0..0c99546e0 100644 --- a/lib/src/models/filtering/token-filter.cpp +++ b/lib/src/models/filtering/token-filter.cpp @@ -14,7 +14,7 @@ QString TokenFilter::toString() const bool TokenFilter::compare(const Filter& rhs) const { - auto other = dynamic_cast(&rhs); + const auto other = dynamic_cast(&rhs); if (other == Q_NULLPTR) return false; diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index de9dcfbf7..3c46a6390 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -97,7 +97,7 @@ Image::Image(const Image &other) } Image::Image(Site *site, QMap details, Profile *profile, Page* parent) - : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(Q_NULLPTR) + : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(Q_NULLPTR), m_loadImageError(QNetworkReply::NetworkError::NoError) { m_settings = m_profile->getSettings(); @@ -417,15 +417,6 @@ void Image::parseDetails() emit finishedLoadingTags(); } -/** - * Return the filename of the image according to the user's settings. - * @param fn The user's filename. - * @param pth The user's root save path. - * @param counter Current image count (used for batch downloads). - * @param complex Whether the filename is complex or not (contains conditionals). - * @param simple True to force using the fn and pth parameters. - * @return The filename of the image, with any token replaced. - */ QStringList Image::path(QString fn, QString pth, int counter, bool complex, bool simple, bool maxLength, bool shouldFixFilename, bool getFull) const { if (!simple) @@ -912,7 +903,7 @@ QColor Image::color() const // Blacklisted QStringList detected = m_profile->getBlacklist().match(tokens(m_profile)); if (!detected.isEmpty()) - return QColor(0, 0, 0); + return { 0, 0, 0 }; // Favorited (except for exact favorite search) auto favorites = m_profile->getFavorites(); @@ -920,21 +911,21 @@ QColor Image::color() const if (!m_parent->search().contains(tag.text())) for (const Favorite &fav : favorites) if (fav.getName() == tag.text()) - return QColor(255, 192, 203); + { return { 255, 192, 203 }; } // Image with a parent if (m_parentId != 0) - return QColor(204, 204, 0); + return { 204, 204, 0 }; // Image with children if (m_hasChildren) - return QColor(0, 255, 0); + return { 0, 255, 0 }; // Pending image if (m_status == "pending") - return QColor(0, 0, 255); + return { 0, 0, 255 }; - return QColor(); + return {}; } QString Image::tooltip() const diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index d42826432..b74b359d8 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -260,15 +260,6 @@ QNetworkRequest Site::makeRequest(QUrl url, Page *page, const QString &ref, Imag return request; } -/** - * Get an URL from the site. - * - * @param url The URL to get - * @param page The related page - * @param ref The type of referer to use (page, image, etc.) - * @param img The related image - * @return The equivalent network request - */ void Site::getAsync(QueryType type, const QUrl &url, const std::function &callback, Page *page, const QString &ref, Image *img) { m_lastCallback = callback; diff --git a/lib/src/models/site.h b/lib/src/models/site.h index d2d0a314f..3da6f617e 100644 --- a/lib/src/models/site.h +++ b/lib/src/models/site.h @@ -61,9 +61,9 @@ class Site : public QObject void syncSettings() const; MixedSettings *settings() const; TagDatabase *tagDatabase() const; - QNetworkRequest makeRequest(QUrl url, Page *page = nullptr, const QString &referer = "", Image *img = nullptr); - QNetworkReply *get(const QUrl &url, Page *page = nullptr, const QString &referer = "", Image *img = nullptr); - void getAsync(QueryType type, const QUrl &url, const std::function &callback, Page *page = nullptr, const QString &referer = "", Image *img = nullptr); + QNetworkRequest makeRequest(QUrl url, Page *page = nullptr, const QString &ref = "", Image *img = nullptr); + QNetworkReply *get(const QUrl &url, Page *page = nullptr, const QString &ref = "", Image *img = nullptr); + void getAsync(QueryType type, const QUrl &url, const std::function &callback, Page *page = nullptr, const QString &ref = "", Image *img = nullptr); QUrl fixUrl(const QUrl &url) const { return fixUrl(url.toString()); } QUrl fixUrl(const QString &url, const QUrl &old = QUrl()) const; diff --git a/lib/src/secure-file.cpp b/lib/src/secure-file.cpp index 21b8362c5..6c12bada5 100644 --- a/lib/src/secure-file.cpp +++ b/lib/src/secure-file.cpp @@ -10,7 +10,7 @@ SecureFile::SecureFile(const QString &filename, const QString &key) quint64 SecureFile::generateIntKey(const QString &key) const { - const auto data = QByteArray::fromRawData((const char*)key.utf16(), key.length() * 2); + const auto data = QByteArray::fromRawData(reinterpret_cast(key.utf16()), key.length() * 2); QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5); Q_ASSERT(hash.size() == 16); QDataStream stream(hash); diff --git a/lib/src/tags/tag-name-format.h b/lib/src/tags/tag-name-format.h index 7e0ae05ad..92b44e650 100644 --- a/lib/src/tags/tag-name-format.h +++ b/lib/src/tags/tag-name-format.h @@ -27,7 +27,7 @@ class TagNameFormat QString formatted(const QString &word, int index) const; private: - CaseFormat m_caseFormat; + CaseFormat m_caseFormat = CaseFormat::Lower; QString m_wordSeparator; }; diff --git a/lib/src/tags/tag-stylist.cpp b/lib/src/tags/tag-stylist.cpp index c93d58e8f..a72f49c4f 100644 --- a/lib/src/tags/tag-stylist.cpp +++ b/lib/src/tags/tag-stylist.cpp @@ -57,7 +57,7 @@ QString TagStylist::stylished(const Tag &tag, const QMap &styl key = "favorites"; QString txt = tag.text(); - QString ret = QString("%3").arg(tag.text(), styles.value(key), noUnderscores ? txt.replace('_', ' ') : tag.text()); + QString ret = QString(R"(%3)").arg(tag.text(), styles.value(key), noUnderscores ? txt.replace('_', ' ') : tag.text()); if (count && tag.count() > 0) ret += QString(" (%L1)").arg(tag.count()); From fcfbecd010ed70c95760d988863dc2c8cd6810e4 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 22:48:35 +0200 Subject: [PATCH 040/112] Replace Q_NULLPTR by nullptr for consistency --- CrashReporter/crash-reporter-window.h | 2 +- e2e/src/main.cpp | 4 ++-- gui/src/aboutwindow.h | 2 +- gui/src/batch-download-image.cpp | 4 ++-- gui/src/batch-download-image.h | 4 ++-- gui/src/batch/addgroupwindow.h | 2 +- gui/src/batch/adduniquewindow.cpp | 4 ++-- gui/src/batch/adduniquewindow.h | 2 +- gui/src/batch/batchwindow.cpp | 2 +- gui/src/batch/batchwindow.h | 2 +- gui/src/image-context-menu.h | 2 +- gui/src/mainwindow.cpp | 10 +++++----- gui/src/monitoring-center.h | 2 +- gui/src/searchwindow.h | 2 +- gui/src/settings/conditionwindow.h | 2 +- gui/src/settings/customwindow.h | 2 +- gui/src/settings/filenamewindow.h | 2 +- gui/src/settings/log-window.h | 2 +- gui/src/settings/optionswindow.h | 2 +- gui/src/settings/startwindow.h | 2 +- gui/src/settings/web-service-window.cpp | 2 +- gui/src/settings/web-service-window.h | 2 +- gui/src/sources/sitewindow.h | 2 +- gui/src/sources/sourcessettingswindow.h | 2 +- gui/src/sources/sourceswindow.cpp | 2 +- gui/src/sources/sourceswindow.h | 2 +- gui/src/tabs/search-tab.h | 2 +- gui/src/tag-context-menu.h | 2 +- gui/src/threads/image-loader-queue.h | 2 +- gui/src/threads/image-loader.h | 2 +- gui/src/threads/resizer.h | 2 +- gui/src/ui/QAffiche.cpp | 2 +- gui/src/ui/QAffiche.h | 2 +- gui/src/ui/QBouton.h | 2 +- gui/src/ui/fixed-size-grid-layout.cpp | 10 +++++----- gui/src/ui/qclosabletabwidget.cpp | 2 +- gui/src/ui/textedit.cpp | 4 ++-- gui/src/ui/textedit.h | 2 +- gui/src/ui/verticalscrollarea.h | 2 +- gui/src/updater/update-dialog.cpp | 4 ++-- gui/src/updater/update-dialog.h | 2 +- gui/src/utils/blacklist-fix/blacklist-fix-1.h | 2 +- gui/src/utils/blacklist-fix/blacklist-fix-2.h | 2 +- gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.h | 2 +- gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.h | 2 +- gui/src/utils/md5-fix/md5-fix.h | 2 +- .../utils/rename-existing/rename-existing-1.h | 2 +- .../utils/rename-existing/rename-existing-2.h | 2 +- gui/src/utils/tag-loader/tag-loader.h | 2 +- gui/src/viewer/details-window.h | 2 +- gui/src/viewer/zoom-window.cpp | 2 +- lib/src/commands/sql-worker.h | 2 +- lib/src/custom-network-access-manager.h | 2 +- lib/src/downloader/downloader.cpp | 2 +- lib/src/downloader/extension-rotator.h | 2 +- lib/src/downloader/file-downloader.cpp | 2 +- lib/src/downloader/file-downloader.h | 2 +- lib/src/downloader/image-downloader.cpp | 2 +- lib/src/downloader/image-downloader.h | 6 +++--- lib/src/loader/downloadable-downloader.cpp | 2 +- lib/src/loader/downloadable-downloader.h | 2 +- lib/src/loader/loader-query.cpp | 2 +- lib/src/login/http-login.cpp | 4 ++-- lib/src/login/url-login.cpp | 4 ++-- lib/src/models/api/javascript-api.cpp | 4 ++-- lib/src/models/api/javascript-console-helper.h | 2 +- lib/src/models/filtering/filter-factory.cpp | 2 +- lib/src/models/filtering/meta-filter.cpp | 2 +- lib/src/models/filtering/tag-filter.cpp | 2 +- lib/src/models/filtering/token-filter.cpp | 2 +- lib/src/models/image.cpp | 8 ++++---- lib/src/models/image.h | 2 +- lib/src/models/page-api.cpp | 2 +- lib/src/models/page-api.h | 2 +- lib/src/models/page.h | 2 +- lib/src/models/profile.cpp | 4 ++-- lib/src/models/site.cpp | 6 +++--- lib/src/models/source-guesser.cpp | 4 ++-- lib/src/models/source.cpp | 8 ++++---- lib/src/tags/tag-api.cpp | 2 +- lib/src/tags/tag-api.h | 2 +- lib/src/updater/program-updater.cpp | 2 +- lib/src/vendor/qcustomnetworkreply.h | 2 +- tests/src/downloader/image-downloader-test.cpp | 16 ++++++++-------- 84 files changed, 120 insertions(+), 120 deletions(-) diff --git a/CrashReporter/crash-reporter-window.h b/CrashReporter/crash-reporter-window.h index 2e65b5cf9..b65dd3579 100644 --- a/CrashReporter/crash-reporter-window.h +++ b/CrashReporter/crash-reporter-window.h @@ -14,7 +14,7 @@ class CrashReporterWindow : public QMainWindow Q_OBJECT public: - explicit CrashReporterWindow(QWidget *parent = Q_NULLPTR); + explicit CrashReporterWindow(QWidget *parent = nullptr); ~CrashReporterWindow() override; public slots: diff --git a/e2e/src/main.cpp b/e2e/src/main.cpp index 6ee37fa7a..c640c186b 100644 --- a/e2e/src/main.cpp +++ b/e2e/src/main.cpp @@ -121,11 +121,11 @@ int main(int argc, char *argv[]) const int pagei = apiSearch[1].toDouble(); const int limit = apiSearch[2].toDouble(); - Api *api = Q_NULLPTR; + Api *api = nullptr; for (Api *a : site->getApis()) if (a->getName().toLower() == apiName.toLower()) api = a; - if (api == Q_NULLPTR) + if (api == nullptr) continue; auto page = new Page(profile, site, allSites.values(), QStringList() << search, pagei, limit); diff --git a/gui/src/aboutwindow.h b/gui/src/aboutwindow.h index daccccc92..7b88a90cf 100644 --- a/gui/src/aboutwindow.h +++ b/gui/src/aboutwindow.h @@ -17,7 +17,7 @@ class AboutWindow : public QDialog Q_OBJECT public: - explicit AboutWindow(const QString &v, QWidget *parent = Q_NULLPTR); + explicit AboutWindow(const QString &v, QWidget *parent = nullptr); ~AboutWindow() override; public slots: diff --git a/gui/src/batch-download-image.cpp b/gui/src/batch-download-image.cpp index caab32049..4d21bebd6 100644 --- a/gui/src/batch-download-image.cpp +++ b/gui/src/batch-download-image.cpp @@ -3,14 +3,14 @@ const DownloadQuery *BatchDownloadImage::query() const { - if (queryGroup != Q_NULLPTR) + if (queryGroup != nullptr) return queryGroup; return queryImage; } int BatchDownloadImage::siteId(const QList &groups) const { - if (queryGroup != Q_NULLPTR) + if (queryGroup != nullptr) return groups.indexOf(*queryGroup) + 1; return -1; } diff --git a/gui/src/batch-download-image.h b/gui/src/batch-download-image.h index 5612464e9..96115060f 100644 --- a/gui/src/batch-download-image.h +++ b/gui/src/batch-download-image.h @@ -16,8 +16,8 @@ class BatchDownloadImage // Public members QSharedPointer image; - const DownloadQueryGroup *queryGroup = Q_NULLPTR; - const DownloadQueryImage *queryImage = Q_NULLPTR; + const DownloadQueryGroup *queryGroup = nullptr; + const DownloadQueryImage *queryImage = nullptr; }; bool operator==(const BatchDownloadImage &lhs, const BatchDownloadImage &rhs); diff --git a/gui/src/batch/addgroupwindow.h b/gui/src/batch/addgroupwindow.h index d5ca9bc52..2c3ed1312 100644 --- a/gui/src/batch/addgroupwindow.h +++ b/gui/src/batch/addgroupwindow.h @@ -21,7 +21,7 @@ class AddGroupWindow : public QDialog Q_OBJECT public: - AddGroupWindow(Site *selected, Profile *profile, QWidget *parent = Q_NULLPTR); + AddGroupWindow(Site *selected, Profile *profile, QWidget *parent = nullptr); public slots: void ok(); diff --git a/gui/src/batch/adduniquewindow.cpp b/gui/src/batch/adduniquewindow.cpp index 6eb323ec6..dd2f4a190 100644 --- a/gui/src/batch/adduniquewindow.cpp +++ b/gui/src/batch/adduniquewindow.cpp @@ -12,7 +12,7 @@ AddUniqueWindow::AddUniqueWindow(Site *selected, Profile *profile, QWidget *parent) - : QDialog(parent), ui(new Ui::AddUniqueWindow), m_page(Q_NULLPTR), m_sites(profile->getSites()), m_close(Q_NULLPTR), m_profile(profile) + : QDialog(parent), ui(new Ui::AddUniqueWindow), m_page(nullptr), m_sites(profile->getSites()), m_close(nullptr), m_profile(profile) { ui->setupUi(this); @@ -53,7 +53,7 @@ void AddUniqueWindow::ok(bool close) m_close = close; Api *api = site->detailsApi(); - if (api != Q_NULLPTR) + if (api != nullptr) { const QString url = api->detailsUrl(ui->lineId->text().toULongLong(), ui->lineMd5->text(), site).url; diff --git a/gui/src/batch/adduniquewindow.h b/gui/src/batch/adduniquewindow.h index 88ec2902e..9decaf486 100644 --- a/gui/src/batch/adduniquewindow.h +++ b/gui/src/batch/adduniquewindow.h @@ -22,7 +22,7 @@ class AddUniqueWindow : public QDialog Q_OBJECT public: - AddUniqueWindow(Site *selected, Profile *profile, QWidget *parent = Q_NULLPTR); + AddUniqueWindow(Site *selected, Profile *profile, QWidget *parent = nullptr); public slots: void add(); diff --git a/gui/src/batch/batchwindow.cpp b/gui/src/batch/batchwindow.cpp index 2e3e9e006..1d557468b 100644 --- a/gui/src/batch/batchwindow.cpp +++ b/gui/src/batch/batchwindow.cpp @@ -216,7 +216,7 @@ void batchWindow::updateColumns() int batchWindow::indexOf(const QString &url) { const int i = m_urls.indexOf(url); - if (i < 0 || ui->tableWidget->item(i, 1) == Q_NULLPTR) + if (i < 0 || ui->tableWidget->item(i, 1) == nullptr) return -1; return i; } diff --git a/gui/src/batch/batchwindow.h b/gui/src/batch/batchwindow.h index ca2d7acec..44bfdf388 100644 --- a/gui/src/batch/batchwindow.h +++ b/gui/src/batch/batchwindow.h @@ -23,7 +23,7 @@ class batchWindow : public QDialog Q_OBJECT public: - explicit batchWindow(QSettings *settings, QWidget *parent = Q_NULLPTR); + explicit batchWindow(QSettings *settings, QWidget *parent = nullptr); ~batchWindow() override; int currentValue() const; int currentMax() const; diff --git a/gui/src/image-context-menu.h b/gui/src/image-context-menu.h index 910a5acbe..23b8a4150 100644 --- a/gui/src/image-context-menu.h +++ b/gui/src/image-context-menu.h @@ -14,7 +14,7 @@ class ImageContextMenu : public QMenu Q_OBJECT public: - ImageContextMenu(QSettings *settings, QSharedPointer img, mainWindow *mw, QWidget *parent = Q_NULLPTR); + ImageContextMenu(QSettings *settings, QSharedPointer img, mainWindow *mw, QWidget *parent = nullptr); protected slots: void openInBrowser(); diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index a86aef7cb..d581ca714 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -1681,7 +1681,7 @@ void mainWindow::_getAll() void mainWindow::getAllGetImageIfNotBlacklisted(const BatchDownloadImage &download, int siteId) { // Early return if we want to download blacklisted images - if (download.queryGroup == Q_NULLPTR || download.queryGroup->getBlacklisted) + if (download.queryGroup == nullptr || download.queryGroup->getBlacklisted) { getAllGetImage(download, siteId); return; @@ -1769,11 +1769,11 @@ void mainWindow::getAllPerformTags() log(QStringLiteral("Tags received"), Logger::Info); - const BatchDownloadImage *downloadPtr = Q_NULLPTR; + const BatchDownloadImage *downloadPtr = nullptr; for (const BatchDownloadImage &i : qAsConst(m_getAllDownloading)) if (i.image.data() == sender()) downloadPtr = &i; - if (downloadPtr == Q_NULLPTR) + if (downloadPtr == nullptr) { log(QStringLiteral("Tags received from unknown sender"), Logger::Error); return; @@ -1875,11 +1875,11 @@ void mainWindow::getAllGetImageSaved(const QSharedPointer &img, QMapsetupUi(this); diff --git a/gui/src/settings/web-service-window.h b/gui/src/settings/web-service-window.h index 2e492a929..82d0f4d85 100644 --- a/gui/src/settings/web-service-window.h +++ b/gui/src/settings/web-service-window.h @@ -19,7 +19,7 @@ class WebServiceWindow : public QDialog Q_OBJECT public: - explicit WebServiceWindow(const ReverseSearchEngine *webService, QWidget *parent = Q_NULLPTR); + explicit WebServiceWindow(const ReverseSearchEngine *webService, QWidget *parent = nullptr); ~WebServiceWindow() override; protected slots: diff --git a/gui/src/sources/sitewindow.h b/gui/src/sources/sitewindow.h index 0738e3663..7b0e89679 100644 --- a/gui/src/sources/sitewindow.h +++ b/gui/src/sources/sitewindow.h @@ -18,7 +18,7 @@ class SiteWindow : public QDialog Q_OBJECT public: - explicit SiteWindow(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit SiteWindow(Profile *profile, QWidget *parent = nullptr); ~SiteWindow() override; public slots: diff --git a/gui/src/sources/sourcessettingswindow.h b/gui/src/sources/sourcessettingswindow.h index 99ac79f20..b5dbc1e91 100644 --- a/gui/src/sources/sourcessettingswindow.h +++ b/gui/src/sources/sourcessettingswindow.h @@ -18,7 +18,7 @@ class SourcesSettingsWindow : public QDialog Q_OBJECT public: - explicit SourcesSettingsWindow(Profile *profile, Site* site, QWidget *parent = Q_NULLPTR); + explicit SourcesSettingsWindow(Profile *profile, Site* site, QWidget *parent = nullptr); ~SourcesSettingsWindow() override; public slots: diff --git a/gui/src/sources/sourceswindow.cpp b/gui/src/sources/sourceswindow.cpp index 44f1032a0..2bc705a00 100644 --- a/gui/src/sources/sourceswindow.cpp +++ b/gui/src/sources/sourceswindow.cpp @@ -15,7 +15,7 @@ sourcesWindow::sourcesWindow(Profile *profile, const QList &selected, QWidget *parent) - : QDialog(parent), ui(new Ui::sourcesWindow), m_profile(profile), m_selected(selected), m_sites(profile->getSites()), m_sources(profile->getSources()), m_checkForSourceReply(Q_NULLPTR) + : QDialog(parent), ui(new Ui::sourcesWindow), m_profile(profile), m_selected(selected), m_sites(profile->getSites()), m_sources(profile->getSources()), m_checkForSourceReply(nullptr) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); diff --git a/gui/src/sources/sourceswindow.h b/gui/src/sources/sourceswindow.h index b06138a24..93636acf2 100644 --- a/gui/src/sources/sourceswindow.h +++ b/gui/src/sources/sourceswindow.h @@ -24,7 +24,7 @@ class sourcesWindow : public QDialog Q_OBJECT public: - explicit sourcesWindow(Profile *profile, const QList &selected, QWidget *parent = Q_NULLPTR); + explicit sourcesWindow(Profile *profile, const QList &selected, QWidget *parent = nullptr); ~sourcesWindow() override; public slots: diff --git a/gui/src/tabs/search-tab.h b/gui/src/tabs/search-tab.h index ed8fbce54..aeeb8ba1e 100644 --- a/gui/src/tabs/search-tab.h +++ b/gui/src/tabs/search-tab.h @@ -57,7 +57,7 @@ class searchTab : public QWidget void setSelectedSources(QSettings *settings); void setTagsFromPages(const QMap > > &pages); void addHistory(const QString &tags, int page, int ipp, int cols); - QStringList reasonsToFail(Page *page, const QStringList &completion = QStringList(), QString *meant = Q_NULLPTR); + QStringList reasonsToFail(Page *page, const QStringList &completion = QStringList(), QString *meant = nullptr); void clear(); TextEdit *createAutocomplete(); void loadImageThumbnail(Page *page, QSharedPointer img, const QString &url); diff --git a/gui/src/tag-context-menu.h b/gui/src/tag-context-menu.h index 74b8a7032..aa189e0a6 100644 --- a/gui/src/tag-context-menu.h +++ b/gui/src/tag-context-menu.h @@ -14,7 +14,7 @@ class TagContextMenu : public QMenu Q_OBJECT public: - TagContextMenu(QString tag, QList allTags, QUrl browserUrl, Profile *profile, bool setImage = false, QWidget *parent = Q_NULLPTR); + TagContextMenu(QString tag, QList allTags, QUrl browserUrl, Profile *profile, bool setImage = false, QWidget *parent = nullptr); protected slots: void favorite(); diff --git a/gui/src/threads/image-loader-queue.h b/gui/src/threads/image-loader-queue.h index c86845d54..05f2ba917 100644 --- a/gui/src/threads/image-loader-queue.h +++ b/gui/src/threads/image-loader-queue.h @@ -11,7 +11,7 @@ class ImageLoaderQueue : public QObject Q_OBJECT public: - explicit ImageLoaderQueue(ImageLoader *imageLoader, QObject *parent = Q_NULLPTR); + explicit ImageLoaderQueue(ImageLoader *imageLoader, QObject *parent = nullptr); public slots: void load(const QByteArray &data); diff --git a/gui/src/threads/image-loader.h b/gui/src/threads/image-loader.h index e786a0c37..f5a9ad431 100644 --- a/gui/src/threads/image-loader.h +++ b/gui/src/threads/image-loader.h @@ -9,7 +9,7 @@ class ImageLoader : public QObject Q_OBJECT public: - explicit ImageLoader(QObject *parent = Q_NULLPTR); + explicit ImageLoader(QObject *parent = nullptr); public slots: void load(const QByteArray &data); diff --git a/gui/src/threads/resizer.h b/gui/src/threads/resizer.h index aa0a686e4..1e71acfb0 100644 --- a/gui/src/threads/resizer.h +++ b/gui/src/threads/resizer.h @@ -11,7 +11,7 @@ class Resizer : public QObject Q_OBJECT public: - explicit Resizer(QObject *parent = Q_NULLPTR); + explicit Resizer(QObject *parent = nullptr); public slots: void setSize(QSize size); diff --git a/gui/src/ui/QAffiche.cpp b/gui/src/ui/QAffiche.cpp index ffd23cd3c..821b29556 100644 --- a/gui/src/ui/QAffiche.cpp +++ b/gui/src/ui/QAffiche.cpp @@ -70,7 +70,7 @@ void QAffiche::leaveEvent(QEvent* e) void QAffiche::resizeEvent(QResizeEvent* e) { QMovie *mov = movie(); - if (mov != Q_NULLPTR) + if (mov != nullptr) { const QSize &movieSize = mov->currentPixmap().size(); const QSize &newSize = e->size(); diff --git a/gui/src/ui/QAffiche.h b/gui/src/ui/QAffiche.h index 3f139d37f..1a69489d4 100644 --- a/gui/src/ui/QAffiche.h +++ b/gui/src/ui/QAffiche.h @@ -10,7 +10,7 @@ class QAffiche : public QLabel Q_OBJECT public: - explicit QAffiche(const QVariant &id = QVariant(), int border = 0, QColor color = QColor(), QWidget *parent = Q_NULLPTR); + explicit QAffiche(const QVariant &id = QVariant(), int border = 0, QColor color = QColor(), QWidget *parent = nullptr); void setImage(const QImage &); void setImage(const QPixmap &); Qt::MouseButton lastPressed(); diff --git a/gui/src/ui/QBouton.h b/gui/src/ui/QBouton.h index f2ce2ad98..f61411503 100644 --- a/gui/src/ui/QBouton.h +++ b/gui/src/ui/QBouton.h @@ -10,7 +10,7 @@ class QBouton : public QPushButton Q_OBJECT public: - explicit QBouton(QVariant id = 0, bool resizeInsteadOfCropping = false, bool smartSizeHint = false, int border = 0, QColor color = QColor(), QWidget *parent = Q_NULLPTR); + explicit QBouton(QVariant id = 0, bool resizeInsteadOfCropping = false, bool smartSizeHint = false, int border = 0, QColor color = QColor(), QWidget *parent = nullptr); QVariant id() const; void mousePressEvent(QMouseEvent *event) override; QSize sizeHint() const override; diff --git a/gui/src/ui/fixed-size-grid-layout.cpp b/gui/src/ui/fixed-size-grid-layout.cpp index 2d3346d21..8f8df61cb 100644 --- a/gui/src/ui/fixed-size-grid-layout.cpp +++ b/gui/src/ui/fixed-size-grid-layout.cpp @@ -13,7 +13,7 @@ FixedSizeGridLayout::FixedSizeGridLayout(int hSpacing, int vSpacing) FixedSizeGridLayout::~FixedSizeGridLayout() { QLayoutItem *item; - while ((item = takeAt(0)) != Q_NULLPTR) + while ((item = takeAt(0)) != nullptr) delete item; } @@ -58,7 +58,7 @@ QLayoutItem *FixedSizeGridLayout::takeAt(int index) if (index >= 0 && index < m_items.size()) return m_items.takeAt(index); - return Q_NULLPTR; + return nullptr; } @@ -82,7 +82,7 @@ int FixedSizeGridLayout::verticalSpacing() const Qt::Orientations FixedSizeGridLayout::expandingDirections() const { - return Q_NULLPTR; + return nullptr; } bool FixedSizeGridLayout::hasHeightForWidth() const @@ -163,8 +163,8 @@ int FixedSizeGridLayout::smartSpacing(QStyle::PixelMetric pm) const if (parent->isWidgetType()) { auto *pw = dynamic_cast(parent); - if (pw != Q_NULLPTR) - return pw->style()->pixelMetric(pm, Q_NULLPTR, pw); + if (pw != nullptr) + return pw->style()->pixelMetric(pm, nullptr, pw); } return dynamic_cast(parent)->spacing(); diff --git a/gui/src/ui/qclosabletabwidget.cpp b/gui/src/ui/qclosabletabwidget.cpp index efc431268..14448bb60 100644 --- a/gui/src/ui/qclosabletabwidget.cpp +++ b/gui/src/ui/qclosabletabwidget.cpp @@ -14,7 +14,7 @@ bool QClosableTabWidget::eventFilter(QObject *o, QEvent *e) if (o == tabBar() && e->type() == QEvent::MouseButtonPress) { auto *mouseEvent = dynamic_cast(e); - if (mouseEvent != Q_NULLPTR && mouseEvent->button() == Qt::MiddleButton) + if (mouseEvent != nullptr && mouseEvent->button() == Qt::MiddleButton) { const int index = tabBar()->tabAt(mouseEvent->pos()); QWidget *w = widget(index); diff --git a/gui/src/ui/textedit.cpp b/gui/src/ui/textedit.cpp index ace8d22f9..aa0684e36 100644 --- a/gui/src/ui/textedit.cpp +++ b/gui/src/ui/textedit.cpp @@ -11,7 +11,7 @@ TextEdit::TextEdit(Profile *profile, QWidget *parent) - : QTextEdit(parent), c(Q_NULLPTR), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()) + : QTextEdit(parent), c(nullptr), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()) { setTabChangesFocus(true); setWordWrapMode(QTextOption::NoWrap); @@ -129,7 +129,7 @@ void TextEdit::setCompleter(QCompleter *completer) // Disconnect the previous completer if (c) - QObject::disconnect(c, Q_NULLPTR, this, Q_NULLPTR); + QObject::disconnect(c, nullptr, this, nullptr); // Set the new completer and connect it to the field c = completer; diff --git a/gui/src/ui/textedit.h b/gui/src/ui/textedit.h index 983752a8d..5650278a7 100644 --- a/gui/src/ui/textedit.h +++ b/gui/src/ui/textedit.h @@ -13,7 +13,7 @@ class TextEdit : public QTextEdit Q_OBJECT public: - explicit TextEdit(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit TextEdit(Profile *profile, QWidget *parent = nullptr); void setCompleter(QCompleter *completer); QCompleter *completer() const; QSize sizeHint() const override; diff --git a/gui/src/ui/verticalscrollarea.h b/gui/src/ui/verticalscrollarea.h index f249056b1..3a8c49d7d 100644 --- a/gui/src/ui/verticalscrollarea.h +++ b/gui/src/ui/verticalscrollarea.h @@ -11,7 +11,7 @@ class VerticalScrollArea : public QScrollArea Q_OBJECT public: - explicit VerticalScrollArea(QWidget *parent = Q_NULLPTR); + explicit VerticalScrollArea(QWidget *parent = nullptr); void resizeEvent(QResizeEvent *event) override; void setScrollEnabled(bool enabled); void wheelEvent(QWheelEvent* e) override; diff --git a/gui/src/updater/update-dialog.cpp b/gui/src/updater/update-dialog.cpp index 58c7fb363..e2bcabb80 100644 --- a/gui/src/updater/update-dialog.cpp +++ b/gui/src/updater/update-dialog.cpp @@ -9,7 +9,7 @@ UpdateDialog::UpdateDialog(bool *shouldQuit, QWidget *parent) - : QDialog(Q_NULLPTR), ui(new Ui::UpdateDialog), m_shouldQuit(shouldQuit), m_parent(parent) + : QDialog(nullptr), ui(new Ui::UpdateDialog), m_shouldQuit(shouldQuit), m_parent(parent) { ui->setupUi(this); @@ -96,7 +96,7 @@ void UpdateDialog::downloadFinished(const QString &path) QProcess::startDetached(path); - if (m_parent != Q_NULLPTR) + if (m_parent != nullptr) { m_parent->close(); } *m_shouldQuit = true; diff --git a/gui/src/updater/update-dialog.h b/gui/src/updater/update-dialog.h index 36d586d08..22c08cf44 100644 --- a/gui/src/updater/update-dialog.h +++ b/gui/src/updater/update-dialog.h @@ -17,7 +17,7 @@ class UpdateDialog : public QDialog Q_OBJECT public: - explicit UpdateDialog(bool *shouldQuit, QWidget *parent = Q_NULLPTR); + explicit UpdateDialog(bool *shouldQuit, QWidget *parent = nullptr); ~UpdateDialog() override; signals: diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-1.h b/gui/src/utils/blacklist-fix/blacklist-fix-1.h index 648a0ced7..f330da646 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-1.h +++ b/gui/src/utils/blacklist-fix/blacklist-fix-1.h @@ -20,7 +20,7 @@ class BlacklistFix1 : public QDialog Q_OBJECT public: - explicit BlacklistFix1(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit BlacklistFix1(Profile *profile, QWidget *parent = nullptr); ~BlacklistFix1() override; private slots: diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-2.h b/gui/src/utils/blacklist-fix/blacklist-fix-2.h index 90e37f17d..de5402ad2 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-2.h +++ b/gui/src/utils/blacklist-fix/blacklist-fix-2.h @@ -18,7 +18,7 @@ class BlacklistFix2 : public QDialog Q_OBJECT public: - explicit BlacklistFix2(QList> details, Blacklist blacklist, QWidget *parent = Q_NULLPTR); + explicit BlacklistFix2(QList> details, Blacklist blacklist, QWidget *parent = nullptr); ~BlacklistFix2() override; private slots: diff --git a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.h b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.h index 053b50951..1919b2266 100644 --- a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.h +++ b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.h @@ -19,7 +19,7 @@ class EmptyDirsFix1 : public QDialog Q_OBJECT public: - explicit EmptyDirsFix1(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit EmptyDirsFix1(Profile *profile, QWidget *parent = nullptr); ~EmptyDirsFix1() override; public slots: diff --git a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.h b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.h index 21d45ea6c..6072a1b4c 100644 --- a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.h +++ b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-2.h @@ -19,7 +19,7 @@ class EmptyDirsFix2 : public QDialog Q_OBJECT public: - explicit EmptyDirsFix2(const QStringList &folders, QWidget *parent = Q_NULLPTR); + explicit EmptyDirsFix2(const QStringList &folders, QWidget *parent = nullptr); ~EmptyDirsFix2() override; bool removeDir(QString); diff --git a/gui/src/utils/md5-fix/md5-fix.h b/gui/src/utils/md5-fix/md5-fix.h index 7f0f9aa58..90d627ebf 100644 --- a/gui/src/utils/md5-fix/md5-fix.h +++ b/gui/src/utils/md5-fix/md5-fix.h @@ -18,7 +18,7 @@ class md5Fix : public QDialog Q_OBJECT public: - explicit md5Fix(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit md5Fix(Profile *profile, QWidget *parent = nullptr); ~md5Fix() override; private slots: diff --git a/gui/src/utils/rename-existing/rename-existing-1.h b/gui/src/utils/rename-existing/rename-existing-1.h index e3dd3722c..3e78b5e7e 100644 --- a/gui/src/utils/rename-existing/rename-existing-1.h +++ b/gui/src/utils/rename-existing/rename-existing-1.h @@ -21,7 +21,7 @@ class RenameExisting1 : public QDialog Q_OBJECT public: - explicit RenameExisting1(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit RenameExisting1(Profile *profile, QWidget *parent = nullptr); ~RenameExisting1() override; private slots: diff --git a/gui/src/utils/rename-existing/rename-existing-2.h b/gui/src/utils/rename-existing/rename-existing-2.h index 1434803f4..eae9dcccd 100644 --- a/gui/src/utils/rename-existing/rename-existing-2.h +++ b/gui/src/utils/rename-existing/rename-existing-2.h @@ -17,7 +17,7 @@ class RenameExisting2 : public QDialog Q_OBJECT public: - explicit RenameExisting2(QList details, QString folder, QWidget *parent = Q_NULLPTR); + explicit RenameExisting2(QList details, QString folder, QWidget *parent = nullptr); ~RenameExisting2() override; void deleteDir(const QString &path); diff --git a/gui/src/utils/tag-loader/tag-loader.h b/gui/src/utils/tag-loader/tag-loader.h index 307f2cdeb..7075084b1 100644 --- a/gui/src/utils/tag-loader/tag-loader.h +++ b/gui/src/utils/tag-loader/tag-loader.h @@ -20,7 +20,7 @@ class TagLoader : public QDialog Q_OBJECT public: - explicit TagLoader(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit TagLoader(Profile *profile, QWidget *parent = nullptr); ~TagLoader() override; protected: diff --git a/gui/src/viewer/details-window.h b/gui/src/viewer/details-window.h index d692abbe6..5fc7d57df 100644 --- a/gui/src/viewer/details-window.h +++ b/gui/src/viewer/details-window.h @@ -18,7 +18,7 @@ class DetailsWindow : public QDialog Q_OBJECT public: - explicit DetailsWindow(Profile *profile, QWidget *parent = Q_NULLPTR); + explicit DetailsWindow(Profile *profile, QWidget *parent = nullptr); ~DetailsWindow() override; void setImage(const QSharedPointer &image); diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 9b1a66e9c..d2014efa7 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -26,7 +26,7 @@ ZoomWindow::ZoomWindow(QList> images, const QSharedPointer &image, Site *site, Profile *profile, mainWindow *parent) - : QWidget(Q_NULLPTR, Qt::Window), m_parent(parent), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()), m_ignore(profile->getIgnored()), m_settings(profile->getSettings()), ui(new Ui::ZoomWindow), m_site(site), m_timeout(300), m_tooBig(false), m_loadedImage(false), m_loadedDetails(false), m_finished(false), m_size(0), m_fullScreen(nullptr), m_isFullscreen(false), m_isSlideshowRunning(false), m_images(std::move(images)), m_displayImage(QPixmap()), m_displayMovie(Q_NULLPTR), m_labelImageScaled(false) + : QWidget(nullptr, Qt::Window), m_parent(parent), m_profile(profile), m_favorites(profile->getFavorites()), m_viewItLater(profile->getKeptForLater()), m_ignore(profile->getIgnored()), m_settings(profile->getSettings()), ui(new Ui::ZoomWindow), m_site(site), m_timeout(300), m_tooBig(false), m_loadedImage(false), m_loadedDetails(false), m_finished(false), m_size(0), m_fullScreen(nullptr), m_isFullscreen(false), m_isSlideshowRunning(false), m_images(std::move(images)), m_displayImage(QPixmap()), m_displayMovie(nullptr), m_labelImageScaled(false) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); diff --git a/lib/src/commands/sql-worker.h b/lib/src/commands/sql-worker.h index 13c660e90..0904ef78e 100644 --- a/lib/src/commands/sql-worker.h +++ b/lib/src/commands/sql-worker.h @@ -10,7 +10,7 @@ class SqlWorker : public QThread Q_OBJECT public: - SqlWorker(QString driver, QString host, QString user, QString password, QString database, QObject *parent = Q_NULLPTR); + SqlWorker(QString driver, QString host, QString user, QString password, QString database, QObject *parent = nullptr); bool connect(); static QString escape(const QVariant &val); diff --git a/lib/src/custom-network-access-manager.h b/lib/src/custom-network-access-manager.h index 91daf8816..e721475b4 100644 --- a/lib/src/custom-network-access-manager.h +++ b/lib/src/custom-network-access-manager.h @@ -11,7 +11,7 @@ class CustomNetworkAccessManager : public QNetworkAccessManager Q_OBJECT public: - explicit CustomNetworkAccessManager(QObject *parent = Q_NULLPTR); + explicit CustomNetworkAccessManager(QObject *parent = nullptr); QNetworkReply *get(const QNetworkRequest &request); void sslErrorHandler(QNetworkReply *reply, const QList &errors); diff --git a/lib/src/downloader/downloader.cpp b/lib/src/downloader/downloader.cpp index 78dc5d180..cc201df1e 100644 --- a/lib/src/downloader/downloader.cpp +++ b/lib/src/downloader/downloader.cpp @@ -32,7 +32,7 @@ void Downloader::clear() } Downloader::Downloader(Profile *profile, QStringList tags, QStringList postFiltering, QList sources, int page, int max, int perPage, QString location, QString filename, QString user, QString password, bool blacklist, Blacklist blacklistedTags, bool noDuplicates, int tagsMin, QString tagsFormat, Downloader *previous) - : m_profile(profile), m_lastPage(Q_NULLPTR), m_tags(std::move(tags)), m_postFiltering(std::move(postFiltering)), m_sites(std::move(sources)), m_page(page), m_max(max), m_perPage(perPage), m_waiting(0), m_ignored(0), m_duplicates(0), m_tagsMin(tagsMin), m_location(std::move(location)), m_filename(std::move(filename)), m_user(std::move(user)), m_password(std::move(password)), m_blacklist(blacklist), m_noDuplicates(noDuplicates), m_tagsFormat(std::move(tagsFormat)), m_blacklistedTags(std::move(blacklistedTags)), m_cancelled(false), m_quit(false), m_previous(previous) + : m_profile(profile), m_lastPage(nullptr), m_tags(std::move(tags)), m_postFiltering(std::move(postFiltering)), m_sites(std::move(sources)), m_page(page), m_max(max), m_perPage(perPage), m_waiting(0), m_ignored(0), m_duplicates(0), m_tagsMin(tagsMin), m_location(std::move(location)), m_filename(std::move(filename)), m_user(std::move(user)), m_password(std::move(password)), m_blacklist(blacklist), m_noDuplicates(noDuplicates), m_tagsFormat(std::move(tagsFormat)), m_blacklistedTags(std::move(blacklistedTags)), m_cancelled(false), m_quit(false), m_previous(previous) { } void Downloader::setQuit(bool quit) diff --git a/lib/src/downloader/extension-rotator.h b/lib/src/downloader/extension-rotator.h index 79c0e2ae5..e0f3a2695 100644 --- a/lib/src/downloader/extension-rotator.h +++ b/lib/src/downloader/extension-rotator.h @@ -13,7 +13,7 @@ class ExtensionRotator : public QObject public: ExtensionRotator() = default; explicit ExtensionRotator(const ExtensionRotator &other); - explicit ExtensionRotator(const QString &initialExtension, const QStringList &extensions, QObject *parent = Q_NULLPTR); + explicit ExtensionRotator(const QString &initialExtension, const QStringList &extensions, QObject *parent = nullptr); QString next(); private: diff --git a/lib/src/downloader/file-downloader.cpp b/lib/src/downloader/file-downloader.cpp index ece7de1a2..13547accc 100644 --- a/lib/src/downloader/file-downloader.cpp +++ b/lib/src/downloader/file-downloader.cpp @@ -6,7 +6,7 @@ FileDownloader::FileDownloader(QObject *parent) - : QObject(parent), m_reply(Q_NULLPTR), m_writeError(false) + : QObject(parent), m_reply(nullptr), m_writeError(false) {} bool FileDownloader::start(QNetworkReply *reply, const QString &path) diff --git a/lib/src/downloader/file-downloader.h b/lib/src/downloader/file-downloader.h index 0d3278a39..612dba0be 100644 --- a/lib/src/downloader/file-downloader.h +++ b/lib/src/downloader/file-downloader.h @@ -11,7 +11,7 @@ class FileDownloader : public QObject Q_OBJECT public: - explicit FileDownloader(QObject *parent = Q_NULLPTR); + explicit FileDownloader(QObject *parent = nullptr); bool start(QNetworkReply *reply, const QString &path); bool start(QNetworkReply *reply, const QStringList &paths); diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 53dc514e8..a7fabbace 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -85,7 +85,7 @@ void ImageDownloader::loadImage() connect(&m_fileDownloader, &FileDownloader::writeError, this, &ImageDownloader::writeError, Qt::UniqueConnection); // Delete previous replies for retries - if (m_reply != Q_NULLPTR) + if (m_reply != nullptr) { m_reply->deleteLater(); } // Load the image directly on the disk diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index 3fd48c9a2..1b55e78f8 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -12,8 +12,8 @@ class ImageDownloader : public QObject Q_OBJECT public: - ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent = Q_NULLPTR, bool loadTags = false, bool rotate = true); - ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent = Q_NULLPTR, bool rotate = true); + ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool loadTags = false, bool rotate = true); + ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool rotate = true); public slots: void save(); @@ -48,7 +48,7 @@ class ImageDownloader : public QObject bool m_writeError; bool m_rotate; - QNetworkReply *m_reply = Q_NULLPTR; + QNetworkReply *m_reply = nullptr; QString m_url = ""; bool m_tryingSample = false; }; diff --git a/lib/src/loader/downloadable-downloader.cpp b/lib/src/loader/downloadable-downloader.cpp index c3aaf1aac..ff09663f2 100644 --- a/lib/src/loader/downloadable-downloader.cpp +++ b/lib/src/loader/downloadable-downloader.cpp @@ -59,7 +59,7 @@ void DownloadableDownloader::preloaded() // Load the image directly on the disk log(QStringLiteral("Loading and saving image in %1").arg(m_paths.first())); m_url = m_site->fixUrl(url); - QNetworkReply *reply = m_site->get(m_url, Q_NULLPTR, QStringLiteral("image"), Q_NULLPTR); // TODO(Bionus) + QNetworkReply *reply = m_site->get(m_url, nullptr, QStringLiteral("image"), nullptr); // TODO(Bionus) connect(&m_fileDownloader, &FileDownloader::writeError, this, &DownloadableDownloader::writeError, Qt::UniqueConnection); connect(&m_fileDownloader, &FileDownloader::networkError, this, &DownloadableDownloader::networkError, Qt::UniqueConnection); connect(&m_fileDownloader, &FileDownloader::success, this, &DownloadableDownloader::success, Qt::UniqueConnection); diff --git a/lib/src/loader/downloadable-downloader.h b/lib/src/loader/downloadable-downloader.h index 6232c7d5c..59a91df30 100644 --- a/lib/src/loader/downloadable-downloader.h +++ b/lib/src/loader/downloadable-downloader.h @@ -15,7 +15,7 @@ class DownloadableDownloader : public QObject Q_OBJECT public: - explicit DownloadableDownloader(QSharedPointer downloadable, Site *site, int count, bool addMd5, bool startCommands, bool loadTags, QObject *parent = Q_NULLPTR); + explicit DownloadableDownloader(QSharedPointer downloadable, Site *site, int count, bool addMd5, bool startCommands, bool loadTags, QObject *parent = nullptr); void setPath(const Filename &filename, const QString &folder); void setPath(const QStringList &paths); void save(); diff --git a/lib/src/loader/loader-query.cpp b/lib/src/loader/loader-query.cpp index 88e4955cc..e6c21079b 100644 --- a/lib/src/loader/loader-query.cpp +++ b/lib/src/loader/loader-query.cpp @@ -45,7 +45,7 @@ LoaderData LoaderQuery::next() // Load results QEventLoop loop; - Page request(profile, m_site, QList() << m_site, tags, page + m_offset, perPage, postFiltering, true, Q_NULLPTR); + Page request(profile, m_site, QList() << m_site, tags, page + m_offset, perPage, postFiltering, true, nullptr); QObject::connect(&request, &Page::finishedLoading, &loop, &QEventLoop::quit); QObject::connect(&request, &Page::failedLoading, &loop, &QEventLoop::quit); request.load(false); diff --git a/lib/src/login/http-login.cpp b/lib/src/login/http-login.cpp index ef1b50236..fe7c8d646 100644 --- a/lib/src/login/http-login.cpp +++ b/lib/src/login/http-login.cpp @@ -9,7 +9,7 @@ HttpLogin::HttpLogin(QString type, Site *site, CustomNetworkAccessManager *manager, MixedSettings *settings) - : m_type(std::move(type)), m_site(site), m_loginReply(Q_NULLPTR), m_manager(manager), m_settings(settings) + : m_type(std::move(type)), m_site(site), m_loginReply(nullptr), m_manager(manager), m_settings(settings) {} bool HttpLogin::isTestable() const @@ -32,7 +32,7 @@ void HttpLogin::login() { query.addQueryItem(key, m_settings->value(key).toString()); } m_settings->endGroup(); - if (m_loginReply != Q_NULLPTR) + if (m_loginReply != nullptr) { m_loginReply->abort(); m_loginReply->deleteLater(); diff --git a/lib/src/login/url-login.cpp b/lib/src/login/url-login.cpp index eb50e642f..cb07c2d28 100644 --- a/lib/src/login/url-login.cpp +++ b/lib/src/login/url-login.cpp @@ -7,7 +7,7 @@ UrlLogin::UrlLogin(Site *site, QNetworkAccessManager *manager, MixedSettings *settings) - : m_site(site), m_manager(manager), m_settings(settings), m_page(Q_NULLPTR) + : m_site(site), m_manager(manager), m_settings(settings), m_page(nullptr) {} bool UrlLogin::isTestable() const @@ -17,7 +17,7 @@ bool UrlLogin::isTestable() const void UrlLogin::login() { - if (m_page != Q_NULLPTR) + if (m_page != nullptr) { m_page->abort(); m_page->deleteLater(); diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index 54656cf6e..34237f9e6 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -65,7 +65,7 @@ void JavascriptApi::fillUrlObject(const QJSValue &result, Site *site, PageUrl &r { url = result.toString(); } // Site-ize url - if (site != Q_NULLPTR) + if (site != nullptr) { url = site->fixLoginUrl(url); url = site->fixUrl(url).toString(); @@ -425,7 +425,7 @@ PageUrl JavascriptApi::checkUrl() const } const QJSValue result = urlFunction.call(); - fillUrlObject(result, Q_NULLPTR, ret); + fillUrlObject(result, nullptr, ret); return ret; } diff --git a/lib/src/models/api/javascript-console-helper.h b/lib/src/models/api/javascript-console-helper.h index 2db64a6dc..c092a416f 100644 --- a/lib/src/models/api/javascript-console-helper.h +++ b/lib/src/models/api/javascript-console-helper.h @@ -9,7 +9,7 @@ class JavascriptConsoleHelper : public QObject Q_OBJECT public: - explicit JavascriptConsoleHelper(QString prefix, QObject *parent = Q_NULLPTR); + explicit JavascriptConsoleHelper(QString prefix, QObject *parent = nullptr); Q_INVOKABLE void debug(const QString &msg) const; Q_INVOKABLE void error(const QString &msg) const; diff --git a/lib/src/models/filtering/filter-factory.cpp b/lib/src/models/filtering/filter-factory.cpp index 830f66ffc..87546693c 100644 --- a/lib/src/models/filtering/filter-factory.cpp +++ b/lib/src/models/filtering/filter-factory.cpp @@ -38,5 +38,5 @@ Filter *FilterFactory::build(QString filter) return new TagFilter(filter.trimmed(), invert); } - return Q_NULLPTR; + return nullptr; } diff --git a/lib/src/models/filtering/meta-filter.cpp b/lib/src/models/filtering/meta-filter.cpp index b20f3d4a7..bc44f2fd8 100644 --- a/lib/src/models/filtering/meta-filter.cpp +++ b/lib/src/models/filtering/meta-filter.cpp @@ -16,7 +16,7 @@ QString MetaFilter::toString() const bool MetaFilter::compare(const Filter& rhs) const { const auto other = dynamic_cast(&rhs); - if (other == Q_NULLPTR) + if (other == nullptr) return false; return m_type == other->m_type && m_val == other->m_val; diff --git a/lib/src/models/filtering/tag-filter.cpp b/lib/src/models/filtering/tag-filter.cpp index 64cc0d948..1f9608df6 100644 --- a/lib/src/models/filtering/tag-filter.cpp +++ b/lib/src/models/filtering/tag-filter.cpp @@ -19,7 +19,7 @@ QString TagFilter::toString() const bool TagFilter::compare(const Filter& rhs) const { const auto other = dynamic_cast(&rhs); - if (other == Q_NULLPTR) + if (other == nullptr) return false; return m_tag == other->m_tag; diff --git a/lib/src/models/filtering/token-filter.cpp b/lib/src/models/filtering/token-filter.cpp index 0c99546e0..6917a6748 100644 --- a/lib/src/models/filtering/token-filter.cpp +++ b/lib/src/models/filtering/token-filter.cpp @@ -15,7 +15,7 @@ QString TokenFilter::toString() const bool TokenFilter::compare(const Filter& rhs) const { const auto other = dynamic_cast(&rhs); - if (other == Q_NULLPTR) + if (other == nullptr) return false; return m_token == other->m_token; diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 3c46a6390..9443e73c0 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -38,7 +38,7 @@ QString removeCacheUrl(QString url) } Image::Image() - : m_profile(Q_NULLPTR), m_extensionRotator(Q_NULLPTR) + : m_profile(nullptr), m_extensionRotator(nullptr) { } // TODO(Bionus): clean up this mess @@ -97,7 +97,7 @@ Image::Image(const Image &other) } Image::Image(Site *site, QMap details, Profile *profile, Page* parent) - : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(Q_NULLPTR), m_loadImageError(QNetworkReply::NetworkError::NoError) + : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(nullptr), m_loadImageError(QNetworkReply::NetworkError::NoError) { m_settings = m_profile->getSettings(); @@ -136,7 +136,7 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* else { Api *api = m_parentSite->detailsApi(); - if (api != Q_NULLPTR) + if (api != nullptr) { m_pageUrl = api->detailsUrl(m_id, m_md5, m_parentSite).url; } } m_pageUrl = site->fixUrl(m_pageUrl).toString(); @@ -353,7 +353,7 @@ void Image::parseDetails() // Get an api able to parse details Api *api = m_parentSite->detailsApi(); - if (api == Q_NULLPTR) + if (api == nullptr) return; // Parse source diff --git a/lib/src/models/image.h b/lib/src/models/image.h index 00063e0cf..796c2b624 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -22,7 +22,7 @@ class Image : public QObject, public Downloadable public: Image(); - Image(Site *site, QMap details, Profile *profile, Page *parent = Q_NULLPTR); + Image(Site *site, QMap details, Profile *profile, Page *parent = nullptr); Image(const Image &other); int value() const; QStringList path(QString fn = "", QString pth = "", int counter = 0, bool complex = true, bool simple = false, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false) const; diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 8251e4be1..7c4935415 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -15,7 +15,7 @@ PageApi::PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags, int page, int limit, PostFilter postFiltering, bool smart, QObject *parent, int pool, int lastPage, qulonglong lastPageMinId, qulonglong lastPageMaxId) - : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(std::move(tags)), m_errors(QStringList()), m_postFiltering(std::move(postFiltering)), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(Q_NULLPTR), m_replyTags(Q_NULLPTR) + : QObject(parent), m_parentPage(parentPage), m_profile(profile), m_site(site), m_api(api), m_search(std::move(tags)), m_errors(QStringList()), m_postFiltering(std::move(postFiltering)), m_imagesPerPage(limit), m_lastPage(lastPage), m_lastPageMinId(lastPageMinId), m_lastPageMaxId(lastPageMaxId), m_smart(smart), m_reply(nullptr), m_replyTags(nullptr) { m_imagesCount = -1; m_maxImagesCount = -1; diff --git a/lib/src/models/page-api.h b/lib/src/models/page-api.h index 5f3c4b948..92f10f9ba 100644 --- a/lib/src/models/page-api.h +++ b/lib/src/models/page-api.h @@ -23,7 +23,7 @@ class PageApi : public QObject Error }; - explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags = QStringList(), int page = 1, int limit = 25, PostFilter postFiltering = PostFilter(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); + explicit PageApi(Page *parentPage, Profile *profile, Site *site, Api *api, QStringList tags = QStringList(), int page = 1, int limit = 25, PostFilter postFiltering = PostFilter(), bool smart = false, QObject *parent = nullptr, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); void setLastPage(Page *page); const QList> &images() const; bool isImageCountSure() const; diff --git a/lib/src/models/page.h b/lib/src/models/page.h index b6dae2ed9..a18b2241c 100644 --- a/lib/src/models/page.h +++ b/lib/src/models/page.h @@ -18,7 +18,7 @@ class Page : public QObject Q_OBJECT public: - explicit Page(Profile *profile, Site *site, const QList &sites, QStringList tags = QStringList(), int page = 1, int limit = 25, const QStringList &postFiltering = QStringList(), bool smart = false, QObject *parent = Q_NULLPTR, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); + explicit Page(Profile *profile, Site *site, const QList &sites, QStringList tags = QStringList(), int page = 1, int limit = 25, const QStringList &postFiltering = QStringList(), bool smart = false, QObject *parent = nullptr, int pool = 0, int lastPage = 0, qulonglong lastPageMinId = 0, qulonglong lastPageMaxId = 0); ~Page() override; void setLastPage(Page *page); void fallback(bool loadIfPossible = true); diff --git a/lib/src/models/profile.cpp b/lib/src/models/profile.cpp index 0bf5cea09..dde733af4 100644 --- a/lib/src/models/profile.cpp +++ b/lib/src/models/profile.cpp @@ -10,10 +10,10 @@ Profile::Profile() - : m_settings(Q_NULLPTR), m_commands(Q_NULLPTR) + : m_settings(nullptr), m_commands(nullptr) {} Profile::Profile(QSettings *settings, QList favorites, QStringList keptForLater, QString path) - : m_path(std::move(path)), m_settings(settings), m_favorites(std::move(favorites)), m_keptForLater(std::move(keptForLater)), m_commands(Q_NULLPTR) + : m_path(std::move(path)), m_settings(settings), m_favorites(std::move(favorites)), m_keptForLater(std::move(keptForLater)), m_commands(nullptr) {} Profile::Profile(QString path) : m_path(std::move(path)) diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index b74b359d8..e465d2868 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -31,7 +31,7 @@ Site::Site(QString url, Source *source) - : m_type(source->getName()), m_url(std::move(url)), m_source(source), m_settings(Q_NULLPTR), m_manager(Q_NULLPTR), m_cookieJar(Q_NULLPTR), m_updateReply(Q_NULLPTR), m_tagsReply(Q_NULLPTR), m_tagDatabase(Q_NULLPTR), m_login(Q_NULLPTR), m_loggedIn(LoginStatus::Unknown), m_autoLogin(true) + : m_type(source->getName()), m_url(std::move(url)), m_source(source), m_settings(nullptr), m_manager(nullptr), m_cookieJar(nullptr), m_updateReply(nullptr), m_tagsReply(nullptr), m_tagDatabase(nullptr), m_login(nullptr), m_loggedIn(LoginStatus::Unknown), m_autoLogin(true) { // Create the access manager and get its slots m_manager = new CustomNetworkAccessManager(this); @@ -229,7 +229,7 @@ QNetworkRequest Site::makeRequest(QUrl url, Page *page, const QString &ref, Imag QString referer = m_settings->value("referer"+(!ref.isEmpty() ? "_"+ref : QString())).toString(); if (referer.isEmpty() && !ref.isEmpty()) { referer = m_settings->value("referer", "none").toString(); } - if (referer != "none" && (referer != "page" || page != Q_NULLPTR)) + if (referer != "none" && (referer != "page" || page != nullptr)) { QString refHeader; if (referer == "host") @@ -368,7 +368,7 @@ Api *Site::detailsApi() const for (Api *api : m_apis) if (api->canLoadDetails()) return api; - return Q_NULLPTR; + return nullptr; } bool Site::autoLogin() const { return m_autoLogin; } diff --git a/lib/src/models/source-guesser.cpp b/lib/src/models/source-guesser.cpp index 38a03b9e3..05b57ada6 100644 --- a/lib/src/models/source-guesser.cpp +++ b/lib/src/models/source-guesser.cpp @@ -64,6 +64,6 @@ Source *SourceGuesser::start() } } - emit finished(Q_NULLPTR); - return Q_NULLPTR; + emit finished(nullptr); + return nullptr; } diff --git a/lib/src/models/source.cpp b/lib/src/models/source.cpp index cf1ab4de1..08c3e1edc 100644 --- a/lib/src/models/source.cpp +++ b/lib/src/models/source.cpp @@ -25,9 +25,9 @@ QString getUpdaterBaseUrl() QJSEngine *Source::jsEngine() { - static QJSEngine *engine = Q_NULLPTR; + static QJSEngine *engine = nullptr; - if (engine == Q_NULLPTR) + if (engine == nullptr) { engine = new QJSEngine(); engine->globalObject().setProperty("Grabber", engine->newQObject(new JavascriptGrabberHelper(*engine))); @@ -51,9 +51,9 @@ QJSEngine *Source::jsEngine() } QMutex *Source::jsEngineMutex() { - static QMutex *mutex = Q_NULLPTR; + static QMutex *mutex = nullptr; - if (mutex == Q_NULLPTR) + if (mutex == nullptr) { mutex = new QMutex(); } return mutex; diff --git a/lib/src/tags/tag-api.cpp b/lib/src/tags/tag-api.cpp index a7e05105f..7bf2ef26d 100755 --- a/lib/src/tags/tag-api.cpp +++ b/lib/src/tags/tag-api.cpp @@ -7,7 +7,7 @@ TagApi::TagApi(Profile *profile, Site *site, Api *api, int page, int limit, QObject *parent) - : QObject(parent), m_profile(profile), m_site(site), m_api(api), m_page(page), m_limit(limit), m_reply(Q_NULLPTR) + : QObject(parent), m_profile(profile), m_site(site), m_api(api), m_page(page), m_limit(limit), m_reply(nullptr) { const QString url = api->tagsUrl(page, limit, site).url; m_url = m_site->fixUrl(url); diff --git a/lib/src/tags/tag-api.h b/lib/src/tags/tag-api.h index 2955a8d8d..de6f154e4 100644 --- a/lib/src/tags/tag-api.h +++ b/lib/src/tags/tag-api.h @@ -21,7 +21,7 @@ class TagApi : public QObject Error }; - explicit TagApi(Profile *profile, Site *site, Api *api, int page = 1, int limit = 1000, QObject *parent = Q_NULLPTR); + explicit TagApi(Profile *profile, Site *site, Api *api, int page = 1, int limit = 1000, QObject *parent = nullptr); ~TagApi() override; void load(bool rateLimit = false); const QList &tags() const; diff --git a/lib/src/updater/program-updater.cpp b/lib/src/updater/program-updater.cpp index 238ceae6e..9e88cc85b 100644 --- a/lib/src/updater/program-updater.cpp +++ b/lib/src/updater/program-updater.cpp @@ -12,7 +12,7 @@ ProgramUpdater::ProgramUpdater() { } ProgramUpdater::ProgramUpdater(QString baseUrl) - : m_baseUrl(std::move(baseUrl)), m_downloadReply(Q_NULLPTR) + : m_baseUrl(std::move(baseUrl)), m_downloadReply(nullptr) { } void ProgramUpdater::checkForUpdates() const diff --git a/lib/src/vendor/qcustomnetworkreply.h b/lib/src/vendor/qcustomnetworkreply.h index b2c99ce16..26227a08f 100644 --- a/lib/src/vendor/qcustomnetworkreply.h +++ b/lib/src/vendor/qcustomnetworkreply.h @@ -9,7 +9,7 @@ class QCustomNetworkReply : public QNetworkReply Q_OBJECT public: - explicit QCustomNetworkReply(QObject *parent = Q_NULLPTR); + explicit QCustomNetworkReply(QObject *parent = nullptr); ~QCustomNetworkReply() override; void setHttpStatusCode(int code, const QByteArray &statusText = QByteArray()); diff --git a/tests/src/downloader/image-downloader-test.cpp b/tests/src/downloader/image-downloader-test.cpp index d5db819df..8eec735e0 100644 --- a/tests/src/downloader/image-downloader-test.cpp +++ b/tests/src/downloader/image-downloader-test.cpp @@ -46,7 +46,7 @@ Image *ImageDownloaderTest::createImage(bool noMd5) void ImageDownloaderTest::testSuccessBasic() { QSharedPointer img(createImage()); - ImageDownloader downloader(img, "out.jpg", "tests/resources/tmp", 1, false, false, Q_NULLPTR, false, false); + ImageDownloader downloader(img, "out.jpg", "tests/resources/tmp", 1, false, false, nullptr, false, false); QMap expected; expected.insert(QDir::toNativeSeparators("tests/resources/tmp/out.jpg"), Image::SaveResult::Saved); @@ -57,7 +57,7 @@ void ImageDownloaderTest::testSuccessBasic() void ImageDownloaderTest::testSuccessLoadTags() { QSharedPointer img(createImage()); - ImageDownloader downloader(img, "%copyright%.%ext%", "tests/resources/tmp", 1, false, false, Q_NULLPTR, true, false); + ImageDownloader downloader(img, "%copyright%.%ext%", "tests/resources/tmp", 1, false, false, nullptr, true, false); QMap expected; expected.insert(QDir::toNativeSeparators("tests/resources/tmp/to heart 2.jpg"), Image::SaveResult::Saved); @@ -68,7 +68,7 @@ void ImageDownloaderTest::testSuccessLoadTags() void ImageDownloaderTest::testOpenError() { QSharedPointer img(createImage()); - ImageDownloader downloader(img, "///", "///root/toto", 1, false, false, Q_NULLPTR, false, false); + ImageDownloader downloader(img, "///", "///root/toto", 1, false, false, nullptr, false, false); QMap expected; expected.insert(QDir::toNativeSeparators("//root/toto/"), Image::SaveResult::Error); @@ -79,7 +79,7 @@ void ImageDownloaderTest::testOpenError() void ImageDownloaderTest::testNotFound() { QSharedPointer img(createImage()); - ImageDownloader downloader(img, "out.jpg", "tests/resources/tmp", 1, false, false, Q_NULLPTR, false, false); + ImageDownloader downloader(img, "out.jpg", "tests/resources/tmp", 1, false, false, nullptr, false, false); QMap expected; expected.insert(QDir::toNativeSeparators("tests/resources/tmp/out.jpg"), Image::SaveResult::NotFound); @@ -92,7 +92,7 @@ void ImageDownloaderTest::testNotFound() void ImageDownloaderTest::testNetworkError() { QSharedPointer img(createImage()); - ImageDownloader downloader(img, "out.jpg", "tests/resources/tmp", 1, false, false, Q_NULLPTR, false, false); + ImageDownloader downloader(img, "out.jpg", "tests/resources/tmp", 1, false, false, nullptr, false, false); QMap expected; expected.insert(QDir::toNativeSeparators("tests/resources/tmp/out.jpg"), Image::SaveResult::NetworkError); @@ -105,7 +105,7 @@ void ImageDownloaderTest::testNetworkError() void ImageDownloaderTest::testOriginalMd5() { QSharedPointer img(createImage()); - ImageDownloader downloader(img, "%md5%.%ext%", "tests/resources/tmp", 1, false, false, Q_NULLPTR, false, false); + ImageDownloader downloader(img, "%md5%.%ext%", "tests/resources/tmp", 1, false, false, nullptr, false, false); QMap expected; expected.insert(QDir::toNativeSeparators("tests/resources/tmp/1bc29b36f623ba82aaf6724fd3b16718.jpg"), Image::SaveResult::Saved); @@ -116,7 +116,7 @@ void ImageDownloaderTest::testOriginalMd5() void ImageDownloaderTest::testGeneratedMd5() { QSharedPointer img(createImage(true)); - ImageDownloader downloader(img, "%md5%.%ext%", "tests/resources/tmp", 1, false, false, Q_NULLPTR, false, false); + ImageDownloader downloader(img, "%md5%.%ext%", "tests/resources/tmp", 1, false, false, nullptr, false, false); QMap expected; expected.insert(QDir::toNativeSeparators("tests/resources/tmp/956ddde86fb5ce85218b21e2f49e5c50.jpg"), Image::SaveResult::Saved); @@ -127,7 +127,7 @@ void ImageDownloaderTest::testGeneratedMd5() void ImageDownloaderTest::testRotateExtension() { QSharedPointer img(createImage()); - ImageDownloader downloader(img, "%md5%.%ext%", "tests/resources/tmp", 1, false, false, Q_NULLPTR, false, true); + ImageDownloader downloader(img, "%md5%.%ext%", "tests/resources/tmp", 1, false, false, nullptr, false, true); QMap expected; expected.insert(QDir::toNativeSeparators("tests/resources/tmp/1bc29b36f623ba82aaf6724fd3b16718.png"), Image::SaveResult::Saved); From e6b00797a5d1132c8bbca21f9720e65d32491905 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 22:57:46 +0200 Subject: [PATCH 041/112] Add comparison tests for filters --- .../src/models/filtering/meta-filter-test.cpp | 12 ++++++++++ tests/src/models/filtering/meta-filter-test.h | 1 + .../src/models/filtering/tag-filter-test.cpp | 23 ++++++++++++++++++- tests/src/models/filtering/tag-filter-test.h | 4 +++- .../models/filtering/token-filter-test.cpp | 7 ++++++ .../src/models/filtering/token-filter-test.h | 1 + 6 files changed, 46 insertions(+), 2 deletions(-) diff --git a/tests/src/models/filtering/meta-filter-test.cpp b/tests/src/models/filtering/meta-filter-test.cpp index 93c2a76df..be0f127fd 100644 --- a/tests/src/models/filtering/meta-filter-test.cpp +++ b/tests/src/models/filtering/meta-filter-test.cpp @@ -10,6 +10,14 @@ void MetaFilterTest::testToString() QCOMPARE(MetaFilter("meta", "val", true).toString(), QString("-meta:val")); } +void MetaFilterTest::testCompare() +{ + QCOMPARE(MetaFilter("meta", "val") == MetaFilter("meta", "val"), true); + QCOMPARE(MetaFilter("meta", "val") == MetaFilter("meta", "val", true), false); + QCOMPARE(MetaFilter("meta", "val") == MetaFilter("another meta", "val"), false); + QCOMPARE(MetaFilter("meta", "val") == MetaFilter("meta", "another val"), false); +} + void MetaFilterTest::testMatchInvalidToken() { QMap tokens; @@ -43,6 +51,8 @@ void MetaFilterTest::testMatchMathematical() // Basic QCOMPARE(MetaFilter("id", ">1000").match(tokens), QString()); + QCOMPARE(MetaFilter("id", ">=1000").match(tokens), QString()); + QCOMPARE(MetaFilter("id", "<1000").match(tokens), QString("image's id does not match")); QCOMPARE(MetaFilter("id", "<=1000").match(tokens), QString("image's id does not match")); QCOMPARE(MetaFilter("id", "1000..").match(tokens), QString()); QCOMPARE(MetaFilter("id", "..1000").match(tokens), QString("image's id does not match")); @@ -51,6 +61,8 @@ void MetaFilterTest::testMatchMathematical() // Invert QCOMPARE(MetaFilter("id", ">1000", true).match(tokens), QString("image's id match")); + QCOMPARE(MetaFilter("id", ">=1000", true).match(tokens), QString("image's id match")); + QCOMPARE(MetaFilter("id", "<1000", true).match(tokens), QString()); QCOMPARE(MetaFilter("id", "<=1000", true).match(tokens), QString()); QCOMPARE(MetaFilter("id", "1000..", true).match(tokens), QString("image's id match")); QCOMPARE(MetaFilter("id", "..1000", true).match(tokens), QString()); diff --git a/tests/src/models/filtering/meta-filter-test.h b/tests/src/models/filtering/meta-filter-test.h index b0149c23d..1f33d0a9f 100644 --- a/tests/src/models/filtering/meta-filter-test.h +++ b/tests/src/models/filtering/meta-filter-test.h @@ -10,6 +10,7 @@ class MetaFilterTest : public TestSuite private slots: void testToString(); + void testCompare(); void testMatchInvalidToken(); void testMatchGrabber(); void testMatchMathematical(); diff --git a/tests/src/models/filtering/tag-filter-test.cpp b/tests/src/models/filtering/tag-filter-test.cpp index 5f888c318..d4b96d8ca 100644 --- a/tests/src/models/filtering/tag-filter-test.cpp +++ b/tests/src/models/filtering/tag-filter-test.cpp @@ -10,7 +10,14 @@ void TagFilterTest::testToString() QCOMPARE(TagFilter("test", true).toString(), QString("-test")); } -void TagFilterTest::testMatch() +void TagFilterTest::testCompare() +{ + QCOMPARE(TagFilter("test") == TagFilter("test"), true); + QCOMPARE(TagFilter("test") == TagFilter("test", true), false); + QCOMPARE(TagFilter("test") == TagFilter("another test"), false); +} + +void TagFilterTest::testMatchExact() { QMap tokens; tokens.insert("allos", Token(QStringList() << "ok" << "ok2")); @@ -24,5 +31,19 @@ void TagFilterTest::testMatch() QCOMPARE(TagFilter("nok", true).match(tokens), QString()); } +void TagFilterTest::testMatchWildcard() +{ + QMap tokens; + tokens.insert("allos", Token(QStringList() << "abc" << "bcd" << "cde", "def")); + + // Basic + QCOMPARE(TagFilter("bc*").match(tokens), QString()); + QCOMPARE(TagFilter("ef*").match(tokens), QString("image does not contains \"ef*\"")); + + // Invert + QCOMPARE(TagFilter("bc*", true).match(tokens), QString("image contains \"bc*\"")); + QCOMPARE(TagFilter("ef*", true).match(tokens), QString()); +} + static TagFilterTest instance; diff --git a/tests/src/models/filtering/tag-filter-test.h b/tests/src/models/filtering/tag-filter-test.h index bf6d585c1..c89d92929 100644 --- a/tests/src/models/filtering/tag-filter-test.h +++ b/tests/src/models/filtering/tag-filter-test.h @@ -10,7 +10,9 @@ class TagFilterTest : public TestSuite private slots: void testToString(); - void testMatch(); + void testCompare(); + void testMatchExact(); + void testMatchWildcard(); }; #endif // TAG_FILTER_TEST_H diff --git a/tests/src/models/filtering/token-filter-test.cpp b/tests/src/models/filtering/token-filter-test.cpp index 332dfd6bd..060e19974 100644 --- a/tests/src/models/filtering/token-filter-test.cpp +++ b/tests/src/models/filtering/token-filter-test.cpp @@ -10,6 +10,13 @@ void TokenFilterTest::testToString() QCOMPARE(TokenFilter("test", true).toString(), QString("-%test%")); } +void TokenFilterTest::testCompare() +{ + QCOMPARE(TokenFilter("test") == TokenFilter("test"), true); + QCOMPARE(TokenFilter("test") == TokenFilter("test", true), false); + QCOMPARE(TokenFilter("test") == TokenFilter("another test"), false); +} + void TokenFilterTest::testMatchInt() { QMap tokens; diff --git a/tests/src/models/filtering/token-filter-test.h b/tests/src/models/filtering/token-filter-test.h index a33ed3ec2..987ec05a3 100644 --- a/tests/src/models/filtering/token-filter-test.h +++ b/tests/src/models/filtering/token-filter-test.h @@ -10,6 +10,7 @@ class TokenFilterTest : public TestSuite private slots: void testToString(); + void testCompare(); void testMatchInt(); void testMatchString(); void testMatchStringList(); From 3381254e42f50af16ce3764032a0bb90ec80308f Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 23:17:58 +0200 Subject: [PATCH 042/112] Add test for Blacklist::toString --- lib/src/models/filtering/blacklist.cpp | 3 ++- tests/src/models/filtering/blacklist-test.cpp | 10 ++++++++++ tests/src/models/filtering/blacklist-test.h | 1 + 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/src/models/filtering/blacklist.cpp b/lib/src/models/filtering/blacklist.cpp index 5b68bdcee..b858d9fb1 100644 --- a/lib/src/models/filtering/blacklist.cpp +++ b/lib/src/models/filtering/blacklist.cpp @@ -62,13 +62,14 @@ QString Blacklist::toString() const QString ret; for (const auto &filters : qAsConst(m_filters)) { + if (!ret.isEmpty()) + { ret.append("\n"); } for (int i = 0; i < filters.count(); ++i) { if (i != 0) { ret.append(' '); } ret.append(filters[i]->toString()); } - ret.append("\n"); } return ret; } diff --git a/tests/src/models/filtering/blacklist-test.cpp b/tests/src/models/filtering/blacklist-test.cpp index 7edf3d787..d53694d71 100644 --- a/tests/src/models/filtering/blacklist-test.cpp +++ b/tests/src/models/filtering/blacklist-test.cpp @@ -4,6 +4,16 @@ #include "models/filtering/blacklist.h" +void BlacklistTest::testToString() +{ + Blacklist blacklist; + blacklist.add("tag1"); + blacklist.add(QStringList() << "tag2" << "tag3"); + blacklist.add("tag4"); + + QCOMPARE(blacklist.toString(), QString("tag1\ntag2 tag3\ntag4")); +} + void BlacklistTest::testContains() { Blacklist blacklist(QStringList() << "tag1" << "tag2"); diff --git a/tests/src/models/filtering/blacklist-test.h b/tests/src/models/filtering/blacklist-test.h index 78e5ad4dc..b59abf439 100644 --- a/tests/src/models/filtering/blacklist-test.h +++ b/tests/src/models/filtering/blacklist-test.h @@ -9,6 +9,7 @@ class BlacklistTest : public TestSuite Q_OBJECT private slots: + void testToString(); void testContains(); void testRemove(); void testMatch(); From 330ac614b563075658df24e522f7dcf8086d8685 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 23:21:42 +0200 Subject: [PATCH 043/112] Use std::sort instead of qSort --- gui/src/mainwindow.cpp | 4 ++-- gui/src/settings/optionswindow.cpp | 3 ++- gui/src/tabs/search-tab.cpp | 3 ++- lib/src/models/filename.cpp | 2 +- tests/src/tags/tag-test.cpp | 7 ++++--- 5 files changed, 11 insertions(+), 8 deletions(-) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index d581ca714..a6839c489 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -752,7 +752,7 @@ void mainWindow::batchClearSelUniques() } void mainWindow::batchRemoveGroups(QList rows) { - qSort(rows); + std::sort(rows.begin(), rows.end()); int rem = 0; for (int i : qAsConst(rows)) @@ -769,7 +769,7 @@ void mainWindow::batchRemoveGroups(QList rows) } void mainWindow::batchRemoveUniques(QList rows) { - qSort(rows); + std::sort(rows.begin(), rows.end()); int rem = 0; for (int i : qAsConst(rows)) diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index ddc7bdc1e..24b5daf1f 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include "functions.h" #include "helpers.h" @@ -651,7 +652,7 @@ void optionsWindow::swapWebServices(int a, int b) m_webServices[a].setOrder(pos); // Re-order web services - qSort(m_webServices.begin(), m_webServices.end(), sortByOrder); + std::sort(m_webServices.begin(), m_webServices.end(), sortByOrder); m_webServicesIds.clear(); for (int i = 0; i < m_webServices.count(); ++i) m_webServicesIds.insert(m_webServices[i].id(), i); diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index 62faa0d84..c4b29b91a 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "downloader/download-query-image.h" #include "downloader/image-downloader.h" #include "functions.h" @@ -156,7 +157,7 @@ void searchTab::setTagsFromPages(const QMap> } // We sort tags by frequency - qSort(tagList.begin(), tagList.end(), sortTagsByCount); + std::sort(tagList.begin(), tagList.end(), sortTagsByCount); m_tags = tagList; m_parent->setTags(m_tags, this); diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index 7c48c2f6f..7128b8933 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -491,7 +491,7 @@ QString Filename::optionedValue(const QVariant &val, const QString &key, const Q if (options.contains("separator")) { tagSeparator = fixSeparator(options["separator"]); } if (options.contains("sort")) - { qSort(vals); } + { std::sort(vals.begin(), vals.end()); } // Clean each value separately for (QString &t : vals) diff --git a/tests/src/tags/tag-test.cpp b/tests/src/tags/tag-test.cpp index 216802bda..bbb46a656 100644 --- a/tests/src/tags/tag-test.cpp +++ b/tests/src/tags/tag-test.cpp @@ -1,5 +1,6 @@ #include "tag-test.h" #include +#include void TagTest::init() @@ -145,7 +146,7 @@ void TagTest::testSortTagsByType() tagList.append(Tag("second", "character", 4, QStringList() << "tag4")); tagList.append(Tag("first", "unknown", 5, QStringList() << "tag5")); - qSort(tagList.begin(), tagList.end(), sortTagsByType); + std::sort(tagList.begin(), tagList.end(), sortTagsByType); QCOMPARE(tagList[0].text(), QString("third")); QCOMPARE(tagList[1].text(), QString("second")); @@ -162,7 +163,7 @@ void TagTest::testSortTagsByName() tagList.append(Tag("second", "character", 4, QStringList() << "tag4")); tagList.append(Tag("first", "unknown", 5, QStringList() << "tag5")); - qSort(tagList.begin(), tagList.end(), sortTagsByName); + std::sort(tagList.begin(), tagList.end(), sortTagsByName); QCOMPARE(tagList[0].text(), QString("first")); QCOMPARE(tagList[1].text(), QString("fourth")); @@ -179,7 +180,7 @@ void TagTest::testSortTagsByCount() tagList.append(Tag("second", "character", 4, QStringList() << "tag4")); tagList.append(Tag("first", "unknown", 5, QStringList() << "tag5")); - qSort(tagList.begin(), tagList.end(), sortTagsByCount); + std::sort(tagList.begin(), tagList.end(), sortTagsByCount); QCOMPARE(tagList[0].text(), QString("first")); QCOMPARE(tagList[1].text(), QString("second")); From 191473ace16e9c90aecfc15b243422b39238c12b Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 23:34:39 +0200 Subject: [PATCH 044/112] Add sorting tests for the Favorite class --- gui/src/mainwindow.cpp | 2 +- gui/src/tabs/favorites-tab.cpp | 2 +- lib/src/models/favorite.cpp | 2 +- lib/src/models/favorite.h | 2 +- lib/src/models/monitor.cpp | 13 +++++++ lib/src/models/monitor.h | 3 ++ tests/src/models/favorite-test.cpp | 60 ++++++++++++++++++++++++++++++ tests/src/models/favorite-test.h | 4 ++ 8 files changed, 84 insertions(+), 4 deletions(-) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index a6839c489..b0ff3786e 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -915,7 +915,7 @@ void mainWindow::updateFavorites() if (order == "note") { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByNote); } else if (order == "lastviewed") - { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByLastviewed); } + { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByLastViewed); } else { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByName); } if (reverse) diff --git a/gui/src/tabs/favorites-tab.cpp b/gui/src/tabs/favorites-tab.cpp index e5f414371..630e7bcad 100644 --- a/gui/src/tabs/favorites-tab.cpp +++ b/gui/src/tabs/favorites-tab.cpp @@ -118,7 +118,7 @@ void favoritesTab::updateFavorites() if (order == "note") { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByNote); } else if (order == "lastviewed") - { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByLastviewed); } + { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByLastViewed); } else { std::sort(m_favorites.begin(), m_favorites.end(), Favorite::sortByName); } if (reverse) diff --git a/lib/src/models/favorite.cpp b/lib/src/models/favorite.cpp index 63cbe06db..b38610c0a 100644 --- a/lib/src/models/favorite.cpp +++ b/lib/src/models/favorite.cpp @@ -114,7 +114,7 @@ bool Favorite::sortByNote(const Favorite &s1, const Favorite &s2) { return s1.getNote() < s2.getNote(); } bool Favorite::sortByName(const Favorite &s1, const Favorite &s2) { return s1.getName().toLower() < s2.getName().toLower(); } -bool Favorite::sortByLastviewed(const Favorite &s1, const Favorite &s2) +bool Favorite::sortByLastViewed(const Favorite &s1, const Favorite &s2) { return s1.getLastViewed() < s2.getLastViewed(); } diff --git a/lib/src/models/favorite.h b/lib/src/models/favorite.h index a9578f0b0..01313f9ce 100644 --- a/lib/src/models/favorite.h +++ b/lib/src/models/favorite.h @@ -41,7 +41,7 @@ class Favorite static bool sortByNote(const Favorite &s1, const Favorite &s2); static bool sortByName(const Favorite &s1, const Favorite &s2); - static bool sortByLastviewed(const Favorite &s1, const Favorite &s2); + static bool sortByLastViewed(const Favorite &s1, const Favorite &s2); private: QString m_name; diff --git a/lib/src/models/monitor.cpp b/lib/src/models/monitor.cpp index 262033415..e6ab9c406 100644 --- a/lib/src/models/monitor.cpp +++ b/lib/src/models/monitor.cpp @@ -68,3 +68,16 @@ Monitor Monitor::fromJson(const QJsonObject &json, const QMap &s return Monitor(site, interval, lastCheck, cumulated, preciseCumulated); } + + +bool operator==(const Monitor &lhs, const Monitor &rhs) +{ + return lhs.site() == rhs.site() + && lhs.interval() == rhs.interval() + && lhs.lastCheck() == rhs.lastCheck() + && lhs.cumulated() == rhs.cumulated() + && lhs.preciseCumulated() == rhs.preciseCumulated(); +} + +bool operator!=(const Monitor &lhs, const Monitor &rhs) +{ return !(lhs == rhs); } diff --git a/lib/src/models/monitor.h b/lib/src/models/monitor.h index 462beab55..5d5dfad3e 100644 --- a/lib/src/models/monitor.h +++ b/lib/src/models/monitor.h @@ -34,4 +34,7 @@ class Monitor bool m_preciseCumulated; }; +bool operator==(const Monitor &lhs, const Monitor &rhs); +bool operator!=(const Monitor &lhs, const Monitor &rhs); + #endif // MONITORING_H diff --git a/tests/src/models/favorite-test.cpp b/tests/src/models/favorite-test.cpp index 77c7f3b1e..9c4f16591 100644 --- a/tests/src/models/favorite-test.cpp +++ b/tests/src/models/favorite-test.cpp @@ -1,5 +1,6 @@ #include "favorite-test.h" #include +#include #include "functions.h" @@ -76,6 +77,17 @@ void FavoriteTest::testSetImagePath() QCOMPARE(fav.getImagePath(), QString("test/newimage.jpg")); } +void FavoriteTest::testGetMonitors() +{ + QDateTime date = QDateTime::fromString("2016-07-02 16:35:12", "yyyy-MM-dd HH:mm:ss"); + Monitor monitor(nullptr, 60, date); + Favorite fav("fate/stay_night", 50, date, QList() << monitor, "test/test.jpg"); + fav.setImagePath("test/newimage.jpg"); + + QCOMPARE(fav.getMonitors().count(), 1); + QCOMPARE(fav.getMonitors().first(), monitor); +} + void FavoriteTest::testEquals() { QDateTime date = QDateTime::fromString("2016-07-02 16:35:12", "yyyy-MM-dd HH:mm:ss"); @@ -211,5 +223,53 @@ void FavoriteTest::testFromString() QCOMPARE(actual.getLastViewed(), expected.getLastViewed()); } +void FavoriteTest::testSortByNote() +{ + QList favorites = + { + Favorite("f1", 2, QDateTime(QDate(2018, 1, 3))), + Favorite("f2", 3, QDateTime(QDate(2018, 1, 1))), + Favorite("f3", 1, QDateTime(QDate(2018, 1, 2))) + }; + + std::sort(favorites.begin(), favorites.end(), Favorite::sortByNote); + + QCOMPARE(favorites[0].getName(), QString("f3")); + QCOMPARE(favorites[1].getName(), QString("f1")); + QCOMPARE(favorites[2].getName(), QString("f2")); +} + +void FavoriteTest::testSortByName() +{ + QList favorites = + { + Favorite("f1", 2, QDateTime(QDate(2018, 1, 3))), + Favorite("f2", 3, QDateTime(QDate(2018, 1, 1))), + Favorite("f3", 1, QDateTime(QDate(2018, 1, 2))) + }; + + std::sort(favorites.begin(), favorites.end(), Favorite::sortByName); + + QCOMPARE(favorites[0].getName(), QString("f1")); + QCOMPARE(favorites[1].getName(), QString("f2")); + QCOMPARE(favorites[2].getName(), QString("f3")); +} + +void FavoriteTest::testSortByLastViewed() +{ + QList favorites = + { + Favorite("f1", 2, QDateTime(QDate(2018, 1, 3))), + Favorite("f2", 3, QDateTime(QDate(2018, 1, 1))), + Favorite("f3", 1, QDateTime(QDate(2018, 1, 2))) + }; + + std::sort(favorites.begin(), favorites.end(), Favorite::sortByLastViewed); + + QCOMPARE(favorites[0].getName(), QString("f2")); + QCOMPARE(favorites[1].getName(), QString("f3")); + QCOMPARE(favorites[2].getName(), QString("f1")); +} + static FavoriteTest instance; diff --git a/tests/src/models/favorite-test.h b/tests/src/models/favorite-test.h index 04b97419e..8c9a43925 100644 --- a/tests/src/models/favorite-test.h +++ b/tests/src/models/favorite-test.h @@ -19,6 +19,7 @@ class FavoriteTest : public TestSuite void testSetLastViewed(); void testGetImagePath(); void testSetImagePath(); + void testGetMonitors(); void testEquals(); void testEqualsAll(); void testEqualsCase(); @@ -32,6 +33,9 @@ class FavoriteTest : public TestSuite #endif void testToString(); void testFromString(); + void testSortByNote(); + void testSortByName(); + void testSortByLastViewed(); }; #endif // FAVORITE_TEST_H From 2e037a244827107047c76cd7f7eb1ac5f4d51783 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 11 Jul 2018 23:45:59 +0200 Subject: [PATCH 045/112] Remove source code for old Api classes --- lib/src/models/api/api.cpp | 233 +--------------- lib/src/models/api/api.h | 31 ++- lib/src/models/api/html-api.cpp | 213 --------------- lib/src/models/api/html-api.h | 18 -- lib/src/models/api/javascript-api.cpp | 2 +- lib/src/models/api/json-api.cpp | 252 ------------------ lib/src/models/api/json-api.h | 17 -- lib/src/models/api/rss-api.cpp | 88 ------ lib/src/models/api/rss-api.h | 18 -- lib/src/models/api/xml-api.cpp | 161 ----------- lib/src/models/api/xml-api.h | 17 -- lib/src/models/monitor.cpp | 1 - lib/src/models/source.cpp | 51 +--- .../integration/integration-test-suite.cpp | 9 - tests/src/models/source-test.cpp | 32 ++- tests/src/models/source-test.h | 2 + tests/src/test-suite.cpp | 44 +-- tests/src/test-suite.h | 4 +- 18 files changed, 78 insertions(+), 1115 deletions(-) delete mode 100644 lib/src/models/api/html-api.cpp delete mode 100644 lib/src/models/api/html-api.h delete mode 100644 lib/src/models/api/json-api.cpp delete mode 100644 lib/src/models/api/json-api.h delete mode 100644 lib/src/models/api/rss-api.cpp delete mode 100644 lib/src/models/api/rss-api.h delete mode 100644 lib/src/models/api/xml-api.cpp delete mode 100644 lib/src/models/api/xml-api.h diff --git a/lib/src/models/api/api.cpp b/lib/src/models/api/api.cpp index 3c8334b0c..89972b394 100644 --- a/lib/src/models/api/api.cpp +++ b/lib/src/models/api/api.cpp @@ -22,204 +22,12 @@ Api::Api(QString name, QMap data) QString Api::getName() const { return m_name; } -bool Api::needAuth() const { return contains("Urls/NeedAuth") && value("Urls/NeedAuth").toLower() == "true"; } bool Api::contains(const QString &key) const { return m_data.contains(key); } QString Api::value(const QString &key) const { return m_data.value(key); } -PageUrl Api::pageUrl(const QString &search, int page, int limit, int lastPage, int lastPageMinId, int lastPageMaxId, Site *site) const -{ - PageUrl ret; - QString url; - QString srch = search; - - // Default tag is none is given - if (m_data.contains("DefaultTag") && srch.isEmpty()) - { - srch = m_data.value("DefaultTag"); } - - // Find page number - const int forced = forcedLimit(); - const int pidLimit = forced > 0 ? forced : limit; - const int pid = pidLimit * (page - 1); - page = page - 1 + m_data.value("FirstPage").toInt(); - - // Custom URL for pool search - if (m_data.contains("Urls/Pools")) - { - QRegularExpression poolRx("pool:(\\d+)"); - auto match = poolRx.match(srch); - if (match.hasMatch()) - { - url = m_data.value("Urls/Pools"); - url.replace("{pool}", match.captured(1)); - } - } - - // Home URL for empty searches - if (url.isEmpty()) - { - if (srch.isEmpty() && m_data.contains("Urls/Home")) - { url = m_data.value("Urls/Home"); } - else - { url = m_data.value("Urls/Tags"); } - } - - // Return an error if we are trying to do a search on a non-compatible API - if (!srch.isEmpty() && !url.contains("{tags}")) - { - ret.error = tr("Tag search is impossible with the chosen source (%1).").arg(m_name); - return ret; - } - - int maxPage = -1; - if (site->isLoggedIn() && m_data.contains("Urls/MaxPageLoggedIn")) - { maxPage = m_data.value("Urls/MaxPageLoggedIn").toInt(); } - else if (m_data.contains("Urls/MaxPage")) - { maxPage = m_data.value("Urls/MaxPage").toInt(); } - - const bool isAltPage = maxPage >= 0 && page > maxPage && page - 1 <= lastPage && lastPage <= page + 1; - if (m_data.contains("Urls/NormalPage")) - { url.replace("{cpage}", isAltPage ? "{altpage}" : m_data.value("Urls/NormalPage")); } - if (isAltPage) - { - url.replace("{altpage}", m_data.value("Urls/AltPage" + QString(lastPage > page ? "Prev" : "Next"))); - url.replace("{pagepart}", ""); - } - else - { - if (m_data.contains("Urls/PagePart")) - { url.replace("{pagepart}", m_data.value("Urls/PagePart")); } - url.replace("{altpage}", ""); - } - - // Basic replaces - url.replace("{tags}", QUrl::toPercentEncoding(srch)); - url.replace("{limit}", QString::number(limit)); - - // Previous page replaces - url.replace("{min}", QString::number(lastPageMinId)); - url.replace("{max}", QString::number(lastPageMaxId)); - url.replace("{min-1}", QString::number(lastPageMinId - 1)); - url.replace("{max-1}", QString::number(lastPageMaxId - 1)); - url.replace("{min+1}", QString::number(lastPageMinId + 1)); - url.replace("{max+1}", QString::number(lastPageMaxId + 1)); - - // Page replaces - url.replace("{pid}", QString::number(pid)); - url.replace("{page}", QString::number(page)); - - // Add login information - url = site->fixLoginUrl(url, value("Urls/Login")); - - ret.url = url; - return ret; -} - -PageUrl Api::tagsUrl(int page, int limit, Site *site) const -{ - PageUrl ret; - QString url = value("Urls/TagApi"); - - // Basic information - page = page - 1 + value("FirstPage").toInt(); - url.replace("{page}", QString::number(page)); - url.replace("{limit}", QString::number(limit)); - - // Add login information - url = site->fixLoginUrl(url, value("Urls/Login")); - - ret.url = url; - return ret; -} - -PageUrl Api::detailsUrl(qulonglong id, const QString &md5, Site *site) const -{ - PageUrl ret; - - QString url = value("Urls/Html/Post"); - url.replace("{id}", QString::number(id)); - url.replace("{md5}", md5); - url = site->fixLoginUrl(url, value("Urls/Login")); - - ret.url = url; - return ret; -} - -ParsedDetails Api::parseDetails(const QString &source, Site *site) const -{ - Q_UNUSED(source); - Q_UNUSED(site); - - ParsedDetails ret; - ret.error = "Not implemented"; - return ret; -} - -PageUrl Api::checkUrl() const -{ - PageUrl ret; - ret.url = value("Check/Url"); - return ret; -} - -ParsedCheck Api::parseCheck(const QString &source) const -{ - ParsedCheck ret; - - QRegularExpression rx(value("Check/Regex")); - ret.ok = rx.match(source).hasMatch(); - - return ret; -} - - -QString Api::parseSetImageUrl(Site *site, const QString &settingUrl, const QString &settingReplaces, QString ret, QMap *d, bool replaces, const QString &def) const -{ - if (contains(settingUrl) && ret.length() < 5) - { - QStringList options = value(settingUrl).split('|'); - for (QString opt : options) - { - if (opt.contains("{tim}") && d->value("tim").isEmpty()) - return QString(); - - opt.replace("{id}", d->value("id")) - .replace("{md5}", d->value("md5")) - .replace("{ext}", d->value("ext", "jpg")) - .replace("{tim}", d->value("tim")) - .replace("{website}", site->url()); - - if (!opt.endsWith("/." + d->value("ext")) && !opt.contains('{')) - { - ret = opt; - break; - } - } - } - else if (contains(settingReplaces) && replaces) - { - if (ret.isEmpty() && !def.isEmpty()) - ret = def; - - QStringList reps = value(settingReplaces).split('&'); - for (const QString &rep : reps) - { - const QRegularExpression rgx(rep.left(rep.indexOf("->"))); - ret.replace(rgx, rep.right(rep.size() - rep.indexOf("->") - 2)); - } - } - QString fixed = site->fixUrl(ret).toString(); - - // Clean fake webp files - if (fixed.endsWith(QLatin1String(".jpg.webp"))) - fixed = fixed.left(fixed.length() - 5); - - return fixed; -} - -QSharedPointer Api::parseImage(Page *parentPage, QMap d, int position, const QList &tags, bool replaces) const +QSharedPointer Api::parseImage(Page *parentPage, QMap d, int position, const QList &tags) const { Site *site = parentPage->site(); @@ -235,14 +43,6 @@ QSharedPointer Api::parseImage(Page *parentPage, QMap d if (!d.contains("preview_url")) { d["preview_url"] = ""; } - if (replaces) - { - // Fix urls - d["file_url"] = parseSetImageUrl(site, "Urls/Image", "Urls/ImageReplaces", d["file_url"], &d, true, d["preview_url"]); - d["sample_url"] = parseSetImageUrl(site, "Urls/Sample", "Urls/SampleReplaces", d["sample_url"], &d, true, d["preview_url"]); - d["preview_url"] = parseSetImageUrl(site, "Urls/Preview", "Urls/PreviewReplaces", d["preview_url"], &d); - } - if (d["file_url"].isEmpty()) { d["file_url"] = d["preview_url"]; } if (d["sample_url"].isEmpty()) @@ -268,34 +68,3 @@ QSharedPointer Api::parseImage(Page *parentPage, QMap d return img; } - -bool Api::canLoadTags() const -{ return contains("Urls/TagApi"); } -bool Api::canLoadDetails() const -{ return contains("Urls/Post"); } -bool Api::canLoadCheck() const -{ return contains("Check/Url") && contains("Check/Regex"); } -int Api::forcedLimit() const -{ return contains("Urls/Limit") ? value("Urls/Limit").toInt() : 0; } -int Api::maxLimit() const -{ - const int forced = forcedLimit(); - if (forced > 0) - return forced; - - return contains("Urls/MaxLimit") ? value("Urls/MaxLimit").toInt() : 0; -} - -QStringList Api::modifiers() const -{ return value("Modifiers").trimmed().split(" ", QString::SkipEmptyParts); } -QStringList Api::forcedTokens() const -{ - QStringList ret; - if (contains("Regex/NeedLoad")) - ret.append("*"); - if (contains("Regex/ForceImageUrl")) - ret.append("file_url"); - if ((m_name == "Html" || m_name == "Rss") && contains("Regex/ImageDate")) - ret.append("date"); - return ret; -} diff --git a/lib/src/models/api/api.h b/lib/src/models/api/api.h index bf263fe31..2ca94284f 100644 --- a/lib/src/models/api/api.h +++ b/lib/src/models/api/api.h @@ -54,7 +54,7 @@ class Api : public QObject // Getters QString getName() const; - virtual bool needAuth() const; + virtual bool needAuth() const = 0; // Info getters bool contains(const QString &key) const; @@ -62,25 +62,24 @@ class Api : public QObject QString operator[](const QString &key) const { return value(key); } // API - virtual PageUrl pageUrl(const QString &search, int page, int limit, int lastPage, int lastPageMinId, int lastPageMaxId, Site *site) const; + virtual PageUrl pageUrl(const QString &search, int page, int limit, int lastPage, int lastPageMinId, int lastPageMaxId, Site *site) const = 0; virtual ParsedPage parsePage(Page *parentPage, const QString &source, int first, int limit) const = 0; - virtual PageUrl tagsUrl(int page, int limit, Site *site) const; + virtual PageUrl tagsUrl(int page, int limit, Site *site) const = 0; virtual ParsedTags parseTags(const QString &source, Site *site) const = 0; - virtual PageUrl detailsUrl(qulonglong id, const QString &md5, Site *site) const; - virtual ParsedDetails parseDetails(const QString &source, Site *site) const; - virtual PageUrl checkUrl() const; - virtual ParsedCheck parseCheck(const QString &source) const; - virtual bool canLoadTags() const; - virtual bool canLoadDetails() const; - virtual bool canLoadCheck() const; - virtual int forcedLimit() const; - virtual int maxLimit() const; - virtual QStringList modifiers() const; - virtual QStringList forcedTokens() const; + virtual PageUrl detailsUrl(qulonglong id, const QString &md5, Site *site) const = 0; + virtual ParsedDetails parseDetails(const QString &source, Site *site) const = 0; + virtual PageUrl checkUrl() const = 0; + virtual ParsedCheck parseCheck(const QString &source) const = 0; + virtual bool canLoadTags() const = 0; + virtual bool canLoadDetails() const = 0; + virtual bool canLoadCheck() const = 0; + virtual int forcedLimit() const = 0; + virtual int maxLimit() const = 0; + virtual QStringList modifiers() const = 0; + virtual QStringList forcedTokens() const = 0; protected: - QSharedPointer parseImage(Page *parentPage, QMap d, int position, const QList &tags = QList(), bool replaces = true) const; - QString parseSetImageUrl(Site *site, const QString &settingUrl, const QString &settingReplaces, QString ret, QMap *d, bool replaces = true, const QString &def = QString()) const; + QSharedPointer parseImage(Page *parentPage, QMap d, int position, const QList &tags = QList()) const; private: QString m_name; diff --git a/lib/src/models/api/html-api.cpp b/lib/src/models/api/html-api.cpp deleted file mode 100644 index 94c11e665..000000000 --- a/lib/src/models/api/html-api.cpp +++ /dev/null @@ -1,213 +0,0 @@ -#include "models/api/html-api.h" -#include -#include -#include "functions.h" -#include "models/api/api.h" -#include "models/site.h" -#include "tags/tag-database.h" -#include "vendor/json.h" - - -HtmlApi::HtmlApi(const QMap &data) - : Api("Html", data) -{} - -ParsedPage HtmlApi::parsePage(Page *parentPage, const QString &source, int first, int limit) const -{ - ParsedPage ret; - - // Getting tags - if (contains("Regex/Tags")) - { - QList tgs = Tag::FromRegexp(value("Regex/Tags"), source); - if (!tgs.isEmpty()) - { ret.tags = tgs; } - } - - // Getting images - QRegularExpression rxImages(value("Regex/Image"), QRegularExpression::DotMatchesEverythingOption); - auto matches = rxImages.globalMatch(source); - int id = 0; - while (matches.hasNext()) - { - const auto &match = matches.next(); - QMap d = multiMatchToMap(match, rxImages.namedCaptureGroups()); - - // JSON elements - if (d.contains("json") && !d["json"].isEmpty()) - { - QVariant src = Json::parse(d["json"]); - if (!src.isNull()) - { - QMap map = src.toMap(); - for (auto it = map.begin(); it != map.end(); ++it) - { d[it.key()] = it.value().toString(); } - } - } - - QSharedPointer img = parseImage(parentPage, d, id + first); - if (!img.isNull()) - { ret.images.append(img); } - - id++; - } - - // Navigation - if (contains("Regex/NextPage")) - { - QRegularExpression rxNextPage(value("Regex/NextPage")); - auto match = rxNextPage.match(source); - if (match.hasMatch()) - { ret.urlNextPage = QUrl(match.captured(1)); } - } - if (contains("Regex/PrevPage")) - { - QRegularExpression rxPrevPage(value("Regex/PrevPage")); - auto match = rxPrevPage.match(source); - if (match.hasMatch()) - { ret.urlPrevPage = QUrl(match.captured(1)); } - } - - // Last page - if (contains("LastPage")) - { ret.pageCount = value("LastPage").toInt(); } - else if (contains("Regex/LastPage")) - { - QRegularExpression rxlast(value("Regex/LastPage")); - auto match = rxlast.match(source); - const int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; - if (cnt > 0) - { - int pagesCount = cnt; - if (value("Urls/Tags").contains("{pid}") || (contains("Urls/PagePart") && value("Urls/PagePart").contains("{pid}"))) - { - const int forced = forcedLimit(); - const int ppid = forced > 0 ? forced : limit; - pagesCount = qFloor(static_cast(pagesCount) / static_cast(ppid)) + 1; - } - ret.pageCount = pagesCount; - } - } - - // Count images - if (contains("Regex/Count")) - { - QRegularExpression rxlast(value("Regex/Count")); - auto match = rxlast.match(source); - const int cnt = match.hasMatch() ? match.captured(1).remove(",").toInt() : 0; - if (cnt > 0) - { ret.imageCount = cnt; } - } - - // Wiki - if (contains("Regex/Wiki")) - { - QRegularExpression rxwiki(value("Regex/Wiki"), QRegularExpression::DotMatchesEverythingOption); - auto match = rxwiki.match(source); - if (match.hasMatch()) - { - QString wiki = match.captured(1); - wiki.remove("/wiki/show?title="); - wiki.remove(QRegularExpression("

    Full entry »

    ")); - wiki.replace("
    ", "").replace("
    ", ""); - ret.wiki = wiki; - } - } - - return ret; -} - -ParsedTags HtmlApi::parseTags(const QString &source, Site *site) const -{ - ParsedTags ret; - QMap tagTypes = site->tagDatabase()->tagTypes(); - - // Read tags - QRegularExpression rx(value("Regex/TagApi"), QRegularExpression::DotMatchesEverythingOption); - auto matches = rx.globalMatch(source); - while (matches.hasNext()) - { - auto match = matches.next(); - - // Parse result using the regex - QMap d; - for (const QString &group : rx.namedCaptureGroups()) - { - if (group.isEmpty()) - continue; - - QString val = match.captured(group); - if (!val.isEmpty()) - { d[group] = val.trimmed(); } - } - - // Map variables - const int id = d.contains("id") ? d["id"].toInt() : 0; - const QString name = d["tag"]; - const int count = d.contains("count") ? d["count"].toInt() : 0; - const int typeId = d.contains("typeId") ? d["typeId"].toInt() : -1; - const QString ttype = d["type"]; - - const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); - ret.tags.append(Tag(id, name, tagType, count)); - } - - return ret; -} - -ParsedDetails HtmlApi::parseDetails(const QString &source, Site *site) const -{ - Q_UNUSED(site); - ParsedDetails ret; - - // Pools - if (contains("Regex/Pools")) - { - QRegularExpression rx(value("Regex/Pools")); - auto matches = rx.globalMatch(source); - while (matches.hasNext()) - { - auto match = matches.next(); - const int previous = match.captured(1).toInt(); - const int id = match.captured(2).toInt(); - const QString name = match.captured(3); - const int next = match.captured(4).toInt(); - ret.pools.append(Pool(id, name, 0, next, previous)); - } - } - - // Tags - QString rxtags; - if (contains("Regex/ImageTags")) - { rxtags = value("Regex/ImageTags"); } - else if (contains("Regex/Tags")) - { rxtags = value("Regex/Tags"); } - if (!rxtags.isEmpty()) - { ret.tags = Tag::FromRegexp(rxtags, source); } - - // Image url - if (contains("Regex/ImageUrl")) - { - QRegularExpression rx(value("Regex/ImageUrl")); - auto matches = rx.globalMatch(source); - while (matches.hasNext()) - { - auto match = matches.next(); - ret.imageUrl = match.captured(1).replace("&", "&"); - } - } - - // Image date - if (contains("Regex/ImageDate")) - { - QRegularExpression rx(value("Regex/ImageDate")); - auto matches = rx.globalMatch(source); - while (matches.hasNext()) - { - auto match = matches.next(); - ret.createdAt = qDateTimeFromString(match.captured(1)); - } - } - - return ret; -} diff --git a/lib/src/models/api/html-api.h b/lib/src/models/api/html-api.h deleted file mode 100644 index 4b3a7839b..000000000 --- a/lib/src/models/api/html-api.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef HTML_API_H -#define HTML_API_H - -#include "models/api/api.h" - - -class HtmlApi : public Api -{ - Q_OBJECT - - public: - explicit HtmlApi(const QMap &data); - ParsedPage parsePage(Page *parentPage, const QString &source, int first, int limit) const override; - ParsedTags parseTags(const QString &source, Site *site) const override; - ParsedDetails parseDetails(const QString &source, Site *site) const override; -}; - -#endif // HTML_API_H diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index 34237f9e6..8e4e46924 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -228,7 +228,7 @@ ParsedPage JavascriptApi::parsePage(Page *parentPage, const QString &source, int if (!d.isEmpty()) { const int id = d["id"].toInt(); - QSharedPointer img = parseImage(parentPage, d, id + first, tags, false); + QSharedPointer img = parseImage(parentPage, d, id + first, tags); if (!img.isNull()) { ret.images.append(img); } } diff --git a/lib/src/models/api/json-api.cpp b/lib/src/models/api/json-api.cpp deleted file mode 100644 index f21713fc8..000000000 --- a/lib/src/models/api/json-api.cpp +++ /dev/null @@ -1,252 +0,0 @@ -#include "models/api/api.h" -#include "models/api/json-api.h" -#include "models/page.h" -#include "models/site.h" -#include "tags/tag-database.h" -#include "vendor/json.h" - - -JsonApi::JsonApi(const QMap &data) - : Api("Json", data) -{} - -ParsedPage JsonApi::parsePage(Page *parentPage, const QString &source, int first, int limit) const -{ - Q_UNUSED(limit); - - ParsedPage ret; - - // Parsing - QVariant src = Json::parse(source); - if (src.isNull()) - { - ret.error = QStringLiteral("Error parsing JSON file: \"%1\"").arg(source.left(500)); - return ret; - } - - // Check JSON error message - QMap data = src.toMap(); - if (data.contains("success") && !data["success"].toBool()) - { - ret.error = QStringLiteral("JSON error reply: \"%1\"").arg(data["reason"].toString()); - return ret; - } - - if (data.contains("total")) - { ret.imageCount = data.value("total").toInt(); } - - // Get the list of posts - QList sourc = src.toList(); - QStringList postsKey = QStringList() << "images" << "search" << "posts"; - for (int i = 0; i < postsKey.count() && sourc.isEmpty(); ++i) - { sourc = data.value(postsKey[i]).toList(); } - - for (int id = 0; id < sourc.count(); id++) - { - QList tags; - - QMap sc = sourc.at(id + first).toMap(); - QMap d; - if (sc.contains("tag_string")) - { - QStringList infos, assoc; - infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score" << "tags_artist" << "tags_character" << "tags_copyright" << "tags_general"; - assoc << "created_at" << "status" << "source" << "has_comments" << "file_url" << "large_file_url" << "change" << "sample_width" << "has_children" << "preview_file_url" << "image_width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "image_height" << "has_notes" << "uploader_id" << "file_size" << "id" << "preview_height" << "rating" << "tag_string" << "uploader_name" << "score" << "tag_string_artist" << "tag_string_character" << "tag_string_copyright" << "tag_string_general"; - for (int i = 0; i < infos.count(); i++) - { d[infos.at(i)] = sc.value(assoc.at(i)).toString().trimmed(); } - } - else if (sc.contains("tag_ids")) - { - QStringList from, to; - from << "created_at" << "source_url" << "image" << "image" << "width" << "sha512_hash" << "height" << "id" << "tags" << "uploader" << "score"; - to << "created_at" << "source" << "file_url" << "preview_url" << "width" << "md5" << "height" << "id" << "tags" << "author" << "score"; - for (int i = 0; i < from.count(); i++) - { d[to[i]] = sc.value(from[i]).toString().trimmed(); } - } - // Anime-pictures format - else if (sc.contains("download_count")) - { - QStringList from, to; - from << "pubtime" << "small_preview" << "width" << "md5" << "height" << "id" << "score_number" << "big_preview" << "ext" << "size"; - to << "created_at" << "preview_url" << "width" << "md5" << "height" << "id" << "score" << "sample_url" << "ext" << "filesize"; - for (int i = 0; i < from.count(); i++) - { d[to[i]] = sc.value(from[i]).toString().trimmed(); } - } - // Twitter format - else if (sc.contains("retweet_count")) - { - if (!sc.contains("extended_entities")) - continue; - - auto entities = sc.value("extended_entities").toMap(); - if (!entities.contains("media")) - continue; - - auto medias = entities.value("media").toList(); - if (medias.isEmpty()) - continue; - - auto media = medias.first().toMap(); - auto sizes = media.value("sizes").toMap(); - - d["id"] = sc.value("id_str").toString(); - d["created_at"] = sc.value("created_at").toString(); - d["preview_url"] = media.value("media_url_https").toString() + ":thumb"; - if (sizes.contains("medium")) - { d["sample_url"] = media.value("media_url_https").toString() + ":medium"; } - - auto size = sizes.value("large").toMap(); - d["width"] = QString::number(size.value("w").toInt()); - d["height"] = QString::number(size.value("h").toInt()); - - if (media.contains("video_info")) - { - int maxBitrate = -1; - auto videoInfo = media.value("video_info").toMap(); - auto variants = videoInfo.value("variants").toList(); - for (const QVariant &variant : variants) - { - auto variantInfo = variant.toMap(); - const int bitrate = variantInfo.value("bitrate").toInt(); - if (bitrate > maxBitrate) - { - maxBitrate = bitrate; - d["file_url"] = variantInfo.value("url").toString(); - } - } - } - else - { d["file_url"] = media.value("media_url_https").toString() + ":large"; } - } - else - { - QStringList infos; - infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score"; - for (int i = 0; i < infos.count(); i++) - { d[infos.at(i)] = sc.value(infos.at(i)).toString().trimmed(); } - } - - // Tags as objects (Sankaku) - QMap tagTypes = parentPage->site()->tagDatabase()->tagTypes(); - if (sc.contains("tags") && sc["tags"].type() == QVariant::List && !tagTypes.isEmpty()) - { - QList tgs = sc["tags"].toList(); - if (!tgs.isEmpty()) - { - QMap tagTypesIds; - for (auto it = tagTypes.begin(); it != tagTypes.end(); ++it) - tagTypesIds.insert(it.key(), it.value().name()); - - for (const QVariant &tagData : tgs) - { - QMap tag = tagData.toMap(); - if (tag.contains("name")) - tags.append(Tag(tag["name"].toString(), Tag::GetType(tag["type"].toString(), tagTypesIds), tag["count"].toInt())); - } - } - } - - // Typed tags (e621) - if (sc.contains("tags") && sc["tags"].type() == QVariant::Map) - { - QMap scTypes = sc["tags"].toMap(); - for (auto it = scTypes.begin(); it != scTypes.end(); ++it) - { - const TagType tType(it.key()); - QList tagList = it.value().toList(); - for (const QVariant &iTag : tagList) - { tags.append(Tag(iTag.toString(), tType)); } - } - } - - // Booru-on-rails sizes - if (sc.contains("representations")) - { - QMap sizes = sc.value("representations").toMap(); - if (sizes.contains("thumb")) - { d["preview_url"] = sizes["thumb"].toString(); } - if (sizes.contains("large")) - { d["sample_url"] = sizes["large"].toString(); } - if (sizes.contains("full")) - { d["file_url"] = sizes["full"].toString(); } - } - - // Object creation date - if (sc.contains("created_at")) - { - QMap time = sc.value("created_at").toMap(); - if (!time.isEmpty() && time.contains("s")) - { d["created_at"] = time.value("s").toString(); } - } - - QSharedPointer img = parseImage(parentPage, d, id + first, tags); - if (!img.isNull()) - { ret.images.append(img); } - } - - return ret; -} - -ParsedTags JsonApi::parseTags(const QString &source, Site *site) const -{ - ParsedTags ret; - QMap tagTypes = site->tagDatabase()->tagTypes(); - - // Read source - QVariant src = Json::parse(source); - if (src.isNull()) - { - ret.error = QStringLiteral("Error parsing JSON file: \"%1\"").arg(source.left(500)); - return ret; - } - QMap data = src.toMap(); - - // Check for a JSON error message - if (data.contains("success") && !data["success"].toBool()) - { - ret.error = QStringLiteral("JSON error reply: \"%1\"").arg(data["reason"].toString()); - return ret; - } - - // Tag variables definitions - int id; - QString name; - int count; - int typeId; - QString ttype; - - // Read tags - QList sourc = src.toList(); - for (const QVariant &el : sourc) - { - QMap sc = el.toMap(); - - ttype.clear(); - if (sc.contains("short_description")) - { - id = sc.value("id").toInt(); - name = sc.value("name").toString(); - count = sc.value("images").toInt(); - ttype = sc.value("category").toString(); - } - else if (sc.contains("post_count")) - { - id = sc.value("id").toInt(); - name = sc.value("name").toString(); - count = sc.value("post_count").toInt(); - typeId = sc.value("category").toInt(); - } - else - { - id = sc.value("id").toInt(); - name = sc.value("name").toString(); - count = sc.value("count").toInt(); - typeId = sc.value("type").toInt(); - } - - const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); - ret.tags.append(Tag(id, name, tagType, count)); - } - - return ret; -} diff --git a/lib/src/models/api/json-api.h b/lib/src/models/api/json-api.h deleted file mode 100644 index eb00b1051..000000000 --- a/lib/src/models/api/json-api.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef JSON_API_H -#define JSON_API_H - -#include "models/api/api.h" - - -class JsonApi : public Api -{ - Q_OBJECT - - public: - explicit JsonApi(const QMap &data); - ParsedPage parsePage(Page *parentPage, const QString &source, int first, int limit) const override; - ParsedTags parseTags(const QString &source, Site *site) const override; -}; - -#endif // JSON_API_H diff --git a/lib/src/models/api/rss-api.cpp b/lib/src/models/api/rss-api.cpp deleted file mode 100644 index 64f83d690..000000000 --- a/lib/src/models/api/rss-api.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include "models/api/rss-api.h" -#include -#include -#include -#include -#include "models/api/api.h" -#include "models/page.h" - - -RssApi::RssApi(const QMap &data) - : Api("Rss", data) -{} - -ParsedPage RssApi::parsePage(Page *parentPage, const QString &source, int first, int limit) const -{ - Q_UNUSED(limit); - - ParsedPage ret; - - // Parsing - QDomDocument doc; - QString errorMsg; - int errorLine, errorColumn; - if (!doc.setContent(source, false, &errorMsg, &errorLine, &errorColumn)) - { - ret.error = QStringLiteral("Error parsing RSS file: %1 (%2 - %3).").arg(errorMsg).arg(errorLine).arg(errorColumn); - return ret; - } - QDomElement docElem = doc.documentElement(); - - // Reading posts - QDomNodeList nodeList = docElem.elementsByTagName("item"); - for (int id = 0; id < nodeList.count(); id++) - { - QDomNodeList children = nodeList.at(id + first).childNodes(); - QMap d, dat; - for (int i = 0; i < children.size(); i++) - { - QString content = children.at(i).childNodes().at(0).nodeValue(); - if (!content.isEmpty()) - { dat.insert(children.at(i).nodeName(), content.trimmed()); } - else - { dat.insert(children.at(i).nodeName(), children.at(i).attributes().namedItem("url").nodeValue().trimmed()); } - } - - d.insert("page_url", dat["link"]); - d.insert("tags", dat["media:keywords"]); - d.insert("preview_url", dat["media:thumbnail"]); - d.insert("file_url", dat["media:content"]); - - // Shimmie - if (dat.contains("dc:creator")) - { d.insert("author", dat["dc:creator"]); } - if (dat.contains("enclosure")) - { d.insert("file_url", dat["enclosure"]); } - if (dat.contains("pubDate")) - { d.insert("created_at", QString::number(QDateTime::fromString(dat["pubDate"], "ddd, dd MMM yyyy hh:mm:ss +0000").toTime_t())); } - - if (!d.contains("id")) - { - QRegularExpression rx("/(\\d+)"); - auto match = rx.match(d["page_url"]); - if (match.hasMatch()) - { d.insert("id", match.captured(1)); } - } - - QSharedPointer img = parseImage(parentPage, d, id + first); - if (!img.isNull()) - { ret.images.append(img); } - } - - return ret; -} - -bool RssApi::canLoadDetails() const -{ - return false; -} - -ParsedTags RssApi::parseTags(const QString &source, Site *site) const -{ - Q_UNUSED(source); - Q_UNUSED(site); - - ParsedTags ret; - ret.error = "Not implemented"; - return ret; -} diff --git a/lib/src/models/api/rss-api.h b/lib/src/models/api/rss-api.h deleted file mode 100644 index a74fe9189..000000000 --- a/lib/src/models/api/rss-api.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef RSS_API_H -#define RSS_API_H - -#include "models/api/api.h" - - -class RssApi : public Api -{ - Q_OBJECT - - public: - explicit RssApi(const QMap &data); - ParsedPage parsePage(Page *parentPage, const QString &source, int first, int limit) const override; - ParsedTags parseTags(const QString &source, Site *site) const override; - bool canLoadDetails() const override; -}; - -#endif // RSS_API_H diff --git a/lib/src/models/api/xml-api.cpp b/lib/src/models/api/xml-api.cpp deleted file mode 100644 index 94afadf99..000000000 --- a/lib/src/models/api/xml-api.cpp +++ /dev/null @@ -1,161 +0,0 @@ -#include "models/api/xml-api.h" -#include -#include "models/api/api.h" -#include "models/site.h" -#include "tags/tag-database.h" - - -XmlApi::XmlApi(const QMap &data) - : Api("Xml", data) -{} - -ParsedPage XmlApi::parsePage(Page *parentPage, const QString &source, int first, int limit) const -{ - Q_UNUSED(limit); - - ParsedPage ret; - - // Parsing - QDomDocument doc; - QString errorMsg; - int errorLine, errorColumn; - if (!doc.setContent(source, false, &errorMsg, &errorLine, &errorColumn)) - { - ret.error = QStringLiteral("Error parsing XML file: %1 (%2 - %3).").arg(errorMsg).arg(errorLine).arg(errorColumn); - return ret; - } - QDomElement docElem = doc.documentElement(); - - // Getting last page - int count = docElem.attributes().namedItem("count").nodeValue().toInt(); - const QString database = docElem.attributes().namedItem("type").nodeValue(); - if (count == 0 && database == QLatin1String("array")) - { count = docElem.elementsByTagName("total-count").at(0).toElement().text().toInt(); } - if (count > 0) - { ret.imageCount = count; } - - // Reading posts - QDomNodeList nodeList = docElem.elementsByTagName("post"); - for (int id = 0; id < nodeList.count(); id++) - { - QDomNode node = nodeList.at(id + first); - QMap d; - QList tags; - if (database == QLatin1String("array")) - { - if (node.namedItem("md5").isNull()) - continue; - - QStringList infos, assoc; - infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score" << "tags_artist" << "tags_character" << "tags_copyright" << "tags_general" << "tags_meta" << "ext"; - assoc << "created-at" << "status" << "source" << "has_comments" << "file-url" << "large-file-url" << "change" << "sample_width" << "has-children" << "preview-file-url" << "image-width" << "md5" << "preview_width" << "sample_height" << "parent-id" << "image-height" << "has_notes" << "uploader-id" << "file_size" << "id" << "preview_height" << "rating" << "tag-string" << "uploader-name" << "score" << "tag-string-artist" << "tag-string-character" << "tag-string-copyright" << "tag-string-general" << "tag-string-meta" << "file-ext"; - - if (node.namedItem("preview-file-url").isNull()) - { - // New syntax with old keys - for (int i = 0; i < infos.count(); i++) - { - QDomNode item = node.namedItem(infos.at(i)); - if (!item.isNull()) - { d[infos.at(i)] = item.toElement().text(); } - } - } - else - { - for (int i = 0; i < infos.count(); i++) - { d[infos.at(i)] = node.namedItem(assoc.at(i)).toElement().text(); } - } - - // Typed tags - QDomNodeList tagTypes = node.namedItem("tags").childNodes(); - if (!tagTypes.isEmpty()) - { - for (int typeId = 0; typeId < tagTypes.count(); ++typeId) - { - QDomNode tagType = tagTypes.at(typeId); - const TagType tType(tagType.nodeName()); - QDomNodeList tagList = tagType.childNodes(); - for (int iTag = 0; iTag < tagList.count(); ++iTag) - { tags.append(Tag(tagList.at(iTag).toElement().text(), tType)); } - } - } - } - else - { - QStringList infos; - infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score"; - for (int i = 0; i < infos.count(); i++) - { - d[infos.at(i)] = node.attributes().isEmpty() - ? node.namedItem(infos.at(i)).toElement().text() - : node.attributes().namedItem(infos.at(i)).nodeValue().trimmed(); - } - } - - QSharedPointer img = parseImage(parentPage, d, id + first, tags); - if (!img.isNull()) - { ret.images.append(img); } - } - - return ret; -} - -ParsedTags XmlApi::parseTags(const QString &source, Site *site) const -{ - ParsedTags ret; - QMap tagTypes = site->tagDatabase()->tagTypes(); - - // Tag variables definitions - int id; - QString name; - int count; - int typeId; - QString ttype; - - // Read source - QDomDocument doc; - QString errorMsg; - int errorLine, errorColumn; - if (!doc.setContent(source, false, &errorMsg, &errorLine, &errorColumn)) - { - ret.error = QStringLiteral("Error parsing XML file: %1 (%2 - %3).").arg(errorMsg).arg(errorLine).arg(errorColumn); - return ret; - } - QDomElement docElem = doc.documentElement(); - - // Read tags - QDomNodeList nodeList = docElem.elementsByTagName("tag"); - for (int i = 0; i < nodeList.count(); i++) - { - QDomNode node = nodeList.at(i); - QDomNamedNodeMap attr = node.attributes(); - - ttype.clear(); - if (!node.namedItem("post-count").isNull()) - { - id = node.namedItem("id").toElement().text().toInt(); - name = node.namedItem("name").toElement().text(); - count = node.namedItem("post-count").toElement().text().toInt(); - typeId = node.namedItem("category").toElement().text().toInt(); - } - else if (attr.contains("name")) - { - id = attr.namedItem("id").toAttr().value().toInt(); - name = attr.namedItem("name").toAttr().value(); - count = attr.namedItem("count").toAttr().value().toInt(); - typeId = attr.namedItem("type").toAttr().value().toInt(); - } - else - { - id = node.namedItem("id").toElement().text().toInt(); - name = node.namedItem("name").toElement().text(); - count = node.namedItem("count").toElement().text().toInt(); - typeId = node.namedItem("type").toElement().text().toInt(); - } - - const TagType tagType = !ttype.isEmpty() ? TagType(ttype) : (tagTypes.contains(typeId) ? tagTypes[typeId] : TagType()); - ret.tags.append(Tag(id, name, tagType, count)); - } - - return ret; -} diff --git a/lib/src/models/api/xml-api.h b/lib/src/models/api/xml-api.h deleted file mode 100644 index 268469bf3..000000000 --- a/lib/src/models/api/xml-api.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef XML_API_H -#define XML_API_H - -#include "models/api/api.h" - - -class XmlApi : public Api -{ - Q_OBJECT - - public: - explicit XmlApi(const QMap &data); - ParsedPage parsePage(Page *parentPage, const QString &source, int first, int limit) const override; - ParsedTags parseTags(const QString &source, Site *site) const override; -}; - -#endif // XML_API_H diff --git a/lib/src/models/monitor.cpp b/lib/src/models/monitor.cpp index e6ab9c406..acfeaaaf1 100644 --- a/lib/src/models/monitor.cpp +++ b/lib/src/models/monitor.cpp @@ -65,7 +65,6 @@ Monitor Monitor::fromJson(const QJsonObject &json, const QMap &s const QDateTime lastCheck = QDateTime::fromString(json["lastCheck"].toString(), Qt::ISODate); const int cumulated = json["cumulated"].toInt(); const bool preciseCumulated = json["preciseCumulated"].toBool(); - return Monitor(site, interval, lastCheck, cumulated, preciseCumulated); } diff --git a/lib/src/models/source.cpp b/lib/src/models/source.cpp index 08c3e1edc..82efa15b3 100644 --- a/lib/src/models/source.cpp +++ b/lib/src/models/source.cpp @@ -3,13 +3,9 @@ #include #include "functions.h" #include "models/api/api.h" -#include "models/api/html-api.h" #include "models/api/javascript-api.h" #include "models/api/javascript-console-helper.h" #include "models/api/javascript-grabber-helper.h" -#include "models/api/json-api.h" -#include "models/api/rss-api.h" -#include "models/api/xml-api.h" #include "models/profile.h" #include "models/site.h" @@ -87,9 +83,8 @@ Source::Source(Profile *profile, const QString &dir) }; // Javascript models - const bool enableJs = m_profile->getSettings()->value("enableJsModels", true).toBool(); QFile js(m_dir + "/model.js"); - if (enableJs && js.exists() && js.open(QIODevice::ReadOnly | QIODevice::Text)) + if (js.exists() && js.open(QIODevice::ReadOnly | QIODevice::Text)) { log(QStringLiteral("Using Javascript model for %1").arg(m_diskName), Logger::Debug); @@ -125,49 +120,7 @@ Source::Source(Profile *profile, const QString &dir) js.close(); } else - { - if (enableJs) - { log(QStringLiteral("Javascript model not found for %1").arg(m_diskName), Logger::Warning); } - - log(QStringLiteral("Using XML model for %1").arg(m_diskName), Logger::Debug); - - m_name = details.value("Name"); - - // Get the list of possible API for this Source - QStringList possibleApis = QStringList() << "Xml" << "Json" << "Rss" << "Html"; - QStringList availableApis; - for (const QString &api : possibleApis) - if (details.contains("Urls/" + api + "/Tags")) - availableApis.append(api); - - if (!availableApis.isEmpty()) - { - m_apis.reserve(availableApis.count()); - for (const QString &apiName : availableApis) - { - Api *api = nullptr; - if (apiName == QLatin1String("Html")) - { api = new HtmlApi(details); } - else if (apiName == QLatin1String("Json")) - { api = new JsonApi(details); } - else if (apiName == QLatin1String("Rss")) - { api = new RssApi(details); } - else if (apiName == QLatin1String("Xml")) - { api = new XmlApi(details); } - - if (api != nullptr) - { m_apis.append(api); } - else - { log(QStringLiteral("Unknown API type '%1'").arg(apiName), Logger::Error); } - } - } - else - { log(QStringLiteral("No valid source has been found in the model.xml file from %1.").arg(m_name)); } - - // Read tag naming format - const auto caseFormat = caseAssoc.value(details.value("TagFormat/Case", "lower"), TagNameFormat::Lower); - m_tagNameFormat = TagNameFormat(caseFormat, details.value("TagFormat/WordSeparator", "_")); - } + { log(QStringLiteral("Javascript model not found for %1").arg(m_diskName), Logger::Warning); } } file.close(); diff --git a/tests/src/integration/integration-test-suite.cpp b/tests/src/integration/integration-test-suite.cpp index e818cffb0..07e84e51b 100755 --- a/tests/src/integration/integration-test-suite.cpp +++ b/tests/src/integration/integration-test-suite.cpp @@ -36,10 +36,7 @@ QList IntegrationTestSuite::getImages(const QString &site, const QString m_filesToRemove.append(settings.fileName()); m_profile = new Profile("tests/resources/"); - bool oldJavaScript = m_profile->getSettings()->value("enableJsModels", true).toBool(); - m_profile->getSettings()->setValue("enableJsModels", true); m_source = new Source(m_profile, "tests/resources/sites/" + site); - m_profile->getSettings()->setValue("enableJsModels", oldJavaScript); QList sites; m_site = new Site(source, m_source); @@ -105,10 +102,7 @@ QList IntegrationTestSuite::getPageTags(const QString &site, const QString { CustomNetworkAccessManager::NextFiles.enqueue("tests/resources/pages/" + source + "/" + file); } m_profile = new Profile("tests/resources/"); - bool oldJavaScript = m_profile->getSettings()->value("enableJsModels", true).toBool(); - m_profile->getSettings()->setValue("enableJsModels", true); m_source = new Source(m_profile, "tests/resources/sites/" + site); - m_profile->getSettings()->setValue("enableJsModels", oldJavaScript); QList sites; m_site = new Site(source, m_source); @@ -174,10 +168,7 @@ QList IntegrationTestSuite::getTags(const QString &site, const QString &sou { CustomNetworkAccessManager::NextFiles.enqueue("tests/resources/pages/" + source + "/" + file); } m_profile = new Profile("tests/resources/"); - bool oldJavaScript = m_profile->getSettings()->value("enableJsModels", true).toBool(); - m_profile->getSettings()->setValue("enableJsModels", true); m_source = new Source(m_profile, "tests/resources/sites/" + site); - m_profile->getSettings()->setValue("enableJsModels", oldJavaScript); m_site = new Site(source, m_source); m_site->setAutoLogin(false); diff --git a/tests/src/models/source-test.cpp b/tests/src/models/source-test.cpp index 6d8ae0cce..bab9b67d7 100644 --- a/tests/src/models/source-test.cpp +++ b/tests/src/models/source-test.cpp @@ -23,14 +23,26 @@ void SourceTest::cleanup() void SourceTest::testMissingXml() { + setupSource("Danbooru (2.0)", "tests/resources/sites/tmp/"); QFile::remove("tests/resources/sites/tmp/model.xml"); Source source(m_profile, "tests/resources/sites/tmp"); QVERIFY(source.getApis().isEmpty()); } +void SourceTest::testMissingJavascript() +{ + setupSource("Danbooru (2.0)", "tests/resources/sites/tmp/"); + QFile::remove("tests/resources/sites/tmp/model.js"); + + Source source(m_profile, "tests/resources/sites/tmp"); + QVERIFY(source.getApis().isEmpty()); +} + void SourceTest::testInvalidXml() { + setupSource("Danbooru (2.0)", "tests/resources/sites/tmp/"); + QFile f("tests/resources/sites/tmp/model.xml"); f.open(QFile::WriteOnly); f.write(QString("test").toUtf8()); @@ -40,10 +52,23 @@ void SourceTest::testInvalidXml() QVERIFY(source.getApis().isEmpty()); } +void SourceTest::testInvalidJavascript() +{ + setupSource("Danbooru (2.0)", "tests/resources/sites/tmp/"); + + QFile f("tests/resources/sites/tmp/model.js"); + f.open(QFile::WriteOnly); + f.write(QString("test").toUtf8()); + f.close(); + + Source source(m_profile, "tests/resources/sites/tmp"); + QVERIFY(source.getApis().isEmpty()); +} + void SourceTest::testMissingSites() { - QFile::remove("tests/resources/sites/tmp/model.xml"); - QFile("release/sites/Danbooru (2.0)/model.xml").copy("tests/resources/sites/tmp/model.xml"); + setupSource("Danbooru (2.0)", "tests/resources/sites/tmp/"); + QFile f("tests/resources/sites/tmp/sites.txt"); f.open(QFile::WriteOnly | QFile::Truncate | QFile::Text); f.write(QString("\n\n\r\ndanbooru.donmai.us\n").toUtf8()); @@ -56,9 +81,8 @@ void SourceTest::testMissingSites() void SourceTest::testIgnoreEmptySites() { - QFile::remove("tests/resources/sites/tmp/model.xml"); + setupSource("Danbooru (2.0)", "tests/resources/sites/tmp/"); QFile::remove("tests/resources/sites/tmp/sites.txt"); - QFile("release/sites/Danbooru (2.0)/model.xml").copy("tests/resources/sites/tmp/model.xml"); Source source(m_profile, "tests/resources/sites/tmp"); QVERIFY(!source.getApis().isEmpty()); diff --git a/tests/src/models/source-test.h b/tests/src/models/source-test.h index d46eac834..b09b41809 100644 --- a/tests/src/models/source-test.h +++ b/tests/src/models/source-test.h @@ -16,7 +16,9 @@ class SourceTest : public TestSuite void cleanup(); void testMissingXml(); + void testMissingJavascript(); void testInvalidXml(); + void testInvalidJavascript(); void testMissingSites(); void testIgnoreEmptySites(); diff --git a/tests/src/test-suite.cpp b/tests/src/test-suite.cpp index 5df052ad9..22b50949d 100755 --- a/tests/src/test-suite.cpp +++ b/tests/src/test-suite.cpp @@ -7,27 +7,37 @@ TestSuite::TestSuite() getSuites().append(this); } -void TestSuite::setupSource(const QString &site) +void TestSuite::setupSource(const QString &source, QString dir) { - QFile::remove("tests/resources/sites/helper.js"); - QFile("release/sites/helper.js").copy("tests/resources/sites/helper.js"); - - QDir().mkpath("tests/resources/sites/" + site); - QFile::remove("tests/resources/sites/" + site + "/sites.txt"); - QFile::remove("tests/resources/sites/" + site +"/model.xml"); - QFile::remove("tests/resources/sites/" + site +"/model.js"); - QFile("release/sites/" + site +"/sites.txt").copy("tests/resources/sites/" + site +"/sites.txt"); - QFile("release/sites/" + site +"/model.xml").copy("tests/resources/sites/" + site +"/model.xml"); - QFile("release/sites/" + site +"/model.js").copy("tests/resources/sites/" + site +"/model.js"); + if (dir.isEmpty()) + { + dir = "tests/resources/sites/"; + + QFile::remove(dir + "helper.js"); + QFile("release/sites/helper.js").copy(dir + "helper.js"); + + dir += source; + } + + QDir().mkpath(dir); + QFile::remove(dir + "/model.js"); + QFile::remove(dir + "/model.xml"); + QFile::remove(dir + "/sites.txt"); + QFile("release/sites/" + source + "/model.js").copy(dir + "/model.js"); + QFile("release/sites/" + source + "/model.xml").copy(dir + "/model.xml"); + QFile("release/sites/" + source + "/sites.txt").copy(dir + "/sites.txt"); } -void TestSuite::setupSite(const QString &site, const QString &source) +void TestSuite::setupSite(const QString &source, const QString &site, QString dir) { - QDir().mkpath("tests/resources/sites/" + site + "/" + source); - QFile::remove("tests/resources/sites/" + site +"/" + source + "/defaults.ini"); - QFile::remove("tests/resources/sites/" + site +"/" + source + "/settings.ini"); - if (QFile::exists("release/sites/" + site +"/" + source + "/defaults.ini")) - { QFile("release/sites/" + site +"/" + source + "/defaults.ini").copy("tests/resources/sites/" + site +"/" + source + "/defaults.ini"); } + if (dir.isEmpty()) + { dir = "tests/resources/sites/" + source + "/" + site; } + + QDir().mkpath(dir); + QFile::remove(dir + "/defaults.ini"); + QFile::remove(dir + "/settings.ini"); + if (QFile::exists("release/sites/" + source + "/" + site + "/defaults.ini")) + { QFile("release/sites/" + source + "/" + site + "/defaults.ini").copy(dir + "/defaults.ini"); } } QList &TestSuite::getSuites() diff --git a/tests/src/test-suite.h b/tests/src/test-suite.h index 9804f8cd1..dd375d59a 100644 --- a/tests/src/test-suite.h +++ b/tests/src/test-suite.h @@ -46,8 +46,8 @@ class TestSuite : public QObject public: TestSuite(); - void setupSource(const QString &site); - void setupSite(const QString &site, const QString &source); + void setupSource(const QString &site, QString dir = QString()); + void setupSite(const QString &site, const QString &source, QString dir = QString()); static QList &getSuites(); }; From e0a2477545c32b00211b6a4b4a7c870ef582d7a3 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 01:12:18 +0200 Subject: [PATCH 046/112] Add tests for the MixedSettings class --- lib/src/mixed-settings.cpp | 2 +- tests/src/mixed-settings-test.cpp | 96 +++++++++++++++++++++++++++++++ tests/src/mixed-settings-test.h | 27 +++++++++ 3 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 tests/src/mixed-settings-test.cpp create mode 100644 tests/src/mixed-settings-test.h diff --git a/lib/src/mixed-settings.cpp b/lib/src/mixed-settings.cpp index 697012b07..428cee878 100644 --- a/lib/src/mixed-settings.cpp +++ b/lib/src/mixed-settings.cpp @@ -74,7 +74,7 @@ void MixedSettings::beginGroup(const QString &prefix) void MixedSettings::endGroup() { - for (QSettings *setting : qAsConst( m_settings)) + for (QSettings *setting : qAsConst(m_settings)) setting->endGroup(); } diff --git a/tests/src/mixed-settings-test.cpp b/tests/src/mixed-settings-test.cpp new file mode 100644 index 000000000..1ff95e99f --- /dev/null +++ b/tests/src/mixed-settings-test.cpp @@ -0,0 +1,96 @@ +#include "mixed-settings.h" +#include +#include "mixed-settings-test.h" + + +void MixedSettingsTest::init() +{ + m_child = new QSettings("tests/resources/tmp/child.ini", QSettings::IniFormat); + m_parent = new QSettings("tests/resources/tmp/parent.ini", QSettings::IniFormat); + + m_child->clear(); + m_parent->clear(); +} + +void MixedSettingsTest::testValueFirstValid() +{ + MixedSettings settings(QList() << m_child << m_parent); + + m_child->setValue("test", "child"); + m_parent->setValue("test", "parent"); + QVariant v1 = m_child->value("test"); + QVariant v2 = m_child->value("test"); + + QCOMPARE(settings.value("test").toString(), QString("child")); +} + +void MixedSettingsTest::testValueDefault() +{ + MixedSettings settings(QList() << m_child << m_parent); + + QCOMPARE(settings.value("test", "default").toString(), QString("default")); +} + +void MixedSettingsTest::testSetValueResetToParent() +{ + MixedSettings settings(QList() << m_child << m_parent); + + m_child->setValue("test", "child"); + m_parent->setValue("test", "parent"); + + settings.setValue("test", "parent", "default"); + settings.sync(); + + QCOMPARE(m_child->value("test", "none").toString(), QString("none")); + QCOMPARE(m_parent->value("test", "none").toString(), QString("parent")); +} + +void MixedSettingsTest::testSetValueResetToDefault() +{ + MixedSettings settings(QList() << m_child << m_parent); + + m_child->setValue("test", "child"); + + settings.setValue("test", "default", "default"); + settings.sync(); + + QCOMPARE(m_child->value("test", "none").toString(), QString("none")); + QCOMPARE(m_parent->value("test", "none").toString(), QString("none")); +} + +void MixedSettingsTest::testSetValueOverrideParent() +{ + MixedSettings settings(QList() << m_child << m_parent); + + m_parent->setValue("test", "parent"); + + settings.setValue("test", "child", "default"); + settings.sync(); + + QCOMPARE(m_child->value("test", "none").toString(), QString("child")); + QCOMPARE(m_parent->value("test", "none").toString(), QString("parent")); +} + +void MixedSettingsTest::testSetValueOverrideDefault() +{ + MixedSettings settings(QList() << m_child << m_parent); + + settings.setValue("test", "child", "default"); + settings.sync(); + + QCOMPARE(m_child->value("test", "none").toString(), QString("child")); + QCOMPARE(m_parent->value("test", "none").toString(), QString("none")); +} + +void MixedSettingsTest::testChildKeys() +{ + MixedSettings settings(QList() << m_child << m_parent); + + m_child->setValue("child", "value"); + m_parent->setValue("parent", "value"); + + QCOMPARE(settings.childKeys(), QStringList() << "child" << "parent"); +} + + +static MixedSettingsTest instance; diff --git a/tests/src/mixed-settings-test.h b/tests/src/mixed-settings-test.h new file mode 100644 index 000000000..e05ae02dc --- /dev/null +++ b/tests/src/mixed-settings-test.h @@ -0,0 +1,27 @@ +#ifndef MIXED_SETTINGS_TEST_H +#define MIXED_SETTINGS_TEST_H + +#include "test-suite.h" + + +class MixedSettingsTest : public TestSuite +{ + Q_OBJECT + + private slots: + void init(); + + void testValueFirstValid(); + void testValueDefault(); + void testSetValueResetToParent(); + void testSetValueResetToDefault(); + void testSetValueOverrideParent(); + void testSetValueOverrideDefault(); + void testChildKeys(); + + private: + QSettings *m_child; + QSettings *m_parent; +}; + +#endif // MIXED_SETTINGS_TEST_H From bae3f7c9e4cf8c705f3af79a0b011f6d2bd00393 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 01:33:14 +0200 Subject: [PATCH 047/112] Remove useless condition in SourceGuesser --- lib/src/models/source-guesser.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/src/models/source-guesser.cpp b/lib/src/models/source-guesser.cpp index 05b57ada6..b3560df9a 100644 --- a/lib/src/models/source-guesser.cpp +++ b/lib/src/models/source-guesser.cpp @@ -23,9 +23,6 @@ Source *SourceGuesser::start() for (Source *source : qAsConst(m_sources)) { - if (source->getApis().isEmpty()) - continue; - Api *api = source->getApis().first(); if (api->canLoadCheck()) { From f333d89d9f18620d2cdb468cda26f9b272f28915 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 00:56:45 +0200 Subject: [PATCH 048/112] Replace usages of Json lib by Qt lib --- lib/src/models/site.cpp | 12 +- lib/src/updater/program-updater.cpp | 18 +- lib/src/updater/program-updater.h | 2 +- lib/src/vendor/json.cpp | 426 ---------------------------- lib/src/vendor/json.h | 159 ----------- 5 files changed, 18 insertions(+), 599 deletions(-) delete mode 100644 lib/src/vendor/json.cpp delete mode 100644 lib/src/vendor/json.h diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index e465d2868..ad2f6cbc1 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -1,4 +1,7 @@ #include "models/site.h" +#include +#include +#include #include #include #include @@ -19,7 +22,6 @@ #include "models/source.h" #include "tags/tag-database.h" #include "tags/tag-database-factory.h" -#include "vendor/json.h" #ifdef QT_DEBUG // #define CACHE_POLICY QNetworkRequest::PreferCache @@ -305,17 +307,17 @@ void Site::loadTags(int page, int limit) void Site::finishedTags() { - const QString source = m_tagsReply->readAll(); + const QByteArray source = m_tagsReply->readAll(); m_tagsReply->deleteLater(); QList tags; - QVariant src = Json::parse(source); + QJsonDocument src = QJsonDocument::fromJson(source); if (!src.isNull()) { - QList sourc = src.toList(); + QJsonArray sourc = src.array(); tags.reserve(sourc.count()); for (int id = 0; id < sourc.count(); id++) { - QMap sc = sourc.at(id).toMap(); + QJsonObject sc = sourc[id].toObject(); const int cat = sc.value("category").toInt(); tags.append(Tag(sc.value("name").toString(), cat == 0 ? "general" : (cat == 1 ? "artist" : (cat == 3 ? "copyright" : "character")), diff --git a/lib/src/updater/program-updater.cpp b/lib/src/updater/program-updater.cpp index 9e88cc85b..5d57fca53 100644 --- a/lib/src/updater/program-updater.cpp +++ b/lib/src/updater/program-updater.cpp @@ -1,10 +1,12 @@ #include "updater/program-updater.h" #include #include +#include +#include +#include #include #include #include "logger.h" -#include "vendor/json.h" ProgramUpdater::ProgramUpdater() @@ -33,8 +35,8 @@ void ProgramUpdater::checkForUpdatesDone() auto *reply = dynamic_cast(sender()); m_source = reply->readAll(); - QVariant json = Json::parse(m_source); - QMap lastRelease = json.toMap(); + QJsonDocument json = QJsonDocument::fromJson(m_source); + QJsonObject lastRelease = json.object(); #if defined NIGHTLY QString latest = lastRelease["target_commitish"].toString(); @@ -56,16 +58,16 @@ void ProgramUpdater::checkForUpdatesDone() QUrl ProgramUpdater::latestUrl() const { - QVariant json = Json::parse(m_source); - QMap lastRelease = json.toMap(); + QJsonDocument json = QJsonDocument::fromJson(m_source); + QJsonObject lastRelease = json.object(); return QUrl(lastRelease["html_url"].toString()); } void ProgramUpdater::downloadUpdate() { - QVariant json = Json::parse(m_source); - QMap lastRelease = json.toMap(); - QMap lastAsset = lastRelease["assets"].toList().first().toMap(); + QJsonDocument json = QJsonDocument::fromJson(m_source); + QJsonObject lastRelease = json.object(); + QJsonObject lastAsset = lastRelease["assets"].toArray().first().toObject(); QUrl url(lastAsset["browser_download_url"].toString()); m_updateFilename = url.fileName(); diff --git a/lib/src/updater/program-updater.h b/lib/src/updater/program-updater.h index 2d522a700..9ee0a8db9 100644 --- a/lib/src/updater/program-updater.h +++ b/lib/src/updater/program-updater.h @@ -30,7 +30,7 @@ class ProgramUpdater : public Updater private: QString m_baseUrl; QNetworkReply *m_downloadReply; - QString m_source; + QByteArray m_source; QString m_newVersion; QString m_updateFilename; }; diff --git a/lib/src/vendor/json.cpp b/lib/src/vendor/json.cpp deleted file mode 100644 index 9ee44884b..000000000 --- a/lib/src/vendor/json.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/** - * @file json.h - * - * @author Eeli Reilin , - * Mikko Ahonen - * @version 0.1 - * @date 8/25/2010 - */ - -#include "json.h" - -/** - * 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(); - } -} - -/** - * 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; - - return QVariant(numberStr); -} - -/** - * 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; -} diff --git a/lib/src/vendor/json.h b/lib/src/vendor/json.h deleted file mode 100644 index e5f3b4816..000000000 --- a/lib/src/vendor/json.h +++ /dev/null @@ -1,159 +0,0 @@ -/** - * \file json.h - * - * \author Eeli Reilin , - * Mikko Ahonen - * \version 0.1 - * \date 8/25/2010 - */ - -#ifndef JSON_H -#define JSON_H - -#include -#include - - - -/** - * \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); - - 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); -}; - -#endif //JSON_H From e81a78d772b28ac01d245bb1d4336268054082ea Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 09:16:29 +0200 Subject: [PATCH 049/112] Remove dead Tag construction code --- lib/src/functions.cpp | 23 --------------- lib/src/functions.h | 1 - lib/src/tags/tag.cpp | 69 ------------------------------------------- lib/src/tags/tag.h | 2 -- 4 files changed, 95 deletions(-) diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index 3ddf4751c..87061c957 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -799,29 +799,6 @@ bool isVariantEmpty(const QVariant &value) } } -QMap multiMatchToMap(const QRegularExpressionMatch &match, const QStringList &groups) -{ - QMap data; - for (QString group : groups) - { - if (group.isEmpty()) - continue; - - QString val = match.captured(group); - if (val.isEmpty()) - continue; - - const int underscorePos = group.lastIndexOf('_'); - bool ok; - group.midRef(underscorePos + 1).toInt(&ok); - if (underscorePos != -1 && ok) - { group = group.left(underscorePos); } - data[group] = val; - } - - return data; -} - QString decodeHtmlEntities(const QString &html) { QByteArray data = html.toUtf8(); diff --git a/lib/src/functions.h b/lib/src/functions.h index 17d1d026c..c4b043324 100644 --- a/lib/src/functions.h +++ b/lib/src/functions.h @@ -48,7 +48,6 @@ QString getExtension(const QString &url); QString setExtension(QString url, const QString &extension); bool isUrl(const QString &str); bool isVariantEmpty(const QVariant &value); -QMap multiMatchToMap(const QRegularExpressionMatch &match, const QStringList &groups); bool setFileCreationDate(const QString &path, const QDateTime &datetime); void shutDown(int timeout = 0); diff --git a/lib/src/tags/tag.cpp b/lib/src/tags/tag.cpp index 5a2fe0648..a7700269c 100644 --- a/lib/src/tags/tag.cpp +++ b/lib/src/tags/tag.cpp @@ -60,75 +60,6 @@ Tag::Tag(int id, const QString &text, TagType type, int count, QStringList relat } } -Tag Tag::FromCapture(const QRegularExpressionMatch &match, const QStringList &groups) -{ - QMap data = multiMatchToMap(match, groups); - - // Tag - QString tag; - if (data.contains("tag")) - { - tag = data["tag"].replace(" ", "_").replace("&", "&").trimmed(); - } - - // Type - QString type; - if (data.contains("type")) - { - static QMap types = - { - { 0, "general" }, - { 1, "artist" }, - { 2, "unknown" }, - { 3, "copyright" }, - { 4, "character" }, - { 5, "species" }, - { 6, "generalmeta" }, - }; - type = Tag::GetType(data.value("type").trimmed(), types); - } - - // Count - int count = 0; - if (data.contains("count")) - { - QString countStr = data.value("count").toLower().trimmed(); - countStr.remove(','); - if (countStr.endsWith('k')) - { - QStringRef withoutK = countStr.leftRef(countStr.length() - 1).trimmed(); - count = qRound(withoutK.toDouble() * 1000); - } - else - { count = countStr.toInt(); } - } - - return Tag(tag, type, count); -} - -QList Tag::FromRegexp(const QString &rx, const QString &source) -{ - QRegularExpression rxtags(rx); - - QList ret; - QSet got; - - auto matches = rxtags.globalMatch(source); - while (matches.hasNext()) - { - const auto &match = matches.next(); - Tag tag = Tag::FromCapture(match, rxtags.namedCaptureGroups()); - - if (!got.contains(tag.text())) - { - got.insert(tag.text()); - ret.append(tag); - } - } - - return ret; -} - QString Tag::GetType(QString type, QMap ids) { type = type.toLower().trimmed(); diff --git a/lib/src/tags/tag.h b/lib/src/tags/tag.h index f81be1948..ea270dd92 100644 --- a/lib/src/tags/tag.h +++ b/lib/src/tags/tag.h @@ -15,8 +15,6 @@ class Tag explicit Tag(const QString &text, const QString &type = "unknown", int count = 0, const QStringList &related = QStringList()); explicit Tag(const QString &text, const TagType &type, int count = 0, const QStringList &related = QStringList()); explicit Tag(int id, const QString &text, TagType type, int count = 0, QStringList related = QStringList()); - static Tag FromCapture(const QRegularExpressionMatch &match, const QStringList &groups); - static QList FromRegexp(const QString &rx, const QString &source); static QString GetType(QString type, QMap ids = QMap()); void setId(int id); void setText(const QString &text); From a57c0dd9c0618eceffeabc2891aa3b1be4096cdb Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 09:19:30 +0200 Subject: [PATCH 050/112] Add tests for TagDatabase::count --- tests/src/tags/tag-database-test-suite.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/src/tags/tag-database-test-suite.cpp b/tests/src/tags/tag-database-test-suite.cpp index db0bbe5ab..4c49d3b57 100644 --- a/tests/src/tags/tag-database-test-suite.cpp +++ b/tests/src/tags/tag-database-test-suite.cpp @@ -39,6 +39,8 @@ void TagDatabaseTestSuite::testEmptyContainsNone() QCOMPARE(types.count(), 0); qDebug() << "Elapsed" << elapsed << "ms"; QVERIFY(elapsed < 20); + + QCOMPARE(m_database->count(), 0); } void TagDatabaseTestSuite::testFilledContainsAll() @@ -57,6 +59,8 @@ void TagDatabaseTestSuite::testFilledContainsAll() QCOMPARE(types.value("tag3").name(), QString("copyright")); qDebug() << "Elapsed" << elapsed << "ms"; QVERIFY(elapsed < 10); + + QCOMPARE(m_database->count(), 4); } void TagDatabaseTestSuite::testFilledContainsSome() From 1897b50417a30cb6065f93a2f486bd95314ffce7 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 09:24:46 +0200 Subject: [PATCH 051/112] Add TagName comparison tests --- tests/src/tags/tag-name-test.cpp | 16 ++++++++++++++++ tests/src/tags/tag-name-test.h | 1 + 2 files changed, 17 insertions(+) diff --git a/tests/src/tags/tag-name-test.cpp b/tests/src/tags/tag-name-test.cpp index 1c45725a3..7ee7e4905 100644 --- a/tests/src/tags/tag-name-test.cpp +++ b/tests/src/tags/tag-name-test.cpp @@ -28,5 +28,21 @@ void TagNameTest::testFormatted() QCOMPARE(TagName("TAG NAME", capsSpace).formatted(upperFirstDash), QString("Tag-name")); } +void TagNameTest::testCompare() +{ + TagNameFormat capsSpace(TagNameFormat::Caps, " "); + TagNameFormat upperFirstDash(TagNameFormat::UpperFirst, "-"); + + // Valid + QCOMPARE(TagName("Tag-name", upperFirstDash) == TagName("tag_name"), true); + QCOMPARE(TagName("TAG NAME", capsSpace) == TagName("tag_name"), true); + QCOMPARE(TagName("Tag-name", upperFirstDash) == TagName("TAG NAME", capsSpace), true); + + // Invalid + QCOMPARE(TagName("Tag-name-2", upperFirstDash) == TagName("tag_name"), false); + QCOMPARE(TagName("TAG NAME 2", capsSpace) == TagName("tag_name"), false); + QCOMPARE(TagName("Tag-name 2", upperFirstDash) == TagName("TAG NAME", capsSpace), false); +} + static TagNameTest instance; diff --git a/tests/src/tags/tag-name-test.h b/tests/src/tags/tag-name-test.h index fb2c76f8f..8e0504dfc 100644 --- a/tests/src/tags/tag-name-test.h +++ b/tests/src/tags/tag-name-test.h @@ -13,6 +13,7 @@ class TagNameTest : public TestSuite void testNormalizedValid(); void testNormalizedInvalid(); void testFormatted(); + void testCompare(); }; #endif // TAG_NAME_TEST_H From 2c86989686c1d95c188d28a37fbd09355f951e84 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 12:53:04 +0200 Subject: [PATCH 052/112] Use QUrl instead of QString when necessary --- gui/src/batch/batchwindow.cpp | 25 +++++----- gui/src/batch/batchwindow.h | 22 ++++----- gui/src/mainwindow.cpp | 4 +- gui/src/mainwindow.h | 4 +- gui/src/tabs/search-tab.cpp | 10 ++-- gui/src/tabs/search-tab.h | 5 +- gui/src/viewer/zoom-window.cpp | 16 +++---- gui/src/viewer/zoom-window.h | 6 ++- lib/src/downloader/downloader.cpp | 6 +-- lib/src/downloader/image-downloader.cpp | 8 ++-- lib/src/downloader/image-downloader.h | 2 +- lib/src/functions.cpp | 36 ++++++-------- lib/src/functions.h | 3 +- lib/src/loader/downloadable-downloader.cpp | 4 +- lib/src/loader/downloadable.h | 2 +- lib/src/models/image.cpp | 56 +++++++++++----------- lib/src/models/image.h | 10 ++-- tests/src/functions-test.cpp | 18 +++---- tests/src/integration/e621-test.cpp | 2 +- tests/src/models/image-test.cpp | 4 +- 20 files changed, 117 insertions(+), 126 deletions(-) diff --git a/gui/src/batch/batchwindow.cpp b/gui/src/batch/batchwindow.cpp index 1d557468b..bdbd5ddac 100644 --- a/gui/src/batch/batchwindow.cpp +++ b/gui/src/batch/batchwindow.cpp @@ -24,9 +24,6 @@ batchWindow::batchWindow(QSettings *settings, QWidget *parent) ui->checkRemove->setChecked(m_settings->value("Batch/remove", false).toBool()); ui->checkScrollToDownload->setChecked(m_settings->value("Batch/scrollToDownload", true).toBool()); - m_speeds = QMap(); - m_urls = QStringList(); - m_time = new QTime; m_time->start(); m_start = new QTime; @@ -176,7 +173,7 @@ void batchWindow::copyToClipboard() void batchWindow::setCount(int cnt) { ui->tableWidget->setRowCount(cnt); } -void batchWindow::addImage(const QString &url, int batch, double size) +void batchWindow::addImage(const QUrl &url, int batch, double size) { m_urls.append(url); @@ -186,7 +183,7 @@ void batchWindow::addImage(const QString &url, int batch, double size) ui->tableWidget->setItem(m_items, 0, id); ui->tableWidget->setItem(m_items, 1, new QTableWidgetItem(QString::number(batch))); - ui->tableWidget->setItem(m_items, 2, new QTableWidgetItem(url)); + ui->tableWidget->setItem(m_items, 2, new QTableWidgetItem(url.toString())); const QString unit = getUnit(&size); ui->tableWidget->setItem(m_items, 3, new QTableWidgetItem(size > 0 ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0) + " " + unit : QString())); ui->tableWidget->setItem(m_items, 4, new QTableWidgetItem()); @@ -213,21 +210,21 @@ void batchWindow::updateColumns() ui->tableWidget->resizeColumnToContents(0); ui->tableWidget->repaint(); } -int batchWindow::indexOf(const QString &url) +int batchWindow::indexOf(const QUrl &url) { const int i = m_urls.indexOf(url); if (i < 0 || ui->tableWidget->item(i, 1) == nullptr) return -1; return i; } -int batchWindow::batch(const QString &url) +int batchWindow::batch(const QUrl &url) { const int i = indexOf(url); if (i == -1) return -1; return ui->tableWidget->item(i, 1)->text().toInt(); } -void batchWindow::loadingImage(const QString &url) +void batchWindow::loadingImage(const QUrl &url) { if (m_start->isNull()) m_start->start(); @@ -252,25 +249,25 @@ void batchWindow::scrollTo(int i) m_lastDownloading = i; } } -void batchWindow::imageUrlChanged(const QString &before, const QString &after) +void batchWindow::imageUrlChanged(const QUrl &before, const QUrl &after) { const int i = indexOf(before); if (i != -1) { m_urls[i] = after; - ui->tableWidget->item(i, 2)->setText(after); + ui->tableWidget->item(i, 2)->setText(after.toString()); ui->tableWidget->item(i, 3)->setText(QString()); ui->tableWidget->item(i, 4)->setText(QString()); ui->tableWidget->item(i, 5)->setText("0 %"); } } -void batchWindow::statusImage(const QString &url, int percent) +void batchWindow::statusImage(const QUrl &url, int percent) { const int i = indexOf(url); if (i != -1) ui->tableWidget->item(i, 5)->setText(QString::number(percent)+" %"); } -void batchWindow::speedImage(const QString &url, double speed) +void batchWindow::speedImage(const QUrl &url, double speed) { m_speeds[url] = static_cast(speed); const QString unit = getUnit(&speed) + "/s"; @@ -281,7 +278,7 @@ void batchWindow::speedImage(const QString &url, double speed) drawSpeed(); } -void batchWindow::sizeImage(const QString &url, double size) +void batchWindow::sizeImage(const QUrl &url, double size) { int i = indexOf(url); if (i != -1) @@ -293,7 +290,7 @@ void batchWindow::sizeImage(const QString &url, double size) ui->tableWidget->item(i, 3)->setText(label); } } -void batchWindow::loadedImage(const QString &url, Downloadable::SaveResult result) +void batchWindow::loadedImage(const QUrl &url, Downloadable::SaveResult result) { static QIcon ignoredIcon(":/images/status/ignored.png"); static QIcon errorIcon(":/images/status/error.png"); diff --git a/gui/src/batch/batchwindow.h b/gui/src/batch/batchwindow.h index 44bfdf388..1597e7a39 100644 --- a/gui/src/batch/batchwindow.h +++ b/gui/src/batch/batchwindow.h @@ -30,8 +30,8 @@ class batchWindow : public QDialog int totalValue() const; int totalMax() const; int endAction(); - int indexOf(const QString &url); - int batch(const QString &url); + int indexOf(const QUrl &url); + int batch(const QUrl &url); void setCount(int); void updateColumns(); bool endRemove(); @@ -46,18 +46,18 @@ class batchWindow : public QDialog void setCurrentMax(int max); void setTotalValue(int val); void setTotalMax(int max); - void addImage(const QString &, int, double); - void sizeImage(const QString &, double); - void loadingImage(const QString &url); - void statusImage(const QString &, int); - void speedImage(const QString &, double); - void loadedImage(const QString &url, Downloadable::SaveResult result); + void addImage(const QUrl &url, int batch, double size); + void sizeImage(const QUrl &url, double size); + void loadingImage(const QUrl &url); + void statusImage(const QUrl &url, int percent); + void speedImage(const QUrl &url, double speed); + void loadedImage(const QUrl &url, Downloadable::SaveResult result); void on_buttonDetails_clicked(bool visible); void closeEvent(QCloseEvent *) override; void copyToClipboard(); void cancel(); void drawSpeed(); - void imageUrlChanged(const QString &before, const QString &after); + void imageUrlChanged(const QUrl &before, const QUrl &after); void scrollTo(int i); void pause(); void skip(); @@ -72,9 +72,9 @@ class batchWindow : public QDialog QSettings *m_settings; QSize m_currentSize; int m_imagesCount, m_items, m_images, m_maxSpeeds, m_lastDownloading; - QStringList m_urls; + QList m_urls; QList m_progressBars; - QMap m_speeds; + QMap m_speeds; QList m_mean; bool m_cancel, m_paused; QTime *m_time, *m_start; diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index b0ff3786e..88ba72306 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -1726,7 +1726,7 @@ void mainWindow::getAllImageOk(const BatchDownloadImage &download, int siteId, b _getAll(); } -void mainWindow::imageUrlChanged(const QString &before, const QString &after) +void mainWindow::imageUrlChanged(const QUrl &before, const QUrl &after) { m_downloadTimeLast.insert(after, m_downloadTimeLast[before]); m_downloadTimeLast.remove(before); @@ -1735,7 +1735,7 @@ void mainWindow::imageUrlChanged(const QString &before, const QString &after) } void mainWindow::getAllProgress(const QSharedPointer &img, qint64 bytesReceived, qint64 bytesTotal) { - const QString url = img->url(); + const QUrl url = img->url(); if (img->fileSize() == 0) { img->setFileSize(bytesTotal); diff --git a/gui/src/mainwindow.h b/gui/src/mainwindow.h index 9ce52f1fc..831f202ca 100644 --- a/gui/src/mainwindow.h +++ b/gui/src/mainwindow.h @@ -143,7 +143,7 @@ class mainWindow : public QMainWindow void on_buttonInitSettings_clicked(); void saveSettings(); void on_buttonFolder_clicked(); - void imageUrlChanged(const QString &, const QString &); + void imageUrlChanged(const QUrl &before, const QUrl &after); void updateCompleters(); void setSource(const QString &site); void setTags(const QList &tags, searchTab *from = nullptr); @@ -182,7 +182,7 @@ class mainWindow : public QMainWindow QList m_tabs, m_tabsWaitingForPreload; QList m_selectedSites; favoritesTab *m_favoritesTab; - QMap m_downloadTime, m_downloadTimeLast; + QMap m_downloadTime, m_downloadTimeLast; QList m_progressBars; QList m_batchs; QMap m_batchPending; diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index c4b29b91a..1f16d585f 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -494,11 +494,11 @@ void searchTab::finishedLoadingTags(Page *page) setPageLabelText(m_siteLabels[page->site()], page, imgs); } -void searchTab::loadImageThumbnail(Page *page, QSharedPointer img, const QString &url) +void searchTab::loadImageThumbnail(Page *page, QSharedPointer img, const QUrl &url) { Site *site = page->site(); - QNetworkReply *reply = site->get(site->fixUrl(url), page, "preview"); + QNetworkReply *reply = site->get(site->fixUrl(url.toString()), page, "preview"); reply->setParent(this); m_thumbnailsLoading[reply] = std::move(img); @@ -536,7 +536,7 @@ void searchTab::finishedLoadingPreview() QUrl redirection = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redirection.isEmpty()) { - loadImageThumbnail(img->page(), img, redirection.toString()); + loadImageThumbnail(img->page(), img, redirection); reply->deleteLater(); return; } @@ -555,7 +555,7 @@ void searchTab::finishedLoadingPreview() reply->deleteLater(); if (preview.isNull()) { - log(QStringLiteral("One of the thumbnails is empty (%1).").arg(img->url(Image::Size::Thumbnail)), Logger::Error); + log(QStringLiteral("One of the thumbnails is empty (%1).").arg(img->url(Image::Size::Thumbnail).toString()), Logger::Error); if (img->hasTag(QStringLiteral("flash"))) { preview.load(QStringLiteral(":/images/flash.png")); } else @@ -1470,8 +1470,6 @@ void searchTab::setFavoriteImage(const QString &name) QList searchTab::sources() { return m_selectedSources; } -const QStringList &searchTab::selectedImages() const -{ return m_selectedImages; } const QList &searchTab::results() const { return m_tags; } diff --git a/gui/src/tabs/search-tab.h b/gui/src/tabs/search-tab.h index aeeb8ba1e..6233a0026 100644 --- a/gui/src/tabs/search-tab.h +++ b/gui/src/tabs/search-tab.h @@ -44,7 +44,6 @@ class searchTab : public QWidget QString postFilter(); virtual void setTags(const QString &tags, bool preload = true) = 0; virtual bool validateImage(const QSharedPointer &img, QString &error); - const QStringList &selectedImages() const; void setSources(const QList &sources); void setImagesPerPage(int ipp); void setColumns(int columns); @@ -60,7 +59,7 @@ class searchTab : public QWidget QStringList reasonsToFail(Page *page, const QStringList &completion = QStringList(), QString *meant = nullptr); void clear(); TextEdit *createAutocomplete(); - void loadImageThumbnail(Page *page, QSharedPointer img, const QString &url); + void loadImageThumbnail(Page *page, QSharedPointer img, const QUrl &url); QBouton *createImageThumbnail(int position, const QSharedPointer &img); FixedSizeGridLayout *createImagesLayout(QSettings *settings); void thumbnailContextMenu(int position, const QSharedPointer &img); @@ -142,7 +141,7 @@ class searchTab : public QWidget qulonglong m_lastPageMaxId, m_lastPageMinId; const QMap &m_sites; QMap m_boutons; - QStringList m_selectedImages; + QList m_selectedImages; QList> m_selectedImagesPtrs; QList m_selectedSources; QSignalMapper *m_checkboxesSignalMapper; diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index d2014efa7..8ee424700 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -144,7 +144,7 @@ void ZoomWindow::go() if (m_settings->value("autodownload", false).toBool() || (whitelisted && m_settings->value("whitelist_download", "image").toString() == "image")) { saveImage(); } - m_url = m_image->getDisplayableUrl().toString(); + m_url = m_image->getDisplayableUrl(); auto *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(update())); @@ -374,7 +374,7 @@ void ZoomWindow::setfavorite() void ZoomWindow::load(bool force) { - log(QStringLiteral("Loading image from %1").arg(m_url)); + log(QStringLiteral("Loading image from %1").arg(m_url.toString())); m_source.clear(); @@ -489,7 +489,7 @@ void ZoomWindow::replyFinishedDetails() // Fix extension when it should be guessed const QString fext = m_source.section('.', -1); - m_url = m_url.section('.', 0, -2) + "." + fext; + m_url = setExtension(m_url, fext); m_image->setFileExtension(fext); m_finished = true; @@ -592,7 +592,7 @@ void ZoomWindow::setButtonState(bool fav, SaveButtonState state) void ZoomWindow::replyFinishedZoom(QNetworkReply::NetworkError err, const QString &errorString) { - log(QStringLiteral("Image received from %1").arg(m_url)); + log(QStringLiteral("Image received from %1").arg(m_url.toString())); ui->progressBarDownload->hide(); m_finished = true; @@ -613,14 +613,14 @@ void ZoomWindow::replyFinishedZoom(QNetworkReply::NetworkError err, const QStrin { m_tooBig = true; if (!m_image->isVideo()) - { error(this, tr("File is too big to be displayed.\n%1").arg(m_image->url())); } + { error(this, tr("File is too big to be displayed.\n%1").arg(m_image->url().toString())); } } else if (err == QNetworkReply::ContentNotFoundError) { showLoadingError("Image not found."); } else if (err == QNetworkReply::UnknownContentError) { showLoadingError("Error loading the image."); } else if (err != QNetworkReply::OperationCanceledError) - { error(this, tr("An unexpected error occured loading the image (%1 - %2).\n%3").arg(err).arg(errorString, m_image->url())); } + { error(this, tr("An unexpected error occured loading the image (%1 - %2).\n%3").arg(err).arg(errorString, m_image->url().toString())); } } void ZoomWindow::showLoadingError(const QString &message) @@ -688,7 +688,7 @@ void ZoomWindow::draw() if (m_image->isVideo()) return; - const QString fn = m_url.section('/', -1).section('?', 0, 0).toLower(); + const QString fn = m_url.fileName().toLower(); // We need a filename to display animations, so we get it if we're not already loading from a file QString filename; @@ -1100,7 +1100,7 @@ void ZoomWindow::showThumbnail() } } -void ZoomWindow::urlChanged(const QString &before, const QString &after) +void ZoomWindow::urlChanged(const QUrl &before, const QUrl &after) { Q_UNUSED(before); m_url = after; diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index 3d8ec358b..0cfc5945e 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -66,7 +66,7 @@ class ZoomWindow : public QWidget void setfavorite(); void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); void colore(); - void urlChanged(const QString &before, const QString &after); + void urlChanged(const QUrl &before, const QUrl &after); void showDetails(); void pendingUpdate(); void updateButtonPlus(); @@ -128,7 +128,9 @@ class ZoomWindow : public QWidget Site *m_site; int m_timeout, m_mustSave; bool m_tooBig, m_loadedImage, m_loadedDetails; - QString id, m_url, m_saveUrl, rating, score, user; + QString id; + QUrl m_url, m_saveUrl; + QString rating, score, user; QAffiche *m_labelTagsTop, *m_labelTagsLeft; QTimer *m_resizeTimer; QTime m_imageTime; diff --git a/lib/src/downloader/downloader.cpp b/lib/src/downloader/downloader.cpp index cc201df1e..79845a145 100644 --- a/lib/src/downloader/downloader.cpp +++ b/lib/src/downloader/downloader.cpp @@ -231,7 +231,7 @@ void Downloader::loadNext() if (!m_images.isEmpty()) { const QSharedPointer image = m_images.takeFirst(); - log("Loading image '"+image->url()+"'"); + log(QString("Loading image '%1'").arg(image->url().toString())); auto dwl = new ImageDownloader(image, m_filename, m_location, 0, true, false); connect(dwl, &ImageDownloader::saved, this, &Downloader::finishedLoadingImage); connect(dwl, &ImageDownloader::saved, dwl, &ImageDownloader::deleteLater); @@ -364,7 +364,7 @@ void Downloader::finishedLoadingImage(const QSharedPointer &image, const if (m_cancelled) return; - log(QStringLiteral("Received image '%1'").arg(image->url())); + log(QStringLiteral("Received image '%1'").arg(image->url().toString())); if (!m_quit) emit finishedImage(image); @@ -461,7 +461,7 @@ void Downloader::finishedLoadingUrls(Page *page) int i = 0; for (const QSharedPointer &img : images) if (m_max <= 0 || i++ < m_max) - urls.append(img->url()); + urls.append(img->url().toString()); if (m_quit) returnStringList(urls); diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index a7fabbace..b2201fa79 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -91,7 +91,7 @@ void ImageDownloader::loadImage() // Load the image directly on the disk log(QStringLiteral("Loading and saving image in %1").arg(m_paths.first())); Site *site = m_image->parentSite(); - m_reply = site->get(site->fixUrl(m_url), m_image->page(), QStringLiteral("image"), m_image.data()); + m_reply = site->get(site->fixUrl(m_url.toString()), m_image->page(), QStringLiteral("image"), m_image.data()); m_reply->setParent(this); connect(m_reply, &QNetworkReply::downloadProgress, this, &ImageDownloader::downloadProgressImage); @@ -156,7 +156,7 @@ void ImageDownloader::networkError(QNetworkReply::NetworkError error, const QStr else { m_url = setExtension(m_url, newext); - log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url)); + log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url.toString())); } m_image->setUrl(m_url); @@ -170,7 +170,7 @@ void ImageDownloader::networkError(QNetworkReply::NetworkError error, const QStr } else if (error != QNetworkReply::OperationCanceledError) { - log(QStringLiteral("Network error for the image: %1: %2 (%3)").arg(m_image->url().toHtmlEscaped()).arg(error).arg(msg), Logger::Error); + log(QStringLiteral("Network error for the image: %1: %2 (%3)").arg(m_image->url().toString().toHtmlEscaped()).arg(error).arg(msg), Logger::Error); emit saved(m_image, makeMap(m_paths, Image::SaveResult::NetworkError)); } } @@ -181,7 +181,7 @@ void ImageDownloader::success() QUrl redir = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redir.isEmpty()) { - m_url = redir.toString(); + m_url = redir; loadImage(); return; } diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index 1b55e78f8..b14fa12bb 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -49,7 +49,7 @@ class ImageDownloader : public QObject bool m_rotate; QNetworkReply *m_reply = nullptr; - QString m_url = ""; + QUrl m_url; bool m_tryingSample = false; }; diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index 87061c957..dc0348dd7 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -425,31 +425,25 @@ void openTray() } QString getExtension(const QUrl &url) -{ return getExtension(url.toString()); } -QString getExtension(const QString &url) { - QString ext; - const int pPos = url.lastIndexOf('.'); - if (pPos != -1 && pPos > url.indexOf('/', 7)) - { - ext = url.right(url.length() - pPos - 1); - if (ext.contains('?')) - ext = ext.section('?', 0, -2); - } - return ext; + const QString filename = url.fileName(); + const int lastDot = filename.lastIndexOf('.'); + + if (lastDot != -1) + return filename.mid(lastDot + 1); + + return QString(); } -QString setExtension(QString url, const QString &extension) +QUrl setExtension(QUrl url, const QString &extension) { - const int pPos = url.lastIndexOf('.'); - if (pPos != -1 && pPos > url.indexOf('/', 7)) - { - const int qPos = url.indexOf('?', pPos); - if (qPos != -1) - url.replace(pPos + 1, qPos - pPos - 1, extension); - else - url = url.left(pPos) + "." + extension; - } + QString path = url.path(); + + const int lastSlash = path.lastIndexOf('/'); + const int lastDot = path.midRef(lastSlash + 1).lastIndexOf('.'); + if (lastDot != -1) + url.setPath(path.left(lastDot + lastSlash + 1) + "." + extension); + return url; } diff --git a/lib/src/functions.h b/lib/src/functions.h index c4b043324..142471cc7 100644 --- a/lib/src/functions.h +++ b/lib/src/functions.h @@ -44,8 +44,7 @@ QString stripTags(QString); QString getUnit(double *size); QString formatFilesize(double size); QString getExtension(const QUrl &url); -QString getExtension(const QString &url); -QString setExtension(QString url, const QString &extension); +QUrl setExtension(QUrl url, const QString &extension); bool isUrl(const QString &str); bool isVariantEmpty(const QVariant &value); diff --git a/lib/src/loader/downloadable-downloader.cpp b/lib/src/loader/downloadable-downloader.cpp index ff09663f2..7fcbf5798 100644 --- a/lib/src/loader/downloadable-downloader.cpp +++ b/lib/src/loader/downloadable-downloader.cpp @@ -33,7 +33,7 @@ void DownloadableDownloader::save() void DownloadableDownloader::preloaded() { - const QString url = m_downloadable->url(Downloadable::Size::Full); + const QUrl url = m_downloadable->url(Downloadable::Size::Full); QStringList paths = !m_paths.isEmpty() ? m_paths : m_downloadable->paths(m_filename, m_folder, m_count); // Sometimes we don't even need to download the image to save it @@ -58,7 +58,7 @@ void DownloadableDownloader::preloaded() // Load the image directly on the disk log(QStringLiteral("Loading and saving image in %1").arg(m_paths.first())); - m_url = m_site->fixUrl(url); + m_url = m_site->fixUrl(url.toString()); QNetworkReply *reply = m_site->get(m_url, nullptr, QStringLiteral("image"), nullptr); // TODO(Bionus) connect(&m_fileDownloader, &FileDownloader::writeError, this, &DownloadableDownloader::writeError, Qt::UniqueConnection); connect(&m_fileDownloader, &FileDownloader::networkError, this, &DownloadableDownloader::networkError, Qt::UniqueConnection); diff --git a/lib/src/loader/downloadable.h b/lib/src/loader/downloadable.h index 072b6e29d..36f3f1150 100644 --- a/lib/src/loader/downloadable.h +++ b/lib/src/loader/downloadable.h @@ -37,7 +37,7 @@ class Downloadable virtual ~Downloadable() = default; virtual void preload(const Filename &filename) = 0; - virtual QString url(Size size) const = 0; + virtual QUrl url(Size size) const = 0; virtual QStringList paths(const Filename &filename, const QString &folder, int count) const = 0; const QMap &tokens(Profile *profile) const; virtual SaveResult preSave(const QString &path) = 0; diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 9443e73c0..e0613de89 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -22,17 +22,17 @@ #define MAX_LOAD_FILESIZE (1024*1024*50) -QString removeCacheUrl(QString url) +QUrl removeCacheUrl(QUrl url) { - QString get = url.section('?', 1, 1); - if (get.isEmpty()) + const QString query = url.query(); + if (query.isEmpty()) return url; // Only remove ?integer bool ok; - get.toInt(&ok); + query.toInt(&ok); if (ok) - return url.section('?', 0, 0); + url.setQuery(QString()); return url; } @@ -211,7 +211,7 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* tag.setType(dbTypes[tag.text()]); // Get file url and try to improve it to save bandwidth - m_url = m_fileUrl.toString(); + m_url = m_fileUrl; const QString ext = getExtension(m_url); if (details.contains("ext") && !details["ext"].isEmpty()) { @@ -222,11 +222,11 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* else if (ext == QLatin1String("jpg") && !m_previewUrl.isEmpty()) { bool fixed = false; - const QString previewExt = getExtension(details["preview_url"]); + const QString previewExt = getExtension(QUrl(details["preview_url"])); if (!m_sampleUrl.isEmpty()) { // Guess extension from sample url - const QString sampleExt = getExtension(details["sample_url"]); + const QString sampleExt = getExtension(QUrl(details["sample_url"])); if (sampleExt != QLatin1String("jpg") && sampleExt != QLatin1String("png") && sampleExt != ext && previewExt == ext) { m_url = setExtension(m_url, sampleExt); @@ -249,14 +249,14 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* { setFileExtension(QStringLiteral("webm")); } } } - else if (details.contains("image") && details["image"].contains("MB // gif\" height=\"") && !m_url.endsWith(".gif", Qt::CaseInsensitive)) + else if (details.contains("image") && details["image"].contains("MB // gif\" height=\"") && ext != QLatin1String("gif")) { m_url = setExtension(m_url, QStringLiteral("gif")); } // Remove ? in urls m_url = removeCacheUrl(m_url); - m_fileUrl = removeCacheUrl(m_fileUrl.toString()); - m_sampleUrl = removeCacheUrl(m_sampleUrl.toString()); - m_previewUrl = removeCacheUrl(m_previewUrl.toString()); + m_fileUrl = removeCacheUrl(m_fileUrl); + m_sampleUrl = removeCacheUrl(m_sampleUrl); + m_previewUrl = removeCacheUrl(m_previewUrl); // We use the sample URL as the URL for zip files (ugoira) or if the setting is set const bool downloadOriginals = m_settings->value("Save/downloadoriginals", true).toBool(); @@ -376,10 +376,10 @@ void Image::parseDetails() // Image url if (!ret.imageUrl.isEmpty()) { - const QString before = m_url; + const QUrl before = m_url; QUrl newUrl = m_parentSite->fixUrl(ret.imageUrl, before); - m_url = newUrl.toString(); + m_url = newUrl; m_fileUrl = newUrl; if (before != m_url) @@ -452,7 +452,7 @@ void Image::loadImage(bool inMemory, bool force) m_loadImage->deleteLater(); if (force) - setUrl(fileUrl().toString()); + setUrl(m_fileUrl); m_loadImage = m_parentSite->get(m_parentSite->fixUrl(m_url), m_parent, "image", this); m_loadImage->setParent(this); @@ -501,7 +501,7 @@ void Image::finishedImageS(bool inMemory) { m_loadImage->deleteLater(); m_loadImage = nullptr; - m_url = redir.toString(); + m_url = redir; loadImage(); return; } @@ -518,14 +518,14 @@ void Image::finishedImageS(bool inMemory) { if (isLast) { - setUrl(m_sampleUrl.toString()); + setUrl(m_sampleUrl); m_tryingSample = true; log(QStringLiteral("Image not found. New try with its sample...")); } else { m_url = setExtension(m_url, newext); - log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url)); + log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url.toString())); } loadImage(); @@ -695,7 +695,7 @@ Image::SaveResult Image::save(const QString &path, bool force, bool basic, bool } else { - log(QStringLiteral("MD5 \"%1\" of the image %2 already found in file %3").arg(md5(), url(), md5Duplicate)); + log(QStringLiteral("MD5 \"%1\" of the image %2 already found in file %3").arg(md5(), url().toString(), md5Duplicate)); return SaveResult::Ignored; } @@ -812,7 +812,7 @@ QList Image::filteredTags(const QStringList &remove) const } -const QString &Image::url() const { return m_url; } +const QUrl &Image::url() const { return m_url; } const QString &Image::rating() const { return m_rating; } Site *Image::parentSite() const { return m_parentSite; } const QList &Image::tags() const { return m_tags; } @@ -859,11 +859,11 @@ QStringList Image::tagsString() const return tags; } -void Image::setUrl(const QString &u) +void Image::setUrl(const QUrl &url) { setFileSize(0); - emit urlChanged(m_url, u); - m_url = u; + emit urlChanged(m_url, url); + m_url = url; refreshTokens(); } void Image::setSize(QSize size) { m_size = size; refreshTokens(); } @@ -1057,7 +1057,7 @@ void Image::setRating(const QString &rating) void Image::setFileExtension(const QString &ext) { m_url = setExtension(m_url, ext); - m_fileUrl = setExtension(m_fileUrl.toString(), ext); + m_fileUrl = setExtension(m_fileUrl, ext); refreshTokens(); } @@ -1080,12 +1080,12 @@ QString Image::isAnimated() const } -QString Image::url(Size size) const +QUrl Image::url(Size size) const { switch (size) { - case Size::Thumbnail: return m_previewUrl.toString(); - case Size::Sample: return m_sampleUrl.toString(); + case Size::Thumbnail: return m_previewUrl; + case Size::Sample: return m_sampleUrl; default: return m_url; } } @@ -1120,7 +1120,7 @@ QMap Image::generateTokens(Profile *profile) const tokens.insert("pool", Token(poolMatch.hasMatch() ? poolMatch.captured(1) : "", "")); // Metadata - tokens.insert("filename", Token(QUrl::fromPercentEncoding(m_url.section('/', -1).section('.', 0, -2).toUtf8()), "")); + tokens.insert("filename", Token(QUrl::fromPercentEncoding(m_url.fileName().section('.', 0, -2).toUtf8()), "")); tokens.insert("website", Token(m_parentSite->url(), "")); tokens.insert("websitename", Token(m_parentSite->name(), "")); tokens.insert("md5", Token(md5(), "")); diff --git a/lib/src/models/image.h b/lib/src/models/image.h index 796c2b624..f6b3f8680 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -32,7 +32,7 @@ class Image : public QObject, public Downloadable QMap save(const QStringList &paths, bool addMd5 = true, bool startCommands = false, int count = 1, bool force = false); QMap save(const QString &filename, const QString &path, bool addMd5 = true, bool startCommands = false, int count = 1); QString md5() const; - const QString &url() const; + const QUrl &url() const; const QString &rating() const; const QList &tags() const; QList filteredTags(const QStringList &remove) const; @@ -56,7 +56,7 @@ class Image : public QObject, public Downloadable bool hasTag(QString tag) const; bool hasAnyTag(const QStringList &tags) const; bool hasAllTags(const QStringList &tags) const; - void setUrl(const QString &); + void setUrl(const QUrl &url); void setData(const QByteArray &data); void setSize(QSize size); void setFileSize(int size); @@ -75,7 +75,7 @@ class Image : public QObject, public Downloadable QList detailsData() const override; // Downloadable - QString url(Size size) const override; + QUrl url(Size size) const override; void preload(const Filename &filename) override; QStringList paths(const Filename &filename, const QString &folder, int count) const override; QMap generateTokens(Profile *profile) const override; @@ -113,7 +113,7 @@ class Image : public QObject, public Downloadable void finishedLoadingTags(); void finishedImage(QNetworkReply::NetworkError, const QString &); void downloadProgressImage(qint64, qint64); - void urlChanged(const QString &before, const QString &after); + void urlChanged(const QUrl &before, const QUrl &after); private: Profile *m_profile; @@ -121,7 +121,7 @@ class Image : public QObject, public Downloadable qulonglong m_id; int m_score, m_parentId, m_fileSize, m_authorId; bool m_hasChildren, m_hasNote, m_hasComments, m_hasScore; - QString m_url; + QUrl m_url; QString mutable m_md5; QString m_author, m_name, m_status, m_rating, m_source, m_site, m_savePath; QUrl m_pageUrl, m_fileUrl, m_sampleUrl, m_previewUrl; diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index 12198f6a0..b7fc73906 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -49,17 +49,19 @@ void FunctionsTest::testFormatFilesize() void FunctionsTest::testGetExtension() { - QCOMPARE(getExtension(""), QString("")); - QCOMPARE(getExtension("http://test.com/file"), QString("")); - QCOMPARE(getExtension("http://test.com/file.jpg"), QString("jpg")); - QCOMPARE(getExtension("http://test.com/file.jpg?toto=1"), QString("jpg")); + QCOMPARE(getExtension(QUrl("")), QString("")); + QCOMPARE(getExtension(QUrl("http://test.com/file")), QString("")); + QCOMPARE(getExtension(QUrl("http://test.com/some.dir/file")), QString("")); + QCOMPARE(getExtension(QUrl("http://test.com/file.jpg")), QString("jpg")); + QCOMPARE(getExtension(QUrl("http://test.com/file.jpg?toto=1")), QString("jpg")); + QCOMPARE(getExtension(QUrl("http://test.com/file.jpg?toto=1")), QString("jpg")); } void FunctionsTest::testSetExtension() { - QCOMPARE(setExtension("", "png"), QString("")); - QCOMPARE(setExtension("http://test.com/file", "png"), QString("http://test.com/file")); - QCOMPARE(setExtension("http://test.com/file.jpg", "png"), QString("http://test.com/file.png")); - QCOMPARE(setExtension("http://test.com/file.jpg?toto=1", "png"), QString("http://test.com/file.png?toto=1")); + QCOMPARE(setExtension(QUrl(""), "png"), QString("")); + QCOMPARE(setExtension(QUrl("http://test.com/file"), "png"), QString("http://test.com/file")); + QCOMPARE(setExtension(QUrl("http://test.com/file.jpg"), "png"), QString("http://test.com/file.png")); + QCOMPARE(setExtension(QUrl("http://test.com/file.jpg?toto=1"), "png"), QString("http://test.com/file.png?toto=1")); } void FunctionsTest::testLevenshtein() diff --git a/tests/src/integration/e621-test.cpp b/tests/src/integration/e621-test.cpp index 2a8512c20..4abae1fee 100644 --- a/tests/src/integration/e621-test.cpp +++ b/tests/src/integration/e621-test.cpp @@ -15,7 +15,7 @@ void E621Test::testSwfUrls() for (Image *img : images) { md5s.append(img->md5()); - urls.append(img->url()); + urls.append(img->url().toString()); } // Check results diff --git a/tests/src/models/image-test.cpp b/tests/src/models/image-test.cpp index f39f459ae..fdf4e1fed 100644 --- a/tests/src/models/image-test.cpp +++ b/tests/src/models/image-test.cpp @@ -275,7 +275,7 @@ void ImageTest::testLoadDetailsImageUrl() QVERIFY(spy.wait()); // Compare result - QVERIFY(m_img->url().endsWith("/__kousaka_tamaki_to_heart_2_drawn_by_date_senpen__0cc748f006b9636f0c268250ea157995.jpg")); + QCOMPARE(m_img->url().fileName(), QString("__kousaka_tamaki_to_heart_2_drawn_by_date_senpen__0cc748f006b9636f0c268250ea157995.jpg")); } void ImageTest::testSave() @@ -394,7 +394,7 @@ void ImageTest::testSetUrl() QString url = "http://google.fr"; QCOMPARE(m_img->url() != url, true); - m_img->setUrl(url); + m_img->setUrl(QUrl(url)); QCOMPARE(m_img->url(), url); } From fa7420c5df48454e20ee1109cab66270ab6e000e Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 14:14:19 +0200 Subject: [PATCH 053/112] Add tests for qFontToCss --- tests/src/functions-test.cpp | 20 ++++++++++++++++++++ tests/src/functions-test.h | 1 + 2 files changed, 21 insertions(+) diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index b7fc73906..06c103a44 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -19,6 +19,26 @@ void FunctionsTest::testFixFilenameLinux() assertFixFilename(1, "folder/image.jpg", "/home/test/", "folder/image.jpg"); } +static QFont makeFont(const QString &name, int size, bool usePixels, int weight, QFont::Style style) +{ + QFont font(name); + if (usePixels) + font.setPixelSize(size); + else + font.setPointSize(size); + font.setWeight(weight); + font.setStyle(style); + return font; +} +void FunctionsTest::testFontToCss() +{ + QCOMPARE(qFontToCss(makeFont("Arial", 12, false, QFont::Normal, QFont::StyleNormal)), QString("font-family:'Arial'; font-size:12pt; font-style:normal; font-weight:400; text-decoration:none;")); + QCOMPARE(qFontToCss(makeFont("Arial", 12, true, QFont::Normal, QFont::StyleNormal)), QString("font-family:'Arial'; font-size:12px; font-style:normal; font-weight:400; text-decoration:none;")); + QCOMPARE(qFontToCss(makeFont("Arial", 12, false, QFont::Bold, QFont::StyleNormal)), QString("font-family:'Arial'; font-size:12pt; font-style:normal; font-weight:600; text-decoration:none;")); + QCOMPARE(qFontToCss(makeFont("Arial", 12, false, QFont::Normal, QFont::StyleItalic)), QString("font-family:'Arial'; font-size:12pt; font-style:italic; font-weight:400; text-decoration:none;")); + QCOMPARE(qFontToCss(makeFont("Arial", 12, false, QFont::Normal, QFont::StyleOblique)), QString("font-family:'Arial'; font-size:12pt; font-style:oblique; font-weight:400; text-decoration:none;")); +} + void FunctionsTest::testGetUnit() { QStringList units = FILESIZE_UNITS; diff --git a/tests/src/functions-test.h b/tests/src/functions-test.h index d1374a633..38f3a3ecb 100644 --- a/tests/src/functions-test.h +++ b/tests/src/functions-test.h @@ -11,6 +11,7 @@ class FunctionsTest : public TestSuite private slots: void testFixFilenameWindows(); void testFixFilenameLinux(); + void testFontToCss(); void testGetUnit(); void testFormatFilesize(); void testGetExtension(); From db4e92202640ec8237db0585fbdffeece03211b7 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 14:22:29 +0200 Subject: [PATCH 054/112] Add tests for isVariantEmpty --- tests/src/functions-test.cpp | 30 ++++++++++++++++++++++++++++++ tests/src/functions-test.h | 1 + 2 files changed, 31 insertions(+) diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index 06c103a44..ee804c9ed 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -39,6 +39,36 @@ void FunctionsTest::testFontToCss() QCOMPARE(qFontToCss(makeFont("Arial", 12, false, QFont::Normal, QFont::StyleOblique)), QString("font-family:'Arial'; font-size:12pt; font-style:oblique; font-weight:400; text-decoration:none;")); } +void FunctionsTest::testIsVariantEmpty() +{ + // Int + QCOMPARE(isVariantEmpty(QVariant(0)), true); + QCOMPARE(isVariantEmpty(QVariant(1)), false); + + // List + QCOMPARE(isVariantEmpty(QList()), true); + QCOMPARE(isVariantEmpty(QList() << 0), false); + QCOMPARE(isVariantEmpty(QList() << 1), false); + + // Map + QCOMPARE(isVariantEmpty(QMap()), true); + QCOMPARE(isVariantEmpty(QMap {{ "", 0 }}), false); + QCOMPARE(isVariantEmpty(QMap {{ "", 1 }}), false); + + // String + QCOMPARE(isVariantEmpty(QString()), true); + QCOMPARE(isVariantEmpty(QString("")), true); + QCOMPARE(isVariantEmpty(QString("test")), false); + + // String list + QCOMPARE(isVariantEmpty(QStringList()), true); + QCOMPARE(isVariantEmpty(QStringList() << ""), false); + QCOMPARE(isVariantEmpty(QStringList() << "test"), false); + + // Others + QCOMPARE(isVariantEmpty(QRect(1, 2, 3, 4)), false); +} + void FunctionsTest::testGetUnit() { QStringList units = FILESIZE_UNITS; diff --git a/tests/src/functions-test.h b/tests/src/functions-test.h index 38f3a3ecb..3518b4a5a 100644 --- a/tests/src/functions-test.h +++ b/tests/src/functions-test.h @@ -12,6 +12,7 @@ class FunctionsTest : public TestSuite void testFixFilenameWindows(); void testFixFilenameLinux(); void testFontToCss(); + void testIsVariantEmpty(); void testGetUnit(); void testFormatFilesize(); void testGetExtension(); From a9d8609c925940ba807f95164abc8eafd3def50a Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 14:50:42 +0200 Subject: [PATCH 055/112] Add tests for copyRecursively --- lib/src/functions.cpp | 2 +- tests/resources/recurse/test.txt | 0 tests/resources/recurse/test/test1.txt | 0 tests/resources/recurse/test/test2.txt | 0 tests/src/functions-test.cpp | 13 +++++++++++++ tests/src/functions-test.h | 1 + 6 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 tests/resources/recurse/test.txt create mode 100644 tests/resources/recurse/test/test1.txt create mode 100644 tests/resources/recurse/test/test2.txt diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index dc0348dd7..fae6ee93c 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -278,7 +278,7 @@ bool copyRecursively(QString srcFilePath, QString tgtFilePath) // Try to create the target directory QDir targetDir(tgtFilePath); targetDir.cdUp(); - if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName())) + if (!targetDir.mkdir(QDir(tgtFilePath).dirName())) return false; QDir sourceDir(srcFilePath); diff --git a/tests/resources/recurse/test.txt b/tests/resources/recurse/test.txt new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/recurse/test/test1.txt b/tests/resources/recurse/test/test1.txt new file mode 100644 index 000000000..e69de29bb diff --git a/tests/resources/recurse/test/test2.txt b/tests/resources/recurse/test/test2.txt new file mode 100644 index 000000000..e69de29bb diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index ee804c9ed..b442c3641 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -3,6 +3,19 @@ #include "functions-test.h" +void FunctionsTest::testCopyRecursively() +{ + QString from = QDir::toNativeSeparators("tests/resources/recurse/"); + QString to = QDir::toNativeSeparators("tests/resources/tmp/recurse/"); + + QDir(to).removeRecursively(); + + QCOMPARE(copyRecursively(from, to), true); + QCOMPARE(QFile::exists(to + "test.txt"), true); + QCOMPARE(QFile::exists(to + "test/test1.txt"), true); + QCOMPARE(QFile::exists(to + "test/test2.txt"), true); +} + void FunctionsTest::testFixFilenameWindows() { assertFixFilename(0, "", "C:\\test\\image.jpg", "C:\\test\\image.jpg"); diff --git a/tests/src/functions-test.h b/tests/src/functions-test.h index 3518b4a5a..079b21e87 100644 --- a/tests/src/functions-test.h +++ b/tests/src/functions-test.h @@ -9,6 +9,7 @@ class FunctionsTest : public TestSuite Q_OBJECT private slots: + void testCopyRecursively(); void testFixFilenameWindows(); void testFixFilenameLinux(); void testFontToCss(); From 7f5fb2343dc7f905b7464ae9851c8489ad81dd13 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 14:15:02 +0200 Subject: [PATCH 056/112] Add tests for getExtensionFromHeader --- lib/src/functions.cpp | 4 ++-- tests/resources/minimal/bmp.bmp | Bin 0 -> 58 bytes tests/resources/minimal/gif.gif | Bin 0 -> 799 bytes tests/resources/minimal/ico.ico | Bin 0 -> 70 bytes tests/resources/minimal/jpg.jpg | Bin 0 -> 803 bytes tests/resources/minimal/mp4.mp4 | Bin 0 -> 843 bytes tests/resources/minimal/png.png | Bin 0 -> 156 bytes tests/resources/minimal/swf.swf | Bin 0 -> 140 bytes tests/resources/minimal/webm.webm | Bin 0 -> 185 bytes tests/src/functions-test.cpp | 20 ++++++++++++++++++++ tests/src/functions-test.h | 1 + 11 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 tests/resources/minimal/bmp.bmp create mode 100644 tests/resources/minimal/gif.gif create mode 100644 tests/resources/minimal/ico.ico create mode 100644 tests/resources/minimal/jpg.jpg create mode 100644 tests/resources/minimal/mp4.mp4 create mode 100644 tests/resources/minimal/png.png create mode 100644 tests/resources/minimal/swf.swf create mode 100644 tests/resources/minimal/webm.webm diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index fae6ee93c..5a61c0683 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -633,7 +633,7 @@ QString getExtensionFromHeader(const QByteArray &data12) return QStringLiteral("png"); // JPG - if (data3 == "\255\216\255") + if (data3 == "\377\330\377") return QStringLiteral("jpg"); // BMP @@ -641,7 +641,7 @@ QString getExtensionFromHeader(const QByteArray &data12) return QStringLiteral("bmp"); // WEBM - if (data4 == "\026\069\223\163") + if (data4 == "\032\105\337\243") return QStringLiteral("webm"); // MP4 diff --git a/tests/resources/minimal/bmp.bmp b/tests/resources/minimal/bmp.bmp new file mode 100644 index 0000000000000000000000000000000000000000..3058464650f8b5f6534bdcad91f5ddffd731d2f6 GIT binary patch literal 58 icmZ?rwPJt(Ga#h_#Eft(0g(Wbhxs5FCeYB(@E-tV1_fjQ literal 0 HcmV?d00001 diff --git a/tests/resources/minimal/gif.gif b/tests/resources/minimal/gif.gif new file mode 100644 index 0000000000000000000000000000000000000000..670b055830b487a88395aa16843bd534f61f2f08 GIT binary patch literal 799 ucmZ?wbhEHbWMp7u_|Cx4(9pmz3PwX~6BCHX%mf6? z%q%R-K)}Mn#>&FN3S_ggv$C>*01GQSJ3AXYhzT+TY5-6dGaCyt3rLtW@c#gVAP3Mp zjLeKm3`~NI%z}*nk1)ssUCIhE8{{t#U}R!uVP#|I;N;>4D%dK(z{JSR%*4XX3Unb* zwiYPQz#_;hq-f~KCLEZ^u2d*u)Hrb=hqBYggQ7tfKd2Zd6*X~kiHS={N~x-;YiMej zn3|beSXw!|xVpJ}czOkggocGjL`Eg2q^6~3WM&nYl$MoOR8}>&w6?W(baqXeJZ0*% z=`&`|TC{k{(q+q6tX#Ee^OmjKw(r=v>(JpNM~@vpaq`rq%U7;myME*5t%r{uKY9A> z`HPpYK7RWAxYE#}NLy#lQnh Tx=e!1f(-Ty8jHFZ{@(-uH$T(3 literal 0 HcmV?d00001 diff --git a/tests/resources/minimal/mp4.mp4 b/tests/resources/minimal/mp4.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..3c76f5c9f3e4bba9c34fe7d4753ab7c53a03383e GIT binary patch literal 843 zcmZuw%`XE{5TB<$dLW8Q8hWU35Fd^DIEp459EiAxgNW6)O*i)0X7|~IQ{%+JAL1rH zPn?L0Kg7-5!TQZ^x2jAs?>FNkm97WVdjL=zCoi7kkvh12Ba7al* z6Nwv2bph^Edz+_=4U-o<3O-dxtwg0v9+C%P$9Hi(icM{>L`Z z8OxC#hf}p$t&28-AovQ<{fKsr1JFDAAnc|0r3tjav!}gq2@y}XSR*forMYIrBr(=1Ojee^84>?;W&%7j?V4Wn z{0Th&Ift+(Le) z6E{S-Tul)Q6zhy%vE!)FypGGgW!v%-&SKuOClrTXV6U-L!g>S=Afp!1@ literal 0 HcmV?d00001 diff --git a/tests/resources/minimal/png.png b/tests/resources/minimal/png.png new file mode 100644 index 0000000000000000000000000000000000000000..3b51b9a051ac1fe7cd66417412e8f26f06519ef3 GIT binary patch literal 156 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx1SBVv2j2s6ii6yp7}lMWc?smOq&xaLGB9lH z=l+w(3gmMZctjR6Fz_7)VaDV6D^h@hk|nMYCBgY=CFO}lsSE{)nRz98d8s7|CVB>X th6Zc7xDEgn@p!s8hDd}bXJlkBFfg+)Ha_GO)d7k#c)I$ztaD0e0sx%3C1n5r literal 0 HcmV?d00001 diff --git a/tests/resources/minimal/swf.swf b/tests/resources/minimal/swf.swf new file mode 100644 index 0000000000000000000000000000000000000000..c6195c41eebe7b3b2006eff39a268320e973feac GIT binary patch literal 140 zcmZ<@4`%OSU|^_VV2x*B;9tPNz{AL3&zuVs>d;|eVaQD_E>28OWk@bcO)NJIrm-+^FmW*ZGdKW+0pm9pO8@`> literal 0 HcmV?d00001 diff --git a/tests/resources/minimal/webm.webm b/tests/resources/minimal/webm.webm new file mode 100644 index 0000000000000000000000000000000000000000..38e17b83e617bed65caab62105a1f91a18f215f6 GIT binary patch literal 185 zcmb1gy}#H&!Ktm0(dj!7e`;iL`rOFj)a1ZYo|=^F)ZWPC)Y`}-5!{gO&@1Y>GR;9l z>-t6qW_~9J-v$S^@{GjX+{$oA7|W&8fy1HSfdK@>Le^zF7_M{ByWYr{e6*2qP9uZT z);SK$rFkiB4y Date: Thu, 12 Jul 2018 15:19:03 +0200 Subject: [PATCH 057/112] Fix non implicit cast from QString to QUrl in FunctionsTest --- tests/src/functions-test.cpp | 8 ++++---- tests/src/integration/sankaku-test.cpp | 6 +++--- tests/src/models/image-test.cpp | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index 2ed214e8c..b2914322a 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -141,10 +141,10 @@ void FunctionsTest::testGetExtension() } void FunctionsTest::testSetExtension() { - QCOMPARE(setExtension(QUrl(""), "png"), QString("")); - QCOMPARE(setExtension(QUrl("http://test.com/file"), "png"), QString("http://test.com/file")); - QCOMPARE(setExtension(QUrl("http://test.com/file.jpg"), "png"), QString("http://test.com/file.png")); - QCOMPARE(setExtension(QUrl("http://test.com/file.jpg?toto=1"), "png"), QString("http://test.com/file.png?toto=1")); + QCOMPARE(setExtension(QUrl(""), "png"), QUrl("")); + QCOMPARE(setExtension(QUrl("http://test.com/file"), "png"), QUrl("http://test.com/file")); + QCOMPARE(setExtension(QUrl("http://test.com/file.jpg"), "png"), QUrl("http://test.com/file.png")); + QCOMPARE(setExtension(QUrl("http://test.com/file.jpg?toto=1"), "png"), QUrl("http://test.com/file.png?toto=1")); } void FunctionsTest::testLevenshtein() diff --git a/tests/src/integration/sankaku-test.cpp b/tests/src/integration/sankaku-test.cpp index 284c01dc8..66df15d5b 100755 --- a/tests/src/integration/sankaku-test.cpp +++ b/tests/src/integration/sankaku-test.cpp @@ -36,11 +36,11 @@ void SankakuTest::testAnimatedUrls() // Check results QCOMPARE(images.count(), 20); QCOMPARE(images[0]->md5(), QString("6e7901eea2a5a2d2b96244593ed190df")); - QCOMPARE(images[0]->url(), QString("https://is.sankakucomplex.com/data/6e/79/6e7901eea2a5a2d2b96244593ed190df.gif")); + QCOMPARE(images[0]->url(), QUrl("https://is.sankakucomplex.com/data/6e/79/6e7901eea2a5a2d2b96244593ed190df.gif")); QCOMPARE(images[1]->md5(), QString("97b3355a7af0bfabc67f2678a4a837fd")); - QCOMPARE(images[1]->url(), QString("https://is.sankakucomplex.com/data/97/b3/97b3355a7af0bfabc67f2678a4a837fd.gif")); + QCOMPARE(images[1]->url(), QUrl("https://is.sankakucomplex.com/data/97/b3/97b3355a7af0bfabc67f2678a4a837fd.gif")); QCOMPARE(images[2]->md5(), QString("d9f7f5089da4a677846d77da2c146088")); - QCOMPARE(images[2]->url(), QString("https://is.sankakucomplex.com/data/d9/f7/d9f7f5089da4a677846d77da2c146088.webm")); + QCOMPARE(images[2]->url(), QUrl("https://is.sankakucomplex.com/data/d9/f7/d9f7f5089da4a677846d77da2c146088.webm")); } diff --git a/tests/src/models/image-test.cpp b/tests/src/models/image-test.cpp index fdf4e1fed..25f7f9fca 100644 --- a/tests/src/models/image-test.cpp +++ b/tests/src/models/image-test.cpp @@ -72,12 +72,12 @@ void ImageTest::testConstructor() // Default img = new Image(); - QCOMPARE(img->url(), QString()); + QCOMPARE(img->url(), QUrl()); img->deleteLater(); // Without parent site img = new Image(nullptr, m_details, m_profile); - QCOMPARE((int)img->id(), 0); + QCOMPARE(static_cast(img->id()), 0); img->deleteLater(); // With a given page URL @@ -391,10 +391,10 @@ void ImageTest::testSaveLog() void ImageTest::testSetUrl() { - QString url = "http://google.fr"; + QUrl url("http://google.fr"); QCOMPARE(m_img->url() != url, true); - m_img->setUrl(QUrl(url)); + m_img->setUrl(url); QCOMPARE(m_img->url(), url); } From 7d13794e38162bac60ac2da70b460b5e5896af4b Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 12 Jul 2018 17:38:38 +0200 Subject: [PATCH 058/112] Fix useless copy in sourcesWindow --- gui/src/sources/sourceswindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/sources/sourceswindow.cpp b/gui/src/sources/sourceswindow.cpp index 2bc705a00..242c86c95 100644 --- a/gui/src/sources/sourceswindow.cpp +++ b/gui/src/sources/sourceswindow.cpp @@ -126,7 +126,7 @@ void sourcesWindow::valid() void sourcesWindow::openSite(const QString &site) const { - QDesktopServices::openUrl(QUrl(m_sites.value(site)->fixUrl("/"))); + QDesktopServices::openUrl(m_sites.value(site)->fixUrl("/")); } void sourcesWindow::settingsSite(const QString &site) From 5e876158007fb81be50175d83379a95be287051f Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 16:52:49 +0200 Subject: [PATCH 059/112] Allow to force download with the ImageDownloader class --- lib/src/downloader/image-downloader.cpp | 43 +++++++++++++------------ lib/src/downloader/image-downloader.h | 5 +-- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index b2201fa79..0e382d994 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -11,12 +11,12 @@ #include "models/source.h" -ImageDownloader::ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent, bool loadTags, bool rotate) - : QObject(parent), m_image(std::move(img)), m_fileDownloader(this), m_filename(std::move(filename)), m_path(std::move(path)), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) +ImageDownloader::ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent, bool loadTags, bool rotate, bool force) + : QObject(parent), m_image(std::move(img)), m_fileDownloader(this), m_filename(std::move(filename)), m_path(std::move(path)), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate), m_force(force) {} -ImageDownloader::ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent, bool rotate) - : QObject(parent), m_image(std::move(img)), m_fileDownloader(this), m_loadTags(false), m_paths(std::move(paths)), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate) +ImageDownloader::ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent, bool rotate, bool force) + : QObject(parent), m_image(std::move(img)), m_fileDownloader(this), m_loadTags(false), m_paths(std::move(paths)), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate), m_force(force) {} void ImageDownloader::save() @@ -54,24 +54,27 @@ void ImageDownloader::loadedSave() } // Try to save the image if it's already loaded or exists somewhere else on disk - QMap result = m_image->save(QStringList() << m_temporaryPath, m_addMd5, m_startCommands, m_count, false); - bool needLoading = false; - bool saveOk = false; - for (Image::SaveResult res : result) + if (!m_force) { - if (res == Image::SaveResult::NotLoaded) - needLoading = true; - else if (res == Image::SaveResult::Saved || res == Image::SaveResult::Copied || res == Image::SaveResult::Moved) - saveOk = true; - } + QMap result = m_image->save(QStringList() << m_temporaryPath, m_addMd5, m_startCommands, m_count, false); + bool needLoading = false; + bool saveOk = false; + for (Image::SaveResult res : result) + { + if (res == Image::SaveResult::NotLoaded) + needLoading = true; + else if (res == Image::SaveResult::Saved || res == Image::SaveResult::Copied || res == Image::SaveResult::Moved) + saveOk = true; + } - // If we don't need any loading, we can return already - if (!needLoading) - { - if (saveOk) - { result = postSaving(result); } - emit saved(m_image, result); - return; + // If we don't need any loading, we can return already + if (!needLoading) + { + if (saveOk) + { result = postSaving(result); } + emit saved(m_image, result); + return; + } } m_url = m_image->url(Image::Size::Full); diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index b14fa12bb..b19309de3 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -12,8 +12,8 @@ class ImageDownloader : public QObject Q_OBJECT public: - ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool loadTags = false, bool rotate = true); - ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool rotate = true); + ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool loadTags = false, bool rotate = true, bool force = false); + ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool rotate = true, bool force = false); public slots: void save(); @@ -47,6 +47,7 @@ class ImageDownloader : public QObject bool m_startCommands; bool m_writeError; bool m_rotate; + bool m_force; QNetworkReply *m_reply = nullptr; QUrl m_url; From b74509fd569a8b44fd2474fb77dd6c59fbd4d9c1 Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 16:54:51 +0200 Subject: [PATCH 060/112] Allow to set an image temporary file that will automatically be delete --- lib/src/models/image.cpp | 15 +++++++++++++++ lib/src/models/image.h | 4 +++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index e0613de89..4253cc040 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -290,6 +290,12 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* m_pools = QList(); } +Image::~Image() +{ + if (!m_temporaryPath.isEmpty()) + QFile::remove(m_temporaryPath); +} + void Image::loadDetails(bool rateLimit) { if (m_loadingDetails) @@ -834,6 +840,15 @@ ExtensionRotator *Image::extensionRotator() const { return m_extensionRotator; } void Image::setPreviewImage(const QPixmap &preview) { m_imagePreview = preview; } +void Image::setTemporaryPath(const QString &path) +{ + setSavePath(path); + + if (!m_temporaryPath.isEmpty()) + QFile::remove(m_temporaryPath); + + m_temporaryPath = path; +} void Image::setSavePath(const QString &path) { m_savePath = path; diff --git a/lib/src/models/image.h b/lib/src/models/image.h index f6b3f8680..c8b4a419b 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -24,6 +24,7 @@ class Image : public QObject, public Downloadable Image(); Image(Site *site, QMap details, Profile *profile, Page *parent = nullptr); Image(const Image &other); + ~Image(); int value() const; QStringList path(QString fn = "", QString pth = "", int counter = 0, bool complex = true, bool simple = false, bool maxLength = true, bool shouldFixFilename = true, bool getFull = false) const; QStringList stylishedTags(Profile *profile) const; @@ -61,6 +62,7 @@ class Image : public QObject, public Downloadable void setSize(QSize size); void setFileSize(int size); void setFileExtension(const QString &ext); + void setTemporaryPath(const QString &path); void setSavePath(const QString &path); bool shouldDisplaySample() const; QUrl getDisplayableUrl() const; @@ -123,7 +125,7 @@ class Image : public QObject, public Downloadable bool m_hasChildren, m_hasNote, m_hasComments, m_hasScore; QUrl m_url; QString mutable m_md5; - QString m_author, m_name, m_status, m_rating, m_source, m_site, m_savePath; + QString m_author, m_name, m_status, m_rating, m_source, m_site, m_temporaryPath, m_savePath; QUrl m_pageUrl, m_fileUrl, m_sampleUrl, m_previewUrl; QSize m_size; QPixmap m_imagePreview; From c4259fde86e9621ec6c911dc07349e75b148719f Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 16:57:50 +0200 Subject: [PATCH 061/112] Use ImageDownloader in ZoomWindow to prevent high memory usage --- gui/src/viewer/zoom-window.cpp | 80 +++++++++++++++------------------- gui/src/viewer/zoom-window.h | 4 +- 2 files changed, 38 insertions(+), 46 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 8ee424700..478146416 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -382,23 +382,28 @@ void ZoomWindow::load(bool force) ui->progressBarDownload->setValue(0); ui->progressBarDownload->show(); - connect(m_image.data(), &Image::downloadProgressImage, this, &ZoomWindow::downloadProgress); - connect(m_image.data(), &Image::finishedImage, this, &ZoomWindow::replyFinishedZoom); - if (m_image->shouldDisplaySample()) { m_saveUrl = m_image->url(); m_image->setUrl(m_url); } + const QString fn = m_profile->tempPath() + QDir::separator() + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; + auto dwl = new ImageDownloader(m_image, QStringList() << fn, 1, false, false, this, true, force); + connect(dwl, &ImageDownloader::downloadProgress, this, &ZoomWindow::downloadProgress); + connect(dwl, &ImageDownloader::saved, this, &ZoomWindow::replyFinishedZoom); + connect(dwl, &ImageDownloader::saved, dwl, &ImageDownloader::deleteLater); + m_imageTime.start(); - m_image->loadImage(true, force); + dwl->save(); } #define PERCENT 0.05 #define TIME 500 -void ZoomWindow::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) +void ZoomWindow::downloadProgress(QSharedPointer img, qint64 bytesReceived, qint64 bytesTotal) { + Q_UNUSED(img); + ui->progressBarDownload->setMaximum(bytesTotal); ui->progressBarDownload->setValue(bytesReceived); @@ -590,9 +595,12 @@ void ZoomWindow::setButtonState(bool fav, SaveButtonState state) } } -void ZoomWindow::replyFinishedZoom(QNetworkReply::NetworkError err, const QString &errorString) +void ZoomWindow::replyFinishedZoom(QSharedPointer img, const QMap &result) { + Q_UNUSED(img); + log(QStringLiteral("Image received from %1").arg(m_url.toString())); + Image::SaveResult res = result.first(); ui->progressBarDownload->hide(); m_finished = true; @@ -600,27 +608,30 @@ void ZoomWindow::replyFinishedZoom(QNetworkReply::NetworkError err, const QStrin if (m_image->shouldDisplaySample()) { m_image->setUrl(m_saveUrl); } - if (err == QNetworkReply::NoError) + if (res == 500) + { + m_tooBig = true; + if (!m_image->isVideo()) + { error(this, tr("File is too big to be displayed.\n%1").arg(m_image->url().toString())); } + } + else if (res == Image::SaveResult::NotFound) + { showLoadingError("Image not found."); } + else if (res == Image::SaveResult::NetworkError) + { showLoadingError("Error loading the image."); } + else if (res == Image::SaveResult::Error) + { showLoadingError("Error saving the image."); } + else { m_url = m_image->url(); + m_source = result.firstKey(); m_loadedImage = true; + img->setTemporaryPath(m_source); + updateWindowTitle(); pendingUpdate(); draw(); } - else if (err == 500) - { - m_tooBig = true; - if (!m_image->isVideo()) - { error(this, tr("File is too big to be displayed.\n%1").arg(m_image->url().toString())); } - } - else if (err == QNetworkReply::ContentNotFoundError) - { showLoadingError("Image not found."); } - else if (err == QNetworkReply::UnknownContentError) - { showLoadingError("Error loading the image."); } - else if (err != QNetworkReply::OperationCanceledError) - { error(this, tr("An unexpected error occured loading the image (%1 - %2).\n%3").arg(err).arg(errorString, m_image->url().toString())); } } void ZoomWindow::showLoadingError(const QString &message) @@ -688,27 +699,10 @@ void ZoomWindow::draw() if (m_image->isVideo()) return; - const QString fn = m_url.fileName().toLower(); - - // We need a filename to display animations, so we get it if we're not already loading from a file - QString filename; - if (!m_source.isEmpty()) - { filename = m_source; } - else if (!m_isAnimated.isEmpty()) - { - filename = QDir::temp().absoluteFilePath("grabber-" + fn); - QFile f(filename); - if (f.open(QFile::WriteOnly)) - { - f.write(m_image->data()); - f.close(); - } - } - // GIF (using QLabel support for QMovie) if (!m_isAnimated.isEmpty()) { - m_displayMovie = new QMovie(filename, m_isAnimated.toLatin1(), this); + m_displayMovie = new QMovie(m_source, m_isAnimated.toLatin1(), this); m_displayMovie->start(); const QSize &movieSize = m_displayMovie->currentPixmap().size(); const QSize &imageSize = m_labelImage->size(); @@ -723,11 +717,10 @@ void ZoomWindow::draw() if (m_isFullscreen && m_fullScreen != nullptr && m_fullScreen->isVisible()) { m_fullScreen->setMovie(m_displayMovie); } - return; } // Images - if (!m_source.isEmpty()) + else { m_displayImage = QPixmap(); m_displayImage.load(m_source); @@ -736,10 +729,6 @@ void ZoomWindow::draw() if (m_isFullscreen && m_fullScreen != nullptr && m_fullScreen->isVisible()) { m_fullScreen->setImage(m_displayImage.scaled(QApplication::desktop()->screenGeometry().size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } } - else - { - emit loadImage(m_image->data()); - } } @@ -1150,7 +1139,10 @@ void ZoomWindow::load(const QSharedPointer &image) preloaded.insert(pos); log(QStringLiteral("Preloading data for image #%1").arg(pos)); m_images[pos]->loadDetails(); - m_images[pos]->loadImage(); + + const QString fn = m_profile->tempPath() + QDir::separator() + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; + auto dwl = new ImageDownloader(m_images[pos], QStringList() << fn, 1, false, false, this); + connect(dwl, &ImageDownloader::saved, dwl, &ImageDownloader::deleteLater); } } diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index 0cfc5945e..61fb59027 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -47,7 +47,7 @@ class ZoomWindow : public QWidget public slots: void update(bool onlySize = false, bool force = false); void replyFinishedDetails(); - void replyFinishedZoom(QNetworkReply::NetworkError err = QNetworkReply::NoError, const QString &errorString = ""); + void replyFinishedZoom(QSharedPointer img, const QMap &result); void display(const QPixmap &, int); void saveNQuit(); void saveNQuitFav(); @@ -64,7 +64,7 @@ class ZoomWindow : public QWidget void contextMenu(QPoint); void openInNewTab(); void setfavorite(); - void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); + void downloadProgress(QSharedPointer img, qint64 bytesReceived, qint64 bytesTotal); void colore(); void urlChanged(const QUrl &before, const QUrl &after); void showDetails(); From faef86bf2e90b484c96d31d292f01028453b19c2 Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 17:28:45 +0200 Subject: [PATCH 062/112] Remove unused Image::loadImage method --- gui/src/mainwindow.cpp | 16 ++- lib/src/downloader/image-downloader.cpp | 1 - lib/src/models/image.cpp | 180 +----------------------- lib/src/models/image.h | 16 +-- tests/src/models/image-test.cpp | 27 ---- tests/src/models/image-test.h | 3 - 6 files changed, 15 insertions(+), 228 deletions(-) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 88ba72306..4eb2e3646 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -1704,7 +1704,6 @@ void mainWindow::getAllGetImageIfNotBlacklisted(const BatchDownloadImage &downlo void mainWindow::getAllImageOk(const BatchDownloadImage &download, int siteId, bool retry) { - download.image->unload(); m_downloadTime.remove(download.image->url()); m_downloadTimeLast.remove(download.image->url()); @@ -1955,7 +1954,10 @@ void mainWindow::getAllCancel() for (const BatchDownloadImage &download : qAsConst(m_getAllDownloading)) { download.image->abortTags(); - download.image->abortImage(); + } + for (auto it = m_getAllImageDownloaders.begin(); it != m_getAllImageDownloaders.end(); ++it) + { + it.value()->abort(); } for (Downloader *downloader : qAsConst(m_downloaders)) { @@ -1974,7 +1976,10 @@ void mainWindow::getAllSkip() for (const BatchDownloadImage &download : qAsConst(m_getAllDownloading)) { download.image->abortTags(); - download.image->abortImage(); + } + for (auto it = m_getAllImageDownloaders.begin(); it != m_getAllImageDownloaders.end(); ++it) + { + it.value()->abort(); } m_getAllSkippedImages.append(m_getAllDownloading); m_getAllDownloading.clear(); @@ -2089,7 +2094,10 @@ void mainWindow::getAllPause() for (const auto &download : qAsConst(m_getAllDownloading)) { download.image->abortTags(); - download.image->abortImage(); + } + for (auto it = m_getAllImageDownloaders.begin(); it != m_getAllImageDownloaders.end(); ++it) + { + it.value()->abort(); } m_getAll = false; } diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 0e382d994..36598d538 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -131,7 +131,6 @@ QMap ImageDownloader::makeMap(const QStringList &key void ImageDownloader::writeError() { - m_image->abortImage(); emit saved(m_image, makeMap(m_paths, Image::SaveResult::Error)); } diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 4253cc040..ed767210d 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -79,7 +79,6 @@ Image::Image(const Image &other) m_data = other.m_data; m_loadDetails = other.m_loadDetails; - m_loadImage = other.m_loadImage; m_tags = other.m_tags; m_pools = other.m_pools; @@ -90,14 +89,11 @@ Image::Image(const Image &other) m_parentSite = other.m_parentSite; m_extensionRotator = other.m_extensionRotator; - m_loadingPreview = other.m_loadingPreview; m_loadingDetails = other.m_loadingDetails; - m_loadingImage = other.m_loadingImage; - m_tryingSample = other.m_tryingSample; } Image::Image(Site *site, QMap details, Profile *profile, Page* parent) - : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(nullptr), m_loadImageError(QNetworkReply::NetworkError::NoError) + : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(nullptr) { m_settings = m_profile->getSettings(); @@ -280,13 +276,8 @@ Image::Image(Site *site, QMap details, Profile *profile, Page* // Tech details m_parent = parent; m_loadDetails = nullptr; - m_loadImage = nullptr; - m_loadingPreview = false; m_loadingDetails = false; m_loadedDetails = false; - m_loadedImage = false; - m_loadingImage = false; - m_tryingSample = false; m_pools = QList(); } @@ -437,169 +428,6 @@ QStringList Image::path(QString fn, QString pth, int counter, bool complex, bool return filename.path(*this, m_profile, pth, counter, complex, maxLength, shouldFixFilename, getFull); } -void Image::loadImage(bool inMemory, bool force) -{ - if (m_loadingImage) - return; - - if (m_loadedImage && !force) - { - emit finishedImage(QNetworkReply::NoError, ""); - return; - } - - if (m_fileSize > MAX_LOAD_FILESIZE && inMemory) - { - emit finishedImage(static_cast(500), ""); - return; - } - - if (m_loadImage != nullptr) - m_loadImage->deleteLater(); - - if (force) - setUrl(m_fileUrl); - - m_loadImage = m_parentSite->get(m_parentSite->fixUrl(m_url), m_parent, "image", this); - m_loadImage->setParent(this); - m_loadingImage = true; - m_loadedImage = false; - m_data.clear(); - - if (inMemory) - { - connect(m_loadImage, &QNetworkReply::downloadProgress, this, &Image::downloadProgressImageInMemory); - connect(m_loadImage, &QNetworkReply::finished, this, &Image::finishedImageInMemory); - } - else - { - connect(m_loadImage, &QNetworkReply::downloadProgress, this, &Image::downloadProgressImageBasic); - connect(m_loadImage, &QNetworkReply::finished, this, &Image::finishedImageBasic); - } -} - -void Image::finishedImageBasic() -{ - finishedImageS(false); -} -void Image::finishedImageInMemory() -{ - finishedImageS(true); -} -void Image::finishedImageS(bool inMemory) -{ - m_loadingImage = false; - - // Aborted - if (m_loadImage->error() == QNetworkReply::OperationCanceledError) - { - m_loadImage->deleteLater(); - m_loadImage = nullptr; - if (m_fileSize > MAX_LOAD_FILESIZE) - { emit finishedImage(static_cast(500), ""); } - else - { emit finishedImage(QNetworkReply::OperationCanceledError, ""); } - return; - } - - QUrl redir = m_loadImage->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); - if (!redir.isEmpty()) - { - m_loadImage->deleteLater(); - m_loadImage = nullptr; - m_url = redir; - loadImage(); - return; - } - - if (m_loadImage->error() == QNetworkReply::ContentNotFoundError) - { - const bool sampleFallback = m_settings->value("Save/samplefallback", true).toBool(); - QString newext = m_extensionRotator != nullptr ? m_extensionRotator->next() : ""; - - const bool shouldFallback = sampleFallback && !m_sampleUrl.isEmpty(); - const bool isLast = newext.isEmpty() || (shouldFallback && m_tryingSample); - - if (!isLast || (shouldFallback && !m_tryingSample)) - { - if (isLast) - { - setUrl(m_sampleUrl); - m_tryingSample = true; - log(QStringLiteral("Image not found. New try with its sample...")); - } - else - { - m_url = setExtension(m_url, newext); - log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url.toString())); - } - - loadImage(); - return; - } - else - { - log(QStringLiteral("Image not found.")); - } - } - else if (inMemory) - { - m_data.append(m_loadImage->readAll()); - - if (m_fileSize <= 0) - { m_fileSize = m_data.size(); } - } - - const QNetworkReply::NetworkError error = m_loadImage->error(); - const QString errorString = m_loadImage->errorString(); - - m_loadedImage = (error == QNetworkReply::ContentNotFoundError || error == QNetworkReply::NoError); - m_loadImageError = error; - m_loadImage->deleteLater(); - m_loadImage = nullptr; - - emit finishedImage(m_loadImageError, errorString); -} - -void Image::downloadProgressImageBasic(qint64 v1, qint64 v2) -{ - downloadProgressImageS(v1, v2, false); -} -void Image::downloadProgressImageInMemory(qint64 v1, qint64 v2) -{ - downloadProgressImageS(v1, v2, true); -} -void Image::downloadProgressImageS(qint64 v1, qint64 v2, bool inMemory) -{ - // Set filesize if not set - if (m_fileSize == 0 || m_fileSize < v2 / 2) - m_fileSize = v2; - - if (m_loadImage == nullptr || v2 <= 0) - return; - - if (inMemory) - { - if (m_fileSize > MAX_LOAD_FILESIZE) - { - m_loadImage->abort(); - return; - } - - m_data.append(m_loadImage->readAll()); - } - - emit downloadProgressImage(v1, v2); -} -void Image::abortImage() -{ - if (m_loadingImage && m_loadImage->isRunning()) - { - m_loadImage->abort(); - m_loadingImage = false; - } -} - /** * Try to guess the size of the image in pixels for sorting. * @return The guessed number of pixels in the image. @@ -1047,12 +875,6 @@ bool Image::hasAllTags(const QStringList &tags) const return true; } -void Image::unload() -{ - m_loadedImage = false; - m_data.clear(); -} - void Image::setRating(const QString &rating) { static QMap assoc = diff --git a/lib/src/models/image.h b/lib/src/models/image.h index c8b4a419b..e5b1ba642 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -96,19 +96,8 @@ class Image : public QObject, public Downloadable public slots: void loadDetails(bool rateLimit = false); - void loadImage(bool inMemory = true, bool force = false); void abortTags(); - void abortImage(); void parseDetails(); - void unload(); - - private slots: - void finishedImageBasic(); - void finishedImageInMemory(); - void finishedImageS(bool inMemory); - void downloadProgressImageBasic(qint64, qint64); - void downloadProgressImageInMemory(qint64, qint64); - void downloadProgressImageS(qint64, qint64, bool inMemory); signals: void finishedLoadingPreview(); @@ -131,16 +120,15 @@ class Image : public QObject, public Downloadable QPixmap m_imagePreview; QDateTime m_createdAt; QByteArray m_data; - QNetworkReply *m_loadDetails, *m_loadImage; + QNetworkReply *m_loadDetails; QList m_tags; QList m_pools; QTime m_timer; QSettings *m_settings; QStringList m_search; Site *m_parentSite; - QNetworkReply::NetworkError m_loadImageError; ExtensionRotator *m_extensionRotator; - bool m_loadingPreview, m_loadingDetails, m_loadingImage, m_tryingSample, m_loadedDetails, m_loadedImage; + bool m_loadingDetails, m_loadedDetails; bool m_isGallery = false; }; diff --git a/tests/src/models/image-test.cpp b/tests/src/models/image-test.cpp index 25f7f9fca..0d95178a5 100644 --- a/tests/src/models/image-test.cpp +++ b/tests/src/models/image-test.cpp @@ -165,15 +165,6 @@ void ImageTest::testStylishedTags() QCOMPARE(tags[8], QString("tag3"));*/ } -void ImageTest::testUnload() -{ - m_img->setData(QString("test").toLatin1()); - QCOMPARE(m_img->data().isEmpty(), false); - - m_img->unload(); - QCOMPARE(m_img->data().isEmpty(), true); -} - void ImageTest::testValue() { // Guess from image size @@ -214,24 +205,6 @@ void ImageTest::testValue() QCOMPARE(m_img->value(), 500 * 500); } -void ImageTest::testLoadImage() -{ - // Load preview - QSignalSpy spy(m_img, SIGNAL(finishedImage(QNetworkReply::NetworkError, QString))); - m_img->loadImage(); - QVERIFY(spy.wait()); - - // Compare result - QCOMPARE(m_img->data().isEmpty(), false); -} -void ImageTest::testLoadImageAbort() -{ - QSignalSpy spy(m_img, SIGNAL(finishedImage())); - m_img->loadImage(); - m_img->abortImage(); - QVERIFY(!spy.wait(1000)); -} - void ImageTest::testLoadDetails() { // Load details diff --git a/tests/src/models/image-test.h b/tests/src/models/image-test.h index 713a21a23..802f8da5a 100644 --- a/tests/src/models/image-test.h +++ b/tests/src/models/image-test.h @@ -23,10 +23,7 @@ class ImageTest : public TestSuite void testMd5FromData(); //void testMd5FromFile(); void testStylishedTags(); - void testUnload(); void testValue(); - void testLoadImage(); - void testLoadImageAbort(); void testLoadDetails(); void testLoadDetailsAbort(); void testLoadDetailsImageUrl(); From c3feb7247ff0ecc15ca59955fb165d560c91311e Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 17:31:30 +0200 Subject: [PATCH 063/112] Automatically update image filesize in ImageDownloader --- lib/src/downloader/image-downloader.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 36598d538..009559e8d 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -118,6 +118,9 @@ void ImageDownloader::loadImage() void ImageDownloader::downloadProgressImage(qint64 v1, qint64 v2) { + if (m_image->fileSize() == 0 || m_image->fileSize() < v2 / 2) + m_image->setFileSize(v2); + emit downloadProgress(m_image, v1, v2); } From 5364f9691361296987226137ef3aaa49ceddd606 Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 17:31:44 +0200 Subject: [PATCH 064/112] Allow to abort a download in ImageDownloader --- lib/src/downloader/image-downloader.cpp | 6 ++++++ lib/src/downloader/image-downloader.h | 1 + 2 files changed, 7 insertions(+) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 009559e8d..9fe796bb7 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -32,6 +32,12 @@ void ImageDownloader::save() m_image->loadDetails(); } +void ImageDownloader::abort() +{ + if (m_reply != nullptr && m_reply->isRunning()) + m_reply->abort(); +} + void ImageDownloader::loadedSave() { // Get the download path from the image if possible diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index b19309de3..c2800bb92 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -17,6 +17,7 @@ class ImageDownloader : public QObject public slots: void save(); + void abort(); protected: QMap makeMap(const QStringList &keys, Image::SaveResult value); From fb1a3ce702f9ad8933a52b97a3ddec17f2493f1e Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 17:39:01 +0200 Subject: [PATCH 065/112] Stop leaking network replies in ImageDownloader --- lib/src/downloader/image-downloader.cpp | 6 ++++++ lib/src/downloader/image-downloader.h | 1 + 2 files changed, 7 insertions(+) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 9fe796bb7..03532dbe6 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -19,6 +19,12 @@ ImageDownloader::ImageDownloader(QSharedPointer img, QStringList paths, i : QObject(parent), m_image(std::move(img)), m_fileDownloader(this), m_loadTags(false), m_paths(std::move(paths)), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate), m_force(force) {} +ImageDownloader::~ImageDownloader() +{ + if (m_reply != nullptr) + m_reply->deleteLater(); +} + void ImageDownloader::save() { // If we use direct saving or don't want to load tags, we directly save the image diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index c2800bb92..f8e182473 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -14,6 +14,7 @@ class ImageDownloader : public QObject public: ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool loadTags = false, bool rotate = true, bool force = false); ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool rotate = true, bool force = false); + ~ImageDownloader(); public slots: void save(); From 06ce1224461f6272607a343b3839d1ee8e627bc5 Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 13 Jul 2018 18:28:20 +0200 Subject: [PATCH 066/112] Fix ZoomWindow downloaders --- gui/src/viewer/zoom-window.cpp | 40 +++++++++++++++++-------- gui/src/viewer/zoom-window.h | 3 ++ lib/src/downloader/image-downloader.cpp | 5 ++++ lib/src/downloader/image-downloader.h | 1 + 4 files changed, 37 insertions(+), 12 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 478146416..6052cfd14 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -388,14 +388,20 @@ void ZoomWindow::load(bool force) m_image->setUrl(m_url); } - const QString fn = m_profile->tempPath() + QDir::separator() + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; - auto dwl = new ImageDownloader(m_image, QStringList() << fn, 1, false, false, this, true, force); + ImageDownloader *dwl = m_imageDownloaders.value(m_image, nullptr); + if (dwl == nullptr) + { + const QString fn = m_profile->tempPath() + QDir::separator() + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; + dwl = new ImageDownloader(m_image, QStringList() << fn, 1, false, false, this, true, force); + m_imageDownloaders.insert(m_image, dwl); + } connect(dwl, &ImageDownloader::downloadProgress, this, &ZoomWindow::downloadProgress); connect(dwl, &ImageDownloader::saved, this, &ZoomWindow::replyFinishedZoom); - connect(dwl, &ImageDownloader::saved, dwl, &ImageDownloader::deleteLater); m_imageTime.start(); - dwl->save(); + + if (!dwl->isRunning()) + { dwl->save(); } } #define PERCENT 0.05 @@ -597,8 +603,6 @@ void ZoomWindow::setButtonState(bool fav, SaveButtonState state) void ZoomWindow::replyFinishedZoom(QSharedPointer img, const QMap &result) { - Q_UNUSED(img); - log(QStringLiteral("Image received from %1").arg(m_url.toString())); Image::SaveResult res = result.first(); @@ -1037,7 +1041,12 @@ void ZoomWindow::closeEvent(QCloseEvent *e) m_settings->sync(); m_image->abortTags(); - m_image->abortImage(); + + for (auto it = m_imageDownloaders.begin(); it != m_imageDownloaders.end(); ++it) + { + it.value()->abort(); + it.value()->deleteLater(); + } e->accept(); } @@ -1130,19 +1139,28 @@ void ZoomWindow::load(const QSharedPointer &image) { QSet preloaded; const int index = m_images.indexOf(m_image); - for (int i = index - preload; i <= index + preload; ++i) + for (int i = index - preload - 1; i <= index + preload + 1; ++i) { + bool forAbort = i == index - preload - 1 || i == index + preload + 1; int pos = (i + m_images.count()) % m_images.count(); if (pos < 0 || pos == index || pos > m_images.count() || preloaded.contains(pos)) continue; + QSharedPointer img = m_images[pos]; + bool downloaderExists = m_imageDownloaders.contains(img); + if (downloaderExists && forAbort) + m_imageDownloaders[img]->abort(); + if (downloaderExists || forAbort) + continue; + preloaded.insert(pos); log(QStringLiteral("Preloading data for image #%1").arg(pos)); m_images[pos]->loadDetails(); const QString fn = m_profile->tempPath() + QDir::separator() + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; - auto dwl = new ImageDownloader(m_images[pos], QStringList() << fn, 1, false, false, this); - connect(dwl, &ImageDownloader::saved, dwl, &ImageDownloader::deleteLater); + auto dwl = new ImageDownloader(img, QStringList() << fn, 1, false, false, this); + m_imageDownloaders.insert(img, dwl); + dwl->save(); } } @@ -1199,7 +1217,6 @@ int ZoomWindow::firstNonBlacklisted(int direction) void ZoomWindow::next() { m_image->abortTags(); - m_image->abortImage(); const int index = firstNonBlacklisted(+1); load(m_images[index]); @@ -1208,7 +1225,6 @@ void ZoomWindow::next() void ZoomWindow::previous() { m_image->abortTags(); - m_image->abortImage(); const int index = firstNonBlacklisted(-1); load(m_images[index]); diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index 61fb59027..bcc4e5769 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -19,6 +19,7 @@ class QAffiche; class Profile; class mainWindow; class DetailsWindow; +class ImageDownloader; class ImageLoader; class ImageLoaderQueue; @@ -152,6 +153,8 @@ class ZoomWindow : public QWidget QList> m_images; SaveButtonState m_saveButonState, m_saveButonStateFav; + QMap, ImageDownloader*> m_imageDownloaders; + // Display QString m_isAnimated; QPixmap m_displayImage; diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 03532dbe6..42713ff2b 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -25,6 +25,11 @@ ImageDownloader::~ImageDownloader() m_reply->deleteLater(); } +bool ImageDownloader::isRunning() const +{ + return m_reply != nullptr && m_reply->isRunning(); +} + void ImageDownloader::save() { // If we use direct saving or don't want to load tags, we directly save the image diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index f8e182473..e18812377 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -15,6 +15,7 @@ class ImageDownloader : public QObject ImageDownloader(QSharedPointer img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool loadTags = false, bool rotate = true, bool force = false); ImageDownloader(QSharedPointer img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent = nullptr, bool rotate = true, bool force = false); ~ImageDownloader(); + bool isRunning() const; public slots: void save(); From d5c2ad8712db765f325177a9abb2251859540fe6 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 00:13:42 +0200 Subject: [PATCH 067/112] Fix image viewer not re-showing images properly --- gui/src/viewer/zoom-window.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 6052cfd14..be9b54a14 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -395,8 +395,8 @@ void ZoomWindow::load(bool force) dwl = new ImageDownloader(m_image, QStringList() << fn, 1, false, false, this, true, force); m_imageDownloaders.insert(m_image, dwl); } - connect(dwl, &ImageDownloader::downloadProgress, this, &ZoomWindow::downloadProgress); - connect(dwl, &ImageDownloader::saved, this, &ZoomWindow::replyFinishedZoom); + connect(dwl, &ImageDownloader::downloadProgress, this, &ZoomWindow::downloadProgress, Qt::UniqueConnection); + connect(dwl, &ImageDownloader::saved, this, &ZoomWindow::replyFinishedZoom, Qt::UniqueConnection); m_imageTime.start(); From bd2481d683d05e6d50560442004a2c11f24fa002 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 00:14:00 +0200 Subject: [PATCH 068/112] Fix ImageDownloader using unnecessary temporary files --- lib/src/downloader/image-downloader.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 42713ff2b..e74e840a7 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -56,19 +56,18 @@ void ImageDownloader::loadedSave() { m_paths = m_image->path(m_filename, m_path, m_count, true, false, true, true, true); + // Use a random temporary file if we need the MD5 or equivalent Profile *profile = m_image->parentSite()->getSource()->getProfile(); - if (!Filename(m_filename).needTemporaryFile(m_image->tokens(profile))) + if (Filename(m_filename).needTemporaryFile(m_image->tokens(profile))) { - m_temporaryPath = m_paths.first() + ".tmp"; + const QString tmpDir = !m_path.isEmpty() ? m_path : QDir::tempPath(); + m_temporaryPath = tmpDir + "/" + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; } } - // Use a random temporary file if we need the MD5 or equivalent + // Directly use the image path as temporary file if possible if (m_temporaryPath.isEmpty()) - { - const QString tmpDir = !m_path.isEmpty() ? m_path : QDir::tempPath(); - m_temporaryPath = tmpDir + "/" + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; - } + { m_temporaryPath = m_paths.first() + ".tmp"; } // Try to save the image if it's already loaded or exists somewhere else on disk if (!m_force) From 1231343902f1e9374e7f96542f01014a765f3253 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 00:15:59 +0200 Subject: [PATCH 069/112] Fix image temporary files deleted unnecessarily --- lib/src/models/image.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index ed767210d..b6a7b6a15 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -670,6 +670,9 @@ void Image::setPreviewImage(const QPixmap &preview) { m_imagePreview = preview; } void Image::setTemporaryPath(const QString &path) { + if (m_temporaryPath == path) + return; + setSavePath(path); if (!m_temporaryPath.isEmpty()) From be178139360059a62cccf32f07a3c46dd02e4b02 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 16:32:58 +0200 Subject: [PATCH 070/112] Set image count to tag count if coherent with page count (fix #1336) --- lib/src/models/page-api.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 7c4935415..1773d173c 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -93,9 +93,9 @@ void PageApi::load(bool rateLimit, bool force) m_tags.clear(); m_loaded = false; m_pageImageCount = 0; - /*m_imagesCount = -1; + m_imagesCount = -1; m_maxImagesCount = -1; - m_pagesCount = -1;*/ + m_pagesCount = -1; m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply *reply) { log(QStringLiteral("[%1][%2] Loading page %3").arg(m_site->url(), m_format, m_url.toString().toHtmlEscaped()), Logger::Info); @@ -211,7 +211,7 @@ void PageApi::parseActual() { m_wiki = page.wiki; } // Complete image count information from tag count information - if (m_imagesCount < 1) + if (m_imagesCount < 1 || !m_imagesCountSafe) { int found = 0; int min = -1; @@ -227,7 +227,12 @@ void PageApi::parseActual() if (m_search.count() == found) { if (m_search.count() == 1) - { setImageCount(min, false); } + { + const int forcedLimit = m_api->forcedLimit(); + const int perPage = forcedLimit > 0 ? forcedLimit : m_imagesPerPage; + const int expectedPageCount = qCeil(static_cast(min) / perPage); + setImageCount(min, m_pagesCountSafe && expectedPageCount == m_pagesCount); + } setImageMaxCount(min); } } From 2e1e5c0735be4174cb9a24ac63132b204f2943e8 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 17:56:12 +0200 Subject: [PATCH 071/112] Add coveralls to build --- .travis.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fe89782e8..972cd6d78 100755 --- a/.travis.yml +++ b/.travis.yml @@ -29,6 +29,10 @@ addons: - sshpass - lcov +# Install coveralls sender +before_install: + - pip install --user cpp-coveralls + # Qt packages for OS X install: - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then @@ -61,13 +65,17 @@ script: - ./build/tests/tests after_success: - # Upload code coverage + # Upload code coverage (codecov) - if [[ "$TRAVIS_OS_NAME" == "linux" ]] && [[ "$TRAVIS_PULL_REQUEST" == "false" ]]; then lcov --directory . --capture --output-file coverage.info && lcov --remove coverage.info '/usr/*' --output-file coverage.info && lcov --list coverage.info && bash <(curl -s https://codecov.io/bash) ; fi + # Upload code coverage (coveralls) + - if [[ "$TRAVIS_OS_NAME" == "linux" ]] && [[ "$TRAVIS_PULL_REQUEST" == "false" ]]; then + coveralls --exclude build --exclude e2e --exclude tests --exclude CrashReporter --gcov-options '\-lp' + ; fi # Generate release name - if [[ "$TRAVIS_TAG" == "" ]]; then export BUILD_LABEL=$TRAVIS_BRANCH From 47367c4dc6ae7e208874aecb4e75c33f0fa0fabb Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 18:23:18 +0200 Subject: [PATCH 072/112] Ignore moc files in codecov settings --- .codecov.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.codecov.yml b/.codecov.yml index 2e5332948..cafc7cd9c 100644 --- a/.codecov.yml +++ b/.codecov.yml @@ -12,9 +12,11 @@ coverage: changes: false ignore: - - "tests/*" - - "vendor/*" + - "build/*" - "CrashReporter/*" + - "e2e/*" + - "lib/src/vendor/*" + - "tests/*" comment: layout: "header, diff" From 336fc143b9201553fef3d6c00bd34a430d1464f8 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 21:47:33 +0200 Subject: [PATCH 073/112] Use preSave in ImageDownloader --- lib/src/downloader/image-downloader.cpp | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index e74e840a7..612960175 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -72,22 +72,16 @@ void ImageDownloader::loadedSave() // Try to save the image if it's already loaded or exists somewhere else on disk if (!m_force) { - QMap result = m_image->save(QStringList() << m_temporaryPath, m_addMd5, m_startCommands, m_count, false); - bool needLoading = false; - bool saveOk = false; - for (Image::SaveResult res : result) - { - if (res == Image::SaveResult::NotLoaded) - needLoading = true; - else if (res == Image::SaveResult::Saved || res == Image::SaveResult::Copied || res == Image::SaveResult::Moved) - saveOk = true; - } + Image::SaveResult res = m_image->preSave(m_temporaryPath); // If we don't need any loading, we can return already - if (!needLoading) + if (res != Image::SaveResult::NotLoaded) { - if (saveOk) + QMap result {{ m_temporaryPath, res }}; + + if (res == Image::SaveResult::Saved || res == Image::SaveResult::Copied || res == Image::SaveResult::Moved) { result = postSaving(result); } + emit saved(m_image, result); return; } From 25876e9e24b1b026d304f6544216f5a7816d8c5c Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 14 Jul 2018 21:52:12 +0200 Subject: [PATCH 074/112] Use postSave instead of postSaving in ImageDownloader --- lib/src/downloader/image-downloader.cpp | 2 +- lib/src/loader/downloadable-downloader.cpp | 6 ++++-- lib/src/loader/downloadable.h | 2 +- lib/src/models/image.cpp | 5 +---- lib/src/models/image.h | 2 +- 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 612960175..17ad3513a 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -244,7 +244,7 @@ QMap ImageDownloader::postSaving(QMappostSaving(path, m_addMd5, m_startCommands, m_count, false); + m_image->postSave(path, result[path], m_addMd5, m_startCommands, m_count); } if (!moved) diff --git a/lib/src/loader/downloadable-downloader.cpp b/lib/src/loader/downloadable-downloader.cpp index 7fcbf5798..a99442b35 100644 --- a/lib/src/loader/downloadable-downloader.cpp +++ b/lib/src/loader/downloadable-downloader.cpp @@ -51,7 +51,8 @@ void DownloadableDownloader::preloaded() // If we don't need any loading, we return early if (m_paths.isEmpty()) { - m_downloadable->postSave(m_result, m_addMd5, m_startCommands, m_count); + for (auto it = m_result.begin(); it != m_result.end(); ++it) + { m_downloadable->postSave(it.key(), it.value(), m_addMd5, m_startCommands, m_count); } emit saved(m_downloadable, m_result); return; } @@ -101,6 +102,7 @@ void DownloadableDownloader::networkError(QNetworkReply::NetworkError error, con void DownloadableDownloader::success() { setResult(m_paths, Downloadable::SaveResult::Saved); - m_downloadable->postSave(m_result, m_addMd5, m_startCommands, m_count); + for (const QString &path : m_paths) + { m_downloadable->postSave(path, Downloadable::SaveResult::Saved, m_addMd5, m_startCommands, m_count); } emit saved(m_downloadable, m_result); } diff --git a/lib/src/loader/downloadable.h b/lib/src/loader/downloadable.h index 36f3f1150..4d27d7c87 100644 --- a/lib/src/loader/downloadable.h +++ b/lib/src/loader/downloadable.h @@ -41,7 +41,7 @@ class Downloadable virtual QStringList paths(const Filename &filename, const QString &folder, int count) const = 0; const QMap &tokens(Profile *profile) const; virtual SaveResult preSave(const QString &path) = 0; - virtual void postSave(QMap result, bool addMd5, bool startCommands, int count) = 0; + virtual void postSave(const QString &path, SaveResult result, bool addMd5, bool startCommands, int count) = 0; virtual QColor color() const = 0; virtual QString tooltip() const = 0; diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index b6a7b6a15..5c77fbc41 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -1059,10 +1059,7 @@ Image::SaveResult Image::preSave(const QString &path) return save(path, false, false, false, false, 1, false); } -void Image::postSave(QMap result, bool addMd5, bool startCommands, int count) +void Image::postSave(const QString &path, SaveResult res, bool addMd5, bool startCommands, int count) { - const QString &path = result.firstKey(); - const Image::SaveResult res = result[path]; - postSaving(path, addMd5 && res == SaveResult::Saved, startCommands, count); } diff --git a/lib/src/models/image.h b/lib/src/models/image.h index e5b1ba642..149c415ae 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -82,7 +82,7 @@ class Image : public QObject, public Downloadable QStringList paths(const Filename &filename, const QString &folder, int count) const override; QMap generateTokens(Profile *profile) const override; SaveResult preSave(const QString &path) override; - void postSave(QMap result, bool addMd5, bool startCommands, int count) override; + void postSave(const QString &path, SaveResult result, bool addMd5, bool startCommands, int count) override; // Templates template From 37ebdabfd5d07f2ec0fbfe0eeb502610ee9ef423 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 15 Jul 2018 01:55:59 +0200 Subject: [PATCH 075/112] Simplify image storage in zoom window --- gui/src/viewer/zoom-window.cpp | 50 +++++++++++++++------------------- lib/src/models/image.cpp | 11 +++++--- 2 files changed, 29 insertions(+), 32 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index be9b54a14..6c7283d53 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -239,15 +239,8 @@ void ZoomWindow::reloadImage() } void ZoomWindow::copyImageFileToClipboard() { - QString path = m_imagePath; - if (path.isEmpty() || !QFile::exists(path)) - { - QMap files = m_image->save(m_settings->value("Save/filename").toString(), m_profile->tempPath(), false); - path = files.firstKey(); - } - auto *mimeData = new QMimeData(); - mimeData->setUrls({ QUrl::fromLocalFile(path) }); + mimeData->setUrls({ QUrl::fromLocalFile(m_imagePath) }); QApplication::clipboard()->setMimeData(mimeData); } void ZoomWindow::copyImageDataToClipboard() @@ -627,10 +620,10 @@ void ZoomWindow::replyFinishedZoom(QSharedPointer img, const QMapurl(); - m_source = result.firstKey(); + m_imagePath = result.firstKey(); m_loadedImage = true; - img->setTemporaryPath(m_source); + img->setTemporaryPath(m_imagePath); updateWindowTitle(); pendingUpdate(); @@ -786,7 +779,7 @@ Qt::Alignment ZoomWindow::getAlignments(const QString &type) void ZoomWindow::saveNQuit() { - if (!m_imagePath.isEmpty()) + if (!m_source.isEmpty()) { close(); return; @@ -798,7 +791,7 @@ void ZoomWindow::saveNQuit() } void ZoomWindow::saveNQuitFav() { - if (!m_imagePath.isEmpty()) + if (!m_source.isEmpty()) { close(); return; @@ -825,11 +818,17 @@ void ZoomWindow::saveImage(bool fav) case SaveButtonState::Delete: { - QFile f(m_imagePath); - if (m_image->data().isEmpty() && f.open(QFile::ReadOnly)) - { m_image->setData(f.readAll()); } - f.remove(); - m_imagePath = ""; + QString ip = m_imagePath; + QString s = m_source; + bool eq = m_imagePath == m_source; + if (m_imagePath.isEmpty() || m_imagePath == m_source) + { m_imagePath = m_profile->tempPath() + QDir::separator() + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; } + if (QFile::exists(m_imagePath)) + { QFile::remove(m_source); } + else + { QFile::rename(m_source, m_imagePath); } + m_image->setTemporaryPath(m_imagePath); + m_source = ""; setButtonState(fav, SaveButtonState::Save); break; } @@ -846,7 +845,7 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) QMap results; if (saveAs) - { results = m_image->save(QStringList() << m_saveAsPending, true, false, 1, true); } + { QFile::copy(m_imagePath, m_saveAsPending); } else { QString pth = m_settings->value("Save/path"+QString(fav ? "_favorites" : "")).toString().replace("\\", "/"); @@ -871,6 +870,7 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) return QStringList(); } + // SAVE results = m_image->save(m_settings->value("Save/filename"+QString(fav ? "_favorites" : "")).toString(), pth); } @@ -878,7 +878,7 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) { const Image::SaveResult res = it.value(); paths.append(it.key()); - m_imagePath = it.key(); + m_source = it.key(); switch (res) { @@ -896,7 +896,7 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) case Image::SaveResult::Ignored: setButtonState(fav, SaveButtonState::ExistsMd5); - m_imagePath = m_profile->md5Exists(m_image->md5()); + m_source = m_profile->md5Exists(m_image->md5()); break; case Image::SaveResult::AlreadyExists: @@ -1122,6 +1122,7 @@ void ZoomWindow::load(const QSharedPointer &image) m_displayImage = QPixmap(); m_loadedImage = false; + m_source = ""; m_imagePath = ""; m_image = image; m_isAnimated = image->isAnimated(); @@ -1244,14 +1245,7 @@ void ZoomWindow::openFile(bool now) return; } - QString path = m_imagePath; - if (path.isEmpty() || !QFile::exists(path)) - { - QMap files = m_image->save(m_settings->value("Save/filename").toString(), m_profile->tempPath(), false); - path = files.firstKey(); - } - - QDesktopServices::openUrl(QUrl::fromLocalFile(path)); + QDesktopServices::openUrl(QUrl::fromLocalFile(m_imagePath)); } void ZoomWindow::mouseReleaseEvent(QMouseEvent *e) diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 5c77fbc41..b6219207b 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -670,11 +670,11 @@ void Image::setPreviewImage(const QPixmap &preview) { m_imagePreview = preview; } void Image::setTemporaryPath(const QString &path) { + setSavePath(path); + if (m_temporaryPath == path) return; - setSavePath(path); - if (!m_temporaryPath.isEmpty()) QFile::remove(m_temporaryPath); @@ -682,8 +682,11 @@ void Image::setTemporaryPath(const QString &path) } void Image::setSavePath(const QString &path) { - m_savePath = path; - refreshTokens(); + if (path != m_savePath) + { + m_savePath = path; + refreshTokens(); + } } bool Image::shouldDisplaySample() const From 5a16133c4ba5eb77bf049dda408ae44d95ab4957 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 15 Jul 2018 01:56:12 +0200 Subject: [PATCH 076/112] Don't re-save already preloaded images --- gui/src/viewer/zoom-window.cpp | 2 +- lib/src/models/image.cpp | 2 ++ lib/src/models/image.h | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 6c7283d53..4641bae8d 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -1151,7 +1151,7 @@ void ZoomWindow::load(const QSharedPointer &image) bool downloaderExists = m_imageDownloaders.contains(img); if (downloaderExists && forAbort) m_imageDownloaders[img]->abort(); - if (downloaderExists || forAbort) + if (downloaderExists || forAbort || (!img->savePath().isEmpty() && QFile::exists(img->savePath()))) continue; preloaded.insert(pos); diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index b6219207b..56f484e1f 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -688,6 +688,8 @@ void Image::setSavePath(const QString &path) refreshTokens(); } } +QString Image::savePath() const +{ return m_savePath; } bool Image::shouldDisplaySample() const { diff --git a/lib/src/models/image.h b/lib/src/models/image.h index 149c415ae..c39ca00da 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -64,6 +64,7 @@ class Image : public QObject, public Downloadable void setFileExtension(const QString &ext); void setTemporaryPath(const QString &path); void setSavePath(const QString &path); + QString savePath() const; bool shouldDisplaySample() const; QUrl getDisplayableUrl() const; bool isVideo() const; From 346d0db3b5b385c1ab0df974178868f1741152bd Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 15 Jul 2018 02:18:07 +0200 Subject: [PATCH 077/112] Don't reload already temporary loaded image in zoom window --- gui/src/viewer/zoom-window.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 4641bae8d..a81eab11a 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -503,6 +503,20 @@ void ZoomWindow::replyFinishedDetails() draw(); } + + // If the image already has an associated file on disk + else if (!m_image->savePath().isEmpty() && QFile::exists(m_image->savePath())) + { + m_imagePath = m_image->savePath(); + log(QStringLiteral("Image loaded from the file %1").arg(m_imagePath)); + + m_finished = true; + m_loadedImage = true; + pendingUpdate(); + + draw(); + } + // If the file does not exist, we have to load it else { From ee7a2033a07bbd3133c2c4c92d5ad288e2b0366e Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 15 Jul 2018 02:19:47 +0200 Subject: [PATCH 078/112] Fix image not showing in zoom window --- gui/src/viewer/zoom-window.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index a81eab11a..55da03ae5 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -713,7 +713,7 @@ void ZoomWindow::draw() // GIF (using QLabel support for QMovie) if (!m_isAnimated.isEmpty()) { - m_displayMovie = new QMovie(m_source, m_isAnimated.toLatin1(), this); + m_displayMovie = new QMovie(m_imagePath, m_isAnimated.toLatin1(), this); m_displayMovie->start(); const QSize &movieSize = m_displayMovie->currentPixmap().size(); const QSize &imageSize = m_labelImage->size(); @@ -734,7 +734,7 @@ void ZoomWindow::draw() else { m_displayImage = QPixmap(); - m_displayImage.load(m_source); + m_displayImage.load(m_imagePath); update(); if (m_isFullscreen && m_fullScreen != nullptr && m_fullScreen->isVisible()) @@ -832,9 +832,6 @@ void ZoomWindow::saveImage(bool fav) case SaveButtonState::Delete: { - QString ip = m_imagePath; - QString s = m_source; - bool eq = m_imagePath == m_source; if (m_imagePath.isEmpty() || m_imagePath == m_source) { m_imagePath = m_profile->tempPath() + QDir::separator() + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; } if (QFile::exists(m_imagePath)) From 0076b2ef0fd515e61d3f86ea8277a8b48f8e17d3 Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 16 Jul 2018 08:48:16 +0200 Subject: [PATCH 079/112] Make ZoomWindow::saveImageNow return void --- gui/src/viewer/zoom-window.cpp | 26 ++++++++------------------ gui/src/viewer/zoom-window.h | 2 +- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 55da03ae5..faa8fd704 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -675,21 +675,13 @@ void ZoomWindow::pendingUpdate() switch (m_mustSave) { case 1: // Save - saveImageNow(); - break; - case 2: // Save and quit - if (!saveImageNow().isEmpty()) - close(); + saveImageNow(); break; case 3: // Save (fav) - saveImageNow(true); - break; - case 4: // Save and quit (fav) - if (!saveImageNow(true).isEmpty()) - close(); + saveImageNow(true); break; case 5: // Open image in viewer @@ -850,20 +842,20 @@ void ZoomWindow::saveImage(bool fav) } void ZoomWindow::saveImageFav() { saveImage(true); } -QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) +void ZoomWindow::saveImageNow(bool fav, bool saveAs) { - QStringList paths; QMap results; if (saveAs) { QFile::copy(m_imagePath, m_saveAsPending); } else { + QString fn = m_settings->value("Save/filename"+QString(fav ? "_favorites" : "")).toString(); QString pth = m_settings->value("Save/path"+QString(fav ? "_favorites" : "")).toString().replace("\\", "/"); if (pth.right(1) == "/") { pth = pth.left(pth.length()-1); } - if (pth.isEmpty() || m_settings->value("Save/filename").toString().isEmpty()) + if (pth.isEmpty() || fn.isEmpty()) { int reply; if (pth.isEmpty()) @@ -878,17 +870,16 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) options->show(); connect(options, SIGNAL(closed()), this, SLOT(saveImage())); } - return QStringList(); + return; } // SAVE - results = m_image->save(m_settings->value("Save/filename"+QString(fav ? "_favorites" : "")).toString(), pth); + results = m_image->save(fn, pth); } for (auto it = results.begin(); it != results.end(); ++it) { const Image::SaveResult res = it.value(); - paths.append(it.key()); m_source = it.key(); switch (res) @@ -916,7 +907,7 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) default: error(this, tr("Error saving image.")); - return QStringList(); + return; } } @@ -924,7 +915,6 @@ QStringList ZoomWindow::saveImageNow(bool fav, bool saveAs) close(); m_mustSave = 0; - return paths; } void ZoomWindow::saveImageAs() diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index bcc4e5769..371d4a329 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -54,7 +54,7 @@ class ZoomWindow : public QWidget void saveNQuitFav(); void saveImage(bool fav = false); void saveImageFav(); - QStringList saveImageNow(bool fav = false, bool saveAs = false); + void saveImageNow(bool fav = false, bool saveAs = false); void saveImageAs(); void openUrl(const QString &); void openPool(const QString &); From d203261449f65c4993f3571d45564c31002e9250 Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 16 Jul 2018 09:01:50 +0200 Subject: [PATCH 080/112] Use enum instead of int for pending action in image window --- gui/src/viewer/zoom-window.cpp | 39 +++++++++++++++++----------------- gui/src/viewer/zoom-window.h | 12 ++++++++++- 2 files changed, 31 insertions(+), 20 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index faa8fd704..6ea2fe918 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -31,7 +31,8 @@ ZoomWindow::ZoomWindow(QList> images, const QSharedPointer setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); - m_mustSave = 0; + m_pendingAction = PendingNothing; + m_pendingClose = false; restoreGeometry(m_settings->value("Zoom/geometry").toByteArray()); ui->buttonPlus->setChecked(m_settings->value("Zoom/plus", false).toBool()); @@ -655,7 +656,7 @@ void ZoomWindow::showLoadingError(const QString &message) void ZoomWindow::pendingUpdate() { // If we don't want to save, nothing to do - if (m_mustSave == 0) + if (m_pendingAction == PendingNothing) return; // If the image is not even loaded, we cannot save it (unless it's a big file) @@ -663,37 +664,35 @@ void ZoomWindow::pendingUpdate() return; // If the image is loaded but we need their tags and we don't have them, we wait - if (m_mustSave != 6) + if (m_pendingAction != PendingSaveAs) { - const bool fav = (m_mustSave == 3 || m_mustSave == 4); + const bool fav = m_pendingAction == PendingSaveFav; Filename fn(m_settings->value("Save/path" + QString(fav ? "_favorites" : "")).toString()); if (!m_loadedDetails && fn.needExactTags(m_site)) return; } - switch (m_mustSave) + switch (m_pendingAction) { - case 1: // Save - case 2: // Save and quit + case PendingSave: saveImageNow(); break; - case 3: // Save (fav) - case 4: // Save and quit (fav) + case PendingSaveFav: saveImageNow(true); break; - case 5: // Open image in viewer + case PendingOpen: openFile(true); break; - case 6: // Save as + case PendingSaveAs: saveImageNow(false, true); break; } - m_mustSave = 0; + m_pendingAction = PendingNothing; } void ZoomWindow::draw() @@ -792,7 +791,8 @@ void ZoomWindow::saveNQuit() } setButtonState(false, SaveButtonState::Saving); - m_mustSave = 2; + m_pendingAction = PendingSave; + m_pendingClose = true; pendingUpdate(); } void ZoomWindow::saveNQuitFav() @@ -804,7 +804,8 @@ void ZoomWindow::saveNQuitFav() } setButtonState(true, SaveButtonState::Saving); - m_mustSave = 4; + m_pendingAction = PendingSaveFav; + m_pendingClose = true; pendingUpdate(); } @@ -815,7 +816,7 @@ void ZoomWindow::saveImage(bool fav) { case SaveButtonState::Save: setButtonState(fav, SaveButtonState::Saving); - m_mustSave = fav ? 3 : 1; + m_pendingAction = fav ? PendingSaveFav : PendingSave; pendingUpdate(); break; @@ -911,10 +912,10 @@ void ZoomWindow::saveImageNow(bool fav, bool saveAs) } } - if (m_mustSave == 2 || m_mustSave == 4) + if (m_pendingClose) close(); - m_mustSave = 0; + m_pendingClose = false; } void ZoomWindow::saveImageAs() @@ -931,7 +932,7 @@ void ZoomWindow::saveImageAs() m_settings->setValue("Zoom/lastDir", path.section(QDir::separator(), 0, -2)); m_saveAsPending = path; - m_mustSave = 6; + m_pendingAction = PendingSaveAs; pendingUpdate(); } } @@ -1241,7 +1242,7 @@ void ZoomWindow::openFile(bool now) { if (!now) { - m_mustSave = 5; + m_pendingAction = PendingOpen; pendingUpdate(); return; } diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index 371d4a329..34e4197d1 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -39,6 +39,14 @@ class ZoomWindow : public QWidget ExistsDisk, Delete }; + enum PendingAction + { + PendingNothing, + PendingSave, + PendingSaveFav, + PendingSaveAs, + PendingOpen, + }; ZoomWindow(QList> images, const QSharedPointer &image, Site *site, Profile *profile, mainWindow *parent); ~ZoomWindow() override; @@ -127,7 +135,9 @@ class ZoomWindow : public QWidget QSharedPointer m_image; QMap regex, m_details; Site *m_site; - int m_timeout, m_mustSave; + int m_timeout; + PendingAction m_pendingAction; + bool m_pendingClose; bool m_tooBig, m_loadedImage, m_loadedDetails; QString id; QUrl m_url, m_saveUrl; From 030b5ca6016cef094094023a2d4ed9773142b3ea Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 16 Jul 2018 09:22:18 +0200 Subject: [PATCH 081/112] Fix temporary path returned by ImageDownloader when image is already loaded --- lib/src/downloader/image-downloader.cpp | 7 ++++--- lib/src/downloader/image-downloader.h | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 17ad3513a..5eceeb7bc 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -80,7 +80,7 @@ void ImageDownloader::loadedSave() QMap result {{ m_temporaryPath, res }}; if (res == Image::SaveResult::Saved || res == Image::SaveResult::Copied || res == Image::SaveResult::Moved) - { result = postSaving(result); } + { result = postSaving(res); } emit saved(m_image, result); return; @@ -204,7 +204,7 @@ void ImageDownloader::success() emit saved(m_image, postSaving()); } -QMap ImageDownloader::postSaving(QMap result) +QMap ImageDownloader::postSaving(Image::SaveResult saveResult) { m_image->setSavePath(m_temporaryPath); @@ -214,6 +214,7 @@ QMap ImageDownloader::postSaving(QMap result; for (int i = 0; i < m_paths.count(); ++i) { const QString &path = m_paths[i]; @@ -242,7 +243,7 @@ QMap ImageDownloader::postSaving(QMappostSave(path, result[path], m_addMd5, m_startCommands, m_count); } diff --git a/lib/src/downloader/image-downloader.h b/lib/src/downloader/image-downloader.h index e18812377..9a3d3f413 100644 --- a/lib/src/downloader/image-downloader.h +++ b/lib/src/downloader/image-downloader.h @@ -23,7 +23,7 @@ class ImageDownloader : public QObject protected: QMap makeMap(const QStringList &keys, Image::SaveResult value); - QMap postSaving(QMap result = QMap()); + QMap postSaving(Image::SaveResult saveResult = Image::SaveResult::Saved); signals: void downloadProgress(QSharedPointer img, qint64 v1, qint64 v2); From a28f33918a4f03807899abf5fb3a7d99dc2fa016 Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 16 Jul 2018 09:26:10 +0200 Subject: [PATCH 082/112] Use ImageDownloader instead of Image::save in ZoomWindow --- gui/src/viewer/zoom-window.cpp | 82 ++++++++++++++++++---------------- gui/src/viewer/zoom-window.h | 3 +- 2 files changed, 46 insertions(+), 39 deletions(-) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 6ea2fe918..87ea6a7ba 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -676,23 +676,18 @@ void ZoomWindow::pendingUpdate() switch (m_pendingAction) { case PendingSave: - saveImageNow(); - break; - case PendingSaveFav: - saveImageNow(true); + case PendingSaveAs: + saveImageNow(); break; case PendingOpen: openFile(true); break; - case PendingSaveAs: - saveImageNow(false, true); - break; + default: + return; } - - m_pendingAction = PendingNothing; } void ZoomWindow::draw() @@ -843,42 +838,51 @@ void ZoomWindow::saveImage(bool fav) } void ZoomWindow::saveImageFav() { saveImage(true); } -void ZoomWindow::saveImageNow(bool fav, bool saveAs) +void ZoomWindow::saveImageNow() { - QMap results; - - if (saveAs) - { QFile::copy(m_imagePath, m_saveAsPending); } - else + if (m_pendingAction == PendingSaveAs) { - QString fn = m_settings->value("Save/filename"+QString(fav ? "_favorites" : "")).toString(); - QString pth = m_settings->value("Save/path"+QString(fav ? "_favorites" : "")).toString().replace("\\", "/"); - if (pth.right(1) == "/") - { pth = pth.left(pth.length()-1); } + QFile::copy(m_imagePath, m_saveAsPending); + saveImageNowSaved(m_image, QMap()); + return; + } + + const bool fav = m_pendingAction == PendingSaveFav; + QString fn = m_settings->value("Save/filename"+QString(fav ? "_favorites" : "")).toString(); + QString pth = m_settings->value("Save/path"+QString(fav ? "_favorites" : "")).toString().replace("\\", "/"); + if (pth.right(1) == "/") + { pth = pth.left(pth.length()-1); } - if (pth.isEmpty() || fn.isEmpty()) + if (pth.isEmpty() || fn.isEmpty()) + { + int reply; + if (pth.isEmpty()) + { reply = QMessageBox::question(this, tr("Error"), tr("You did not specified a save folder! Do you want to open the options window?"), QMessageBox::Yes | QMessageBox::No); } + else + { reply = QMessageBox::question(this, tr("Error"), tr("You did not specified a save format! Do you want to open the options window?"), QMessageBox::Yes | QMessageBox::No); } + if (reply == QMessageBox::Yes) { - int reply; - if (pth.isEmpty()) - { reply = QMessageBox::question(this, tr("Error"), tr("You did not specified a save folder! Do you want to open the options window?"), QMessageBox::Yes | QMessageBox::No); } - else - { reply = QMessageBox::question(this, tr("Error"), tr("You did not specified a save format! Do you want to open the options window?"), QMessageBox::Yes | QMessageBox::No); } - if (reply == QMessageBox::Yes) - { - auto *options = new optionsWindow(m_profile, parentWidget()); - //options->onglets->setCurrentIndex(3); - options->setWindowModality(Qt::ApplicationModal); - options->show(); - connect(options, SIGNAL(closed()), this, SLOT(saveImage())); - } - return; + auto *options = new optionsWindow(m_profile, parentWidget()); + //options->onglets->setCurrentIndex(3); + options->setWindowModality(Qt::ApplicationModal); + options->show(); + connect(options, SIGNAL(closed()), this, SLOT(saveImage())); } - - // SAVE - results = m_image->save(fn, pth); + return; } - for (auto it = results.begin(); it != results.end(); ++it) + auto downloader = new ImageDownloader(m_image, fn, pth, 1, true, true, this); + connect(downloader, &ImageDownloader::saved, this, &ZoomWindow::saveImageNowSaved); + connect(downloader, &ImageDownloader::saved, downloader, &ImageDownloader::deleteLater); + downloader->save(); +} +void ZoomWindow::saveImageNowSaved(QSharedPointer img, const QMap &result) +{ + Q_UNUSED(img); + + const bool fav = m_pendingAction == PendingSaveFav; + + for (auto it = result.begin(); it != result.end(); ++it) { const Image::SaveResult res = it.value(); m_source = it.key(); @@ -915,6 +919,7 @@ void ZoomWindow::saveImageNow(bool fav, bool saveAs) if (m_pendingClose) close(); + m_pendingAction = PendingNothing; m_pendingClose = false; } @@ -1248,6 +1253,7 @@ void ZoomWindow::openFile(bool now) } QDesktopServices::openUrl(QUrl::fromLocalFile(m_imagePath)); + m_pendingAction = PendingNothing; } void ZoomWindow::mouseReleaseEvent(QMouseEvent *e) diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index 34e4197d1..3682f2827 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -62,7 +62,8 @@ class ZoomWindow : public QWidget void saveNQuitFav(); void saveImage(bool fav = false); void saveImageFav(); - void saveImageNow(bool fav = false, bool saveAs = false); + void saveImageNow(); + void saveImageNowSaved(QSharedPointer img, const QMap &result); void saveImageAs(); void openUrl(const QString &); void openPool(const QString &); From ab2409181b54a862c87633d343abfa8342c0c9c2 Mon Sep 17 00:00:00 2001 From: Bionus Date: Mon, 16 Jul 2018 09:52:59 +0200 Subject: [PATCH 083/112] Fix travis trying to install Coveralls on OSX --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 972cd6d78..939ccf7b3 100755 --- a/.travis.yml +++ b/.travis.yml @@ -31,7 +31,9 @@ addons: # Install coveralls sender before_install: - - pip install --user cpp-coveralls + - if [[ "$TRAVIS_OS_NAME" == "linux" ]] && [[ "$TRAVIS_PULL_REQUEST" == "false" ]]; then + pip install --user cpp-coveralls + ; fi # Qt packages for OS X install: From 9ec380c01be51d437c2b40764261e679d4c35fe9 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 18 Jul 2018 22:11:50 +0200 Subject: [PATCH 084/112] Style fixes --- e2e/src/main.cpp | 10 ++++--- gui/src/batch/adduniquewindow.cpp | 2 +- gui/src/helpers.cpp | 4 +-- gui/src/mainwindow.cpp | 28 +++++++++---------- gui/src/mainwindow.h | 2 +- gui/src/settings/optionswindow.cpp | 8 ++++-- gui/src/settings/optionswindow.h | 2 +- gui/src/sources/sourcessettingswindow.cpp | 4 ++- gui/src/sources/sourcessettingswindow.h | 2 +- gui/src/sources/sourceswindow.cpp | 16 ++--------- gui/src/sources/sourceswindow.h | 2 +- gui/src/tabs/search-tab.cpp | 6 ++-- gui/src/ui/fixed-size-grid-layout.cpp | 18 +++++------- gui/src/ui/textedit.cpp | 16 ++++++----- gui/src/ui/textedit.h | 2 +- gui/src/ui/verticalscrollarea.cpp | 7 +++-- .../rename-existing/rename-existing-1.cpp | 2 +- gui/src/viewer/zoom-window.cpp | 8 ++++-- gui/src/viewer/zoom-window.h | 4 +-- lib/src/downloader/image-downloader.cpp | 2 +- lib/src/functions.cpp | 25 ++++++++--------- lib/src/login/oauth2-login.cpp | 11 ++++---- lib/src/models/api/javascript-api.cpp | 2 +- lib/src/models/filtering/token-filter.cpp | 2 +- lib/src/models/image.cpp | 8 +++--- lib/src/models/site.cpp | 4 +-- 26 files changed, 94 insertions(+), 103 deletions(-) diff --git a/e2e/src/main.cpp b/e2e/src/main.cpp index c640c186b..0ce2817cf 100644 --- a/e2e/src/main.cpp +++ b/e2e/src/main.cpp @@ -78,13 +78,14 @@ int main(int argc, char *argv[]) const QJsonArray rootSearch = root.value("search").toArray(); const QJsonObject sources = root.value("sources").toObject(); - for (const QString &sourceName : sources.keys()) + for (auto it = sources.begin(); it != sources.end(); ++it) { + const QString &sourceName = it.key(); qDebug() << "#" << "Source" << sourceName; QJsonObject sourceJson; Source *source = allSources.value(sourceName); - QJsonObject sites = sources.value(sourceName).toObject(); + QJsonObject sites = it.value().toObject(); const QJsonObject sourceApis = sites.value("apis").toObject(); QJsonArray sourceSearch = rootSearch; @@ -107,11 +108,12 @@ int main(int argc, char *argv[]) { siteSearch = override.value("search").toArray(); } } - for (const QString &apiName : siteApis.keys()) + for (auto ita = siteApis.begin(); ita != siteApis.end(); ++ita) { + const QString &apiName = ita.key(); qDebug() << "###" << "API" << apiName; QJsonObject apiJson; - QJsonArray checks = siteApis.value(apiName).toArray(); + QJsonArray checks = ita.value(api).toArray(); QJsonArray apiSearch = siteSearch; if (checks.count() > 4) diff --git a/gui/src/batch/adduniquewindow.cpp b/gui/src/batch/adduniquewindow.cpp index dd2f4a190..63875fa99 100644 --- a/gui/src/batch/adduniquewindow.cpp +++ b/gui/src/batch/adduniquewindow.cpp @@ -12,7 +12,7 @@ AddUniqueWindow::AddUniqueWindow(Site *selected, Profile *profile, QWidget *parent) - : QDialog(parent), ui(new Ui::AddUniqueWindow), m_page(nullptr), m_sites(profile->getSites()), m_close(nullptr), m_profile(profile) + : QDialog(parent), ui(new Ui::AddUniqueWindow), m_page(nullptr), m_sites(profile->getSites()), m_close(false), m_profile(profile) { ui->setupUi(this); diff --git a/gui/src/helpers.cpp b/gui/src/helpers.cpp index 12d3968dc..01e07af31 100644 --- a/gui/src/helpers.cpp +++ b/gui/src/helpers.cpp @@ -54,12 +54,12 @@ void clearLayout(QLayout *layout) while (layout->count() > 0) { QLayoutItem *item = layout->takeAt(0); - if (item->layout()) + if (item->layout() != nullptr) { clearLayout(item->layout()); item->layout()->deleteLater(); } - if (item->widget()) + if (item->widget() != nullptr) { item->widget()->deleteLater(); } delete item; } diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 4eb2e3646..a8c9c75ac 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -16,7 +16,7 @@ #endif #if defined(Q_OS_WIN) #include - #include "windows.h" + #include "Windows.h" #endif #include #include @@ -171,14 +171,12 @@ void mainWindow::init(const QStringList &args, const QMap &par this->deleteLater(); return; } - else - { - QString srsc; - QStringList keys = sites.keys(); - for (const QString &key : keys) - { srsc += (!srsc.isEmpty() ? ", " : "") + key + " (" + sites.value(key)->type() + ")"; } - log(QStringLiteral("%1 source%2 found: %3").arg(sites.size()).arg(sites.size() > 1 ? "s" : "", srsc), Logger::Info); - } + + QString srsc; + QStringList keys = sites.keys(); + for (const QString &key : keys) + { srsc += (!srsc.isEmpty() ? ", " : "") + key + " (" + sites.value(key)->type() + ")"; } + log(QStringLiteral("%1 source%2 found: %3").arg(sites.size()).arg(sites.size() > 1 ? "s" : "", srsc), Logger::Info); // System tray icon if (m_settings->value("Monitoring/enableTray", false).toBool()) @@ -467,7 +465,7 @@ void mainWindow::addSearchTab(searchTab *w, bool background, bool save) if (title.isEmpty()) { title = "New tab"; } - int pos = m_loaded ? ui->tabWidget->currentIndex() + (!m_tabs.isEmpty()) : m_tabs.count(); + int pos = m_loaded ? ui->tabWidget->currentIndex() + (!m_tabs.isEmpty() ? 1 : 0) : m_tabs.count(); int index = ui->tabWidget->insertTab(pos, w, title); m_tabs.append(w); @@ -486,7 +484,7 @@ void mainWindow::addSearchTab(searchTab *w, bool background, bool save) bool mainWindow::saveTabs(const QString &filename) { - return TabsLoader::save(filename, m_tabs, reinterpret_cast(m_currentTab)); + return TabsLoader::save(filename, m_tabs, qobject_cast(m_currentTab)); } bool mainWindow::loadTabs(const QString &filename) { @@ -1184,7 +1182,7 @@ void mainWindow::getAll(bool all) error(this, tr("You did not specify a save folder!")); return; } - else if (m_settings->value("Save/filename").toString().isEmpty()) + if (m_settings->value("Save/filename").toString().isEmpty()) { error(this, tr("You did not specify a filename!")); return; @@ -1537,7 +1535,7 @@ void mainWindow::getAllImages() // Check whether we need to get the tags first (for the filename) or if we can just download the images directly // TODO(Bionus): having one batch needing it currently causes all batches to need it, should mae it batch (Downloader) dependent m_mustGetTags = needExactTags(m_settings); - for (int f = 0; f < m_groupBatchs.size() && !m_mustGetTags; f++) + for (int f = 0; f < m_groupBatchs.size() && m_mustGetTags == 0; f++) { Filename fn(m_groupBatchs[f].filename); Site *site = m_groupBatchs[f].site; @@ -1547,7 +1545,7 @@ void mainWindow::getAllImages() if (need != 0) m_mustGetTags = need; } - for (int f = 0; f < m_batchs.size() && !m_mustGetTags; f++) + for (int f = 0; f < m_batchs.size() && m_mustGetTags == 0; f++) { Filename fn(m_batchs[f].filename); Site *site = m_batchs[f].site; @@ -1558,7 +1556,7 @@ void mainWindow::getAllImages() m_mustGetTags = need; } - if (m_mustGetTags) + if (m_mustGetTags != 0) log(QStringLiteral("Downloading images details."), Logger::Info); else log(QStringLiteral("Downloading images directly."), Logger::Info); diff --git a/gui/src/mainwindow.h b/gui/src/mainwindow.h index 831f202ca..681984f65 100644 --- a/gui/src/mainwindow.h +++ b/gui/src/mainwindow.h @@ -168,7 +168,7 @@ class mainWindow : public QMainWindow Profile *m_profile; QList &m_favorites; int m_getAllDownloaded, m_getAllExists, m_getAllIgnored, m_getAllIgnoredPre, m_getAll404s, m_getAllErrors, m_getAllSkipped, m_getAllLimit, m_downloads, m_waitForLogin; - int m_allow, m_loaded, m_getAll; + bool m_allow, m_loaded, m_getAll; int m_mustGetTags; int m_forcedTab; QSettings *m_settings; diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index 24b5daf1f..5173538cc 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -87,7 +87,7 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) QStringList types = QStringList() << "text" << "icon" << "both" << "hide"; ui->comboSources->setCurrentIndex(types.indexOf(settings->value("Sources/Types", "icon").toString())); int i = settings->value("Sources/Letters", 3).toInt(); - ui->comboSourcesLetters->setCurrentIndex((i < 0)+(i < -1)); + ui->comboSourcesLetters->setCurrentIndex((i < 0 ? 1 : 0) + (i < -1 ? 1 : 0)); ui->spinSourcesLetters->setValue(i < 0 ? 3 : i); ui->checkPreloadAllTabs->setChecked(settings->value("preloadAllTabs", false).toBool()); @@ -643,7 +643,7 @@ void optionsWindow::moveDownWebService(int id) swapWebServices(i, i + 1); } -int sortByOrder(const ReverseSearchEngine &a, const ReverseSearchEngine &b) +bool sortByOrder(const ReverseSearchEngine &a, const ReverseSearchEngine &b) { return a.order() < b.order(); } void optionsWindow::swapWebServices(int a, int b) { @@ -787,8 +787,10 @@ void treeWidgetRec(int depth, bool& found, int& index, QTreeWidgetItem *current, } } -void optionsWindow::updateContainer(QTreeWidgetItem *current, QTreeWidgetItem *) +void optionsWindow::updateContainer(QTreeWidgetItem *current, QTreeWidgetItem *previous) { + Q_UNUSED(previous); + bool found = false; int index = 0; diff --git a/gui/src/settings/optionswindow.h b/gui/src/settings/optionswindow.h index 78b2bffd8..f3449ec85 100644 --- a/gui/src/settings/optionswindow.h +++ b/gui/src/settings/optionswindow.h @@ -26,7 +26,7 @@ class optionsWindow : public QDialog void setFont(QLineEdit *lineEdit); public slots: - void updateContainer(QTreeWidgetItem *, QTreeWidgetItem *); + void updateContainer(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_comboSourcesLetters_currentIndexChanged(int); void on_buttonFolder_clicked(); void on_buttonFolderFavorites_clicked(); diff --git a/gui/src/sources/sourcessettingswindow.cpp b/gui/src/sources/sourcessettingswindow.cpp index 3be0306d0..f8d5034bb 100644 --- a/gui/src/sources/sourcessettingswindow.cpp +++ b/gui/src/sources/sourcessettingswindow.cpp @@ -187,8 +187,10 @@ void SourcesSettingsWindow::testLogin() m_site->login(true); } -void SourcesSettingsWindow::loginTested(Site*, Site::LoginResult result) +void SourcesSettingsWindow::loginTested(Site *site, Site::LoginResult result) { + Q_UNUSED(site); + switch (result) { case Site::LoginResult::Success: diff --git a/gui/src/sources/sourcessettingswindow.h b/gui/src/sources/sourcessettingswindow.h index b5dbc1e91..9ccdc4198 100644 --- a/gui/src/sources/sourcessettingswindow.h +++ b/gui/src/sources/sourcessettingswindow.h @@ -28,7 +28,7 @@ class SourcesSettingsWindow : public QDialog void addHeader(); void save(); void testLogin(); - void loginTested(Site*, Site::LoginResult); + void loginTested(Site *site, Site::LoginResult result); signals: void siteDeleted(const QString &); diff --git a/gui/src/sources/sourceswindow.cpp b/gui/src/sources/sourceswindow.cpp index 242c86c95..23a7f04ed 100644 --- a/gui/src/sources/sourceswindow.cpp +++ b/gui/src/sources/sourceswindow.cpp @@ -14,25 +14,13 @@ #include "ui/QBouton.h" -sourcesWindow::sourcesWindow(Profile *profile, const QList &selected, QWidget *parent) - : QDialog(parent), ui(new Ui::sourcesWindow), m_profile(profile), m_selected(selected), m_sites(profile->getSites()), m_sources(profile->getSources()), m_checkForSourceReply(nullptr) +sourcesWindow::sourcesWindow(Profile *profile, QList selected, QWidget *parent) + : QDialog(parent), ui(new Ui::sourcesWindow), m_profile(profile), m_selected(std::move(selected)), m_sites(profile->getSites()), m_sources(profile->getSources()), m_checkForSourceReply(nullptr) { setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); restoreGeometry(m_profile->getSettings()->value("Sources/geometry").toByteArray()); - bool checkall = true; - for (int i = 0; i < selected.count(); i++) - { - if (!selected.at(i)) - { - checkall = false; - break; - } - } - if (checkall) - { ui->checkBox->setChecked(true); } - addCheckboxes(); ui->gridLayout->setColumnStretch(0, 1); diff --git a/gui/src/sources/sourceswindow.h b/gui/src/sources/sourceswindow.h index 93636acf2..3d0ec4cdf 100644 --- a/gui/src/sources/sourceswindow.h +++ b/gui/src/sources/sourceswindow.h @@ -24,7 +24,7 @@ class sourcesWindow : public QDialog Q_OBJECT public: - explicit sourcesWindow(Profile *profile, const QList &selected, QWidget *parent = nullptr); + explicit sourcesWindow(Profile *profile, QList selected, QWidget *parent = nullptr); ~sourcesWindow() override; public slots: diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index 1f16d585f..fc4e6448c 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -219,7 +219,7 @@ QStringList searchTab::reasonsToFail(Page* page, const QStringList &completion, if (c > 0) { QStringList res = results.values(), cl = clean.values(); - *meant = ""+res.join(" ")+""; + *meant = QString(R"(%2)").arg(cl.join(" ").toHtmlEscaped(), res.join(" ")); } } @@ -869,7 +869,7 @@ QString getImageAlreadyExists(Image *img, Profile *profile) const QString path = settings->value("Save/path").toString().replace("\\", "/"); const QString fn = settings->value("Save/filename").toString(); - if (!Filename(fn).needExactTags(img->parentSite())) + if (Filename(fn).needExactTags(img->parentSite()) == 0) { QStringList files = img->path(fn, path, 0, true, false, true, true, true); for (const QString &file : files) @@ -1162,7 +1162,7 @@ void searchTab::webZoom(int id) void searchTab::openImage(const QSharedPointer &image) { - if (m_settings->value("Zoom/singleWindow", false).toBool() && m_lastZoomWindow) + if (m_settings->value("Zoom/singleWindow", false).toBool() && !m_lastZoomWindow.isNull()) { m_lastZoomWindow->reuse(m_images, image, image->page()->site()); m_lastZoomWindow->activateWindow(); diff --git a/gui/src/ui/fixed-size-grid-layout.cpp b/gui/src/ui/fixed-size-grid-layout.cpp index 8f8df61cb..5f058b55e 100644 --- a/gui/src/ui/fixed-size-grid-layout.cpp +++ b/gui/src/ui/fixed-size-grid-layout.cpp @@ -64,20 +64,16 @@ QLayoutItem *FixedSizeGridLayout::takeAt(int index) int FixedSizeGridLayout::horizontalSpacing() const { - if (m_hSpace >= 0) { - return m_hSpace; - } else { - return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); - } + return m_hSpace >= 0 + ? m_hSpace + : smartSpacing(QStyle::PM_LayoutHorizontalSpacing); } int FixedSizeGridLayout::verticalSpacing() const { - if (m_vSpace >= 0) { - return m_vSpace; - } else { - return smartSpacing(QStyle::PM_LayoutVerticalSpacing); - } + return m_vSpace >= 0 + ? m_vSpace + : smartSpacing(QStyle::PM_LayoutVerticalSpacing); } Qt::Orientations FixedSizeGridLayout::expandingDirections() const @@ -157,7 +153,7 @@ int FixedSizeGridLayout::doLayout(QRect rect, bool testOnly) const int FixedSizeGridLayout::smartSpacing(QStyle::PixelMetric pm) const { QObject *parent = this->parent(); - if (!parent) + if (parent == nullptr) return -1; if (parent->isWidgetType()) diff --git a/gui/src/ui/textedit.cpp b/gui/src/ui/textedit.cpp index aa0684e36..dd7c82b75 100644 --- a/gui/src/ui/textedit.cpp +++ b/gui/src/ui/textedit.cpp @@ -124,11 +124,11 @@ void TextEdit::setText(const QString &text) void TextEdit::setCompleter(QCompleter *completer) { - if (!completer) + if (completer == nullptr) return; // Disconnect the previous completer - if (c) + if (c != nullptr) QObject::disconnect(c, nullptr, this, nullptr); // Set the new completer and connect it to the field @@ -169,7 +169,7 @@ QString TextEdit::textUnderCursor() const void TextEdit::focusInEvent(QFocusEvent *e) { - if (c) + if (c != nullptr) c->setWidget(this); QTextEdit::focusInEvent(e); @@ -177,7 +177,7 @@ void TextEdit::focusInEvent(QFocusEvent *e) void TextEdit::keyPressEvent(QKeyEvent *e) { - if (c && c->popup()->isVisible()) + if (c != nullptr && c->popup()->isVisible()) { // The following keys are forwarded by the completer to the widget QString curr = c->popup()->currentIndex().data().toString(), under = textUnderCursor(); @@ -204,7 +204,7 @@ void TextEdit::keyPressEvent(QKeyEvent *e) } const bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Space); // CTRL+Space - if (!c || !isShortcut) // do not process the shortcut when we have a completer + if (c == nullptr || !isShortcut) // do not process the shortcut when we have a completer { if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) { @@ -216,7 +216,7 @@ void TextEdit::keyPressEvent(QKeyEvent *e) doColor(); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); - if (!c || (ctrlOrShift && e->text().isEmpty())) + if (c == nullptr || (ctrlOrShift && e->text().isEmpty())) return; static QString eow(" "); @@ -237,8 +237,10 @@ void TextEdit::keyPressEvent(QKeyEvent *e) c->complete(cr); } -void TextEdit::customContextMenuRequested(QPoint) +void TextEdit::customContextMenuRequested(const QPoint &pos) { + Q_UNUSED(pos); + auto *menu = new QMenu(this); auto *favs = new QMenu(tr("Favorites"), menu); auto *favsGroup = new QActionGroup(favs); diff --git a/gui/src/ui/textedit.h b/gui/src/ui/textedit.h index 5650278a7..efc1fef5b 100644 --- a/gui/src/ui/textedit.h +++ b/gui/src/ui/textedit.h @@ -31,7 +31,7 @@ class TextEdit : public QTextEdit private slots: void insertCompletion(const QString &completion); void insertFav(QAction *act); - void customContextMenuRequested(QPoint); + void customContextMenuRequested(const QPoint &pos); void setFavorite(); void unsetFavorite(); void setKfl(); diff --git a/gui/src/ui/verticalscrollarea.cpp b/gui/src/ui/verticalscrollarea.cpp index 5b5badb70..e62787e65 100644 --- a/gui/src/ui/verticalscrollarea.cpp +++ b/gui/src/ui/verticalscrollarea.cpp @@ -29,14 +29,15 @@ void VerticalScrollArea::setScrollEnabled(bool enabled) void VerticalScrollArea::updateWidgetSize() { - if (widget()) + QWidget *w = widget(); + if (w != nullptr) { int maxWidth = width(); if (m_scrollEnabled && verticalScrollBar()->isVisible()) maxWidth -= verticalScrollBar()->width(); - widget()->setMaximumWidth(maxWidth); + w->setMaximumWidth(maxWidth); - widget()->setMaximumHeight(m_scrollEnabled ? QWIDGETSIZE_MAX : height()); + w->setMaximumHeight(m_scrollEnabled ? QWIDGETSIZE_MAX : height()); } } diff --git a/gui/src/utils/rename-existing/rename-existing-1.cpp b/gui/src/utils/rename-existing/rename-existing-1.cpp index 0e0ba3835..053789a7d 100644 --- a/gui/src/utils/rename-existing/rename-existing-1.cpp +++ b/gui/src/utils/rename-existing/rename-existing-1.cpp @@ -125,7 +125,7 @@ void RenameExisting1::on_buttonContinue_clicked() // Check if filename requires details m_filename.setFormat(ui->lineFilenameDestination->text()); - m_needDetails = m_filename.needExactTags(m_sites.value(ui->comboSource->currentText())); + m_needDetails = m_filename.needExactTags(m_sites.value(ui->comboSource->currentText())) != 0; const int response = QMessageBox::question(this, tr("Rename existing images"), tr("You are about to download information from %n image(s). Are you sure you want to continue?", "", m_details.size()), QMessageBox::Yes | QMessageBox::No); if (response == QMessageBox::Yes) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 87ea6a7ba..5114934dc 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -330,8 +330,10 @@ void ZoomWindow::openSaveDirFav() void ZoomWindow::linkHovered(const QString &url) { m_link = url; } -void ZoomWindow::contextMenu(QPoint) +void ZoomWindow::contextMenu(const QPoint &pos) { + Q_UNUSED(pos); + if (m_link.isEmpty()) return; @@ -609,7 +611,7 @@ void ZoomWindow::setButtonState(bool fav, SaveButtonState state) } } -void ZoomWindow::replyFinishedZoom(QSharedPointer img, const QMap &result) +void ZoomWindow::replyFinishedZoom(const QSharedPointer &img, const QMap &result) { log(QStringLiteral("Image received from %1").arg(m_url.toString())); Image::SaveResult res = result.first(); @@ -669,7 +671,7 @@ void ZoomWindow::pendingUpdate() const bool fav = m_pendingAction == PendingSaveFav; Filename fn(m_settings->value("Save/path" + QString(fav ? "_favorites" : "")).toString()); - if (!m_loadedDetails && fn.needExactTags(m_site)) + if (!m_loadedDetails && fn.needExactTags(m_site) != 0) return; } diff --git a/gui/src/viewer/zoom-window.h b/gui/src/viewer/zoom-window.h index 3682f2827..818d8b9e8 100644 --- a/gui/src/viewer/zoom-window.h +++ b/gui/src/viewer/zoom-window.h @@ -56,7 +56,7 @@ class ZoomWindow : public QWidget public slots: void update(bool onlySize = false, bool force = false); void replyFinishedDetails(); - void replyFinishedZoom(QSharedPointer img, const QMap &result); + void replyFinishedZoom(const QSharedPointer &img, const QMap &result); void display(const QPixmap &, int); void saveNQuit(); void saveNQuitFav(); @@ -71,7 +71,7 @@ class ZoomWindow : public QWidget void openSaveDir(bool fav = false); void openSaveDirFav(); void linkHovered(const QString &); - void contextMenu(QPoint); + void contextMenu(const QPoint &pos); void openInNewTab(); void setfavorite(); void downloadProgress(QSharedPointer img, qint64 bytesReceived, qint64 bytesTotal); diff --git a/lib/src/downloader/image-downloader.cpp b/lib/src/downloader/image-downloader.cpp index 5eceeb7bc..bce2816e1 100644 --- a/lib/src/downloader/image-downloader.cpp +++ b/lib/src/downloader/image-downloader.cpp @@ -33,7 +33,7 @@ bool ImageDownloader::isRunning() const void ImageDownloader::save() { // If we use direct saving or don't want to load tags, we directly save the image - if (!m_loadTags || !m_paths.isEmpty() || !Filename(m_filename).needExactTags(m_image->parentSite())) + if (!m_loadTags || !m_paths.isEmpty() || Filename(m_filename).needExactTags(m_image->parentSite()) == 0) { loadedSave(); return; diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index 5a61c0683..9f59152d3 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -14,7 +14,7 @@ #include #include #ifdef Q_OS_WIN - #include + #include #else #include #endif @@ -330,26 +330,25 @@ bool setFileCreationDate(const QString &path, const QDateTime &datetime) auto *filename = new wchar_t[path.length() + 1]; path.toWCharArray(filename); filename[path.length()] = 0; - HANDLE hfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE hfile = CreateFileW(filename, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); delete[] filename; if (hfile == INVALID_HANDLE_VALUE) { log(QStringLiteral("Unable to open file to set creation date (%1): %2").arg(GetLastError()).arg(path), Logger::Error); return false; } - else - { - const LONGLONG ll = Int32x32To64(datetime.toTime_t(), 10000000) + 116444736000000000; - FILETIME pcreationtime; - pcreationtime.dwLowDateTime = static_cast(ll); - pcreationtime.dwHighDateTime = ll >> 32; - if (!SetFileTime(hfile, &pcreationtime, NULL, &pcreationtime)) - { - log(QStringLiteral("Unable to change the file creation date (%1): %2").arg(GetLastError()).arg(path), Logger::Error); - return false; - } + const LONGLONG ll = Int32x32To64(datetime.toTime_t(), 10000000) + 116444736000000000; + FILETIME pcreationtime; + pcreationtime.dwLowDateTime = static_cast(ll); + pcreationtime.dwHighDateTime = ll >> 32; + + if (!SetFileTime(hfile, &pcreationtime, nullptr, &pcreationtime)) + { + log(QStringLiteral("Unable to change the file creation date (%1): %2").arg(GetLastError()).arg(path), Logger::Error); + return false; } + CloseHandle(hfile); #else struct utimbuf timebuffer; diff --git a/lib/src/login/oauth2-login.cpp b/lib/src/login/oauth2-login.cpp index 892d3a9de..f6ec40ef3 100644 --- a/lib/src/login/oauth2-login.cpp +++ b/lib/src/login/oauth2-login.cpp @@ -41,16 +41,15 @@ void OAuth2Login::loginFinished() QJsonDocument jsonDocument = QJsonDocument::fromJson(result.toUtf8()); QJsonObject jsonObject = jsonDocument.object(); - if (jsonObject.value("token_type").toString() == QLatin1String("bearer")) + if (jsonObject.value("token_type").toString() != QLatin1String("bearer")) { - m_token = jsonObject.value("access_token").toString(); - emit loggedIn(Result::Success); + log(QStringLiteral("[%1] Wrong OAuth2 token type received.").arg(m_site->url())); + emit loggedIn(Result::Failure); return; } - else - { log(QStringLiteral("[%1] Wrong OAuth2 token type received.").arg(m_site->url())); } - emit loggedIn(Result::Failure); + m_token = jsonObject.value("access_token").toString(); + emit loggedIn(Result::Success); } void OAuth2Login::complementRequest(QNetworkRequest *request) const diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index 8e4e46924..923b50876 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -143,7 +143,7 @@ QList JavascriptApi::makeTags(const QJSValue &tags, Site *site) const ret.append(Tag(tag.toString())); continue; } - else if (!tag.isObject()) + if (!tag.isObject()) { continue; } const int id = tag.hasProperty("id") && !tag.property("id").isUndefined() ? tag.property("id").toInt() : 0; diff --git a/lib/src/models/filtering/token-filter.cpp b/lib/src/models/filtering/token-filter.cpp index 6917a6748..d5884864a 100644 --- a/lib/src/models/filtering/token-filter.cpp +++ b/lib/src/models/filtering/token-filter.cpp @@ -30,7 +30,7 @@ QString TokenFilter::match(const QMap &tokens, bool invert) cons if (cond && invert) { return QObject::tr("image has a \"%1\" token").arg(m_token); } - else if (!cond && !invert) + if (!cond && !invert) { return QObject::tr("image does not have a \"%1\" token").arg(m_token); } return QString(); diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 56f484e1f..78a32c251 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -441,11 +441,11 @@ int Image::value() const // Get from tags if (hasTag("incredibly_absurdres")) return 10000 * 10000; - else if (hasTag("absurdres")) + if (hasTag("absurdres")) return 3200 * 2400; - else if (hasTag("highres")) + if (hasTag("highres")) return 1600 * 1200; - else if (hasTag("lowres")) + if (hasTag("lowres")) return 500 * 500; return 1200 * 900; @@ -937,7 +937,7 @@ QUrl Image::url(Size size) const void Image::preload(const Filename &filename) { - if (!filename.needExactTags(m_parentSite)) + if (filename.needExactTags(m_parentSite) == 0) return; QEventLoop loop; diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index ad2f6cbc1..9e1215093 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -238,9 +238,9 @@ QNetworkRequest Site::makeRequest(QUrl url, Page *page, const QString &ref, Imag { refHeader = url.scheme() + "://" + url.host(); } else if (referer == "image") { refHeader = fixUrl(url).toString(); } - else if (referer == "page" && page) + else if (referer == "page" && page != nullptr) { refHeader = fixUrl(page->url()).toString(); } - else if (referer == "details" && img) + else if (referer == "details" && img != nullptr) { refHeader = fixUrl(img->pageUrl()).toString(); } request.setRawHeader("Referer", refHeader.toLatin1()); } From edd12aa85867e092b1f3c6d54528e4611dc8aad8 Mon Sep 17 00:00:00 2001 From: Bionus Date: Thu, 19 Jul 2018 09:28:19 +0200 Subject: [PATCH 085/112] Fix crash on startup when not restoring tabs --- gui/src/mainwindow.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index a8c9c75ac..9cbfa60f6 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -59,7 +59,7 @@ mainWindow::mainWindow(Profile *profile) - : ui(new Ui::mainWindow), m_profile(profile), m_favorites(m_profile->getFavorites()), m_downloads(0), m_loaded(false), m_getAll(false), m_forcedTab(-1), m_batchAutomaticRetries(0), m_showLog(true) + : ui(new Ui::mainWindow), m_profile(profile), m_favorites(m_profile->getFavorites()), m_downloads(0), m_loaded(false), m_getAll(false), m_forcedTab(-1), m_progressDialog(nullptr), m_currentTab(nullptr), m_batchAutomaticRetries(0), m_showLog(true) { } void mainWindow::init(const QStringList &args, const QMap ¶ms) { @@ -158,8 +158,6 @@ void mainWindow::init(const QStringList &args, const QMap &par { log(QStringLiteral("Enabling system-wide proxy."), Logger::Info); } } - m_progressDialog = nullptr; - ui->tableBatchGroups->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); ui->tableBatchUniques->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); @@ -320,7 +318,6 @@ void mainWindow::init(const QStringList &args, const QMap &par updateFavorites(); updateKeepForLater(); - m_currentTab = nullptr; log(QStringLiteral("End of initialization"), Logger::Debug); } From 2b029e9edf3191bb360596b3a98b83b87c2c8676 Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 20 Jul 2018 15:53:01 +0200 Subject: [PATCH 086/112] Don't apply wiki styles twice --- gui/src/tabs/search-tab.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index fc4e6448c..bbefc7d22 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -471,7 +471,7 @@ void searchTab::finishedLoadingTags(Page *page) // Wiki if (!page->wiki().isEmpty()) { - m_wiki = ""+page->wiki(); + m_wiki = page->wiki(); m_parent->setWiki(m_wiki); } From 99d35f460a392a2b13732d002a719e3f0c00a73f Mon Sep 17 00:00:00 2001 From: Bionus Date: Fri, 20 Jul 2018 15:53:58 +0200 Subject: [PATCH 087/112] Fix wiki parsing (issue #1347) --- release/sites/Danbooru (2.0)/model.ts | 4 +++- release/sites/Danbooru/model.ts | 4 +++- release/sites/Moebooru/model.ts | 1 - release/sites/Sankaku/model.ts | 4 +++- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/release/sites/Danbooru (2.0)/model.ts b/release/sites/Danbooru (2.0)/model.ts index 66f85e2a6..803660f73 100644 --- a/release/sites/Danbooru (2.0)/model.ts +++ b/release/sites/Danbooru (2.0)/model.ts @@ -256,10 +256,12 @@ export const source: ISource = { } }, parse: (src: string): IParsedSearch => { + let wiki = Grabber.regexToConst("wiki", '
    ]+)>(?.+?)
    ', src); + wiki = wiki.replace(/href="\/wiki_pages\/show_or_new\?title=([^"]+)"/g, 'href="$1"'); return { tags: Grabber.regexToTags('
  • (?:\\s*\\?)?(?:\\s*]* class="search-inc-tag">[^<]+\\s*]* class="search-exl-tag">[^<]+)?\\s*]*href="[^"]+"[^>]*>(?[^<]+)\\s*(?[^<]+)\\s*
  • ', src), images: Grabber.regexToImages(']* id="[^"]*" class="[^"]*"\\s+data-id="(?[^"]*)"\\s+data-has-sound="[^"]*"\\s+data-tags="(?[^"]*)"\\s+data-pools="(?[^"]*)"(?:\\s+data-uploader="(?[^"]*)")?\\s+data-approver-id="(?[^"]*)"\\s+data-rating="(?[^"]*)"\\s+data-width="(?[^"]*)"\\s+data-height="(?[^"]*)"\\s+data-flags="(?[^"]*)"\\s+data-parent-id="(?[^"]*)"\\s+data-has-children="(?[^"]*)"\\s+data-score="(?[^"]*)"\\s+data-views="[^"]*"\\s+data-fav-count="(?[^"]*)"\\s+data-pixiv-id="[^"]*"\\s+data-file-ext="(?[^"]*)"\\s+data-source="(?[^"]*)"\\s+data-top-tagger="[^"]*"\\s+data-uploader-id="[^"]*"\\s+data-normalized-source="[^"]*"\\s+data-is-favorited="[^"]*"\\s+data-md5="(?[^"]*)"\\s+data-file-url="(?[^"]*)"\\s+data-large-file-url="(?[^"]*)"\\s+data-preview-file-url="(?[^"]*)"', src).map(completeImage), - wiki: Grabber.regexToConst("wiki", '
    ]+)>(?.+?)
    ', src), + wiki, pageCount: Grabber.regexToConst("page", ">(?\\d+)<(?:a|span)[^>]*>>><", src), }; }, diff --git a/release/sites/Danbooru/model.ts b/release/sites/Danbooru/model.ts index 6c4ca24a4..642dcabd2 100644 --- a/release/sites/Danbooru/model.ts +++ b/release/sites/Danbooru/model.ts @@ -188,10 +188,12 @@ export const source: ISource = { } }, parse: (src: string): IParsedSearch => { + let wiki = Grabber.regexToConst("wiki", '', src); + wiki = wiki.replace(/href="\/wiki\/show\?title=([^"]+)"/g, 'href="$1"'); return { images: Grabber.regexToImages("Post\\.register\\((?\\{.+?\\})\\);?", src).map(completeImage), tags: Grabber.regexToTags('
  • ]*tag-type-(?[^">]+)(?:|"[^>]*)>.*?]*>(?[^<\\?]+).*?(?\\d+).*?
  • ', src), - wiki: Grabber.regexToConst("wiki", ''), + wiki, pageCount: Grabber.regexToConst("page", '\\d+)[^"]*" rel="last" title="Last Page">'), }; }, diff --git a/release/sites/Moebooru/model.ts b/release/sites/Moebooru/model.ts index ce63ef68e..3f836bcf3 100644 --- a/release/sites/Moebooru/model.ts +++ b/release/sites/Moebooru/model.ts @@ -149,7 +149,6 @@ export const source: any = { return { tags: Grabber.regexToTags('
  • [^" ]+)"[^>]*>(?:[^<]*]*>[^<]*)*[^<]*]*>(?[^<]*)[^<]*]*>(?\\d+)k?[^<]*
  • ', src), images, - wiki: Grabber.regexToConst("wiki", '', src), pageCount, }; }, diff --git a/release/sites/Sankaku/model.ts b/release/sites/Sankaku/model.ts index 2c5c0191b..1cb9d42f1 100644 --- a/release/sites/Sankaku/model.ts +++ b/release/sites/Sankaku/model.ts @@ -85,10 +85,12 @@ export const source: ISource = { parse: (src: string): IParsedSearch => { const searchImageCounts = Grabber.regexMatches('class="?tag-(?:count|type-none)"? title="Post Count: (?[0-9,]+)"', src); const lastPage = Grabber.regexToConst("page", '\\s*(?[0-9,]+)\\s*\\s*>>\\s*', src); + let wiki = Grabber.regexToConst("wiki", '
    ]*>(?.+?)
    ', src); + wiki = wiki.replace(/href="\/wiki\/show\?title=([^"]+)"/g, 'href="$1"'); return { tags: Grabber.regexToTags('
  • ]*tag-type-(?[^">]+)(?:|"[^>]*)>.*?]*>(?[^<\\?]+).*?(?\\d+).*?
  • ', src), images: Grabber.regexToImages(']* id="?p(?\\d+)"?>]*>]* src="(?[^"]+/preview/\\w{2}/\\w{2}/(?[^.]+)\\.[^"]+|[^"]+/download-preview.png)" title="(?[^"]+)"[^>]+>', src).map(completeImage), - wiki: Grabber.regexToConst("wiki", '', src), + wiki, pageCount: lastPage ? Grabber.countToInt(lastPage) : undefined, imageCount: searchImageCounts.length === 1 ? Grabber.countToInt(searchImageCounts[0].count) : undefined, }; From 2a839206d1b77115726f4b9dc700dde9c906aa1d Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 21 Jul 2018 00:05:44 +0200 Subject: [PATCH 088/112] Make wiki text selectable (fix #1347) --- gui/src/mainwindow.ui | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/gui/src/mainwindow.ui b/gui/src/mainwindow.ui index f87b942de..8e92d6253 100644 --- a/gui/src/mainwindow.ui +++ b/gui/src/mainwindow.ui @@ -495,7 +495,7 @@ QTextEdit { 0 0 215 - 36 + 33 @@ -583,7 +583,7 @@ QTextEdit { 0 0 215 - 35 + 33 @@ -704,7 +704,7 @@ QTextEdit { 0 0 203 - 44 + 36 @@ -804,7 +804,7 @@ QTextEdit { 0 0 215 - 36 + 34 @@ -822,6 +822,9 @@ QTextEdit { true + + Qt::TextBrowserInteraction +
    From 919d830662d6c4a7b39137d515d4bc30a781a4d8 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 21 Jul 2018 00:10:56 +0200 Subject: [PATCH 089/112] Don't change wiki from non-current tabs (issue #1347) --- gui/src/mainwindow.cpp | 5 ++++- gui/src/mainwindow.h | 2 +- gui/src/tabs/search-tab.cpp | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 9cbfa60f6..438113813 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -2218,8 +2218,11 @@ bool mainWindow::loadLinkList(const QString &filename) return true; } -void mainWindow::setWiki(const QString &wiki) +void mainWindow::setWiki(const QString &wiki, searchTab *from) { + if (from != nullptr && from != m_currentTab) + return; + ui->labelWiki->setText("" + wiki); } diff --git a/gui/src/mainwindow.h b/gui/src/mainwindow.h index 681984f65..07579045b 100644 --- a/gui/src/mainwindow.h +++ b/gui/src/mainwindow.h @@ -149,7 +149,7 @@ class mainWindow : public QMainWindow void setTags(const QList &tags, searchTab *from = nullptr); void initialLoginsFinished(); QIcon& getIcon(const QString &path); - void setWiki(const QString &); + void setWiki(const QString &wiki, searchTab *from = nullptr); void siteDeleted(Site *site); // Drag & drop diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index bbefc7d22..f6f93f136 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -236,7 +236,7 @@ void searchTab::clear() // Clear page details m_tags.clear(); m_parent->setTags(m_tags, this); - m_parent->setWiki(QString()); + m_parent->setWiki(QString(), this); // Clear layout for (int i = 0; i < ui_layoutResults->rowCount(); ++i) @@ -472,7 +472,7 @@ void searchTab::finishedLoadingTags(Page *page) if (!page->wiki().isEmpty()) { m_wiki = page->wiki(); - m_parent->setWiki(m_wiki); + m_parent->setWiki(m_wiki, this); } const int maxPage = page->pagesCount(); From 952623452790da213cb4b3e09c1b363e3c54743b Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 21 Jul 2018 11:42:58 +0200 Subject: [PATCH 090/112] Force thumbnail extension to JPG on GB 2.0 XML (fix #1348) --- release/sites/Gelbooru (0.2)/model.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/release/sites/Gelbooru (0.2)/model.ts b/release/sites/Gelbooru (0.2)/model.ts index 6fb67c878..d28d8c5de 100644 --- a/release/sites/Gelbooru (0.2)/model.ts +++ b/release/sites/Gelbooru (0.2)/model.ts @@ -10,6 +10,19 @@ function completeImage(img: IImage): IImage { return img; } +function setExtension(url: string, ext: string): string { + const queryPos: number = url.indexOf("?"); + const dotPos: number = url.lastIndexOf(".", queryPos !== -1 ? queryPos : url.length); + const query: string = queryPos === -1 ? "" : url.substr(queryPos); + return url.substr(0, dotPos + 1) + ext + query; +} + +// Fix thumbnails that do not have a JPG extendion +function fixThumbnailExtension(img: IImage): IImage { + img["preview_url"] = setExtension(img["preview_url"], "jpg"); + return img; +} + export const source: ISource = { name: "Gelbooru (0.2)", modifiers: ["rating:safe", "rating:questionable", "rating:explicit", "user:", "fav:", "fastfav:", "md5:", "source:", "id:", "width:", "height:", "score:", "mpixels:", "filesize:", "date:", "gentags:", "arttags:", "chartags:", "copytags:", "approver:", "parent:", "sub:", "order:id", "order:id_desc", "order:score", "order:score_asc", "order:mpixels", "order:mpixels_asc", "order:filesize", "order:landscape", "order:portrait", "order:favcount", "order:rank", "parent:none", "unlocked:rating", "sort:updated", "sort:id", "sort:score", "sort:rating", "sort:user", "sort:height", "sort:width", "sort:parent", "sort:source", "sort:updated"], @@ -36,7 +49,7 @@ export const source: ISource = { const images: IImage[] = []; for (const image of data) { if (image && "@attributes" in image) { - images.push(completeImage(image["@attributes"])); + images.push(fixThumbnailExtension(completeImage(image["@attributes"]))); } } From 95c284444da631150cbaf7529b08881994d31d47 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 21 Jul 2018 23:53:26 +0200 Subject: [PATCH 091/112] Allow to set an user and password to proxy (fix #1350) --- gui/src/mainwindow.cpp | 12 ++++++++++-- gui/src/settings/optionswindow.cpp | 16 ++++++++++++++-- gui/src/settings/optionswindow.ui | 29 ++++++++++++++++++++++++++--- 3 files changed, 50 insertions(+), 7 deletions(-) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 438113813..28b20d3fe 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -149,8 +149,16 @@ void mainWindow::init(const QStringList &args, const QMap &par if (!useSystem) { - QNetworkProxy::ProxyType type = m_settings->value("Proxy/type", "http").toString() == "http" ? QNetworkProxy::HttpProxy : QNetworkProxy::Socks5Proxy; - QNetworkProxy proxy(type, m_settings->value("Proxy/hostName").toString(), m_settings->value("Proxy/port").toInt()); + const QNetworkProxy::ProxyType type = m_settings->value("Proxy/type", "http").toString() == "http" + ? QNetworkProxy::HttpProxy + : QNetworkProxy::Socks5Proxy; + const QNetworkProxy proxy( + type, + m_settings->value("Proxy/hostName").toString(), + m_settings->value("Proxy/port").toInt(), + m_settings->value("Proxy/user").toString(), + m_settings->value("Proxy/password").toString() + ); QNetworkProxy::setApplicationProxy(proxy); log(QStringLiteral("Enabling application proxy on host \"%1\" and port %2.").arg(m_settings->value("Proxy/hostName").toString()).arg(m_settings->value("Proxy/port").toInt()), Logger::Info); } diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index 5173538cc..10dbf5273 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -313,6 +313,8 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) ui->widgetProxy->setEnabled(settings->value("use", false).toBool()); ui->lineProxyHostName->setText(settings->value("hostName").toString()); ui->spinProxyPort->setValue(settings->value("port").toInt()); + ui->lineProxyUser->setText(settings->value("user").toString()); + ui->lineProxyPassword->setText(settings->value("password").toString()); settings->endGroup(); settings->beginGroup("Exec"); @@ -1120,6 +1122,8 @@ void optionsWindow::save() settings->setValue("type", ptypes.at(ui->comboProxyType->currentIndex())); settings->setValue("hostName", ui->lineProxyHostName->text()); settings->setValue("port", ui->spinProxyPort->value()); + settings->setValue("user", ui->lineProxyUser->text()); + settings->setValue("password", ui->lineProxyPassword->text()); settings->endGroup(); settings->beginGroup("Exec"); @@ -1147,8 +1151,16 @@ void optionsWindow::save() if (!useSystem) { - const QNetworkProxy::ProxyType type = settings->value("Proxy/type", "http") == "http" ? QNetworkProxy::HttpProxy : QNetworkProxy::Socks5Proxy; - const QNetworkProxy proxy(type, settings->value("Proxy/hostName").toString(), settings->value("Proxy/port").toInt()); + const QNetworkProxy::ProxyType type = settings->value("Proxy/type", "http") == "http" + ? QNetworkProxy::HttpProxy + : QNetworkProxy::Socks5Proxy; + const QNetworkProxy proxy( + type, + settings->value("Proxy/hostName").toString(), + settings->value("Proxy/port").toInt(), + settings->value("Proxy/user").toString(), + settings->value("Proxy/password").toString() + ); QNetworkProxy::setApplicationProxy(proxy); log(QStringLiteral("Enabling application proxy on host \"%1\" and port %2.").arg(settings->value("Proxy/hostName").toString()).arg(settings->value("Proxy/port").toInt())); } diff --git a/gui/src/settings/optionswindow.ui b/gui/src/settings/optionswindow.ui index 20fb6d62a..e236edc5e 100644 --- a/gui/src/settings/optionswindow.ui +++ b/gui/src/settings/optionswindow.ui @@ -969,8 +969,8 @@ 0 0 - 369 - 377 + 65 + 16 @@ -2614,7 +2614,6 @@ labelColoringSpecies labelColoringKeptForLater labelColoringMetas - horizontalLayoutWidget @@ -2959,6 +2958,30 @@
    + + + + User + + + + + + + Password + + + + + + + + + + QLineEdit::Password + + + From 2dab9d9fa29fa5f566cc07539c9855d00b793c98 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 22 Jul 2018 16:10:15 +0200 Subject: [PATCH 092/112] Save 'search' when downloading single images (fix #1322) --- gui/src/mainwindow.cpp | 11 ++++++----- gui/src/mainwindow.ui | 5 +++++ lib/src/downloader/download-query-image.cpp | 11 +++++++---- lib/src/downloader/download-query-image.h | 4 ++-- lib/src/downloader/download-query-loader.cpp | 2 +- lib/src/models/image.cpp | 1 + lib/src/models/image.h | 1 + 7 files changed, 23 insertions(+), 12 deletions(-) diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index 28b20d3fe..f988a01dc 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -680,9 +680,10 @@ void mainWindow::batchAddUnique(const DownloadQueryImage &query, bool save) addTableItem(ui->tableBatchUniques, row, 3, query.values["tags"]); addTableItem(ui->tableBatchUniques, row, 4, query.values["file_url"]); addTableItem(ui->tableBatchUniques, row, 5, query.values["date"]); - addTableItem(ui->tableBatchUniques, row, 6, query.site->name()); - addTableItem(ui->tableBatchUniques, row, 7, query.filename); - addTableItem(ui->tableBatchUniques, row, 8, query.path); + addTableItem(ui->tableBatchUniques, row, 6, query.values["search"]); + addTableItem(ui->tableBatchUniques, row, 7, query.site->name()); + addTableItem(ui->tableBatchUniques, row, 8, query.filename); + addTableItem(ui->tableBatchUniques, row, 9, query.path); if (save) { saveLinkList(m_profile->getPath() + "/restore.igl"); } @@ -1231,7 +1232,7 @@ void mainWindow::getAll(bool all) tdl.append(row); DownloadQueryImage batch = m_batchs[row]; - Page *page = new Page(m_profile, batch.site, m_profile->getSites().values(), batch.values.value("tags").split(" "), 1, 1, QStringList(), false, this); + Page *page = new Page(m_profile, batch.site, m_profile->getSites().values(), batch.values["search"].split(" "), 1, 1, QStringList(), false, this); BatchDownloadImage d; d.image = QSharedPointer(new Image(batch.site, batch.values, m_profile, page)); @@ -1254,7 +1255,7 @@ void mainWindow::getAll(bool all) dta.insert("filename", batch.filename); dta.insert("folder", batch.path); - Page *page = new Page(m_profile, batch.site, m_profile->getSites().values(), batch.values["tags"].split(" "), 1, 1, QStringList(), false, this); + Page *page = new Page(m_profile, batch.site, m_profile->getSites().values(), batch.values["search"].split(" "), 1, 1, QStringList(), false, this); BatchDownloadImage d; d.image = QSharedPointer(new Image(batch.site, dta, m_profile, page)); diff --git a/gui/src/mainwindow.ui b/gui/src/mainwindow.ui index 8e92d6253..7de96c7ff 100644 --- a/gui/src/mainwindow.ui +++ b/gui/src/mainwindow.ui @@ -210,6 +210,11 @@ Date + + + Search + + Site diff --git a/lib/src/downloader/download-query-image.cpp b/lib/src/downloader/download-query-image.cpp index 84b334142..219f8b3e9 100644 --- a/lib/src/downloader/download-query-image.cpp +++ b/lib/src/downloader/download-query-image.cpp @@ -20,10 +20,10 @@ DownloadQueryImage::DownloadQueryImage(const Image &img, Site *site, const QStri initFromImage(img); } -DownloadQueryImage::DownloadQueryImage(qulonglong id, const QString &md5, const QString &rating, const QString &tags, const QString &fileUrl, const QString &date, Site *site, const QString &filename, const QString &path) +DownloadQueryImage::DownloadQueryImage(qulonglong id, const QString &md5, const QString &rating, const QString &tags, const QString &fileUrl, const QString &date, Site *site, const QString &filename, const QString &path, const QStringList &search) : DownloadQuery(site, filename, path) { - initFromData(id, md5, rating, tags, fileUrl, date); + initFromData(id, md5, rating, tags, fileUrl, date, search); } void DownloadQueryImage::initFromImage(const Image &img) @@ -35,10 +35,10 @@ void DownloadQueryImage::initFromImage(const Image &img) for (const Tag &tag : imgTags) tags.append(tag.text()); - initFromData(img.id(), img.md5(), img.rating(), tags.join(" "), img.fileUrl().toString(), img.createdAt().toString(Qt::ISODate)); + initFromData(img.id(), img.md5(), img.rating(), tags.join(" "), img.fileUrl().toString(), img.createdAt().toString(Qt::ISODate), img.search()); } -void DownloadQueryImage::initFromData(qulonglong id, const QString &md5, const QString &rating, const QString &tags, const QString &fileUrl, const QString &date) +void DownloadQueryImage::initFromData(qulonglong id, const QString &md5, const QString &rating, const QString &tags, const QString &fileUrl, const QString &date, const QStringList &search) { values["filename"] = filename; values["path"] = path; @@ -50,6 +50,7 @@ void DownloadQueryImage::initFromData(qulonglong id, const QString &md5, const Q values["tags"] = tags; values["date"] = date; values["file_url"] = fileUrl; + values["search"] = search.join(' '); } @@ -74,6 +75,7 @@ void DownloadQueryImage::write(QJsonObject &json) const json["tags"] = QJsonArray::fromStringList(values["tags"].split(' ', QString::SkipEmptyParts)); json["file_url"] = values["file_url"]; json["date"] = values["date"]; + json["search"] = values["search"]; json["site"] = site->url(); json["filename"] = QString(filename).replace("\n", "\\n"); @@ -94,6 +96,7 @@ bool DownloadQueryImage::read(const QJsonObject &json, const QMap &u if (!sites.contains(source)) continue; - uniques.append(DownloadQueryImage(infos[0].toULongLong(), infos[1], infos[2], infos[3], infos[4], infos[5], sites[source], infos[7], infos[8])); + uniques.append(DownloadQueryImage(infos[0].toULongLong(), infos[1], infos[2], infos[3], infos[4], infos[5], sites[source], infos[7], infos[8], QStringList())); } else { diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 78a32c251..58b9713dd 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -663,6 +663,7 @@ QPixmap Image::previewImage() const { return m_imagePreview; } const QPixmap &Image::previewImage() { return m_imagePreview; } Page *Image::page() const { return m_parent; } const QByteArray&Image::data() const { return m_data; } +const QStringList&Image::search() const { return m_search; } bool Image::isGallery() const { return m_isGallery; } ExtensionRotator *Image::extensionRotator() const { return m_extensionRotator; } diff --git a/lib/src/models/image.h b/lib/src/models/image.h index c39ca00da..4a949aca5 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -52,6 +52,7 @@ class Image : public QObject, public Downloadable void setPreviewImage(const QPixmap &preview); Page *page() const; const QByteArray &data() const; + const QStringList &search() const; Site *parentSite() const; ExtensionRotator *extensionRotator() const; bool hasTag(QString tag) const; From 441d848ea49664011f38ede80f40111834d9bf18 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 22 Jul 2018 16:37:43 +0200 Subject: [PATCH 093/112] Remove unused DownloadQuery::toString --- lib/src/downloader/download-query-group.cpp | 12 ------------ lib/src/downloader/download-query-group.h | 1 - lib/src/downloader/download-query-image.cpp | 13 ------------- lib/src/downloader/download-query-image.h | 1 - lib/src/downloader/download-query.h | 1 - 5 files changed, 28 deletions(-) diff --git a/lib/src/downloader/download-query-group.cpp b/lib/src/downloader/download-query-group.cpp index d29e6bc29..3626cff69 100644 --- a/lib/src/downloader/download-query-group.cpp +++ b/lib/src/downloader/download-query-group.cpp @@ -16,18 +16,6 @@ DownloadQueryGroup::DownloadQueryGroup(QString tags, int page, int perPage, int { } -QString DownloadQueryGroup::toString(const QString &separator) const -{ - return tags + separator + - QString::number(page) + separator + - QString::number(perpage) + separator + - QString::number(total) + separator + - (getBlacklisted ? "true" : "false") + separator + - site->url() + separator + - QString(filename).replace("\n", "\\n") + separator + - path + separator; -} - void DownloadQueryGroup::write(QJsonObject &json) const { json["tags"] = QJsonArray::fromStringList(tags.split(' ', QString::SkipEmptyParts)); diff --git a/lib/src/downloader/download-query-group.h b/lib/src/downloader/download-query-group.h index 1dcdd3d12..8cc6e6b77 100644 --- a/lib/src/downloader/download-query-group.h +++ b/lib/src/downloader/download-query-group.h @@ -18,7 +18,6 @@ class DownloadQueryGroup : public DownloadQuery explicit DownloadQueryGroup(QString tags, int page, int perPage, int total, QStringList postFiltering, bool getBlacklisted, Site *site, const QString &filename, const QString &path, QString unk = QString()); // Serialization - QString toString(const QString &separator) const override; void write(QJsonObject &json) const override; bool read(const QJsonObject &json, const QMap &sites) override; diff --git a/lib/src/downloader/download-query-image.cpp b/lib/src/downloader/download-query-image.cpp index 219f8b3e9..78578bc5b 100644 --- a/lib/src/downloader/download-query-image.cpp +++ b/lib/src/downloader/download-query-image.cpp @@ -54,19 +54,6 @@ void DownloadQueryImage::initFromData(qulonglong id, const QString &md5, const Q } -QString DownloadQueryImage::toString(const QString &separator) const -{ - return values["id"] + separator + - values["md5"] + separator + - values["rating"] + separator + - values["tags"] + separator + - values["file_url"] + separator + - values["date"] + separator + - site->url() + separator + - filename + separator + - path; -} - void DownloadQueryImage::write(QJsonObject &json) const { json["id"] = values["id"].toInt(); diff --git a/lib/src/downloader/download-query-image.h b/lib/src/downloader/download-query-image.h index 1cddcf0e1..bbc68d94d 100644 --- a/lib/src/downloader/download-query-image.h +++ b/lib/src/downloader/download-query-image.h @@ -21,7 +21,6 @@ class DownloadQueryImage : public DownloadQuery explicit DownloadQueryImage(qulonglong id, const QString &md5, const QString &rating, const QString &tags, const QString &fileUrl, const QString &date, Site *site, const QString &filename, const QString &path, const QStringList &search); // Serialization - QString toString(const QString &separator) const override; void write(QJsonObject &json) const override; bool read(const QJsonObject &json, const QMap &sites) override; diff --git a/lib/src/downloader/download-query.h b/lib/src/downloader/download-query.h index adad96aa2..acd5ea912 100644 --- a/lib/src/downloader/download-query.h +++ b/lib/src/downloader/download-query.h @@ -17,7 +17,6 @@ class DownloadQuery explicit DownloadQuery(Site *site, QString filename, QString path); // Serialization - virtual QString toString(const QString &separator) const = 0; virtual void write(QJsonObject &json) const = 0; virtual bool read(const QJsonObject &json, const QMap &sites) = 0; From a94dcc05ade842a1274b2ef415e7a53e5ce66d2c Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 22 Jul 2018 18:51:32 +0200 Subject: [PATCH 094/112] Update issue templates --- .github/ISSUE_TEMPLATE.md | 22 --------------- .github/ISSUE_TEMPLATE/bug-report.md | 33 +++++++++++++++++++++++ .github/ISSUE_TEMPLATE/crash-report.md | 28 +++++++++++++++++++ .github/ISSUE_TEMPLATE/feature-request.md | 16 +++++++++++ 4 files changed, 77 insertions(+), 22 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .github/ISSUE_TEMPLATE/bug-report.md create mode 100644 .github/ISSUE_TEMPLATE/crash-report.md create mode 100644 .github/ISSUE_TEMPLATE/feature-request.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 5735fe790..000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,22 +0,0 @@ -### What steps will reproduce the problem? - - - - -### What is the expected behavior? What do you get instead? - - - - -### How often does this problem occur? On which sources? - - - - -### What version of the program are you using? On what operating system? - - - - -### Please provide any additional information below - diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 000000000..f62dce109 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve +--- + +**Bug description** +A clear and concise description of what the bug is. + +**Steps to reproduce** +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Context** +* Provide your `main.log` file to see if any obvious error occured. +* Providing your `settings.ini` file will greatly help maintainers reproduce your problem if it may be caused by your configuration. +* If the bug occured during a download, make sure to provide said download as an `.igl` file that Grabber can generate by clicking the `Save` button of the `Downloads` tab. + +Note that both `main.log` and `settings.ini` files can be found in `C:/Users/%USERNAME%/AppData/Local/Bionus/Grabber` in Windows, and in the installation directory on Linux. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**System information** +- OS: [e.g. Windows 10] +- Grabber version: [e.g. 6.0.3] + +**Additional context** +Add any other context about the bug report here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/crash-report.md b/.github/ISSUE_TEMPLATE/crash-report.md new file mode 100644 index 000000000..b79e67acb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/crash-report.md @@ -0,0 +1,28 @@ +--- +name: Crash report +about: Create a report to help us improve +--- + +**Steps to reproduce** +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Context** +* Provide your `main.log` file to see if any obvious error occured. +* Providing your `settings.ini` file will greatly help maintainers reproduce your problem if it may be caused by your configuration. +* If the crash occured during a download, make sure to provide said download as an `.igl` file that Grabber can generate by clicking the `Save` button of the `Downloads` tab. +* Provide the crash dump that was linked by the Crash Reporter tool. + +Note that both `main.log` and `settings.ini` files can be found in `C:/Users/%USERNAME%/AppData/Local/Bionus/Grabber` in Windows, and in the installation directory on Linux. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**System information** +- OS: [e.g. Windows 10] +- Grabber version: [e.g. 6.0.3] + +**Additional context** +Add any other context about the crash report here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md new file mode 100644 index 000000000..b2ac4c41c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.md @@ -0,0 +1,16 @@ +--- +name: Feature request +about: Suggest an idea for this project +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. \ No newline at end of file From db4999ba54a980e07c118533a520767a979aec9b Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 24 Jul 2018 00:40:07 +0200 Subject: [PATCH 095/112] Coding style fixes --- gui/src/batch/adduniquewindow.h | 2 +- gui/src/batch/batchwindow.cpp | 10 +-- gui/src/crashhandler/crashhandler.cpp | 12 ++-- gui/src/crashhandler/crashhandler.h | 6 +- gui/src/main/main.cpp | 30 ++++----- gui/src/mainwindow.cpp | 67 ++++++++++--------- gui/src/mainwindow.h | 16 ++--- gui/src/settings/filenamewindow.cpp | 2 +- gui/src/settings/optionswindow.cpp | 6 +- gui/src/sources/sitewindow.cpp | 4 +- gui/src/sources/sourcessettingswindow.cpp | 4 +- gui/src/sources/sourcessettingswindow.h | 2 +- gui/src/tabs/favorites-tab.cpp | 6 +- gui/src/tabs/favorites-tab.h | 2 +- gui/src/tabs/pool-tab.cpp | 6 +- gui/src/tabs/pool-tab.h | 2 +- gui/src/tabs/search-tab.cpp | 22 +++--- gui/src/tabs/search-tab.h | 6 +- gui/src/tabs/tag-tab.h | 2 +- gui/src/threads/image-loader-queue.cpp | 2 +- gui/src/threads/image-loader.cpp | 2 +- gui/src/ui/QAffiche.cpp | 14 ++-- gui/src/ui/QBouton.cpp | 16 ++--- gui/src/ui/textedit.cpp | 8 +-- gui/src/ui/verticalscrollarea.cpp | 2 +- gui/src/ui/verticalscrollarea.h | 2 +- .../utils/blacklist-fix/blacklist-fix-2.cpp | 6 +- .../utils/empty-dirs-fix/empty-dirs-fix-1.cpp | 8 +-- .../rename-existing/rename-existing-1.cpp | 3 +- gui/src/viewer/zoom-window.cpp | 10 +-- lib/src/commands/commands.cpp | 8 +-- lib/src/commands/sql-worker.cpp | 2 +- lib/src/downloader/download-query-group.cpp | 18 ++--- lib/src/downloader/download-query-group.h | 4 +- lib/src/downloader/download-query-image.cpp | 6 +- lib/src/downloader/downloader.cpp | 6 +- lib/src/functions.cpp | 8 ++- lib/src/functions.cpp~RF155d15f.TMP | 8 ++- lib/src/functions.h | 2 +- lib/src/loader/downloadable.cpp | 3 +- lib/src/logger.cpp | 8 +-- lib/src/logger.h | 10 +-- lib/src/models/favorite.cpp | 8 +-- lib/src/models/favorite.h | 4 +- lib/src/models/filename.cpp | 4 +- lib/src/models/filename.h | 2 +- lib/src/models/filtering/filter.h | 2 +- lib/src/models/filtering/meta-filter.cpp | 24 +++---- lib/src/models/filtering/meta-filter.h | 2 +- lib/src/models/filtering/tag-filter.h | 2 +- lib/src/models/filtering/token-filter.cpp | 2 +- lib/src/models/filtering/token-filter.h | 2 +- lib/src/models/image.cpp | 11 +-- lib/src/models/page-api.cpp | 5 +- lib/src/models/site.cpp | 16 ++--- lib/src/models/source-guesser.cpp | 2 +- lib/src/tags/tag-api.cpp | 3 +- lib/src/vendor/html-entities.cpp | 29 ++++---- lib/src/vendor/qcustomnetworkreply.cpp | 48 ++++++------- 59 files changed, 272 insertions(+), 257 deletions(-) diff --git a/gui/src/batch/adduniquewindow.h b/gui/src/batch/adduniquewindow.h index 9decaf486..3bbb80833 100644 --- a/gui/src/batch/adduniquewindow.h +++ b/gui/src/batch/adduniquewindow.h @@ -29,7 +29,7 @@ class AddUniqueWindow : public QDialog void ok(bool close = true); void replyFinished(Page *p); void addLoadedImage(); - void addImage(const QSharedPointer& img); + void addImage(const QSharedPointer &img); void on_buttonFolder_clicked(); void on_lineFilename_textChanged(const QString &); diff --git a/gui/src/batch/batchwindow.cpp b/gui/src/batch/batchwindow.cpp index bdbd5ddac..75f68a546 100644 --- a/gui/src/batch/batchwindow.cpp +++ b/gui/src/batch/batchwindow.cpp @@ -265,7 +265,7 @@ void batchWindow::statusImage(const QUrl &url, int percent) { const int i = indexOf(url); if (i != -1) - ui->tableWidget->item(i, 5)->setText(QString::number(percent)+" %"); + ui->tableWidget->item(i, 5)->setText(QString::number(percent) + " %"); } void batchWindow::speedImage(const QUrl &url, double speed) { @@ -274,7 +274,7 @@ void batchWindow::speedImage(const QUrl &url, double speed) int i = indexOf(url); if (i != -1) - ui->tableWidget->item(i, 4)->setText(QLocale::system().toString(speed, 'f', speed < 10 ? 2 : 0)+" "+unit); + ui->tableWidget->item(i, 4)->setText(QLocale::system().toString(speed, 'f', speed < 10 ? 2 : 0) + " " + unit); drawSpeed(); } @@ -285,7 +285,7 @@ void batchWindow::sizeImage(const QUrl &url, double size) { const QString unit = getUnit(&size); const QString label = size > 0 - ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0) + " "+unit + ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0) + " " + unit : QString(); ui->tableWidget->item(i, 3)->setText(label); } @@ -355,7 +355,7 @@ void batchWindow::drawSpeed() { for (int i = m_mean.count() - count; i < m_mean.count() - 1; i++) { speedMean += m_mean[i]; } - speedMean = static_cast(speedMean/count); + speedMean = static_cast(speedMean / count); } const QString unitMean = getUnit(&speedMean) + "/s"; @@ -367,7 +367,7 @@ void batchWindow::drawSpeed() const QString fElapsed = elapsed > 3600000 ? tr("h 'h' m 'm' s 's'") : (elapsed > 60000 ? tr("m 'm' s 's'") : tr("s 's'")); const QString fRemaining = remaining > 3600000 ? tr("h 'h' m 'm' s 's'") : (remaining > 60000 ? tr("m 'm' s 's'") : tr("s 's'")); - ui->labelSpeed->setText(QLocale::system().toString(speed, 'f', speed < 10 ? 2 : 0)+" "+unit); + ui->labelSpeed->setText(QLocale::system().toString(speed, 'f', speed < 10 ? 2 : 0) + " " + unit); ui->labelSpeed->setToolTip(tr("Average speed: %1 %2

    Elapsed time: %3
    Remaining time: %4").arg(QLocale::system().toString(speedMean, 'f', speedMean < 10 ? 2 : 0), unitMean, tElapsed.toString(fElapsed), tRemaining.toString(fRemaining))); } diff --git a/gui/src/crashhandler/crashhandler.cpp b/gui/src/crashhandler/crashhandler.cpp index de58dff47..be88ae19a 100644 --- a/gui/src/crashhandler/crashhandler.cpp +++ b/gui/src/crashhandler/crashhandler.cpp @@ -26,12 +26,12 @@ class CrashHandlerPrivate public: CrashHandlerPrivate() { pHandler = NULL; } ~CrashHandlerPrivate() { delete pHandler; } - void InitCrashHandler(const QString& dumpPath); - static google_breakpad::ExceptionHandler* pHandler; + void InitCrashHandler(const QString &dumpPath); + static google_breakpad::ExceptionHandler *pHandler; static bool bReportCrashesToSystem; }; -google_breakpad::ExceptionHandler* CrashHandlerPrivate::pHandler = NULL; +google_breakpad::ExceptionHandler *CrashHandlerPrivate::pHandler = NULL; bool CrashHandlerPrivate::bReportCrashesToSystem = false; @@ -71,7 +71,7 @@ bool DumpCallback(const char* _dump_dir,const char* _minidump_id,void *context, QFile f(savePath("lastdump")); if (f.open(QFile::WriteOnly)) { - f.write(QDir::toNativeSeparators(dir+"/"+mid+".dmp").toLatin1()); + f.write(QDir::toNativeSeparators(dir + "/" + mid + ".dmp").toLatin1()); f.close(); } } @@ -126,7 +126,7 @@ void CrashHandlerPrivate::InitCrashHandler(const QString& dumpPath) /* CrashHandler */ /************************************************************************/ -CrashHandler* CrashHandler::instance() +CrashHandler *CrashHandler::instance() { static CrashHandler globalHandler; return &globalHandler; @@ -151,7 +151,7 @@ bool CrashHandler::writeMinidump() return res; } -void CrashHandler::Init( const QString& reportPath ) +void CrashHandler::Init( const QString &reportPath ) { d->InitCrashHandler(reportPath); } #endif diff --git a/gui/src/crashhandler/crashhandler.h b/gui/src/crashhandler/crashhandler.h index fed5dff6f..2a544ad0f 100644 --- a/gui/src/crashhandler/crashhandler.h +++ b/gui/src/crashhandler/crashhandler.h @@ -9,8 +9,8 @@ class CrashHandlerPrivate; class CrashHandler { public: - static CrashHandler* instance(); - void Init(const QString& reportPath); + static CrashHandler *instance(); + void Init(const QString &reportPath); void setReportCrashesToSystem(bool report); bool writeMinidump(); @@ -18,7 +18,7 @@ class CrashHandler CrashHandler(); ~CrashHandler(); Q_DISABLE_COPY(CrashHandler) - CrashHandlerPrivate* d; + CrashHandlerPrivate *d; }; #endif // CRASHHANDLER_H diff --git a/gui/src/main/main.cpp b/gui/src/main/main.cpp index 3e22e86af..76b3d3af5 100644 --- a/gui/src/main/main.cpp +++ b/gui/src/main/main.cpp @@ -155,21 +155,21 @@ int main(int argc, char *argv[]) if (!gui) { Downloader *dwnldr = new Downloader(profile, - parser.value(tagsOption).split(" ", QString::SkipEmptyParts), - parser.value(postfilteringOption).split(" ", QString::SkipEmptyParts), - profile->getFilteredSites(parser.value(sourceOption).split(" ", QString::SkipEmptyParts)), - parser.value(pageOption).toInt(), - parser.value(limitOption).toInt(), - parser.value(perpageOption).toInt(), - parser.value(pathOption), - parser.value(filenameOption), - parser.value(userOption), - parser.value(passwordOption), - parser.isSet(blacklistOption), - profile->getBlacklist(), - parser.isSet(noDuplicatesOption), - parser.value(tagsMinOption).toInt(), - parser.value(tagsFormatOption)); + parser.value(tagsOption).split(" ", QString::SkipEmptyParts), + parser.value(postfilteringOption).split(" ", QString::SkipEmptyParts), + profile->getFilteredSites(parser.value(sourceOption).split(" ", QString::SkipEmptyParts)), + parser.value(pageOption).toInt(), + parser.value(limitOption).toInt(), + parser.value(perpageOption).toInt(), + parser.value(pathOption), + parser.value(filenameOption), + parser.value(userOption), + parser.value(passwordOption), + parser.isSet(blacklistOption), + profile->getBlacklist(), + parser.isSet(noDuplicatesOption), + parser.value(tagsMinOption).toInt(), + parser.value(tagsFormatOption)); if (parser.isSet(returnCountOption)) dwnldr->getPageCount(); diff --git a/gui/src/mainwindow.cpp b/gui/src/mainwindow.cpp index f988a01dc..e697a61af 100644 --- a/gui/src/mainwindow.cpp +++ b/gui/src/mainwindow.cpp @@ -527,7 +527,8 @@ void mainWindow::tabClosed(searchTab *tab) QJsonObject obj; tab->write(obj); m_closedTabs.append(obj); - if (m_closedTabs.count() > CLOSED_TAB_HISTORY_MAX) { + if (m_closedTabs.count() > CLOSED_TAB_HISTORY_MAX) + { m_closedTabs.removeFirst(); } ui->actionRestoreLastClosedTab->setEnabled(true); @@ -692,7 +693,7 @@ void mainWindow::saveFolder() { QString path = m_settings->value("Save/path").toString().replace("\\", "/"); if (path.right(1) == "/") - { path = path.left(path.length()-1); } + { path = path.left(path.length() - 1); } QDir dir(path); if (dir.exists()) { showInGraphicalShell(path); } @@ -820,7 +821,7 @@ void mainWindow::batchMove(int diff) selection.select(index, index); } - auto* selectionModel = new QItemSelectionModel(ui->tableBatchGroups->model(), this); + auto *selectionModel = new QItemSelectionModel(ui->tableBatchGroups->model(), this); selectionModel->select(selection, QItemSelectionModel::ClearAndSelect); ui->tableBatchGroups->setSelectionModel(selectionModel); } @@ -887,7 +888,7 @@ void mainWindow::updateBatchGroups(int y, int x) } } -Site* mainWindow::getSelectedSiteOrDefault() +Site *mainWindow::getSelectedSiteOrDefault() { if (m_selectedSites.isEmpty()) return m_profile->getSites().first(); @@ -1002,7 +1003,7 @@ void mainWindow::logClear() void mainWindow::logOpen() { QDesktopServices::openUrl("file:///" + m_profile->getPath() + "/main.log"); } -void mainWindow::loadLanguage(const QString& rLanguage, bool quiet) +void mainWindow::loadLanguage(const QString &rLanguage, bool quiet) { if (m_currLang != rLanguage) { @@ -1010,8 +1011,8 @@ void mainWindow::loadLanguage(const QString& rLanguage, bool quiet) QLocale locale = QLocale(m_currLang); QLocale::setDefault(locale); - m_translator.load(savePath("languages/"+m_currLang+".qm", true)); - m_qtTranslator.load(savePath("languages/qt/"+m_currLang+".qm", true)); + m_translator.load(savePath("languages/" + m_currLang + ".qm", true)); + m_qtTranslator.load(savePath("languages/qt/" + m_currLang + ".qm", true)); if (!quiet) { @@ -1023,7 +1024,7 @@ void mainWindow::loadLanguage(const QString& rLanguage, bool quiet) } // Update interface language -void mainWindow::changeEvent(QEvent* event) +void mainWindow::changeEvent(QEvent *event) { // Translation if (event->type() == QEvent::LocaleChange) @@ -1130,7 +1131,7 @@ void mainWindow::options() void mainWindow::optionsClosed() { - for (searchTab* tab : m_tabs) + for (searchTab *tab : m_tabs) { tab->optionsChanged(); tab->updateCheckboxes(); @@ -1381,22 +1382,22 @@ void mainWindow::getAllFinishedLogins() for (int i = 0; i < packs; ++i) { Downloader *downloader = new Downloader(m_profile, - b.tags.split(' '), - b.postFiltering, - QList() << b.site, - b.page + i * pagesPerPack, - (i == packs - 1 ? lastPageImages : imagesPerPack), - b.perpage, - b.path, - b.filename, - nullptr, - nullptr, - b.getBlacklisted, - m_profile->getBlacklist(), - false, - 0, - "", - previous); + b.tags.split(' '), + b.postFiltering, + QList() << b.site, + b.page + i * pagesPerPack, + (i == packs - 1 ? lastPageImages : imagesPerPack), + b.perpage, + b.path, + b.filename, + nullptr, + nullptr, + b.getBlacklisted, + m_profile->getBlacklist(), + false, + 0, + "", + previous); downloader->setData(j.key()); downloader->setQuit(false); @@ -1757,7 +1758,7 @@ void mainWindow::getAllProgress(const QSharedPointer &img, qint64 bytesRe } int percent = 0; - if (bytesTotal> 0) + if (bytesTotal > 0) { const qreal pct = static_cast(bytesReceived) / static_cast(bytesTotal); percent = qFloor(pct * 100); @@ -1818,7 +1819,7 @@ void mainWindow::getAllPerformTags() m_progressDialog->loadedImage(img->url(), Image::SaveResult::AlreadyExists); if (siteId >= 0) { - m_progressBars[siteId - 1]->setValue(m_progressBars[siteId - 1]->value()+1); + m_progressBars[siteId - 1]->setValue(m_progressBars[siteId - 1]->value() + 1); if (m_progressBars[siteId - 1]->value() >= m_progressBars[siteId - 1]->maximum()) { ui->tableBatchGroups->item(row, 0)->setIcon(getIcon(":/images/status/ok.png")); } } @@ -2193,7 +2194,7 @@ bool mainWindow::loadLinkList(const QString &filename) { ui->tableBatchGroups->setRowCount(ui->tableBatchGroups->rowCount() + 1); QString last = queryGroup.unk; - int max = last.rightRef(last.indexOf("/")+1).toInt(), val = last.leftRef(last.indexOf("/")).toInt(); + int max = last.rightRef(last.indexOf("/") + 1).toInt(), val = last.leftRef(last.indexOf("/")).toInt(); int row = ui->tableBatchGroups->rowCount() - 1; addTableItem(ui->tableBatchGroups, row, 1, queryGroup.tags); @@ -2208,7 +2209,7 @@ bool mainWindow::loadLinkList(const QString &filename) queryGroup.unk = "true"; m_groupBatchs.append(queryGroup); - QTableWidgetItem *it = new QTableWidgetItem(getIcon(":/images/status/"+QString(val == max ? "ok" : (val > 0 ? "downloading" : "pending"))+".png"), ""); + QTableWidgetItem *it = new QTableWidgetItem(getIcon(":/images/status/" + QString(val == max ? "ok" : (val > 0 ? "downloading" : "pending")) + ".png"), ""); it->setFlags(it->flags() ^ Qt::ItemIsEditable); it->setTextAlignment(Qt::AlignCenter); ui->tableBatchGroups->setItem(row, 0, it); @@ -2256,7 +2257,7 @@ void mainWindow::siteDeleted(Site *site) batchRemoveUniques(uniquesRows); } -QIcon& mainWindow::getIcon(const QString &path) +QIcon &mainWindow::getIcon(const QString &path) { if (!m_icons.contains(path)) m_icons.insert(path, QIcon(path)); @@ -2426,7 +2427,7 @@ void mainWindow::trayClose() void mainWindow::dragEnterEvent(QDragEnterEvent *event) { - const QMimeData* mimeData = event->mimeData(); + const QMimeData *mimeData = event->mimeData(); // Drop a text containing an URL if (mimeData->hasText()) @@ -2456,9 +2457,9 @@ void mainWindow::dragEnterEvent(QDragEnterEvent *event) } } -void mainWindow::dropEvent(QDropEvent* event) +void mainWindow::dropEvent(QDropEvent *event) { - const QMimeData* mimeData = event->mimeData(); + const QMimeData *mimeData = event->mimeData(); // Drop a text containing an URL if (mimeData->hasText()) diff --git a/gui/src/mainwindow.h b/gui/src/mainwindow.h index 07579045b..c82005d26 100644 --- a/gui/src/mainwindow.h +++ b/gui/src/mainwindow.h @@ -61,8 +61,8 @@ class mainWindow : public QMainWindow void renameExisting(); void utilTagLoader(); // Language - void loadLanguage(const QString&, bool quiet = false); - void changeEvent(QEvent*) override; + void loadLanguage(const QString &, bool quiet = false); + void changeEvent(QEvent *) override; // Favorites void updateFavorites(); void updateKeepForLater(); @@ -80,13 +80,13 @@ class mainWindow : public QMainWindow void updateBatchGroups(int, int); void addGroup(); void addUnique(); - void batchAddGroup(const DownloadQueryGroup& values); + void batchAddGroup(const DownloadQueryGroup &values); void updateGroupCount(); void batchAddUnique(const DownloadQueryImage &query, bool save = true); // Batch download void getAll(bool all = true); void getAllFinishedPage(Page *page); - void getAllFinishedImages(const QList > &images); + void getAllFinishedImages(const QList> &images); void getAllImages(); void getAllGetImage(const BatchDownloadImage &download, int siteId); void getAllGetImageSaved(const QSharedPointer &img, QMap result); @@ -131,7 +131,7 @@ class mainWindow : public QMainWindow void trayMessageClicked(); void trayClose(); // Others - void closeEvent(QCloseEvent*) override; + void closeEvent(QCloseEvent *) override; void onFirstLoad(); void init(const QStringList &args, const QMap ¶ms); void parseArgs(const QStringList &args, const QMap ¶ms); @@ -148,19 +148,19 @@ class mainWindow : public QMainWindow void setSource(const QString &site); void setTags(const QList &tags, searchTab *from = nullptr); void initialLoginsFinished(); - QIcon& getIcon(const QString &path); + QIcon &getIcon(const QString &path); void setWiki(const QString &wiki, searchTab *from = nullptr); void siteDeleted(Site *site); // Drag & drop void dragEnterEvent(QDragEnterEvent *event) override; - void dropEvent(QDropEvent* event) override; + void dropEvent(QDropEvent *event) override; protected: int getRowForSite(int siteId); void getAllGetImageIfNotBlacklisted(const BatchDownloadImage &download, int siteId); void getAllImageOk(const BatchDownloadImage &download, int siteId, bool retry = false); - Site* getSelectedSiteOrDefault(); + Site *getSelectedSiteOrDefault(); void initialLoginsDone(); void addTableItem(QTableWidget *table, int row, int col, const QString &text); diff --git a/gui/src/settings/filenamewindow.cpp b/gui/src/settings/filenamewindow.cpp index 8905c073d..4731b7b19 100644 --- a/gui/src/settings/filenamewindow.cpp +++ b/gui/src/settings/filenamewindow.cpp @@ -85,7 +85,7 @@ void FilenameWindow::on_lineClassic_textChanged(QString text) pos += date.matchedLength(); } - QString value = "'"+text.replace(QRegularExpression("%([^%]+)%"), "' + \\1 + '").remove(" + '' + ").trimmed()+"'"; + QString value = "'" + text.replace(QRegularExpression("%([^%]+)%"), "' + \\1 + '").remove(" + '' + ").trimmed() + "'"; if (value.startsWith("' + ")) { value = value.right(value.length() - 4); } if (value.startsWith("'' + ")) diff --git a/gui/src/settings/optionswindow.cpp b/gui/src/settings/optionswindow.cpp index 10dbf5273..44144fbcd 100644 --- a/gui/src/settings/optionswindow.cpp +++ b/gui/src/settings/optionswindow.cpp @@ -53,8 +53,8 @@ optionsWindow::optionsWindow(Profile *profile, QWidget *parent) ui->checkGetUnloadedPages->setChecked(settings->value("getunloadedpages", false).toBool()); ui->checkInvertToggle->setChecked(settings->value("invertToggle", false).toBool()); ui->checkConfirmClose->setChecked(settings->value("confirm_close", true).toBool()); - QList checkForUpdates = QList() << 0 << 24*60*60 << 7*24*60*60 << 30*24*60*60 << -1; - ui->comboCheckForUpdates->setCurrentIndex(checkForUpdates.indexOf(settings->value("check_for_updates", 24*60*60).toInt())); + QList checkForUpdates = QList() << 0 << 24 * 60 * 60 << 7 * 24 * 60 * 60 << 30 * 24 * 60 * 60 << -1; + ui->comboCheckForUpdates->setCurrentIndex(checkForUpdates.indexOf(settings->value("check_for_updates", 24 * 60 * 60).toInt())); ui->spinImagesPerPage->setValue(settings->value("limit", 20).toInt()); ui->spinColumns->setValue(settings->value("columns", 1).toInt()); @@ -772,7 +772,7 @@ void optionsWindow::on_lineImageBackgroundColor_textChanged() void optionsWindow::on_buttonImageBackgroundColor_clicked() { setColor(ui->lineImageBackgroundColor, true); } -void treeWidgetRec(int depth, bool& found, int& index, QTreeWidgetItem *current, QTreeWidgetItem *sel) +void treeWidgetRec(int depth, bool &found, int &index, QTreeWidgetItem *current, QTreeWidgetItem *sel) { if (current == sel) { diff --git a/gui/src/sources/sitewindow.cpp b/gui/src/sources/sitewindow.cpp index 332275313..27d270680 100644 --- a/gui/src/sources/sitewindow.cpp +++ b/gui/src/sources/sitewindow.cpp @@ -112,7 +112,7 @@ void SiteWindow::finish(Source *src) // Save new sites QFile f(src->getPath() + "/sites.txt"); f.open(QIODevice::ReadOnly); - QString sites = f.readAll(); + QString sites = f.readAll(); f.close(); sites.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\r\n"); QStringList stes = sites.split("\r\n", QString::SkipEmptyParts); @@ -120,7 +120,7 @@ void SiteWindow::finish(Source *src) stes.removeDuplicates(); stes.sort(); f.open(QIODevice::WriteOnly); - f.write(stes.join("\r\n").toLatin1()); + f.write(stes.join("\r\n").toLatin1()); f.close(); m_profile->addSite(site); diff --git a/gui/src/sources/sourcessettingswindow.cpp b/gui/src/sources/sourcessettingswindow.cpp index f8d5034bb..9943c7b47 100644 --- a/gui/src/sources/sourcessettingswindow.cpp +++ b/gui/src/sources/sourcessettingswindow.cpp @@ -164,13 +164,13 @@ void SourcesSettingsWindow::deleteSite() { QFile f(m_site->getSource()->getPath() + "/sites.txt"); f.open(QIODevice::ReadOnly); - QString sites = f.readAll(); + QString sites = f.readAll(); f.close(); sites.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\r\n"); QStringList stes = sites.split("\r\n", QString::SkipEmptyParts); stes.removeAll(m_site->url()); f.open(QIODevice::WriteOnly); - f.write(stes.join("\r\n").toLatin1()); + f.write(stes.join("\r\n").toLatin1()); f.close(); close(); emit siteDeleted(m_site->url()); diff --git a/gui/src/sources/sourcessettingswindow.h b/gui/src/sources/sourcessettingswindow.h index 9ccdc4198..60b2afc2d 100644 --- a/gui/src/sources/sourcessettingswindow.h +++ b/gui/src/sources/sourcessettingswindow.h @@ -18,7 +18,7 @@ class SourcesSettingsWindow : public QDialog Q_OBJECT public: - explicit SourcesSettingsWindow(Profile *profile, Site* site, QWidget *parent = nullptr); + explicit SourcesSettingsWindow(Profile *profile, Site *site, QWidget *parent = nullptr); ~SourcesSettingsWindow() override; public slots: diff --git a/gui/src/tabs/favorites-tab.cpp b/gui/src/tabs/favorites-tab.cpp index 630e7bcad..a36497176 100644 --- a/gui/src/tabs/favorites-tab.cpp +++ b/gui/src/tabs/favorites-tab.cpp @@ -142,7 +142,7 @@ void favoritesTab::updateFavorites() int maxNewImages = 0; bool precise = true; - for (const Monitor& monitor : qAsConst(fav.getMonitors())) + for (const Monitor &monitor : qAsConst(fav.getMonitors())) { if (monitor.cumulated() > maxNewImages) { @@ -177,7 +177,7 @@ void favoritesTab::updateFavorites() { label += QStringLiteral(" (%1%2)").arg(maxNewImages).arg(!precise ? "+" : QString()); } } if (display.contains("d")) - { label += "
    ("+QString::number(fav.getNote())+" % - "+fav.getLastViewed().toString(format)+")"; } + { label += "
    (" + QString::number(fav.getNote()) + " % - " + fav.getLastViewed().toString(format) + ")"; } QAffiche *caption = new QAffiche(fav.getName(), 0, QColor(), this); caption->setText(label); @@ -250,7 +250,7 @@ void favoritesTab::getPage() for (int i = 0; i < actuals.count(); i++) { const auto &page = m_pages[actuals[i]].first(); - const QString search = m_currentTags+" "+m_settings->value("add").toString().toLower().trimmed(); + const QString search = m_currentTags + " " + m_settings->value("add").toString().toLower().trimmed(); const int perpage = unloaded ? ui->spinImagesPerPage->value() : page->images().count(); const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); diff --git a/gui/src/tabs/favorites-tab.h b/gui/src/tabs/favorites-tab.h index d79d18e81..66bdb3923 100644 --- a/gui/src/tabs/favorites-tab.h +++ b/gui/src/tabs/favorites-tab.h @@ -47,7 +47,7 @@ class favoritesTab : public searchTab void setFavoriteViewed(const QString &tag); void viewed(); // Others - void closeEvent(QCloseEvent*) override; + void closeEvent(QCloseEvent *) override; void focusSearch() override; void addResultsPage(Page *page, const QList> &imgs, bool merged, const QString &noResultsMessage = nullptr) override; void setPageLabelText(QLabel *txt, Page *page, const QList> &imgs, const QString &noResultsMessage = nullptr) override; diff --git a/gui/src/tabs/pool-tab.cpp b/gui/src/tabs/pool-tab.cpp index 6144a9714..2b6e37636 100644 --- a/gui/src/tabs/pool-tab.cpp +++ b/gui/src/tabs/pool-tab.cpp @@ -85,7 +85,7 @@ void poolTab::load() // Get the search values QString search = m_search->toPlainText(); QStringList tags = search.trimmed().split(" ", QString::SkipEmptyParts); - tags.prepend("pool:"+QString::number(ui->spinPool->value())); + tags.prepend("pool:" + QString::number(ui->spinPool->value())); loadTags(tags); } @@ -143,7 +143,7 @@ void poolTab::getPage() const bool unloaded = m_settings->value("getunloadedpages", false).toBool(); const int perPage = unloaded ? ui->spinImagesPerPage->value() : page->images().count(); - const QString tags = "pool:"+QString::number(ui->spinPool->value())+" "+m_search->toPlainText()+" "+m_settings->value("add").toString().trimmed(); + const QString tags = "pool:" + QString::number(ui->spinPool->value()) + " " + m_search->toPlainText() + " " + m_settings->value("add").toString().trimmed(); const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); Site *site = m_sites.value(ui->comboSites->currentText()); @@ -161,7 +161,7 @@ void poolTab::getAll() if ((perPage == 0 && total == 0) || (currentCount == 0 && imageCount <= 0)) return; - const QString search = "pool:"+QString::number(ui->spinPool->value())+" "+m_search->toPlainText()+" "+m_settings->value("add").toString().trimmed(); + const QString search = "pool:" + QString::number(ui->spinPool->value()) + " " + m_search->toPlainText() + " " + m_settings->value("add").toString().trimmed(); const QStringList postFiltering = m_postFiltering->toPlainText().split(' ', QString::SkipEmptyParts); Site *site = m_sites.value(ui->comboSites->currentText()); diff --git a/gui/src/tabs/pool-tab.h b/gui/src/tabs/pool-tab.h index e3b6669fc..e9c3c936f 100644 --- a/gui/src/tabs/pool-tab.h +++ b/gui/src/tabs/pool-tab.h @@ -40,7 +40,7 @@ class poolTab : public searchTab void getPage(); void getAll(); // Others - void closeEvent(QCloseEvent*) override; + void closeEvent(QCloseEvent *) override; void on_buttonSearch_clicked(); void setSite(const QString &site); void focusSearch() override; diff --git a/gui/src/tabs/search-tab.cpp b/gui/src/tabs/search-tab.cpp index f6f93f136..a76b282b8 100644 --- a/gui/src/tabs/search-tab.cpp +++ b/gui/src/tabs/search-tab.cpp @@ -163,7 +163,7 @@ void searchTab::setTagsFromPages(const QMap> m_parent->setTags(m_tags, this); } -QStringList searchTab::reasonsToFail(Page* page, const QStringList &completion, QString *meant) +QStringList searchTab::reasonsToFail(Page *page, const QStringList &completion, QString *meant) { QStringList reasons = QStringList(); @@ -203,7 +203,7 @@ QStringList searchTab::reasonsToFail(Page* page, const QStringList &completion, { if (results[tag].isEmpty()) { c++; } - results[tag] = ""+comp+""; + results[tag] = "" + comp + ""; clean[tag] = comp; lev = d; } @@ -318,7 +318,7 @@ void searchTab::setEndlessLoadingMode(bool enabled) m_endlessLoadingEnabled = enabled; } -void searchTab::finishedLoading(Page* page) +void searchTab::finishedLoading(Page *page) { if (m_stop) return; @@ -753,7 +753,7 @@ void searchTab::setMergedLabelText(QLabel *txt, const QListurl().toString().toHtmlEscaped()+"\">"+p->site()->name()+""; + links += QString(!links.isEmpty() ? ", " : QString()) + "url().toString().toHtmlEscaped() + "\">" + p->site()->name() + ""; } } @@ -804,7 +804,7 @@ void searchTab::setPageLabelText(QLabel *txt, Page *page, const QListmaxImagesCount() == -1 ? "?" : tr("max %1").arg(page->maxImagesCount())); const QString countLabel = tr("Page %1 of %2 (%3 of %4)").arg(pageLabel, pageCountStr).arg(totalCount).arg(imageCountStr); - txt->setText("url().toString().toHtmlEscaped()+"\">"+page->site()->name()+" - " + countLabel); + txt->setText("url().toString().toHtmlEscaped() + "\">" + page->site()->name() + " - " + countLabel); } /*if (page->search().join(" ") != m_search->toPlainText() && m_settings->value("showtagwarning", true).toBool()) @@ -823,7 +823,7 @@ void searchTab::setPageLabelText(QLabel *txt, Page *page, const QListerrors().isEmpty() && m_settings->value("showwarnings", true).toBool()) { - txt->setText(txt->text()+"
    "+page->errors().join("
    ")); + txt->setText(txt->text() + "
    " + page->errors().join("
    ")); } } @@ -858,7 +858,7 @@ QBouton *searchTab::createImageThumbnail(int position, const QSharedPointer &image) ZoomWindow *zoom = new ZoomWindow(m_images, image, image->page()->site(), m_profile, m_parent); connect(zoom, SIGNAL(linkClicked(QString)), this, SLOT(setTags(QString))); - connect(zoom, SIGNAL(poolClicked(int,QString)), m_parent, SLOT(addPoolTab(int,QString))); + connect(zoom, SIGNAL(poolClicked(int, QString)), m_parent, SLOT(addPoolTab(int, QString))); zoom->show(); m_lastZoomWindow = zoom; @@ -1435,7 +1435,7 @@ bool searchTab::validateImage(const QSharedPointer &img, QString &error) QStringList detected = m_profile->getBlacklist().match(img->tokens(m_profile)); if (!detected.isEmpty() && m_settings->value("hideblacklisted", false).toBool()) { - error = QStringLiteral("Image #%1 ignored. Reason: %2.").arg(img->id()).arg("\""+detected.join(", ")+"\""); + error = QStringLiteral("Image #%1 ignored. Reason: %2.").arg(img->id()).arg("\"" + detected.join(", ") + "\""); return false; } diff --git a/gui/src/tabs/search-tab.h b/gui/src/tabs/search-tab.h index 6233a0026..7684c71d7 100644 --- a/gui/src/tabs/search-tab.h +++ b/gui/src/tabs/search-tab.h @@ -54,7 +54,7 @@ class searchTab : public QWidget protected: void setSelectedSources(QSettings *settings); - void setTagsFromPages(const QMap > > &pages); + void setTagsFromPages(const QMap>> &pages); void addHistory(const QString &tags, int page, int ipp, int cols); QStringList reasonsToFail(Page *page, const QStringList &completion = QStringList(), QString *meant = nullptr); void clear(); @@ -108,14 +108,14 @@ class searchTab : public QWidget void addResultsImage(const QSharedPointer &img, Page *page, bool merge = false); void finishedLoadingPreview(); // Merged - QList> mergeResults(int page, const QList > &results); + QList> mergeResults(int page, const QList> &results); void addMergedMd5(int page, const QString &md5); bool containsMergedMd5(int page, const QString &md5); // Loading void finishedLoading(Page *page); void failedLoading(Page *page); void httpsRedirect(Page *page); - void postLoading(Page *page, const QList > &imgs); + void postLoading(Page *page, const QList> &imgs); void finishedLoadingTags(Page *page); // Image selection void selectImage(const QSharedPointer &img); diff --git a/gui/src/tabs/tag-tab.h b/gui/src/tabs/tag-tab.h index e477db6a4..622a83143 100644 --- a/gui/src/tabs/tag-tab.h +++ b/gui/src/tabs/tag-tab.h @@ -38,7 +38,7 @@ class tagTab : public searchTab void getPage(); void getAll(); // Others - void closeEvent(QCloseEvent*) override; + void closeEvent(QCloseEvent *) override; void on_buttonSearch_clicked(); void focusSearch() override; void updateTitle() override; diff --git a/gui/src/threads/image-loader-queue.cpp b/gui/src/threads/image-loader-queue.cpp index 70e86db5a..5200900e2 100644 --- a/gui/src/threads/image-loader-queue.cpp +++ b/gui/src/threads/image-loader-queue.cpp @@ -3,7 +3,7 @@ #include "threads/image-loader.h" -ImageLoaderQueue::ImageLoaderQueue(ImageLoader *imageLoader, QObject* parent) +ImageLoaderQueue::ImageLoaderQueue(ImageLoader *imageLoader, QObject *parent) : QObject(parent), m_next(QByteArray()), m_waiting(false), m_cancelNext(false), m_hasNext(false) { connect(this, &ImageLoaderQueue::loadImage, imageLoader, &ImageLoader::load); diff --git a/gui/src/threads/image-loader.cpp b/gui/src/threads/image-loader.cpp index 341a17f7f..454f8fab8 100644 --- a/gui/src/threads/image-loader.cpp +++ b/gui/src/threads/image-loader.cpp @@ -1,7 +1,7 @@ #include "threads/image-loader.h" -ImageLoader::ImageLoader(QObject* parent) +ImageLoader::ImageLoader(QObject *parent) : QObject(parent) { } diff --git a/gui/src/ui/QAffiche.cpp b/gui/src/ui/QAffiche.cpp index 821b29556..ef9a5a6a1 100644 --- a/gui/src/ui/QAffiche.cpp +++ b/gui/src/ui/QAffiche.cpp @@ -14,9 +14,9 @@ QAffiche::QAffiche(const QVariant &id, int border, QColor color, QWidget *parent setText(QString()); } -void QAffiche::mouseDoubleClickEvent(QMouseEvent* e) +void QAffiche::mouseDoubleClickEvent(QMouseEvent *e) { - if(e->button() == Qt::LeftButton) + if (e->button() == Qt::LeftButton) { emit doubleClicked(); emit doubleClicked(m_id.toInt()); @@ -24,7 +24,7 @@ void QAffiche::mouseDoubleClickEvent(QMouseEvent* e) QLabel::mouseDoubleClickEvent(e); } -void QAffiche::mousePressEvent(QMouseEvent* e) +void QAffiche::mousePressEvent(QMouseEvent *e) { m_lastPressed = e->button(); m_pressed = e->button() == Qt::LeftButton || e->button() == Qt::MidButton; @@ -33,7 +33,7 @@ void QAffiche::mousePressEvent(QMouseEvent* e) QLabel::mousePressEvent(e); } -void QAffiche::mouseReleaseEvent(QMouseEvent* e) +void QAffiche::mouseReleaseEvent(QMouseEvent *e) { if (m_pressed && e->button() == Qt::LeftButton && hitLabel(e->pos())) { @@ -53,21 +53,21 @@ void QAffiche::mouseReleaseEvent(QMouseEvent* e) QLabel::mouseReleaseEvent(e); } -void QAffiche::enterEvent(QEvent* e) +void QAffiche::enterEvent(QEvent *e) { emit mouseOver(); emit mouseOver(m_id.toInt()); QLabel::enterEvent(e); } -void QAffiche::leaveEvent(QEvent* e) +void QAffiche::leaveEvent(QEvent *e) { emit mouseOut(); emit mouseOut(m_id.toInt()); QLabel::leaveEvent(e); } -void QAffiche::resizeEvent(QResizeEvent* e) +void QAffiche::resizeEvent(QResizeEvent *e) { QMovie *mov = movie(); if (mov != nullptr) diff --git a/gui/src/ui/QBouton.cpp b/gui/src/ui/QBouton.cpp index e443e80d3..a681f68c5 100644 --- a/gui/src/ui/QBouton.cpp +++ b/gui/src/ui/QBouton.cpp @@ -58,8 +58,8 @@ void QBouton::paintEvent(QPaintEvent *event) const int p = m_border; int x = region.x(); int y = region.y(); - int w = iconSize.width() + 2*p; - int h = iconSize.height() + 2*p; + int w = iconSize.width() + 2 * p; + int h = iconSize.height() + 2 * p; // Ignore invalid images if (w == 0 || h == 0) @@ -76,13 +76,13 @@ void QBouton::paintEvent(QPaintEvent *event) const QIcon::Mode mode = this->isChecked() ? QIcon::Selected : QIcon::Normal; if (w > h) { - icon().paint(&painter, x+p, y+p, w-2*p, w-2*p, Qt::AlignLeft | Qt::AlignTop, mode); - h = h-((h*2*p)/w)+2*p-1; + icon().paint(&painter, x + p, y + p, w - 2 * p, w - 2 * p, Qt::AlignLeft | Qt::AlignTop, mode); + h = h - ((h * 2 * p) / w) + 2 * p - 1; } else { - icon().paint(&painter, x+p, y+p, h-2*p, h-2*p, Qt::AlignLeft | Qt::AlignTop, mode); - w = w-((w*2*p)/h)+2*p-1; + icon().paint(&painter, x + p, y + p, h - 2 * p, h - 2 * p, Qt::AlignLeft | Qt::AlignTop, mode); + w = w - ((w * 2 * p) / h) + 2 * p - 1; } // Clip borders overflows @@ -92,7 +92,7 @@ void QBouton::paintEvent(QPaintEvent *event) if (m_progressMax > 0 && m_progress > 0 && m_progress != m_progressMax) { const int lineHeight = 6; - const int a = p + lineHeight/2; + const int a = p + lineHeight / 2; const qreal ratio = static_cast(m_progress) / m_progressMax; QPoint p1(qMax(x, 0) + a, qMax(y, 0) + a); @@ -111,7 +111,7 @@ void QBouton::paintEvent(QPaintEvent *event) if (p > 0 && m_penColor.isValid()) { QPen pen(m_penColor); - pen.setWidth(p*2); + pen.setWidth(p * 2); painter.setPen(pen); painter.drawRect(qMax(x, 0), qMax(y, 0), qMin(w, size().width()), qMin(h, size().height())); } diff --git a/gui/src/ui/textedit.cpp b/gui/src/ui/textedit.cpp index dd7c82b75..2e83c5adf 100644 --- a/gui/src/ui/textedit.cpp +++ b/gui/src/ui/textedit.cpp @@ -55,7 +55,7 @@ void TextEdit::doColor() const QString colorFavorites = m_profile->getSettings()->value("Coloring/Colors/favorites", "#ffc0cb").toString(); const QString styleFavorites = "color:" + colorFavorites + "; " + qFontToCss(fontFavorites); for (const Favorite &fav : m_favorites) - txt.replace(" "+fav.getName()+" ", " "+fav.getName()+" "); + txt.replace(" " + fav.getName() + " ", " " + fav.getName() + " "); // Color kept for later tags QFont fontKeptForLater; @@ -63,7 +63,7 @@ void TextEdit::doColor() const QString colorKeptForLater = m_profile->getSettings()->value("Coloring/Colors/keptForLater", "#000000").toString(); const QString styleKeptForLater = "color:" + colorKeptForLater + "; " + qFontToCss(fontKeptForLater); for (const QString &tag : m_viewItLater) - txt.replace(" "+tag+" ", " "+tag+" "); + txt.replace(" " + tag + " ", " " + tag + " "); // Color metatags static QRegularExpression regexOr(" ~([^ ]+)"), @@ -144,7 +144,7 @@ QCompleter *TextEdit::completer() const return c; } -void TextEdit::insertCompletion(const QString& completion) +void TextEdit::insertCompletion(const QString &completion) { if (c->widget() != this) return; @@ -223,7 +223,7 @@ void TextEdit::keyPressEvent(QKeyEvent *e) const bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); - if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3 || eow.contains(e->text().right(1)))) + if (!isShortcut && (hasModifier || e->text().isEmpty() || completionPrefix.length() < 3 || eow.contains(e->text().right(1)))) { c->popup()->hide(); return; diff --git a/gui/src/ui/verticalscrollarea.cpp b/gui/src/ui/verticalscrollarea.cpp index e62787e65..95f26a99c 100644 --- a/gui/src/ui/verticalscrollarea.cpp +++ b/gui/src/ui/verticalscrollarea.cpp @@ -41,7 +41,7 @@ void VerticalScrollArea::updateWidgetSize() } } -void VerticalScrollArea::wheelEvent(QWheelEvent* e) +void VerticalScrollArea::wheelEvent(QWheelEvent *e) { QScrollBar *scrollBar = verticalScrollBar(); diff --git a/gui/src/ui/verticalscrollarea.h b/gui/src/ui/verticalscrollarea.h index 3a8c49d7d..5dc582af5 100644 --- a/gui/src/ui/verticalscrollarea.h +++ b/gui/src/ui/verticalscrollarea.h @@ -14,7 +14,7 @@ class VerticalScrollArea : public QScrollArea explicit VerticalScrollArea(QWidget *parent = nullptr); void resizeEvent(QResizeEvent *event) override; void setScrollEnabled(bool enabled); - void wheelEvent(QWheelEvent* e) override; + void wheelEvent(QWheelEvent *e) override; protected: void updateWidgetSize(); diff --git a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp index e87aa7340..4585bb34f 100644 --- a/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp +++ b/gui/src/utils/blacklist-fix/blacklist-fix-2.cpp @@ -23,8 +23,8 @@ BlacklistFix2::BlacklistFix2(QList> details, Blacklist bl found = m_blacklist.match(tokens); color = found.empty() ? "green" : "red"; } - QTableWidgetItem *id = new QTableWidgetItem(QString::number(i+1)); - id->setIcon(QIcon(":/images/colors/"+color+".png")); + QTableWidgetItem *id = new QTableWidgetItem(QString::number(i + 1)); + id->setIcon(QIcon(":/images/colors/" + color + ".png")); ui->tableWidget->setItem(i, 0, id); QLabel *preview = new QLabel(); preview->setPixmap(QPixmap(m_details.at(i).value("path_full")).scaledToHeight(50, Qt::SmoothTransformation)); @@ -68,7 +68,7 @@ void BlacklistFix2::on_buttonOk_clicked() int rem = 0; for (int i : toDelete) { - QFile::remove(m_details.at(ui->tableWidget->item(i - rem, 0)->text().toInt()-1).value("path_full")); + QFile::remove(m_details.at(ui->tableWidget->item(i - rem, 0)->text().toInt() - 1).value("path_full")); ui->tableWidget->removeRow(i - rem); rem++; } diff --git a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp index 425de421f..b1f9d97c6 100644 --- a/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp +++ b/gui/src/utils/empty-dirs-fix/empty-dirs-fix-1.cpp @@ -44,10 +44,10 @@ QStringList EmptyDirsFix1::mkList(const QDir &dir) QStringList dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); for (int i = 0; i < dirs.size(); i++) { - if (isEmpty(QDir(dir.path()+"/"+dirs.at(i)))) - { ret.append(dir.path()+"/"+dirs.at(i)); } + if (isEmpty(QDir(dir.path() + "/" + dirs.at(i)))) + { ret.append(dir.path() + "/" + dirs.at(i)); } else - { mkList(QDir(dir.path()+"/"+dirs.at(i))); } + { mkList(QDir(dir.path() + "/" + dirs.at(i))); } } return ret; } @@ -61,6 +61,6 @@ bool EmptyDirsFix1::isEmpty(const QDir &dir) QStringList dirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); bool empty = true; for (int i = 0; i < dirs.size(); i++) - { empty = empty && isEmpty(QDir(dir.path()+"/"+dirs.at(i))); } + { empty = empty && isEmpty(QDir(dir.path() + "/" + dirs.at(i))); } return empty; } diff --git a/gui/src/utils/rename-existing/rename-existing-1.cpp b/gui/src/utils/rename-existing/rename-existing-1.cpp index 053789a7d..e82cb72ab 100644 --- a/gui/src/utils/rename-existing/rename-existing-1.cpp +++ b/gui/src/utils/rename-existing/rename-existing-1.cpp @@ -112,7 +112,8 @@ void RenameExisting1::on_buttonContinue_clicked() RenameExistingFile det; det.md5 = md5; det.path = QDir::toNativeSeparators(path); - if (!file.second.isEmpty()) { + if (!file.second.isEmpty()) + { QStringList children; children.reserve(file.second.count()); for (const QString &child : file.second) diff --git a/gui/src/viewer/zoom-window.cpp b/gui/src/viewer/zoom-window.cpp index 5114934dc..adf9bc056 100644 --- a/gui/src/viewer/zoom-window.cpp +++ b/gui/src/viewer/zoom-window.cpp @@ -263,7 +263,7 @@ void ZoomWindow::openPool(const QString &url) { emit poolClicked(url.rightRef(url.length() - 5).toInt(), m_image->parentSite()->url()); } else { - Page *p = new Page(m_profile, m_image->parentSite(), m_profile->getSites().values(), QStringList() << "id:"+url, 1, 1, QStringList(), false, this); + Page *p = new Page(m_profile, m_image->parentSite(), m_profile->getSites().values(), QStringList() << "id:" + url, 1, 1, QStringList(), false, this); connect(p, &Page::finishedLoading, this, &ZoomWindow::openPoolId); p->load(); } @@ -301,7 +301,7 @@ void ZoomWindow::openSaveDir(bool fav) const QString fn = m_settings->value("Save/filename" + QString(fav ? "_favorites" : "")).toString(); if (path.right(1) == "/") - { path = path.left(path.length()-1); } + { path = path.left(path.length() - 1); } path = QDir::toNativeSeparators(path); const QStringList files = m_image->path(fn, path); @@ -850,10 +850,10 @@ void ZoomWindow::saveImageNow() } const bool fav = m_pendingAction == PendingSaveFav; - QString fn = m_settings->value("Save/filename"+QString(fav ? "_favorites" : "")).toString(); - QString pth = m_settings->value("Save/path"+QString(fav ? "_favorites" : "")).toString().replace("\\", "/"); + QString fn = m_settings->value("Save/filename" + QString(fav ? "_favorites" : "")).toString(); + QString pth = m_settings->value("Save/path" + QString(fav ? "_favorites" : "")).toString().replace("\\", "/"); if (pth.right(1) == "/") - { pth = pth.left(pth.length()-1); } + { pth = pth.left(pth.length() - 1); } if (pth.isEmpty() || fn.isEmpty()) { diff --git a/lib/src/commands/commands.cpp b/lib/src/commands/commands.cpp index f7c33ab89..34cf13433 100644 --- a/lib/src/commands/commands.cpp +++ b/lib/src/commands/commands.cpp @@ -27,10 +27,10 @@ Commands::Commands(Profile *profile) settings->endGroup(); m_sqlWorker = new SqlWorker(settings->value("Exec/SQL/driver", "QMYSQL").toString(), - settings->value("Exec/SQL/host").toString(), - settings->value("Exec/SQL/user").toString(), - settings->value("Exec/SQL/password").toString(), - settings->value("Exec/SQL/database").toString()); + settings->value("Exec/SQL/host").toString(), + settings->value("Exec/SQL/user").toString(), + settings->value("Exec/SQL/password").toString(), + settings->value("Exec/SQL/database").toString()); m_sqlWorker->setObjectName("SqlThread"); } diff --git a/lib/src/commands/sql-worker.cpp b/lib/src/commands/sql-worker.cpp index 4a5a97cb1..24d306199 100644 --- a/lib/src/commands/sql-worker.cpp +++ b/lib/src/commands/sql-worker.cpp @@ -10,7 +10,7 @@ SqlWorker::SqlWorker(QString driver, QString host, QString user, QString passwor : QThread(parent), m_driver(std::move(driver)), m_host(std::move(host)), m_user(std::move(user)), m_password(std::move(password)), m_database(std::move(database)) { m_enabled = (m_driver == QLatin1String("QSQLITE") && !m_database.isEmpty()) - || (!m_host.isEmpty() && !m_user.isEmpty() && !m_database.isEmpty()); + || (!m_host.isEmpty() && !m_user.isEmpty() && !m_database.isEmpty()); m_started = false; } diff --git a/lib/src/downloader/download-query-group.cpp b/lib/src/downloader/download-query-group.cpp index 3626cff69..72373d209 100644 --- a/lib/src/downloader/download-query-group.cpp +++ b/lib/src/downloader/download-query-group.cpp @@ -71,19 +71,19 @@ bool DownloadQueryGroup::read(const QJsonObject &json, const QMapsetLastPage(m_lastPage); } m_lastPage = page; - log("Loading count '"+page->url().toString()+"'"); + log("Loading count '" + page->url().toString() + "'"); page->loadTags(); return; } @@ -212,7 +212,7 @@ void Downloader::loadNext() if (m_lastPage != nullptr) { page->setLastPage(m_lastPage); } m_lastPage = page; - log("Loading tags '"+page->url().toString()+"'"); + log("Loading tags '" + page->url().toString() + "'"); page->loadTags(); return; } @@ -223,7 +223,7 @@ void Downloader::loadNext() if (m_lastPage != nullptr) { page->setLastPage(m_lastPage); } m_lastPage = page; - log("Loading images '"+page->url().toString()+"'"); + log("Loading images '" + page->url().toString() + "'"); page->load(); return; } diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index 9f59152d3..dcbcaa4f1 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -306,8 +306,10 @@ int levenshtein(QString s1, QString s2) QVector> d(len1 + 1, QVector(len2 + 1)); d[0][0] = 0; - for (int i = 1; i <= len1; ++i) d[i][0] = i; - for (int i = 1; i <= len2; ++i) d[0][i] = i; + for (int i = 1; i <= len1; ++i) + d[i][0] = i; + for (int i = 1; i <= len2; ++i) + d[0][i] = i; for (int i = 1; i <= len1; ++i) { @@ -381,7 +383,7 @@ QMap domToMap(const QDomElement &dom) QMap r = domToMap(n.toElement()); QStringList k = r.keys(); for (int i = 0; i < r.count(); i++) - { details[n.nodeName()+"/"+k.at(i)] = r.value(k.at(i)); } + { details[n.nodeName() + "/" + k.at(i)] = r.value(k.at(i)); } } } return details; diff --git a/lib/src/functions.cpp~RF155d15f.TMP b/lib/src/functions.cpp~RF155d15f.TMP index 5b130a079..58d9ed3ec 100644 --- a/lib/src/functions.cpp~RF155d15f.TMP +++ b/lib/src/functions.cpp~RF155d15f.TMP @@ -306,8 +306,10 @@ int levenshtein(QString s1, QString s2) QVector> d(len1 + 1, QVector(len2 + 1)); d[0][0] = 0; - for (int i = 1; i <= len1; ++i) d[i][0] = i; - for (int i = 1; i <= len2; ++i) d[0][i] = i; + for (int i = 1; i <= len1; ++i) + d[i][0] = i; + for (int i = 1; i <= len2; ++i) + d[0][i] = i; for (int i = 1; i <= len1; ++i) { @@ -382,7 +384,7 @@ QMap domToMap(const QDomElement &dom) QMap r = domToMap(n.toElement()); QStringList k = r.keys(); for (int i = 0; i < r.count(); i++) - { details[n.nodeName()+"/"+k.at(i)] = r.value(k.at(i)); } + { details[n.nodeName() + "/" + k.at(i)] = r.value(k.at(i)); } } } return details; diff --git a/lib/src/functions.h b/lib/src/functions.h index 142471cc7..a718bfc4e 100644 --- a/lib/src/functions.h +++ b/lib/src/functions.h @@ -80,7 +80,7 @@ QList> listFilesFromDirectory(const QDir &dir, const template -QList reversed(const QList & in) +QList reversed(const QList &in) { QList result; std::reverse_copy(in.begin(), in.end(), std::back_inserter(result)); diff --git a/lib/src/loader/downloadable.cpp b/lib/src/loader/downloadable.cpp index de67a8c03..2156cfb53 100644 --- a/lib/src/loader/downloadable.cpp +++ b/lib/src/loader/downloadable.cpp @@ -32,7 +32,8 @@ const QMap &Downloadable::tokens(Profile *profile) const } // Use a lazy token for Grabber meta-tags as it can be expensive to calculate - tokens.insert("grabber", Token([profile, tokens]() { + tokens.insert("grabber", Token([profile, tokens]() + { const QString pth = profile->getSettings()->value("Save/path").toString(); Filename filename(profile->getSettings()->value("Save/filename").toString()); QStringList paths = filename.path(tokens, profile, pth); diff --git a/lib/src/logger.cpp b/lib/src/logger.cpp index ef48aec2a..5bddfc2d1 100644 --- a/lib/src/logger.cpp +++ b/lib/src/logger.cpp @@ -23,7 +23,7 @@ void Logger::setLogLevel(LogLevel level) } -void Logger::messageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message) +void Logger::messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &message) { static QMap messageTypes { @@ -48,7 +48,7 @@ void Logger::messageOutput(QtMsgType type, const QMessageLogContext& context, co Logger::getInstance().log(QStringLiteral("%1 %2").arg(label, message), messageTypes[type]); } -void Logger::noMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message) +void Logger::noMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &message) { Q_UNUSED(type); Q_UNUSED(context); @@ -102,7 +102,7 @@ void Logger::logCommand(const QString &l) m_fCommandsLog.open(QFile::Append | QFile::Text | QFile::Truncate); } - m_fCommandsLog.write(QString(l+"\r\n").toUtf8()); + m_fCommandsLog.write(QString(l + "\r\n").toUtf8()); m_fCommandsLog.flush(); } @@ -114,7 +114,7 @@ void Logger::logCommandSql(const QString &l) m_fCommandsSqlLog.open(QFile::Append | QFile::Text | QFile::Truncate); } - m_fCommandsSqlLog.write(QString(l+"\r\n").toUtf8()); + m_fCommandsSqlLog.write(QString(l + "\r\n").toUtf8()); m_fCommandsSqlLog.flush(); } diff --git a/lib/src/logger.h b/lib/src/logger.h index 8d1f0d5ad..0429616f6 100644 --- a/lib/src/logger.h +++ b/lib/src/logger.h @@ -24,17 +24,17 @@ class Logger : public QObject }; // Singleton pattern - static Logger& getInstance() + static Logger &getInstance() { static Logger instance; return instance; } - Logger(Logger const&) = delete; - void operator=(Logger const&) = delete; + Logger(Logger const &) = delete; + void operator=(Logger const &) = delete; // Handlers for Qt log messages - static void messageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message); - static void noMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& message); + static void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &message); + static void noMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &message); static void setupMessageOutput(bool log); void setLogFile(const QString &path); diff --git a/lib/src/models/favorite.cpp b/lib/src/models/favorite.cpp index b38610c0a..5b68677b2 100644 --- a/lib/src/models/favorite.cpp +++ b/lib/src/models/favorite.cpp @@ -42,8 +42,8 @@ bool Favorite::setImage(const QPixmap &img) m_imagePath = savePath("thumbs/" + getName(true) + ".png"); return img - .scaled(QSize(150, 150), Qt::KeepAspectRatio, Qt::SmoothTransformation) - .save(m_imagePath, "PNG"); + .scaled(QSize(150, 150), Qt::KeepAspectRatio, Qt::SmoothTransformation) + .save(m_imagePath, "PNG"); } QPixmap Favorite::getImage() const { @@ -118,7 +118,7 @@ bool Favorite::sortByLastViewed(const Favorite &s1, const Favorite &s2) { return s1.getLastViewed() < s2.getLastViewed(); } -bool operator==(const Favorite& lhs, const Favorite& rhs) +bool operator==(const Favorite &lhs, const Favorite &rhs) { return lhs.getName().toLower() == rhs.getName().toLower(); } -bool operator!=(const Favorite& lhs, const Favorite& rhs) +bool operator!=(const Favorite &lhs, const Favorite &rhs) { return !(lhs == rhs); } diff --git a/lib/src/models/favorite.h b/lib/src/models/favorite.h index 01313f9ce..42836ae47 100644 --- a/lib/src/models/favorite.h +++ b/lib/src/models/favorite.h @@ -51,7 +51,7 @@ class Favorite QString m_imagePath; }; -bool operator==(const Favorite& lhs, const Favorite& rhs); -bool operator!=(const Favorite& lhs, const Favorite& rhs); +bool operator==(const Favorite &lhs, const Favorite &rhs); +bool operator!=(const Favorite &lhs, const Favorite &rhs); #endif // FAVORITE_H diff --git a/lib/src/models/filename.cpp b/lib/src/models/filename.cpp index 7128b8933..112f891ae 100644 --- a/lib/src/models/filename.cpp +++ b/lib/src/models/filename.cpp @@ -215,7 +215,7 @@ QList> Filename::expandTokens(const QString &filename, QMap if (token.value().type() != QVariant::StringList) continue; - const bool hasToken = !isJavascript && filename.contains(QRegularExpression("%"+key+"(?::[^%]+)?%")); + const bool hasToken = !isJavascript && filename.contains(QRegularExpression("%" + key + "(?::[^%]+)?%")); const bool hasVar = isJavascript && filename.contains(key); if (!hasToken && !hasVar) continue; @@ -585,7 +585,7 @@ bool Filename::isValid(Profile *profile, QString *error) const bool found = false; for (int i = 0; i < tokens.length(); i++) { - if (QRegularExpression("%"+tokens[i]+"(?::[^%]+)?%").match(match.captured(0)).hasMatch()) + if (QRegularExpression("%" + tokens[i] + "(?::[^%]+)?%").match(match.captured(0)).hasMatch()) found = true; } diff --git a/lib/src/models/filename.h b/lib/src/models/filename.h index 3699371de..48e162d20 100644 --- a/lib/src/models/filename.h +++ b/lib/src/models/filename.h @@ -31,7 +31,7 @@ class Filename int needExactTags(Site *site, const QString &api = "") const; int needExactTags(const QStringList &forcedTokens = QStringList()) const; - QList > expandTokens(const QString &filename, QMap tokens, QSettings *settings) const; + QList> expandTokens(const QString &filename, QMap tokens, QSettings *settings) const; QString expandConditionals(const QString &text, const QStringList &tags, const QMap &tokens, QSettings *settings, int depth = 0) const; protected: diff --git a/lib/src/models/filtering/filter.h b/lib/src/models/filtering/filter.h index 95ead6b5e..554f0fc9b 100644 --- a/lib/src/models/filtering/filter.h +++ b/lib/src/models/filtering/filter.h @@ -15,7 +15,7 @@ class Filter virtual QString toString() const = 0; bool operator==(const Filter &rhs) const; - virtual bool compare(const Filter& rhs) const = 0; + virtual bool compare(const Filter &rhs) const = 0; protected: bool m_invert; diff --git a/lib/src/models/filtering/meta-filter.cpp b/lib/src/models/filtering/meta-filter.cpp index bc44f2fd8..96e2a6a0b 100644 --- a/lib/src/models/filtering/meta-filter.cpp +++ b/lib/src/models/filtering/meta-filter.cpp @@ -74,34 +74,34 @@ QString MetaFilter::match(const QMap &tokens, bool invert) const if (token.type() == QVariant::DateTime) { if (m_val.startsWith("..") || m_val.startsWith("<=")) - { cond = input <= toDate(m_val.right(m_val.size()-2)); } + { cond = input <= toDate(m_val.right(m_val.size() - 2)); } else if (m_val.endsWith("..")) - { cond = input >= toDate(m_val.left(m_val.size()-2)); } + { cond = input >= toDate(m_val.left(m_val.size() - 2)); } else if (m_val.startsWith(">=")) - { cond = input >= toDate(m_val.right(m_val.size()-2)); } + { cond = input >= toDate(m_val.right(m_val.size() - 2)); } else if (m_val.startsWith("<")) - { cond = input < toDate(m_val.right(m_val.size()-1)); } + { cond = input < toDate(m_val.right(m_val.size() - 1)); } else if (m_val.startsWith(">")) - { cond = input > toDate(m_val.right(m_val.size()-1)); } + { cond = input > toDate(m_val.right(m_val.size() - 1)); } else if (m_val.contains("..")) - { cond = input >= toDate(m_val.left(m_val.indexOf(".."))) && input <= toDate(m_val.right(m_val.size()-m_val.indexOf("..")-2)); } + { cond = input >= toDate(m_val.left(m_val.indexOf(".."))) && input <= toDate(m_val.right(m_val.size() - m_val.indexOf("..") - 2)); } else { cond = input == toDate(m_val); } } else { if (m_val.startsWith("..") || m_val.startsWith("<=")) - { cond = input <= m_val.rightRef(m_val.size()-2).toInt(); } + { cond = input <= m_val.rightRef(m_val.size() - 2).toInt(); } else if (m_val.endsWith("..")) - { cond = input >= m_val.leftRef(m_val.size()-2).toInt(); } + { cond = input >= m_val.leftRef(m_val.size() - 2).toInt(); } else if (m_val.startsWith(">=")) - { cond = input >= m_val.rightRef(m_val.size()-2).toInt(); } + { cond = input >= m_val.rightRef(m_val.size() - 2).toInt(); } else if (m_val.startsWith("<")) - { cond = input < m_val.rightRef(m_val.size()-1).toInt(); } + { cond = input < m_val.rightRef(m_val.size() - 1).toInt(); } else if (m_val.startsWith(">")) - { cond = input > m_val.rightRef(m_val.size()-1).toInt(); } + { cond = input > m_val.rightRef(m_val.size() - 1).toInt(); } else if (m_val.contains("..")) - { cond = input >= m_val.leftRef(m_val.indexOf("..")).toInt() && input <= m_val.rightRef(m_val.size()-m_val.indexOf("..")-2).toInt(); } + { cond = input >= m_val.leftRef(m_val.indexOf("..")).toInt() && input <= m_val.rightRef(m_val.size() - m_val.indexOf("..") - 2).toInt(); } else { cond = input == m_val.toInt(); } } diff --git a/lib/src/models/filtering/meta-filter.h b/lib/src/models/filtering/meta-filter.h index e78a37ad2..439eb1c6b 100644 --- a/lib/src/models/filtering/meta-filter.h +++ b/lib/src/models/filtering/meta-filter.h @@ -10,7 +10,7 @@ class MetaFilter : public Filter MetaFilter(QString type, QString val, bool invert = false); QString match(const QMap &tokens, bool invert = false) const override; QString toString() const override; - bool compare(const Filter& rhs) const override; + bool compare(const Filter &rhs) const override; private: QString m_type; diff --git a/lib/src/models/filtering/tag-filter.h b/lib/src/models/filtering/tag-filter.h index ac941c1ff..91d5f9e64 100644 --- a/lib/src/models/filtering/tag-filter.h +++ b/lib/src/models/filtering/tag-filter.h @@ -12,7 +12,7 @@ class TagFilter : public Filter explicit TagFilter(QString tag, bool invert = false); QString match(const QMap &tokens, bool invert = false) const override; QString toString() const override; - bool compare(const Filter& rhs) const override; + bool compare(const Filter &rhs) const override; private: QString m_tag; diff --git a/lib/src/models/filtering/token-filter.cpp b/lib/src/models/filtering/token-filter.cpp index d5884864a..1f7828fc8 100644 --- a/lib/src/models/filtering/token-filter.cpp +++ b/lib/src/models/filtering/token-filter.cpp @@ -12,7 +12,7 @@ QString TokenFilter::toString() const return QString(m_invert ? "-" : "") % "%" % m_token % "%"; } -bool TokenFilter::compare(const Filter& rhs) const +bool TokenFilter::compare(const Filter &rhs) const { const auto other = dynamic_cast(&rhs); if (other == nullptr) diff --git a/lib/src/models/filtering/token-filter.h b/lib/src/models/filtering/token-filter.h index 3a6994d21..2177805ab 100644 --- a/lib/src/models/filtering/token-filter.h +++ b/lib/src/models/filtering/token-filter.h @@ -10,7 +10,7 @@ class TokenFilter : public Filter explicit TokenFilter(QString token, bool invert = false); QString match(const QMap &tokens, bool invert = false) const override; QString toString() const override; - bool compare(const Filter& rhs) const override; + bool compare(const Filter &rhs) const override; private: QString m_token; diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 58b9713dd..0ed717052 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -92,7 +92,7 @@ Image::Image(const Image &other) m_loadingDetails = other.m_loadingDetails; } -Image::Image(Site *site, QMap details, Profile *profile, Page* parent) +Image::Image(Site *site, QMap details, Profile *profile, Page *parent) : m_profile(profile), m_id(0), m_parentSite(site), m_extensionRotator(nullptr) { m_settings = m_profile->getSettings(); @@ -662,8 +662,8 @@ QSize Image::size() const { return m_size; } QPixmap Image::previewImage() const { return m_imagePreview; } const QPixmap &Image::previewImage() { return m_imagePreview; } Page *Image::page() const { return m_parent; } -const QByteArray&Image::data() const { return m_data; } -const QStringList&Image::search() const { return m_search; } +const QByteArray &Image::data() const { return m_data; } +const QStringList &Image::search() const { return m_search; } bool Image::isGallery() const { return m_isGallery; } ExtensionRotator *Image::extensionRotator() const { return m_extensionRotator; } @@ -807,7 +807,8 @@ QList Image::detailsData() const const QString yes = tr("yes"); const QString no = tr("no"); - return { + return + { QStrP(tr("Tags"), stylishedTags(m_profile).join(' ')), QStrP(), QStrP(tr("ID"), m_id != 0 ? QString::number(m_id) : unknown), @@ -817,7 +818,7 @@ QList Image::detailsData() const QStrP(tr("Author"), !m_author.isEmpty() ? m_author : unknown), QStrP(), QStrP(tr("Date"), m_createdAt.isValid() ? m_createdAt.toString(tr("'the' MM/dd/yyyy 'at' hh:mm")) : unknown), - QStrP(tr("Size"), !m_size.isEmpty() ? QString::number(m_size.width())+"x"+QString::number(m_size.height()) : unknown), + QStrP(tr("Size"), !m_size.isEmpty() ? QString::number(m_size.width()) + "x" + QString::number(m_size.height()) : unknown), QStrP(tr("Filesize"), m_fileSize != 0 ? formatFilesize(m_fileSize) : unknown), QStrP(), QStrP(tr("Page"), !m_pageUrl.isEmpty() ? QString("%1").arg(m_pageUrl.toString()) : unknown), diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 1773d173c..09126461b 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -97,7 +97,8 @@ void PageApi::load(bool rateLimit, bool force) m_maxImagesCount = -1; m_pagesCount = -1; - m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply *reply) { + m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply * reply) + { log(QStringLiteral("[%1][%2] Loading page %3").arg(m_site->url(), m_format, m_url.toString().toHtmlEscaped()), Logger::Info); m_reply = reply; connect(m_reply, &QNetworkReply::finished, this, &PageApi::parse); @@ -247,7 +248,7 @@ void PageApi::parseActual() for (int t = 0; t < tags.count(); t++) { if (tagsGot.contains(tags[t].text())) - { m_tags[tagsGot.indexOf(tags[t].text())].setCount(m_tags[tagsGot.indexOf(tags[t].text())].count()+1); } + { m_tags[tagsGot.indexOf(tags[t].text())].setCount(m_tags[tagsGot.indexOf(tags[t].text())].count() + 1); } else { m_tags.append(tags[t]); diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index 9e1215093..a6059d489 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -66,9 +66,9 @@ void Site::loadConfig() QSettings *pSettings = m_source->getProfile()->getSettings(); QStringList defaults; defaults << pSettings->value("source_1").toString() - << pSettings->value("source_2").toString() - << pSettings->value("source_3").toString() - << pSettings->value("source_4").toString(); + << pSettings->value("source_2").toString() + << pSettings->value("source_3").toString() + << pSettings->value("source_4").toString(); defaults.removeAll(""); if (defaults.isEmpty()) { defaults = QStringList() << "Xml" << "Json" << "Regex" << "Rss"; } @@ -228,7 +228,7 @@ QNetworkRequest Site::makeRequest(QUrl url, Page *page, const QString &ref, Imag url.setScheme("https"); QNetworkRequest request(url); - QString referer = m_settings->value("referer"+(!ref.isEmpty() ? "_"+ref : QString())).toString(); + QString referer = m_settings->value("referer" + (!ref.isEmpty() ? "_" + ref : QString())).toString(); if (referer.isEmpty() && !ref.isEmpty()) { referer = m_settings->value("referer", "none").toString(); } if (referer != "none" && (referer != "page" || page != nullptr)) @@ -301,7 +301,7 @@ QNetworkReply *Site::getRequest(const QNetworkRequest &request) void Site::loadTags(int page, int limit) { const QString protocol = (m_settings->value("ssl", false).toBool() ? QStringLiteral("https") : QStringLiteral("http")); - m_tagsReply = get(QUrl(protocol + "://"+m_url+"/tags.json?search[hide_empty]=yes&limit="+QString::number(limit)+"&page=" + QString::number(page))); + m_tagsReply = get(QUrl(protocol + "://" + m_url + "/tags.json?search[hide_empty]=yes&limit=" + QString::number(limit) + "&page=" + QString::number(page))); connect(m_tagsReply, &QNetworkReply::finished, this, &Site::finishedTags); } @@ -320,9 +320,9 @@ void Site::finishedTags() QJsonObject sc = sourc[id].toObject(); const int cat = sc.value("category").toInt(); tags.append(Tag(sc.value("name").toString(), - cat == 0 ? "general" : (cat == 1 ? "artist" : (cat == 3 ? "copyright" : "character")), - sc.value("post_count").toInt(), - sc.value("related_tags").toString().split(' '))); + cat == 0 ? "general" : (cat == 1 ? "artist" : (cat == 3 ? "copyright" : "character")), + sc.value("post_count").toInt(), + sc.value("related_tags").toString().split(' '))); } } emit finishedLoadingTags(tags); diff --git a/lib/src/models/source-guesser.cpp b/lib/src/models/source-guesser.cpp index b3560df9a..4f50cc373 100644 --- a/lib/src/models/source-guesser.cpp +++ b/lib/src/models/source-guesser.cpp @@ -35,7 +35,7 @@ Source *SourceGuesser::start() { reply = m_manager->get(QNetworkRequest(getUrl)); QEventLoop loop; - connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); + connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); getUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); diff --git a/lib/src/tags/tag-api.cpp b/lib/src/tags/tag-api.cpp index 7bf2ef26d..c46450096 100755 --- a/lib/src/tags/tag-api.cpp +++ b/lib/src/tags/tag-api.cpp @@ -21,7 +21,8 @@ TagApi::~TagApi() void TagApi::load(bool rateLimit) { - m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply *reply) { + m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply * reply) + { log(QStringLiteral("[%1] Loading tags page %2").arg(m_site->url(), m_url.toString().toHtmlEscaped()), Logger::Info); if (m_reply != nullptr) diff --git a/lib/src/vendor/html-entities.cpp b/lib/src/vendor/html-entities.cpp index fd3afb0e7..2153ecd2a 100644 --- a/lib/src/vendor/html-entities.cpp +++ b/lib/src/vendor/html-entities.cpp @@ -11,7 +11,8 @@ #define UNICODE_MAX 0x10FFFFul -static const char *const NAMED_ENTITIES[][2] = { +static const char *const NAMED_ENTITIES[][2] = +{ { "AElig;", "Æ" }, { "Aacute;", "Á" }, { "Acirc;", "Â" }, @@ -286,20 +287,20 @@ static size_t putc_utf8(unsigned long cp, char *buffer) { unsigned char *bytes = (unsigned char *)buffer; - if(cp <= 0x007Ful) + if (cp <= 0x007Ful) { bytes[0] = (unsigned char)cp; return 1; } - if(cp <= 0x07FFul) + if (cp <= 0x07FFul) { bytes[1] = (unsigned char)((2 << 6) | (cp & 0x3F)); bytes[0] = (unsigned char)((6 << 5) | (cp >> 6)); return 2; } - if(cp <= 0xFFFFul) + if (cp <= 0xFFFFul) { bytes[2] = (unsigned char)(( 2 << 6) | ( cp & 0x3F)); bytes[1] = (unsigned char)(( 2 << 6) | ((cp >> 6) & 0x3F)); @@ -307,7 +308,7 @@ static size_t putc_utf8(unsigned long cp, char *buffer) return 3; } - if(cp <= 0x10FFFFul) + if (cp <= 0x10FFFFul) { bytes[3] = (unsigned char)(( 2 << 6) | ( cp & 0x3F)); bytes[2] = (unsigned char)(( 2 << 6) | ((cp >> 6) & 0x3F)); @@ -323,9 +324,10 @@ static bool parse_entity( const char *current, char **to, const char **from) { const char *end = strchr(current, ';'); - if(!end) return 0; + if (!end) + return 0; - if(current[1] == '#') + if (current[1] == '#') { char *tail = NULL; int errno_save = errno; @@ -337,7 +339,8 @@ static bool parse_entity( bool fail = errno || tail != end || cp > UNICODE_MAX; errno = errno_save; - if(fail) return 0; + if (fail) + return 0; *to += putc_utf8(cp, *to); *from = end + 1; @@ -347,7 +350,8 @@ static bool parse_entity( else { const char *entity = get_named_entity(¤t[1]); - if(!entity) return 0; + if (!entity) + return 0; size_t len = strlen(entity); memcpy(*to, entity, len); @@ -361,17 +365,18 @@ static bool parse_entity( size_t decode_html_entities_utf8(char *dest, const char *src) { - if(!src) src = dest; + if (!src) + src = dest; char *to = dest; const char *from = src; - for(const char *current; (current = strchr(from, '&'));) + for (const char *current; (current = strchr(from, '&'));) { memmove(to, from, (size_t)(current - from)); to += current - from; - if(parse_entity(current, &to, &from)) + if (parse_entity(current, &to, &from)) continue; from = current; diff --git a/lib/src/vendor/qcustomnetworkreply.cpp b/lib/src/vendor/qcustomnetworkreply.cpp index 895b7c8e0..80f1375af 100644 --- a/lib/src/vendor/qcustomnetworkreply.cpp +++ b/lib/src/vendor/qcustomnetworkreply.cpp @@ -6,28 +6,28 @@ struct QCustomNetworkReplyPrivate { - QByteArray content; - qint64 offset; + QByteArray content; + qint64 offset; }; QCustomNetworkReply::QCustomNetworkReply( QObject *parent ) - : QNetworkReply(parent) + : QNetworkReply(parent) { - d = new QCustomNetworkReplyPrivate; + d = new QCustomNetworkReplyPrivate; } QCustomNetworkReply::~QCustomNetworkReply() { - delete d; + delete d; } void QCustomNetworkReply::setHttpStatusCode( int code, const QByteArray &statusText ) { - setAttribute( QNetworkRequest::HttpStatusCodeAttribute, code ); - if ( statusText.isNull() ) - return; + setAttribute( QNetworkRequest::HttpStatusCodeAttribute, code ); + if ( statusText.isNull() ) + return; - setAttribute( QNetworkRequest::HttpReasonPhraseAttribute, statusText ); + setAttribute( QNetworkRequest::HttpReasonPhraseAttribute, statusText ); } void QCustomNetworkReply::setNetworkError( QNetworkReply::NetworkError errorCode, const QString &errorString ) @@ -37,26 +37,26 @@ void QCustomNetworkReply::setNetworkError( QNetworkReply::NetworkError errorCode void QCustomNetworkReply::setHeader( QNetworkRequest::KnownHeaders header, const QVariant &value ) { - QNetworkReply::setHeader( header, value ); + QNetworkReply::setHeader( header, value ); } void QCustomNetworkReply::setContentType( const QByteArray &contentType ) { - setHeader(QNetworkRequest::ContentTypeHeader, contentType); + setHeader(QNetworkRequest::ContentTypeHeader, contentType); } void QCustomNetworkReply::setContent( const QString &content ) { - setContent(content.toUtf8()); + setContent(content.toUtf8()); } void QCustomNetworkReply::setContent( const QByteArray &content ) { - d->content = content; - d->offset = 0; + d->content = content; + d->offset = 0; - open(ReadOnly | Unbuffered); - setHeader(QNetworkRequest::ContentLengthHeader, QVariant(content.size())); + open(ReadOnly | Unbuffered); + setHeader(QNetworkRequest::ContentLengthHeader, QVariant(content.size())); QTimer::singleShot( 0, this, SIGNAL(readyRead()) ); QTimer::singleShot( 0, this, SIGNAL(finished()) ); @@ -70,23 +70,23 @@ void QCustomNetworkReply::abort() qint64 QCustomNetworkReply::bytesAvailable() const { - return d->content.size() - d->offset + QIODevice::bytesAvailable(); + return d->content.size() - d->offset + QIODevice::bytesAvailable(); } bool QCustomNetworkReply::isSequential() const { - return true; + return true; } qint64 QCustomNetworkReply::readData(char *data, qint64 maxSize) { - if (d->offset >= d->content.size()) - return -1; + if (d->offset >= d->content.size()) + return -1; - qint64 number = qMin(maxSize, d->content.size() - d->offset); - memcpy(data, d->content.constData() + d->offset, number); - d->offset += number; + qint64 number = qMin(maxSize, d->content.size() - d->offset); + memcpy(data, d->content.constData() + d->offset, number); + d->offset += number; - return number; + return number; } From fe20f06b501b3b5683950e8fad27c6565a327a8f Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 24 Jul 2018 01:48:03 +0200 Subject: [PATCH 096/112] Fix JS error when wiki is not found on page --- release/sites/Danbooru (2.0)/model.ts | 2 +- release/sites/Danbooru/model.ts | 2 +- release/sites/Sankaku/model.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/release/sites/Danbooru (2.0)/model.ts b/release/sites/Danbooru (2.0)/model.ts index 803660f73..ad4576a28 100644 --- a/release/sites/Danbooru (2.0)/model.ts +++ b/release/sites/Danbooru (2.0)/model.ts @@ -257,7 +257,7 @@ export const source: ISource = { }, parse: (src: string): IParsedSearch => { let wiki = Grabber.regexToConst("wiki", '
    ]+)>(?.+?)
    ', src); - wiki = wiki.replace(/href="\/wiki_pages\/show_or_new\?title=([^"]+)"/g, 'href="$1"'); + wiki = wiki ? wiki.replace(/href="\/wiki_pages\/show_or_new\?title=([^"]+)"/g, 'href="$1"') : wiki; return { tags: Grabber.regexToTags('
  • (?:\\s*\\?)?(?:\\s*]* class="search-inc-tag">[^<]+\\s*]* class="search-exl-tag">[^<]+)?\\s*]*href="[^"]+"[^>]*>(?[^<]+)\\s*(?[^<]+)\\s*
  • ', src), images: Grabber.regexToImages(']* id="[^"]*" class="[^"]*"\\s+data-id="(?[^"]*)"\\s+data-has-sound="[^"]*"\\s+data-tags="(?[^"]*)"\\s+data-pools="(?[^"]*)"(?:\\s+data-uploader="(?[^"]*)")?\\s+data-approver-id="(?[^"]*)"\\s+data-rating="(?[^"]*)"\\s+data-width="(?[^"]*)"\\s+data-height="(?[^"]*)"\\s+data-flags="(?[^"]*)"\\s+data-parent-id="(?[^"]*)"\\s+data-has-children="(?[^"]*)"\\s+data-score="(?[^"]*)"\\s+data-views="[^"]*"\\s+data-fav-count="(?[^"]*)"\\s+data-pixiv-id="[^"]*"\\s+data-file-ext="(?[^"]*)"\\s+data-source="(?[^"]*)"\\s+data-top-tagger="[^"]*"\\s+data-uploader-id="[^"]*"\\s+data-normalized-source="[^"]*"\\s+data-is-favorited="[^"]*"\\s+data-md5="(?[^"]*)"\\s+data-file-url="(?[^"]*)"\\s+data-large-file-url="(?[^"]*)"\\s+data-preview-file-url="(?[^"]*)"', src).map(completeImage), diff --git a/release/sites/Danbooru/model.ts b/release/sites/Danbooru/model.ts index 642dcabd2..e445fd0de 100644 --- a/release/sites/Danbooru/model.ts +++ b/release/sites/Danbooru/model.ts @@ -189,7 +189,7 @@ export const source: ISource = { }, parse: (src: string): IParsedSearch => { let wiki = Grabber.regexToConst("wiki", '', src); - wiki = wiki.replace(/href="\/wiki\/show\?title=([^"]+)"/g, 'href="$1"'); + wiki = wiki ? wiki.replace(/href="\/wiki\/show\?title=([^"]+)"/g, 'href="$1"') : wiki; return { images: Grabber.regexToImages("Post\\.register\\((?\\{.+?\\})\\);?", src).map(completeImage), tags: Grabber.regexToTags('
  • ]*tag-type-(?[^">]+)(?:|"[^>]*)>.*?]*>(?[^<\\?]+).*?(?\\d+).*?
  • ', src), diff --git a/release/sites/Sankaku/model.ts b/release/sites/Sankaku/model.ts index 1cb9d42f1..109adb439 100644 --- a/release/sites/Sankaku/model.ts +++ b/release/sites/Sankaku/model.ts @@ -86,7 +86,7 @@ export const source: ISource = { const searchImageCounts = Grabber.regexMatches('class="?tag-(?:count|type-none)"? title="Post Count: (?[0-9,]+)"', src); const lastPage = Grabber.regexToConst("page", '\\s*(?[0-9,]+)\\s*\\s*>>\\s*', src); let wiki = Grabber.regexToConst("wiki", '
    ]*>(?.+?)
    ', src); - wiki = wiki.replace(/href="\/wiki\/show\?title=([^"]+)"/g, 'href="$1"'); + wiki = wiki ? wiki.replace(/href="\/wiki\/show\?title=([^"]+)"/g, 'href="$1"') : undefined; return { tags: Grabber.regexToTags('
  • ]*tag-type-(?[^">]+)(?:|"[^>]*)>.*?]*>(?[^<\\?]+).*?(?\\d+).*?
  • ', src), images: Grabber.regexToImages(']* id="?p(?\\d+)"?>]*>]* src="(?[^"]+/preview/\\w{2}/\\w{2}/(?[^.]+)\\.[^"]+|[^"]+/download-preview.png)" title="(?[^"]+)"[^>]+>', src).map(completeImage), From 690de0d9a389e906a5324840395c96f7f14ef6f4 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 24 Jul 2018 11:15:29 +0200 Subject: [PATCH 097/112] Fix page count parsing for DB since switch to FA (issue #1331) --- release/sites/Danbooru (2.0)/model.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release/sites/Danbooru (2.0)/model.ts b/release/sites/Danbooru (2.0)/model.ts index ad4576a28..575e65f41 100644 --- a/release/sites/Danbooru (2.0)/model.ts +++ b/release/sites/Danbooru (2.0)/model.ts @@ -262,7 +262,7 @@ export const source: ISource = { tags: Grabber.regexToTags('
  • (?:\\s*\\?)?(?:\\s*]* class="search-inc-tag">[^<]+\\s*]* class="search-exl-tag">[^<]+)?\\s*]*href="[^"]+"[^>]*>(?[^<]+)\\s*(?[^<]+)\\s*
  • ', src), images: Grabber.regexToImages(']* id="[^"]*" class="[^"]*"\\s+data-id="(?[^"]*)"\\s+data-has-sound="[^"]*"\\s+data-tags="(?[^"]*)"\\s+data-pools="(?[^"]*)"(?:\\s+data-uploader="(?[^"]*)")?\\s+data-approver-id="(?[^"]*)"\\s+data-rating="(?[^"]*)"\\s+data-width="(?[^"]*)"\\s+data-height="(?[^"]*)"\\s+data-flags="(?[^"]*)"\\s+data-parent-id="(?[^"]*)"\\s+data-has-children="(?[^"]*)"\\s+data-score="(?[^"]*)"\\s+data-views="[^"]*"\\s+data-fav-count="(?[^"]*)"\\s+data-pixiv-id="[^"]*"\\s+data-file-ext="(?[^"]*)"\\s+data-source="(?[^"]*)"\\s+data-top-tagger="[^"]*"\\s+data-uploader-id="[^"]*"\\s+data-normalized-source="[^"]*"\\s+data-is-favorited="[^"]*"\\s+data-md5="(?[^"]*)"\\s+data-file-url="(?[^"]*)"\\s+data-large-file-url="(?[^"]*)"\\s+data-preview-file-url="(?[^"]*)"', src).map(completeImage), wiki, - pageCount: Grabber.regexToConst("page", ">(?\\d+)<(?:a|span)[^>]*>>><", src), + pageCount: Grabber.regexToConst("page", '>(?\\d+)<(?:a|span)[^>]*>(?:>>|)<', src), }; }, }, From 3bf904f9d8dd9faa55fb33e8b2d35e0bb639e369 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 24 Jul 2018 21:09:42 +0200 Subject: [PATCH 098/112] Fix crash when adding empty header in source settings --- gui/src/sources/sourcessettingswindow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gui/src/sources/sourcessettingswindow.cpp b/gui/src/sources/sourcessettingswindow.cpp index 9943c7b47..f4503aaaa 100644 --- a/gui/src/sources/sourcessettingswindow.cpp +++ b/gui/src/sources/sourcessettingswindow.cpp @@ -305,7 +305,8 @@ void SourcesSettingsWindow::save() QMap headers; for (int i = 0; i < ui->tableHeaders->rowCount(); ++i) { - if (ui->tableHeaders->item(i, 0)->text().isEmpty()) + QTableWidgetItem *item = ui->tableHeaders->item(i, 0); + if (item == nullptr || item->text().isEmpty()) continue; headers.insert(ui->tableHeaders->item(i, 0)->text(), ui->tableHeaders->item(i, 1)->text()); From e0c8277d6ca63df6774213051c9bd1233a4cd907 Mon Sep 17 00:00:00 2001 From: Bionus Date: Tue, 24 Jul 2018 22:40:18 +0200 Subject: [PATCH 099/112] Move async logic from Site to client classes (fix #1342) --- lib/src/models/image.cpp | 29 +++++++++++++++++++++-------- lib/src/models/image.h | 1 + lib/src/models/page-api.cpp | 22 ++++++++++++++++------ lib/src/models/page-api.h | 1 + lib/src/models/site.cpp | 15 ++------------- lib/src/models/site.h | 3 +-- lib/src/tags/tag-api.cpp | 27 ++++++++++++++++++++------- lib/src/tags/tag-api.h | 1 + 8 files changed, 63 insertions(+), 36 deletions(-) diff --git a/lib/src/models/image.cpp b/lib/src/models/image.cpp index 0ed717052..dab922b2c 100644 --- a/lib/src/models/image.cpp +++ b/lib/src/models/image.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include "commands/commands.h" #include "downloader/extension-rotator.h" #include "favorite.h" @@ -298,16 +299,28 @@ void Image::loadDetails(bool rateLimit) return; } - m_parentSite->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::Details, m_pageUrl, [this](QNetworkReply *reply) { - if (m_loadDetails != nullptr) - m_loadDetails->deleteLater(); + // Load the request with a possible delay + int ms = m_parentSite->msToRequest(rateLimit ? Site::QueryType::Retry : Site::QueryType::List); + if (ms > 0) + { QTimer::singleShot(ms, this, SLOT(loadDetailsNow())); } + else + { loadDetailsNow(); } +} +void Image::loadDetailsNow() +{ + if (m_loadDetails != nullptr) + { + if (m_loadDetails->isRunning()) + m_loadDetails->abort(); + + m_loadDetails->deleteLater(); + } - m_loadDetails = reply; - m_loadDetails->setParent(this); - m_loadingDetails = true; + m_loadDetails = m_parentSite->get(m_pageUrl); + m_loadDetails->setParent(this); + m_loadingDetails = true; - connect(m_loadDetails, &QNetworkReply::finished, this, &Image::parseDetails); - }); + connect(m_loadDetails, &QNetworkReply::finished, this, &Image::parseDetails); } void Image::abortTags() { diff --git a/lib/src/models/image.h b/lib/src/models/image.h index 4a949aca5..441f036fc 100644 --- a/lib/src/models/image.h +++ b/lib/src/models/image.h @@ -98,6 +98,7 @@ class Image : public QObject, public Downloadable public slots: void loadDetails(bool rateLimit = false); + void loadDetailsNow(); void abortTags(); void parseDetails(); diff --git a/lib/src/models/page-api.cpp b/lib/src/models/page-api.cpp index 09126461b..255df4e24 100755 --- a/lib/src/models/page-api.cpp +++ b/lib/src/models/page-api.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include "functions.h" #include "image.h" @@ -76,6 +77,9 @@ void PageApi::load(bool rateLimit, bool force) if (!force) return; + if (m_reply->isRunning()) + m_reply->abort(); + m_reply->deleteLater(); m_reply = nullptr; } @@ -97,12 +101,18 @@ void PageApi::load(bool rateLimit, bool force) m_maxImagesCount = -1; m_pagesCount = -1; - m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply * reply) - { - log(QStringLiteral("[%1][%2] Loading page %3").arg(m_site->url(), m_format, m_url.toString().toHtmlEscaped()), Logger::Info); - m_reply = reply; - connect(m_reply, &QNetworkReply::finished, this, &PageApi::parse); - }); + // Load the request with a possible delay + int ms = m_site->msToRequest(rateLimit ? Site::QueryType::Retry : Site::QueryType::List); + if (ms > 0) + { QTimer::singleShot(ms, this, SLOT(loadNow())); } + else + { loadNow(); } +} +void PageApi::loadNow() +{ + log(QStringLiteral("[%1][%2] Loading page %3").arg(m_site->url(), m_format, m_url.toString().toHtmlEscaped()), Logger::Info); + m_reply = m_site->get(m_url); + connect(m_reply, &QNetworkReply::finished, this, &PageApi::parse); } void PageApi::abort() { diff --git a/lib/src/models/page-api.h b/lib/src/models/page-api.h index 92f10f9ba..c3176ccff 100644 --- a/lib/src/models/page-api.h +++ b/lib/src/models/page-api.h @@ -50,6 +50,7 @@ class PageApi : public QObject public slots: void load(bool rateLimit = false, bool force = false); + void loadNow(); void parse(); void abort(); void clear(); diff --git a/lib/src/models/site.cpp b/lib/src/models/site.cpp index a6059d489..5291c1a72 100644 --- a/lib/src/models/site.cpp +++ b/lib/src/models/site.cpp @@ -262,11 +262,8 @@ QNetworkRequest Site::makeRequest(QUrl url, Page *page, const QString &ref, Imag return request; } -void Site::getAsync(QueryType type, const QUrl &url, const std::function &callback, Page *page, const QString &ref, Image *img) +int Site::msToRequest(QueryType type) const { - m_lastCallback = callback; - m_callbackRequest = this->makeRequest(url, page, ref, img); - const qint64 sinceLastRequest = m_lastRequest.msecsTo(QDateTime::currentDateTime()); const QString key = (type == QueryType::Retry ? "retry" : (type == QueryType::List ? "page" : (type == QueryType::Img ? "image" : (type == QueryType::Thumb ? "thumbnail" : "details")))); @@ -274,15 +271,7 @@ void Site::getAsync(QueryType type, const QUrl &url, const std::function 0) - { QTimer::singleShot(ms, this, SLOT(getCallback())); } - else - { getCallback(); } -} - -void Site::getCallback() -{ - m_lastCallback(this->getRequest(m_callbackRequest)); + return ms; } QNetworkReply *Site::get(const QUrl &url, Page *page, const QString &ref, Image *img) diff --git a/lib/src/models/site.h b/lib/src/models/site.h index 3da6f617e..125d75c18 100644 --- a/lib/src/models/site.h +++ b/lib/src/models/site.h @@ -63,7 +63,7 @@ class Site : public QObject TagDatabase *tagDatabase() const; QNetworkRequest makeRequest(QUrl url, Page *page = nullptr, const QString &ref = "", Image *img = nullptr); QNetworkReply *get(const QUrl &url, Page *page = nullptr, const QString &ref = "", Image *img = nullptr); - void getAsync(QueryType type, const QUrl &url, const std::function &callback, Page *page = nullptr, const QString &ref = "", Image *img = nullptr); + int msToRequest(QueryType type) const; QUrl fixUrl(const QUrl &url) const { return fixUrl(url.toString()); } QUrl fixUrl(const QString &url, const QUrl &old = QUrl()) const; @@ -90,7 +90,6 @@ class Site : public QObject void loginFinished(Login::Result result); void loadTags(int page, int limit); void finishedTags(); - void getCallback(); protected: void resetCookieJar(); diff --git a/lib/src/tags/tag-api.cpp b/lib/src/tags/tag-api.cpp index c46450096..68912c760 100755 --- a/lib/src/tags/tag-api.cpp +++ b/lib/src/tags/tag-api.cpp @@ -1,5 +1,6 @@ #include "tags/tag-api.h" #include +#include #include "functions.h" #include "logger.h" #include "models/api/api.h" @@ -21,16 +22,28 @@ TagApi::~TagApi() void TagApi::load(bool rateLimit) { - m_site->getAsync(rateLimit ? Site::QueryType::Retry : Site::QueryType::List, m_url, [this](QNetworkReply * reply) + // Load the request with a possible delay + int ms = m_site->msToRequest(rateLimit ? Site::QueryType::Retry : Site::QueryType::List); + if (ms > 0) + { QTimer::singleShot(ms, this, SLOT(loadNow())); } + else + { loadNow(); } +} + +void TagApi::loadNow() +{ + log(QStringLiteral("[%1] Loading tags page %2").arg(m_site->url(), m_url.toString().toHtmlEscaped()), Logger::Info); + + if (m_reply != nullptr) { - log(QStringLiteral("[%1] Loading tags page %2").arg(m_site->url(), m_url.toString().toHtmlEscaped()), Logger::Info); + if (m_reply->isRunning()) + m_reply->abort(); - if (m_reply != nullptr) - m_reply->deleteLater(); + m_reply->deleteLater(); + } - m_reply = reply; - connect(m_reply, &QNetworkReply::finished, this, &TagApi::parse); - }); + m_reply = m_site->get(m_url); + connect(m_reply, &QNetworkReply::finished, this, &TagApi::parse); } void TagApi::abort() diff --git a/lib/src/tags/tag-api.h b/lib/src/tags/tag-api.h index de6f154e4..ff01ce2c1 100644 --- a/lib/src/tags/tag-api.h +++ b/lib/src/tags/tag-api.h @@ -27,6 +27,7 @@ class TagApi : public QObject const QList &tags() const; public slots: + void loadNow(); void abort(); protected slots: From 04009cefac2115722306abcf0dfe250688be9cc2 Mon Sep 17 00:00:00 2001 From: Bionus Date: Wed, 25 Jul 2018 09:31:11 +0200 Subject: [PATCH 100/112] Fix abolute links not working in wiki --- lib/src/models/api/javascript-api.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/src/models/api/javascript-api.cpp b/lib/src/models/api/javascript-api.cpp index 923b50876..3c940e06f 100644 --- a/lib/src/models/api/javascript-api.cpp +++ b/lib/src/models/api/javascript-api.cpp @@ -245,7 +245,10 @@ ParsedPage JavascriptApi::parsePage(Page *parentPage, const QString &source, int if (results.hasProperty("urlPrevPage") && results.property("urlPrevPage").isString()) { ret.urlPrevPage = results.property("urlPrevPage").toString(); } if (results.hasProperty("wiki") && results.property("wiki").isString()) - { ret.wiki = results.property("wiki").toString(); } + { + ret.wiki = results.property("wiki").toString(); + ret.wiki = ret.wiki.replace("href=\"/", "href=\"" + site->baseUrl() + "/"); + } return ret; } From fba64bbbdefa8bdbb68d2e0ee4c4c25bf3809e9d Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 29 Jul 2018 13:55:56 +0200 Subject: [PATCH 101/112] Log errno when failing to set file mod time on unix --- gui/src/helpers.cpp | 3 +-- lib/src/functions.cpp | 3 ++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/src/helpers.cpp b/gui/src/helpers.cpp index 01e07af31..97da83669 100644 --- a/gui/src/helpers.cpp +++ b/gui/src/helpers.cpp @@ -34,7 +34,6 @@ void showInGraphicalShell(const QString &pathIn) param += QDir::toNativeSeparators(pathIn); QProcess::startDetached("explorer.exe "+param); #elif defined(Q_OS_MAC) - // Q_UNUSED(parent) QStringList scriptArgs; scriptArgs << QLatin1String("-e") << QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"").arg(pathIn); QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs); @@ -42,7 +41,7 @@ void showInGraphicalShell(const QString &pathIn) scriptArgs << QLatin1String("-e") << QLatin1String("tell application \"Finder\" to activate"); QProcess::execute("/usr/bin/osascript", scriptArgs); #else - QDesktopServices::openUrl(QUrl("file:///"+pathIn)); + QDesktopServices::openUrl(QUrl("file:///" + pathIn)); #endif } diff --git a/lib/src/functions.cpp b/lib/src/functions.cpp index dcbcaa4f1..f2e098f37 100644 --- a/lib/src/functions.cpp +++ b/lib/src/functions.cpp @@ -16,6 +16,7 @@ #ifdef Q_OS_WIN #include #else + #include #include #endif #ifdef QT_DEBUG @@ -358,7 +359,7 @@ bool setFileCreationDate(const QString &path, const QDateTime &datetime) const char *filename = path.toStdString().c_str(); if ((utime(filename, &timebuffer)) < 0) { - // log(QStringLiteral("Unable to change the file creation date (%1): %2").arg(errno).arg(path), Logger::Error); + log(QStringLiteral("Unable to change the file creation date (%1): %2").arg(errno).arg(path), Logger::Error); return false; } #endif From 85f9d22ef54da55689da632aabb938909e3e858f Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 4 Aug 2018 01:02:18 +0200 Subject: [PATCH 102/112] Use macro to allow Qt Creator to detect tests --- tests/CMakeLists.txt | 4 +++ tests/src/commands/sql-worker-test.cpp | 2 +- .../src/downloader/extension-rotator-test.cpp | 2 +- tests/src/downloader/file-downloader-test.cpp | 2 +- .../src/downloader/image-downloader-test.cpp | 2 +- tests/src/functions-test.cpp | 2 +- tests/src/integration/behoimi-test.cpp | 2 +- tests/src/integration/booru-org-test.cpp | 2 +- tests/src/integration/danbooru-test.cpp | 2 +- tests/src/integration/derpibooru-test.cpp | 2 +- tests/src/integration/e621-test.cpp | 2 +- tests/src/integration/gelbooru-test.cpp | 2 +- tests/src/integration/sankaku-test.cpp | 2 +- tests/src/integration/zerochan-test.cpp | 2 +- tests/src/loader/token-test.cpp | 2 +- tests/src/main.cpp | 29 ++++++++----------- tests/src/mixed-settings-test.cpp | 2 +- tests/src/models/favorite-test.cpp | 2 +- tests/src/models/filename-test.cpp | 3 +- tests/src/models/filtering/blacklist-test.cpp | 2 +- .../src/models/filtering/meta-filter-test.cpp | 2 +- .../src/models/filtering/post-filter-test.cpp | 2 +- .../src/models/filtering/tag-filter-test.cpp | 2 +- .../models/filtering/token-filter-test.cpp | 2 +- tests/src/models/image-test.cpp | 2 +- tests/src/models/page-api-test.cpp | 2 +- tests/src/models/page-test.cpp | 2 +- tests/src/models/pool-test.cpp | 7 ++++- tests/src/models/profile-test.cpp | 2 +- tests/src/models/site-test.cpp | 2 +- tests/src/models/source-guesser-test.cpp | 2 +- tests/src/models/source-test.cpp | 2 +- tests/src/tags/tag-api-test.cpp | 2 +- .../src/tags/tag-database-in-memory-test.cpp | 2 +- tests/src/tags/tag-database-sqlite-test.cpp | 2 +- tests/src/tags/tag-name-format-test.cpp | 2 +- tests/src/tags/tag-name-test.cpp | 2 +- tests/src/tags/tag-stylist-test.cpp | 2 +- tests/src/tags/tag-test.cpp | 2 +- tests/src/test-suite.h | 3 ++ tests/src/updater/source-updater-test.cpp | 2 +- tests/src/updater/updater-test.cpp | 2 +- 42 files changed, 64 insertions(+), 56 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index c40b1a2a4..0b7968285 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -12,6 +12,10 @@ set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Test Qt5::Widgets) file(GLOB_RECURSE SOURCES "src/*.cpp") include_directories("src/" "../lib/src/") +if(MSVC OR CMAKE_CXX_COMPILER MATCHES "cl\\.exe") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4005") # Suppress "macro redifinition" warnings +endif() + add_executable(${PROJECT_NAME} ${SOURCES}) add_test(${PROJECT_NAME} ${PROJECT_NAME}) target_link_libraries(${PROJECT_NAME} ${QT_LIBRARIES} lib) diff --git a/tests/src/commands/sql-worker-test.cpp b/tests/src/commands/sql-worker-test.cpp index 64e6e9c72..a26e26be9 100644 --- a/tests/src/commands/sql-worker-test.cpp +++ b/tests/src/commands/sql-worker-test.cpp @@ -77,4 +77,4 @@ void SqlWorkerTest::testExecCreateAndInsert() } -static SqlWorkerTest instance; +QTEST_MAIN(SqlWorkerTest) diff --git a/tests/src/downloader/extension-rotator-test.cpp b/tests/src/downloader/extension-rotator-test.cpp index 82d526cc9..ef907d9eb 100644 --- a/tests/src/downloader/extension-rotator-test.cpp +++ b/tests/src/downloader/extension-rotator-test.cpp @@ -77,4 +77,4 @@ void ExtensionRotatorTest::testCopyConstructor() } -static ExtensionRotatorTest instance; +QTEST_MAIN(ExtensionRotatorTest) diff --git a/tests/src/downloader/file-downloader-test.cpp b/tests/src/downloader/file-downloader-test.cpp index 7fcabf74f..5b5eb69a5 100644 --- a/tests/src/downloader/file-downloader-test.cpp +++ b/tests/src/downloader/file-downloader-test.cpp @@ -76,4 +76,4 @@ void FileDownloaderTest::testFailedStart() } -static FileDownloaderTest instance; +QTEST_MAIN(FileDownloaderTest) diff --git a/tests/src/downloader/image-downloader-test.cpp b/tests/src/downloader/image-downloader-test.cpp index 8eec735e0..a04c2d82b 100644 --- a/tests/src/downloader/image-downloader-test.cpp +++ b/tests/src/downloader/image-downloader-test.cpp @@ -168,4 +168,4 @@ void ImageDownloaderTest::assertDownload(QSharedPointer img, ImageDownloa } -static ImageDownloaderTest instance; +QTEST_MAIN(ImageDownloaderTest) diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index b2914322a..e8070f491 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -299,4 +299,4 @@ void FunctionsTest::assertFixFilename(int platform, const QString &filename, con QCOMPARE(actual, expected); } -static FunctionsTest instance; +QTEST_MAIN(FunctionsTest) diff --git a/tests/src/integration/behoimi-test.cpp b/tests/src/integration/behoimi-test.cpp index e39f525e6..f76540702 100644 --- a/tests/src/integration/behoimi-test.cpp +++ b/tests/src/integration/behoimi-test.cpp @@ -109,4 +109,4 @@ void BehoimiTest::testJsonTags() } -static BehoimiTest instance; +QTEST_MAIN(BehoimiTest) diff --git a/tests/src/integration/booru-org-test.cpp b/tests/src/integration/booru-org-test.cpp index 88a65aa8e..f24272981 100644 --- a/tests/src/integration/booru-org-test.cpp +++ b/tests/src/integration/booru-org-test.cpp @@ -38,4 +38,4 @@ void BooruOrgTest::testPageTags() } -static BooruOrgTest instance; +QTEST_MAIN(BooruOrgTest) diff --git a/tests/src/integration/danbooru-test.cpp b/tests/src/integration/danbooru-test.cpp index aa25ccf42..3716dff7c 100644 --- a/tests/src/integration/danbooru-test.cpp +++ b/tests/src/integration/danbooru-test.cpp @@ -90,4 +90,4 @@ void DanbooruTest::testJsonTags() } -static DanbooruTest instance; +QTEST_MAIN(DanbooruTest) diff --git a/tests/src/integration/derpibooru-test.cpp b/tests/src/integration/derpibooru-test.cpp index a6bb4586c..9a286fc9b 100644 --- a/tests/src/integration/derpibooru-test.cpp +++ b/tests/src/integration/derpibooru-test.cpp @@ -65,4 +65,4 @@ void DerpibooruTest::testJsonTags() } -static DerpibooruTest instance; +QTEST_MAIN(DerpibooruTest) diff --git a/tests/src/integration/e621-test.cpp b/tests/src/integration/e621-test.cpp index 4abae1fee..b6b73176f 100644 --- a/tests/src/integration/e621-test.cpp +++ b/tests/src/integration/e621-test.cpp @@ -93,4 +93,4 @@ void E621Test::testJsonTags() } -static E621Test instance; +QTEST_MAIN(E621Test) diff --git a/tests/src/integration/gelbooru-test.cpp b/tests/src/integration/gelbooru-test.cpp index 065808144..7cc2f0311 100644 --- a/tests/src/integration/gelbooru-test.cpp +++ b/tests/src/integration/gelbooru-test.cpp @@ -68,4 +68,4 @@ void GelbooruTest::testHtmlTags() } -static GelbooruTest instance; +QTEST_MAIN(GelbooruTest) diff --git a/tests/src/integration/sankaku-test.cpp b/tests/src/integration/sankaku-test.cpp index 66df15d5b..ed371e7e0 100755 --- a/tests/src/integration/sankaku-test.cpp +++ b/tests/src/integration/sankaku-test.cpp @@ -44,4 +44,4 @@ void SankakuTest::testAnimatedUrls() } -static SankakuTest instance; +QTEST_MAIN(SankakuTest) diff --git a/tests/src/integration/zerochan-test.cpp b/tests/src/integration/zerochan-test.cpp index bda2cd8ae..d5346639a 100644 --- a/tests/src/integration/zerochan-test.cpp +++ b/tests/src/integration/zerochan-test.cpp @@ -42,4 +42,4 @@ void ZerochanTest::testRss() } -static ZerochanTest instance; +QTEST_MAIN(ZerochanTest) diff --git a/tests/src/loader/token-test.cpp b/tests/src/loader/token-test.cpp index bdfea9663..b06187e66 100644 --- a/tests/src/loader/token-test.cpp +++ b/tests/src/loader/token-test.cpp @@ -35,4 +35,4 @@ void TokenTest::testLazyWithoutCaching() } -static TokenTest instance; +QTEST_MAIN(TokenTest) diff --git a/tests/src/main.cpp b/tests/src/main.cpp index 8ab283715..242d72b4a 100644 --- a/tests/src/main.cpp +++ b/tests/src/main.cpp @@ -12,33 +12,28 @@ int main(int argc, char *argv[]) QGuiApplication a(argc, argv); #endif + // A possible format to filter by test suite it to pass their names as arguments QStringList testSuites; - testSuites.reserve(argc - 1); for (int i = 1; i < argc; ++i) - testSuites.append(argv[i]); - - QMap results; - int failed = 0; + { + QString arg(argv[i]); + if (!arg.startsWith('-') && !arg.startsWith("test")) + testSuites.append(argv[i]); + } + // Used for networking and finding test resource files setTestModeEnabled(true); + // Run all selected test suites + int errorCode = 0; for (TestSuite *suite : TestSuite::getSuites()) { if (!testSuites.isEmpty() && !testSuites.contains(suite->metaObject()->className())) continue; - int result = QTest::qExec(suite); - results.insert(suite->metaObject()->className(), result); - if (result != 0) - { - failed++; - } - } - - for (auto it = results.begin(); it != results.end(); ++it) - { - std::cout << '[' << (it.value() != 0 ? "FAIL" : "OK") << "] " << it.key().toStdString() << std::endl; + errorCode |= QTest::qExec(suite, argc, argv); + std::cout << std::endl; } - return failed; + return errorCode; } diff --git a/tests/src/mixed-settings-test.cpp b/tests/src/mixed-settings-test.cpp index 1ff95e99f..820adef56 100644 --- a/tests/src/mixed-settings-test.cpp +++ b/tests/src/mixed-settings-test.cpp @@ -93,4 +93,4 @@ void MixedSettingsTest::testChildKeys() } -static MixedSettingsTest instance; +QTEST_MAIN(MixedSettingsTest) diff --git a/tests/src/models/favorite-test.cpp b/tests/src/models/favorite-test.cpp index 9c4f16591..6febc7968 100644 --- a/tests/src/models/favorite-test.cpp +++ b/tests/src/models/favorite-test.cpp @@ -272,4 +272,4 @@ void FavoriteTest::testSortByLastViewed() } -static FavoriteTest instance; +QTEST_MAIN(FavoriteTest) diff --git a/tests/src/models/filename-test.cpp b/tests/src/models/filename-test.cpp index 01615a9b8..5148d5445 100644 --- a/tests/src/models/filename-test.cpp +++ b/tests/src/models/filename-test.cpp @@ -740,4 +740,5 @@ void FilenameTest::assertExpand(const QString &format, const QString &expected) QCOMPARE(actual, expected); } -static FilenameTest instance; + +QTEST_MAIN(FilenameTest) diff --git a/tests/src/models/filtering/blacklist-test.cpp b/tests/src/models/filtering/blacklist-test.cpp index d53694d71..61486f6ee 100644 --- a/tests/src/models/filtering/blacklist-test.cpp +++ b/tests/src/models/filtering/blacklist-test.cpp @@ -54,4 +54,4 @@ void BlacklistTest::testMatch() } -static BlacklistTest instance; +QTEST_MAIN(BlacklistTest) diff --git a/tests/src/models/filtering/meta-filter-test.cpp b/tests/src/models/filtering/meta-filter-test.cpp index be0f127fd..aaf4fe909 100644 --- a/tests/src/models/filtering/meta-filter-test.cpp +++ b/tests/src/models/filtering/meta-filter-test.cpp @@ -135,4 +135,4 @@ void MetaFilterTest::testMatchString() } -static MetaFilterTest instance; +QTEST_MAIN(MetaFilterTest) diff --git a/tests/src/models/filtering/post-filter-test.cpp b/tests/src/models/filtering/post-filter-test.cpp index e5ae839f9..c063e96a8 100644 --- a/tests/src/models/filtering/post-filter-test.cpp +++ b/tests/src/models/filtering/post-filter-test.cpp @@ -106,4 +106,4 @@ void PostFilterTest::testFilterInvert() } -static PostFilterTest instance; +QTEST_MAIN(PostFilterTest) diff --git a/tests/src/models/filtering/tag-filter-test.cpp b/tests/src/models/filtering/tag-filter-test.cpp index d4b96d8ca..54cc10e93 100644 --- a/tests/src/models/filtering/tag-filter-test.cpp +++ b/tests/src/models/filtering/tag-filter-test.cpp @@ -46,4 +46,4 @@ void TagFilterTest::testMatchWildcard() } -static TagFilterTest instance; +QTEST_MAIN(TagFilterTest) diff --git a/tests/src/models/filtering/token-filter-test.cpp b/tests/src/models/filtering/token-filter-test.cpp index 060e19974..92603db29 100644 --- a/tests/src/models/filtering/token-filter-test.cpp +++ b/tests/src/models/filtering/token-filter-test.cpp @@ -69,4 +69,4 @@ void TokenFilterTest::testMatchStringList() } -static TokenFilterTest instance; +QTEST_MAIN(TokenFilterTest) diff --git a/tests/src/models/image-test.cpp b/tests/src/models/image-test.cpp index 0d95178a5..8f1b01511 100644 --- a/tests/src/models/image-test.cpp +++ b/tests/src/models/image-test.cpp @@ -372,4 +372,4 @@ void ImageTest::testSetUrl() } -static ImageTest instance; +QTEST_MAIN(ImageTest) diff --git a/tests/src/models/page-api-test.cpp b/tests/src/models/page-api-test.cpp index d2fb7e4a7..0144d3c36 100644 --- a/tests/src/models/page-api-test.cpp +++ b/tests/src/models/page-api-test.cpp @@ -66,4 +66,4 @@ void PageApiTest::testParseUrlAltPage() } -static PageApiTest instance; +QTEST_MAIN(PageApiTest) diff --git a/tests/src/models/page-test.cpp b/tests/src/models/page-test.cpp index 16bb2d873..53d1bfe05 100644 --- a/tests/src/models/page-test.cpp +++ b/tests/src/models/page-test.cpp @@ -46,4 +46,4 @@ void PageTest::testLoadTagsAbort() } -static PageTest instance; +QTEST_MAIN(PageTest) diff --git a/tests/src/models/pool-test.cpp b/tests/src/models/pool-test.cpp index d08cb7967..dae900278 100644 --- a/tests/src/models/pool-test.cpp +++ b/tests/src/models/pool-test.cpp @@ -7,25 +7,30 @@ void PoolTest::testGetId() Pool pool(123, "Test pool", 1, 2, 3); QCOMPARE(pool.id(), 123); } + void PoolTest::testGetName() { Pool pool(123, "Test pool", 1, 2, 3); QCOMPARE(pool.name(), QString("Test pool")); } + void PoolTest::testGetCurrent() { Pool pool(123, "Test pool", 1, 2, 3); QCOMPARE(pool.current(), 1); } + void PoolTest::testGetNext() { Pool pool(123, "Test pool", 1, 2, 3); QCOMPARE(pool.next(), 2); } + void PoolTest::testGetPrevious() { Pool pool(123, "Test pool", 1, 2, 3); QCOMPARE(pool.previous(), 3); } -static PoolTest instance; + +QTEST_MAIN(PoolTest) diff --git a/tests/src/models/profile-test.cpp b/tests/src/models/profile-test.cpp index 2f7f63c8d..126fd888d 100644 --- a/tests/src/models/profile-test.cpp +++ b/tests/src/models/profile-test.cpp @@ -216,4 +216,4 @@ void ProfileTest::testMd5ActionKeepDeleted() -static ProfileTest instance; +QTEST_MAIN(ProfileTest) diff --git a/tests/src/models/site-test.cpp b/tests/src/models/site-test.cpp index ff63b8dc0..6a411b6d0 100755 --- a/tests/src/models/site-test.cpp +++ b/tests/src/models/site-test.cpp @@ -227,4 +227,4 @@ void SiteTest::testLoginPost() } -static SiteTest instance; +QTEST_MAIN(SiteTest) diff --git a/tests/src/models/source-guesser-test.cpp b/tests/src/models/source-guesser-test.cpp index 190dad2a8..d557f886c 100644 --- a/tests/src/models/source-guesser-test.cpp +++ b/tests/src/models/source-guesser-test.cpp @@ -73,4 +73,4 @@ void SourceGuesserTest::testDanbooru2() } -static SourceGuesserTest instance; +QTEST_MAIN(SourceGuesserTest) diff --git a/tests/src/models/source-test.cpp b/tests/src/models/source-test.cpp index bab9b67d7..bff229e71 100644 --- a/tests/src/models/source-test.cpp +++ b/tests/src/models/source-test.cpp @@ -90,4 +90,4 @@ void SourceTest::testIgnoreEmptySites() } -static SourceTest instance; +QTEST_MAIN(SourceTest) diff --git a/tests/src/tags/tag-api-test.cpp b/tests/src/tags/tag-api-test.cpp index 06deb040b..eaea768bb 100644 --- a/tests/src/tags/tag-api-test.cpp +++ b/tests/src/tags/tag-api-test.cpp @@ -39,4 +39,4 @@ void TagApiTest::testBasic() } -static TagApiTest instance; +QTEST_MAIN(TagApiTest) diff --git a/tests/src/tags/tag-database-in-memory-test.cpp b/tests/src/tags/tag-database-in-memory-test.cpp index 54307816e..0b434aefc 100644 --- a/tests/src/tags/tag-database-in-memory-test.cpp +++ b/tests/src/tags/tag-database-in-memory-test.cpp @@ -113,4 +113,4 @@ void TagDatabaseInMemoryTest::saveData() } -static TagDatabaseInMemoryTest instance; +QTEST_MAIN(TagDatabaseInMemoryTest) diff --git a/tests/src/tags/tag-database-sqlite-test.cpp b/tests/src/tags/tag-database-sqlite-test.cpp index 15ad80b13..ea9c54f52 100644 --- a/tests/src/tags/tag-database-sqlite-test.cpp +++ b/tests/src/tags/tag-database-sqlite-test.cpp @@ -8,4 +8,4 @@ TagDatabaseSqliteTest::TagDatabaseSqliteTest() {} -static TagDatabaseSqliteTest instance; +QTEST_MAIN(TagDatabaseSqliteTest) diff --git a/tests/src/tags/tag-name-format-test.cpp b/tests/src/tags/tag-name-format-test.cpp index e58f6abff..2b8ca16c0 100644 --- a/tests/src/tags/tag-name-format-test.cpp +++ b/tests/src/tags/tag-name-format-test.cpp @@ -53,4 +53,4 @@ void TagNameFormatTest::testUnknown() } -static TagNameFormatTest instance; +QTEST_MAIN(TagNameFormatTest) diff --git a/tests/src/tags/tag-name-test.cpp b/tests/src/tags/tag-name-test.cpp index 7ee7e4905..902f2c4c4 100644 --- a/tests/src/tags/tag-name-test.cpp +++ b/tests/src/tags/tag-name-test.cpp @@ -45,4 +45,4 @@ void TagNameTest::testCompare() } -static TagNameTest instance; +QTEST_MAIN(TagNameTest) diff --git a/tests/src/tags/tag-stylist-test.cpp b/tests/src/tags/tag-stylist-test.cpp index 9a26ecf10..42f13e71a 100644 --- a/tests/src/tags/tag-stylist-test.cpp +++ b/tests/src/tags/tag-stylist-test.cpp @@ -143,4 +143,4 @@ void TagStylistTest::assertSort(const QString &sort, const QStringList &expected } -static TagStylistTest instance; +QTEST_MAIN(TagStylistTest) diff --git a/tests/src/tags/tag-test.cpp b/tests/src/tags/tag-test.cpp index bbb46a656..f224427c3 100644 --- a/tests/src/tags/tag-test.cpp +++ b/tests/src/tags/tag-test.cpp @@ -228,4 +228,4 @@ void TagTest::testGetType() } -static TagTest instance; +QTEST_MAIN(TagTest) diff --git a/tests/src/test-suite.h b/tests/src/test-suite.h index dd375d59a..3b32bf826 100644 --- a/tests/src/test-suite.h +++ b/tests/src/test-suite.h @@ -7,6 +7,9 @@ #include "models/profile.h" +#define QTEST_MAIN(CLASS_NAME) static CLASS_NAME instance; + + #ifdef _MSC_VER #include diff --git a/tests/src/updater/source-updater-test.cpp b/tests/src/updater/source-updater-test.cpp index d5a1546dc..2a669a54e 100644 --- a/tests/src/updater/source-updater-test.cpp +++ b/tests/src/updater/source-updater-test.cpp @@ -39,4 +39,4 @@ void SourceUpdaterTest::testChanged() #endif -static SourceUpdaterTest instance; +QTEST_MAIN(SourceUpdaterTest) diff --git a/tests/src/updater/updater-test.cpp b/tests/src/updater/updater-test.cpp index e984d9d49..9554115fe 100644 --- a/tests/src/updater/updater-test.cpp +++ b/tests/src/updater/updater-test.cpp @@ -55,4 +55,4 @@ void UpdaterTest::testCompareAlphaToOld() } -static UpdaterTest instance; +QTEST_MAIN(UpdaterTest) From 46b0b6f7c7712fe984473d3c501f7a73b02d0460 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 4 Aug 2018 15:54:48 +0200 Subject: [PATCH 103/112] Disable macro redefinition via pragmas --- tests/CMakeLists.txt | 4 ---- tests/src/test-suite.h | 14 ++++++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0b7968285..c40b1a2a4 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -12,10 +12,6 @@ set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Test Qt5::Widgets) file(GLOB_RECURSE SOURCES "src/*.cpp") include_directories("src/" "../lib/src/") -if(MSVC OR CMAKE_CXX_COMPILER MATCHES "cl\\.exe") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4005") # Suppress "macro redifinition" warnings -endif() - add_executable(${PROJECT_NAME} ${SOURCES}) add_test(${PROJECT_NAME} ${PROJECT_NAME}) target_link_libraries(${PROJECT_NAME} ${QT_LIBRARIES} lib) diff --git a/tests/src/test-suite.h b/tests/src/test-suite.h index 3b32bf826..cdcc3ee40 100644 --- a/tests/src/test-suite.h +++ b/tests/src/test-suite.h @@ -7,8 +7,22 @@ #include "models/profile.h" +#ifdef _MSC_VER + #pragma warning(push) + #pragma warning(disable: 4005) +#else + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wmacro-redefined" +#endif + #define QTEST_MAIN(CLASS_NAME) static CLASS_NAME instance; +#ifdef _MSC_VER + #pragma warning(pop) +#else + #pragma GCC diagnostic pop +#endif + #ifdef _MSC_VER #include From 8afe9c4ba71fd5db31d373003e56d36ee4ce2286 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 4 Aug 2018 15:56:40 +0200 Subject: [PATCH 104/112] Stop using deleted object in PageApiTest --- tests/src/models/page-api-test.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/src/models/page-api-test.cpp b/tests/src/models/page-api-test.cpp index 0144d3c36..49f91b915 100644 --- a/tests/src/models/page-api-test.cpp +++ b/tests/src/models/page-api-test.cpp @@ -26,6 +26,7 @@ void PageApiTest::cleanup() { m_profile->deleteLater(); m_sites.first()->deleteLater(); + m_sites.clear(); m_site->deleteLater(); QFile::remove("tests/resources/sites/Danbooru (2.0)/danbooru.donmai.us/defaults.ini"); From 9d5e694a87ee1b9d33bede3ea426d15f8db92308 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 4 Aug 2018 16:34:11 +0200 Subject: [PATCH 105/112] Reproduce created() behavior in 5.10+ for tests --- tests/src/functions-test.cpp | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index e8070f491..69cb4a77a 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -3,6 +3,20 @@ #include "functions-test.h" +QDateTime fileCreationDate(const QString &path) +{ + QFileInfo fi(path); + #if (QT_VERSION < QT_VERSION_CHECK(5, 10, 0)) + return fi.created(); + #else + QDateTime d = fi.birthTime(); + if (d.isValid()) + return d; + return fi.metadataChangeTime(); + #endif +} + + void FunctionsTest::testCopyRecursively() { QString from = QDir::toNativeSeparators("tests/resources/recurse/"); @@ -255,13 +269,7 @@ void FunctionsTest::testSetFileCreationDate() setFileCreationDate(path, date); - QDateTime created; - #if (QT_VERSION < QT_VERSION_CHECK(5, 10, 0)) - created = QFileInfo(path).created(); - #else - created = QFileInfo(path).birthTime(); - #endif - + QDateTime created = fileCreationDate(path); QCOMPARE(created.toTime_t(), date.toTime_t()); } void FunctionsTest::testSetFileCreationDateUtf8() @@ -271,13 +279,7 @@ void FunctionsTest::testSetFileCreationDateUtf8() setFileCreationDate(path, date); - QDateTime created; - #if (QT_VERSION < QT_VERSION_CHECK(5, 10, 0)) - created = QFileInfo(path).created(); - #else - created = QFileInfo(path).birthTime(); - #endif - + QDateTime created = fileCreationDate(path); QCOMPARE(created.toTime_t(), date.toTime_t()); } From 83894706fb12b4b0079abb6634ca0360405693a4 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sat, 4 Aug 2018 16:47:54 +0200 Subject: [PATCH 106/112] Don't run creation date tests on Travis MacOS --- CMakeLists.txt | 6 ++++++ tests/src/functions-test.cpp | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index d7b6126ab..fc1611be0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,6 +50,12 @@ if((DEFINED ENV{TRAVIS}) AND UNIX AND NOT APPLE AND CMAKE_COMPILER_IS_GNUCXX) include(cmake/CodeCoverage.cmake) setup_target_for_coverage(coverage tests coverage) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage") + add_definitions(-DTRAVIS=1) + if("$ENV{TRAVIS_OS_NAME}" STREQUAL "osx") + add_definitions(-DTRAVIS_OS_OSX=1) + elseif("$ENV{TRAVIS_OS_NAME}" STREQUAL "linux") + add_definitions(-DTRAVIS_OS_LINUX=1) + endif() endif() add_subdirectory(lib) diff --git a/tests/src/functions-test.cpp b/tests/src/functions-test.cpp index 69cb4a77a..9c4b491e0 100644 --- a/tests/src/functions-test.cpp +++ b/tests/src/functions-test.cpp @@ -264,6 +264,7 @@ void FunctionsTest::testParseMarkdownIssueLinks() void FunctionsTest::testSetFileCreationDate() { +#if !defined(Q_OS_MACOS) QString path = "tests/resources/pages/behoimi.org/results.json"; QDateTime date = QDateTime::currentDateTimeUtc(); @@ -271,9 +272,11 @@ void FunctionsTest::testSetFileCreationDate() QDateTime created = fileCreationDate(path); QCOMPARE(created.toTime_t(), date.toTime_t()); +#endif } void FunctionsTest::testSetFileCreationDateUtf8() { +#if !defined(Q_OS_MACOS) QString path = "tests/resources/你好.txt"; QDateTime date = QDateTime::currentDateTimeUtc(); @@ -281,6 +284,7 @@ void FunctionsTest::testSetFileCreationDateUtf8() QDateTime created = fileCreationDate(path); QCOMPARE(created.toTime_t(), date.toTime_t()); +#endif } From aeecc4227f4e3679a8a4b9eda6005b48147cfd88 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 5 Aug 2018 12:52:31 +0200 Subject: [PATCH 107/112] Fix line breaks in issue templates --- .github/ISSUE_TEMPLATE/bug-report.md | 9 ++++++++- .github/ISSUE_TEMPLATE/crash-report.md | 7 ++++++- .github/ISSUE_TEMPLATE/feature-request.md | 6 +++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index f62dce109..9c058c630 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -1,21 +1,25 @@ --- name: Bug report -about: Create a report to help us improve +about: Report a bug to help us fix it --- **Bug description** + A clear and concise description of what the bug is. **Steps to reproduce** + 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** + A clear and concise description of what you expected to happen. **Context** + * Provide your `main.log` file to see if any obvious error occured. * Providing your `settings.ini` file will greatly help maintainers reproduce your problem if it may be caused by your configuration. * If the bug occured during a download, make sure to provide said download as an `.igl` file that Grabber can generate by clicking the `Save` button of the `Downloads` tab. @@ -23,11 +27,14 @@ A clear and concise description of what you expected to happen. Note that both `main.log` and `settings.ini` files can be found in `C:/Users/%USERNAME%/AppData/Local/Bionus/Grabber` in Windows, and in the installation directory on Linux. **Screenshots** + If applicable, add screenshots to help explain your problem. **System information** + - OS: [e.g. Windows 10] - Grabber version: [e.g. 6.0.3] **Additional context** + Add any other context about the bug report here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/crash-report.md b/.github/ISSUE_TEMPLATE/crash-report.md index b79e67acb..ff5c1e63a 100644 --- a/.github/ISSUE_TEMPLATE/crash-report.md +++ b/.github/ISSUE_TEMPLATE/crash-report.md @@ -1,15 +1,17 @@ --- name: Crash report -about: Create a report to help us improve +about: Report a program crash to help us fix it --- **Steps to reproduce** + 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Context** + * Provide your `main.log` file to see if any obvious error occured. * Providing your `settings.ini` file will greatly help maintainers reproduce your problem if it may be caused by your configuration. * If the crash occured during a download, make sure to provide said download as an `.igl` file that Grabber can generate by clicking the `Save` button of the `Downloads` tab. @@ -18,11 +20,14 @@ about: Create a report to help us improve Note that both `main.log` and `settings.ini` files can be found in `C:/Users/%USERNAME%/AppData/Local/Bionus/Grabber` in Windows, and in the installation directory on Linux. **Screenshots** + If applicable, add screenshots to help explain your problem. **System information** + - OS: [e.g. Windows 10] - Grabber version: [e.g. 6.0.3] **Additional context** + Add any other context about the crash report here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md index b2ac4c41c..909b72f57 100644 --- a/.github/ISSUE_TEMPLATE/feature-request.md +++ b/.github/ISSUE_TEMPLATE/feature-request.md @@ -3,14 +3,18 @@ name: Feature request about: Suggest an idea for this project --- -**Is your feature request related to a problem? Please describe.** +**Is your feature request related to a problem? Please describe** + A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** + A clear and concise description of what you want to happen. **Describe alternatives you've considered** + A clear and concise description of any alternative solutions or features you've considered. **Additional context** + Add any other context or screenshots about the feature request here. \ No newline at end of file From 49cc8047c2af53e3419b84dae4145546e8bad72c Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 5 Aug 2018 13:44:52 +0200 Subject: [PATCH 108/112] Don't pass custom arguments to QTest::qExec --- tests/src/main.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/src/main.cpp b/tests/src/main.cpp index 242d72b4a..1404adcee 100644 --- a/tests/src/main.cpp +++ b/tests/src/main.cpp @@ -14,11 +14,14 @@ int main(int argc, char *argv[]) // A possible format to filter by test suite it to pass their names as arguments QStringList testSuites; + QStringList arguments; for (int i = 1; i < argc; ++i) { QString arg(argv[i]); if (!arg.startsWith('-') && !arg.startsWith("test")) - testSuites.append(argv[i]); + testSuites.append(arg); + else + arguments.append(arg); } // Used for networking and finding test resource files @@ -31,7 +34,7 @@ int main(int argc, char *argv[]) if (!testSuites.isEmpty() && !testSuites.contains(suite->metaObject()->className())) continue; - errorCode |= QTest::qExec(suite, argc, argv); + errorCode |= QTest::qExec(suite, arguments); std::cout << std::endl; } From eca0c41c9f5551ec2fb388e5fafa14b28b7be0dc Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 5 Aug 2018 13:45:41 +0200 Subject: [PATCH 109/112] Add support for 'age' post-filter (fix #1354) --- lib/src/models/filtering/meta-filter.cpp | 119 +++++++++++++----- .../src/models/filtering/meta-filter-test.cpp | 20 +++ tests/src/models/filtering/meta-filter-test.h | 1 + 3 files changed, 107 insertions(+), 33 deletions(-) diff --git a/lib/src/models/filtering/meta-filter.cpp b/lib/src/models/filtering/meta-filter.cpp index 96e2a6a0b..518279e6e 100644 --- a/lib/src/models/filtering/meta-filter.cpp +++ b/lib/src/models/filtering/meta-filter.cpp @@ -1,7 +1,9 @@ #include "meta-filter.h" #include #include +#include #include +#include MetaFilter::MetaFilter(QString type, QString val, bool invert) @@ -22,7 +24,7 @@ bool MetaFilter::compare(const Filter& rhs) const return m_type == other->m_type && m_val == other->m_val; } -static int toDate(const QString &text) +static int dateToInt(const QString &text) { QDateTime date = QDateTime::fromString(text, "yyyy-MM-dd"); if (date.isValid()) @@ -33,6 +35,68 @@ static int toDate(const QString &text) return 0; } +static int stringToInt(const QString &text) +{ return text.toInt(); } + +// FIXME(Bionus): remove globals +static QDateTime ageToDateImage; +static QDateTime ageToDateTestNow; +static QDateTime ageToDate(const QString &text) +{ + static QRegularExpression rx("^(\\d+)(\\w+)$"); + auto match = rx.match(text); + if (!match.hasMatch()) + return QDateTime(); + + const int count = match.captured(1).toInt(); + const QString type = match.captured(2); + + // Define "now" with the correct timezone + QDateTime base; + if (ageToDateTestNow.isValid()) + { base = ageToDateTestNow; } + else + { + base = QDateTime::currentDateTimeUtc(); + base.setTimeZone(ageToDateImage.timeZone()); + } + + if (type.startsWith("y")) + return base.addYears(-count); + if (type.startsWith("mo")) + return base.addMonths(-count); + if (type.startsWith("w")) + return base.addDays(-(count * 7)); + if (type.startsWith("d")) + return base.addDays(-count); + if (type.startsWith("h")) + return base.addSecs(-(count * 60 * 60)); + if (type.startsWith("mi")) + return base.addSecs(-(count * 60)); + if (type.startsWith("s")) + return base.addSecs(-count); + + return QDateTime(); +} + +template +static bool rangeCheck(T (*converter)(const QString &), T input, const QString &val) +{ + if (val.startsWith("..") || val.startsWith("<=")) + { return input <= converter(val.right(val.size() - 2)); } + if (val.endsWith("..")) + { return input >= converter(val.left(val.size() - 2)); } + if (val.startsWith(">=")) + { return input >= converter(val.right(val.size() - 2)); } + if (val.startsWith("<")) + { return input < converter(val.right(val.size() - 1)); } + if (val.startsWith(">")) + { return input > converter(val.right(val.size() - 1)); } + if (val.contains("..")) + { return input >= converter(val.left(val.indexOf(".."))) && input <= converter(val.right(val.size() - val.indexOf("..") - 2)); } + return input == converter(val); +} + QString MetaFilter::match(const QMap &tokens, bool invert) const { if (m_invert) @@ -52,6 +116,25 @@ QString MetaFilter::match(const QMap &tokens, bool invert) const return QString(); } + // Non-token metas + if (m_type == "age") + { + if (!tokens.contains("date")) + { return QObject::tr("An image needs a date to be filtered by age"); } + + const QDateTime &date = tokens["date"].value().toDateTime(); + ageToDateImage = date; + ageToDateTestNow = tokens["TESTS_now"].value().toDateTime(); + bool cond = rangeCheck(ageToDate, date, m_val); + + if (cond && !invert) + { return QObject::tr("image's %1 does not match").arg(m_type); } + if (!cond && invert) + { return QObject::tr("image's %1 match").arg(m_type); } + + return QString(); + } + // Meta tokens if (!tokens.contains(m_type)) { @@ -72,39 +155,9 @@ QString MetaFilter::match(const QMap &tokens, bool invert) const bool cond; if (token.type() == QVariant::DateTime) - { - if (m_val.startsWith("..") || m_val.startsWith("<=")) - { cond = input <= toDate(m_val.right(m_val.size() - 2)); } - else if (m_val.endsWith("..")) - { cond = input >= toDate(m_val.left(m_val.size() - 2)); } - else if (m_val.startsWith(">=")) - { cond = input >= toDate(m_val.right(m_val.size() - 2)); } - else if (m_val.startsWith("<")) - { cond = input < toDate(m_val.right(m_val.size() - 1)); } - else if (m_val.startsWith(">")) - { cond = input > toDate(m_val.right(m_val.size() - 1)); } - else if (m_val.contains("..")) - { cond = input >= toDate(m_val.left(m_val.indexOf(".."))) && input <= toDate(m_val.right(m_val.size() - m_val.indexOf("..") - 2)); } - else - { cond = input == toDate(m_val); } - } + { cond = rangeCheck(dateToInt, input, m_val); } else - { - if (m_val.startsWith("..") || m_val.startsWith("<=")) - { cond = input <= m_val.rightRef(m_val.size() - 2).toInt(); } - else if (m_val.endsWith("..")) - { cond = input >= m_val.leftRef(m_val.size() - 2).toInt(); } - else if (m_val.startsWith(">=")) - { cond = input >= m_val.rightRef(m_val.size() - 2).toInt(); } - else if (m_val.startsWith("<")) - { cond = input < m_val.rightRef(m_val.size() - 1).toInt(); } - else if (m_val.startsWith(">")) - { cond = input > m_val.rightRef(m_val.size() - 1).toInt(); } - else if (m_val.contains("..")) - { cond = input >= m_val.leftRef(m_val.indexOf("..")).toInt() && input <= m_val.rightRef(m_val.size() - m_val.indexOf("..") - 2).toInt(); } - else - { cond = input == m_val.toInt(); } - } + { cond = rangeCheck(stringToInt, input, m_val); } if (!cond && !invert) { return QObject::tr("image's %1 does not match").arg(m_type); } diff --git a/tests/src/models/filtering/meta-filter-test.cpp b/tests/src/models/filtering/meta-filter-test.cpp index aaf4fe909..3fb04f45c 100644 --- a/tests/src/models/filtering/meta-filter-test.cpp +++ b/tests/src/models/filtering/meta-filter-test.cpp @@ -134,5 +134,25 @@ void MetaFilterTest::testMatchString() QCOMPARE(MetaFilter("meta", "nok", true).match(tokens), QString()); } +void MetaFilterTest::testMatchAge() +{ + QMap tokens; + QCOMPARE(MetaFilter("age", "1year..1day").match(tokens), QString("An image needs a date to be filtered by age")); + + tokens.insert("date", Token(QDateTime(QDate(2016, 8, 18)))); + tokens.insert("TESTS_now", Token(QDateTime(QDate(2016, 10, 16)))); + + // Basic + QCOMPARE(MetaFilter("age", ">=2hours").match(tokens), QString()); + QCOMPARE(MetaFilter("age", ">1day").match(tokens), QString()); + QCOMPARE(MetaFilter("age", ">1mo").match(tokens), QString()); + QCOMPARE(MetaFilter("age", ">=1y").match(tokens), QString("image's age does not match")); + QCOMPARE(MetaFilter("age", "<1year").match(tokens), QString()); + + // Invert + QCOMPARE(MetaFilter("age", ">=1y", true).match(tokens), QString()); + QCOMPARE(MetaFilter("age", "<1year", true).match(tokens), QString("image's age match")); +} + QTEST_MAIN(MetaFilterTest) diff --git a/tests/src/models/filtering/meta-filter-test.h b/tests/src/models/filtering/meta-filter-test.h index 1f33d0a9f..d2854a3ef 100644 --- a/tests/src/models/filtering/meta-filter-test.h +++ b/tests/src/models/filtering/meta-filter-test.h @@ -18,6 +18,7 @@ class MetaFilterTest : public TestSuite void testMatchRating(); void testMatchSource(); void testMatchString(); + void testMatchAge(); }; #endif // META_FILTER_TEST_H From e54d9642281dffbc04a365d5ac33d5c8aa00ae16 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 5 Aug 2018 17:21:32 +0200 Subject: [PATCH 110/112] Stop converting dates to int before comparison in MetaFilter --- lib/src/models/filtering/meta-filter.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/lib/src/models/filtering/meta-filter.cpp b/lib/src/models/filtering/meta-filter.cpp index 518279e6e..3a4894f3f 100644 --- a/lib/src/models/filtering/meta-filter.cpp +++ b/lib/src/models/filtering/meta-filter.cpp @@ -24,15 +24,15 @@ bool MetaFilter::compare(const Filter& rhs) const return m_type == other->m_type && m_val == other->m_val; } -static int dateToInt(const QString &text) +static QDateTime stringToDate(const QString &text) { QDateTime date = QDateTime::fromString(text, "yyyy-MM-dd"); if (date.isValid()) - { return date.toString("yyyyMMdd").toInt(); } + { return date; } date = QDateTime::fromString(text, "MM/dd/yyyy"); if (date.isValid()) - { return date.toString("yyyyMMdd").toInt(); } - return 0; + { return date; } + return QDateTime(); } static int stringToInt(const QString &text) @@ -148,14 +148,12 @@ QString MetaFilter::match(const QMap &tokens, bool invert) const int input = 0; if (token.type() == QVariant::Int) { input = token.toInt(); } - else if (token.type() == QVariant::DateTime) - { input = token.toDateTime().toString("yyyyMMdd").toInt(); } else if (token.type() == QVariant::ULongLong) { input = token.toULongLong(); } bool cond; if (token.type() == QVariant::DateTime) - { cond = rangeCheck(dateToInt, input, m_val); } + { cond = rangeCheck(stringToDate, token.toDateTime(), m_val); } else { cond = rangeCheck(stringToInt, input, m_val); } From 7f208f66c47eb7e3f6f5c0a2dd44e9b258042578 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 5 Aug 2018 17:24:39 +0200 Subject: [PATCH 111/112] Update language files --- languages/ChineseSimplified.ts | 721 ++++++++++++++++---------------- languages/English.ts | 731 +++++++++++++++++---------------- languages/French.ts | 723 ++++++++++++++++---------------- languages/Russian.ts | 721 ++++++++++++++++---------------- languages/Spanish.ts | 721 ++++++++++++++++---------------- languages/YourLanguage.ts | 731 +++++++++++++++++---------------- 6 files changed, 2263 insertions(+), 2085 deletions(-) diff --git a/languages/ChineseSimplified.ts b/languages/ChineseSimplified.ts index 19d8706d5..00b0620b8 100644 --- a/languages/ChineseSimplified.ts +++ b/languages/ChineseSimplified.ts @@ -28,12 +28,12 @@ 俄语翻译:Николай Тихонов。 - + Grabber is up to date Grabber 已经是最新版本 - + A new version is available: %1 有新版本可用:%1 @@ -124,12 +124,12 @@ 浏览 - + Choose a save folder 选择保存的文件夹 - + No image found. 找不到图片。 @@ -137,16 +137,15 @@ Api - Tag search is impossible with the chosen source (%1). - 选定的来源无法进行标签搜索(%1)。 + 选定的来源无法进行标签搜索(%1)。 BlacklistFix1 - + Blacklist fixer 黑名单修复 @@ -196,17 +195,17 @@ 取消 - + This directory does not exist. 这个目录不存在。 - + If you want to get the MD5 from the filename, you have to include the %md5% token in it. 如果你想要从文件名获得 MD5,你必须先添加 %md5% 变量到文件名中。 - + You are about to download information from %n image(s). Are you sure you want to continue? 你将要下载 %n 张图片的信息。你确定要继续吗? @@ -468,12 +467,12 @@ Javascript 命名方式 - + Warning 警告 - + You script contains error, are you sure you want to save it? 你的脚本包含错误,你确定要保存吗? @@ -517,168 +516,168 @@ 图片包含 "%1" - + <b>Tags:</b> %1<br/><br/> <b>标签:</b> %1<br/><br/> - - + + <b>ID:</b> %1<br/> <b>ID:</b> %1<br/> - + <b>Name:</b> %1<br/> - + <b>Rating:</b> %1<br/> <b>分级:</b> %1<br/> - + <b>Score:</b> %1<br/> <b>得分:</b> %1<br/> - + <b>User:</b> %1<br/><br/> <b>用户:</b> %1<br/><br/> - + <b>Size:</b> %1 x %2<br/> <b>大小:</b> %1 x %2<br/> - + <b>Filesize:</b> %1 %2<br/> <b>文件大小:</b> %1 %2<br/> - + <b>Date:</b> %1 <b>日期:</b> %1 - + 'the 'MM/dd/yyyy' at 'hh:mm 'MM/dd/yyyy' 于 'hh:mm - + <i>Unknown</i> <i>未知</i> - + yes - + no - + Tags 标签 - + ID ID - + MD5 MD5 - + Rating 评级 - + Score 得分 - + Author 作者 - + Date 日期 - + 'the' MM/dd/yyyy 'at' hh:mm 'the' MM/dd/yyyy 'at' hh:mm - + Size 大小 - + Filesize 文件大小 - + Page 页面 - + URL URL - + Source 来源 - + Sample 样本 - + Thumbnail 缩略图 - + Parent 父级 - + yes (#%1) 是 (#%1) - + Comments 评论 - + Children 子级 - + Notes 注释 @@ -800,7 +799,7 @@ Page - + No valid source of the site returned result. 没有有效的站点返回数据来源。 @@ -889,7 +888,7 @@ <b>提示</b> %1 - + MM-dd-yyyy HH.mm MM-dd-yyyy HH.mm @@ -898,99 +897,107 @@ Javascript 测试失败:<br/> - + Filename must not be empty! 文件名不能为空! - + Can't validate Javascript expressions. 无法验证 Javascript 表达式。 - + Your filename doesn't ends by an extension, symbolized by %ext%! You may not be able to open saved files. 你的文件名不以扩展名结束,请添加 %ext%!否则你可能无法打开保存的文件。 - + Your filename is not unique to each image and an image may overwrite a previous one at saving! You should use%md5%, which is unique to each image, to avoid this inconvenience. 你的文件名不唯一,新图片可能会将之前的图片覆盖!你应该使用 %md5%,因为它是唯一的,可以避免不便。 - + The %%1% token does not exist and will not be replaced. %%1% 变量不存在,且不会被替换。 - + Your format contains characters forbidden on Windows! Forbidden characters: * ? " : < > | 你的文件名格式存在 Windows 不允许的字符!不允许的字符: * ? " : < > | - + You have chosen to use the %id% token. Know that it is only unique for a selected site. The same ID can identify different images depending on the site. 你选择使用 %id% 变量。它只在特定的站点唯一。相同的 ID 可能在其他站点代表不同的图片。 - + Valid filename! 文件名有效! - + image has a "%1" token - + image does not have a "%1" token - unknown type "%1" (available types: "%2") - 未知格式 "%1" (可用格式:"%2") + 未知格式 "%1" (可用格式:"%2") - - + + + image's %1 does not match 图片的 %1 不符合 - - + + + image's %1 match 图片的 %1 符合 - + + image is not "%1" 图片不是 "%1" - + + image is "%1" 图片是 "%1" - + + An image needs a date to be filtered by age + + + + image's source does not starts with "%1" 图片的来源不以 "%1" 开头 - + image's source starts with "%1" 图片的来源以 "%1" 开头 - + image does not contains "%1" 图片不包含 "%1" - + image contains "%1" 图片包含 "%1" @@ -999,7 +1006,7 @@ RenameExisting1 - + Rename existing images 重命名已有图片 @@ -1064,7 +1071,7 @@ 如果你想要从文件名获得 MD5,你必须先添加 %md5% 变量到文件名中。 - + You are about to download information from %n image(s). Are you sure you want to continue? 你将要下载 %n 张图片的信息。你确定要继续吗? @@ -1316,12 +1323,12 @@ %v/%m - + The url you entered is not valid. - + Unable to guess site's type. Are you sure about the url? 无法猜测站点类型。你确定这是一个 url 吗? @@ -1696,115 +1703,125 @@ 确定 - + Hash a password 计算密码哈希值 - + Please enter your password below.<br/>It will then be hashed using the format "%1". 请在下面输入你的密码。<br/>它将以 "%1" 的格式计算哈希值。 - + Delete a site 删除站点 - + Are you sure you want to delete the site %1? 你确定想要删除站点 %1 吗? - + Connection... - + Success! 测试成功! - + Failure 测试失败 - + Unable to test 无法测试 + + + Error + 错误 + + + + You should at least select one source + + TagContextMenu - + Remove from favorites 从收藏移除 - + Choose as image 设置为图片 - + Add to favorites 添加到收藏 - + Don't keep for later 取消等下再看 - + Keep for later 等下再看 - + Don't blacklist - + Blacklist 黑名单 - + Don't ignore 取消忽略 - + Ignore 忽略 - + Copy tag - + Copy all tags - + Open in a new tab 在新标签页打开 - + Open in new a window 在新窗口打开 - + Open in browser 在浏览器中打开 @@ -1865,49 +1882,49 @@ TextEdit - + Favorites 收藏 - - + + Remove 移除 - - + + Add 添加 - + Kept for later 等下再看 - + Ratings 评级 - + Sortings 筛选 - + Copy 复制 - + Cut 剪切 - + Paste 粘贴 @@ -1957,14 +1974,14 @@ ZoomWindow - - + + Image 图片 - + Save 保存 @@ -1975,7 +1992,7 @@ - + Save and close 保存并关闭 @@ -1991,13 +2008,13 @@ - + Save (fav) 保存(收藏) - + Save and close (fav) 保存并退出(收藏) @@ -2007,155 +2024,154 @@ 目标文件夹(收藏) - + Reload - + Copy file - + Copy data - + Folder does not exist 文件夹不存在 - + The save folder does not exist yet. Create it? 保存文件夹不存在。创建一个吗? - + Error creating folder. %1 创建文件夹时出错 %1 - - + + Saving... (fav) 保存...(收藏) - - + + Saving... 保存... - + Saved! (fav) 保存完成!(收藏) - + Saved! 保存完成! - + Copied! (fav) 已复制!(收藏) - + Copied! 已复制! - + Moved! (fav) 已移动!(收藏) - + Moved! 已移动! - + MD5 already exists (fav) - + MD5 already exists - + Already exists (fav) - + Already exists - + Delete (fav) - + Delete 删除 - + Close (fav) 关闭(收藏) - + Close 关闭 - + File is too big to be displayed. %1 - An unexpected error occured loading the image (%1 - %2). %3 - 在载入 (%1 - %2) 图片时出错。 + 在载入 (%1 - %2) 图片时出错。 %3 - - + + Error 错误 - + You did not specified a save folder! Do you want to open the options window? 你没有指定保存文件夹!你想要现在打开设置窗口吗? - + You did not specified a save format! Do you want to open the options window? 你没有指定保存格式!你想要现在打开设置窗口吗? - + Error saving image. 保存图片时发生错误。 - + Save image 保存图片 @@ -2174,7 +2190,7 @@ - + Pause 暂停 @@ -2185,7 +2201,7 @@ - + Cancel 取消 @@ -2265,40 +2281,40 @@ 移除 - + Paused 已暂停 - + Resume 恢复 + - h 'h' m 'm' s 's' h 'h' m 'm' s 's' + - m 'm' s 's' m 'm' s 's' + - s 's' s 's' - + <b>Average speed:</b> %1 %2<br/><br/><b>Elapsed time:</b> %3<br/><b>Remaining time:</b> %4 <b>平均速度:</b> %1 %2<br/><br/><b>已耗时间:</b> %3<br/><b>剩余时间:</b> %4 - + Close 关闭 @@ -2542,7 +2558,7 @@ 删除 - + Choose an image 选择一个图片 @@ -2697,8 +2713,8 @@ - - + + Tags 标签 @@ -2724,14 +2740,14 @@ - + Filename 文件名 - - + + Folder 文件夹 @@ -2752,7 +2768,7 @@ - + Add 添加 @@ -2788,242 +2804,247 @@ + Search + 搜索 + + + Site 站点 - + Delete all 删除所有 - + Delete selected 删除已选择的 - + Download 下载 - + Download selected 下载已选择的 - + Move down 下移 - + Load 加载 - - + + Save 保存 - + Move up 上移 - + Log 日志 - + Clear log 清除日志 - + Open log 打开日志 - + Help 帮助 - + Tools 工具 - + View 查看 - + File 文件 - - - + + + Kept for later 等下再看 - - - + + + Favorites 收藏 - - + + Name 名称 - + Note 注释 - + Last viewed 上次查看 - + Ascending 升序 - + Descending 降序 - + Wiki Wiki - + Destination 目标文件名 - + Reset 重置 - + Options 选项 - + Ctrl+P Ctrl+P - + Open destination folder 打开目标文件夹 - + Quit 退出 - + About Grabber 关于 Grabber - + About Qt 关于 Qt - + New tab 新标签页 - + Close tab 关闭标签页 - + Blacklist fixer 黑名单修复 - + Empty folders fixer 空文件夹修复 - + New pool tab 添加新集合标签页 - + MD5 list fixer MD5 列表修复 - + Open options folder 打开选项文件夹 - + Project website 项目网站 - + Report an issue 报告问题 - + Rename existing images 重命名已有图片 - + Project GitHub - + Restore last closed tab - + Tag loader - + No source found 找不到来源 - + No source found. Do you have a configuration problem? Try to reinstall the program. 找不到来源。是否有配置问题?尝试重新安装程序。 @@ -3032,82 +3053,82 @@ 看来上次程序没有正常结束。你想要以不恢复会话的方式启动吗? - + It seems that the application was not properly closed for its last use. Do you want to restore your last session? 看来上次程序没有正常结束。你想要恢复会话吗? - + The Mozilla Firefox addon "Danbooru Downloader" has been detected on your system. Do you want to load its preferences? 检测到你有安装 Firefox 插件 "Danbooru Downloader"。你想要导入它的设置吗? - + Groups (%1/%2) 群组 (%1/%2) - + Confirmation - + Are you sure you want to clear your download list? - + This source is not valid. - + The image per page value must be greater or equal to 1. 每页图片数必须大于等于 1。 - + The image limit must be greater or equal to 0. 图片数限制必须大于或等于 0. - + MM/dd/yyyy MM/dd/yyyy - + <b>Name:</b> %1<br/><b>Note:</b> %2 %%<br/><b>Last view:</b> %3 <b>名称:</b> %1<br/><b>注释:</b> %2 %%<br/><b>上次查看:</b> %3 - + Are you sure you want to quit? 你确定要退出吗? - + Don't keep for later 取消等下再看 - + You did not specify a save folder! 你还没有指定保存文件夹! - + You did not specify a filename! 你还没有指定文件名! - + Logging in, please wait... 登录中,请稍候... - + Downloading pages, please wait... 下载页面中,请稍候... @@ -3118,12 +3139,12 @@ - + Preparing images, please wait... 准备图片中,请稍候... - + Downloading images... 下载图片中... @@ -3138,12 +3159,12 @@ Please solve the issue before resuming the download. 请在恢复下载前修复这些问题。 - + Error 错误 - + An error occured saving the image. %1 Please solve the issue before resuming the download. @@ -3152,114 +3173,114 @@ Please solve the issue before resuming the download. 请在恢复下载前修复这些问题。 - - + + Getting images 获取图片 - + %n file(s) downloaded successfully. %n 个图片已成功下载。 - + %n file(s) ignored. %n 个文件被忽略。 - + %n file(s) already existing. %n 个文件已经存在。 - + %n file(s) not found on the server. %n 个文件在服务器上无法找到。 - + %n file(s) skipped. %n 个文件被跳过。 - + %n error(s). %n 个错误。 - + Errors occured during the images download. Do you want to restart the download of those images? (%1/%2) 下载图片时出现错误。请问你想要重启这些图片的下载吗?(%1/%2) - + &Quit - + Not enough space on the destination drive "%1". Please free some space before resuming the download. - - - + + + Save link list 保存链接列表 - - + + Imageboard-Grabber links (*.igl) Imageboard-Grabber 链接列表 (*.igl) - + Link list saved successfully! 链接列表保存成功! - - + + Error opening file. 打开文件时发生错误。 - - - + + + Load link list 载入链接列表 - + Link list loaded successfully! 链接列表导入完成! - + Loading %n download(s) 正在载入 %n 个下载 - + Choose a save folder 选择保存文件夹 @@ -3481,13 +3502,13 @@ Please free some space before resuming the download. - + Commands 命令行 - + Database 数据库 @@ -3527,12 +3548,12 @@ Please free some space before resuming the download. <i>通过空格分隔标签</i> - + Ignore images containing a blacklisted tag 忽略有黑名单中的标签的图片 - + <i>Images containing a blacklisted tag will not be displayed in the results if this box is checked. Else, a confirmation will be asked before showing one of these images.</i> <i>如果这个选项被选中,所有包含有黑名单中的标签的图片都将不被显示。否则,在显示图片前将弹出提示。</i> @@ -4011,8 +4032,8 @@ Please free some space before resuming the download. - - + + Image 图片 @@ -4205,8 +4226,8 @@ Please free some space before resuming the download. - - + + Color 颜色 @@ -4396,196 +4417,198 @@ Please free some space before resuming the download. - + Hosts 主机 - - + + Horizontal margins 水平间距 - - + + Borders 边框 - + Images 图片 - + Vertical margins 垂直间距 - + Show log 显示日志 - + Blacklisted tags - + <i>One line per blacklist. You can put multiple tags on a single line to make "AND" conditions.</i> - + Delay on startup - + s - + Tray icon - + Minimize to tray - + Close to tray - + Enable system tray icon - + Use proxy 使用代理 - - + + Host 主机 - + Port 端口 - + Type 类型 - + HTTP HTTP - + SOCKS v5 SOCKS v5 - + Use system-wide proxy settings - + Add a web service - - + + Tag (after) 标签(之前) - - + + Tag (before) 标签(之后) - - + + Additional tags: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: the tag<br/><i>%type%</i>: tag type, "general", "artist", "copyright", "character", "model" or "photo_set"<br/><i>%number%</i>: the tag type number (between 0 and 6) 额外标签:: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: the tag<br/><i>%type%</i>: 标签类型, "general", "artist", "copyright", "character", "model" 或 "photo_set"<br/><i>%number%</i>: 标签类型数 ( 0 到 6 之间) - + Start 开始 - + End 结束 - + Credentials 验证 - + + User 用户名 - + + Password 密码 - + Driver 驱动 - + Choose a save folder 选择保存的目录 - + Choose a save folder for favorites 选择收藏保存的目录 - - + + Edit - - + + Remove 移除 - + Choose a color 选择一个颜色 - + Choose a font 选择一个字体 @@ -4660,17 +4683,17 @@ Please free some space before resuming the download. searchTab - + server offline 服务器不在线 - + too many tags 太多标签 - + page too far 页面过多 @@ -4679,22 +4702,23 @@ Please free some space before resuming the download. 有一个缩略图是空的 (<a href="%1">%1</a>)。 - + Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway? 这个图片中的一些标签是白名单中的:%1。但是,也有一些标签是黑名单中的:%2。你依然想要下载吗? - + No result 没有结果 - + Possible reasons: %1 可能的原因:%1 - + + Page %1 of %2 (%3 of %4) 第 %1 页 共 %2 页 (第 %3 页 共 %4 页) @@ -4735,62 +4759,68 @@ Please free some space before resuming the download. 'MM/dd/yyyy' 于 'hh:mm - + HTTPS redirection detected - + An HTTP to HTTPS redirection has been detected for the website %1. Do you want to enable SSL on it? The recommended setting is 'yes'. - + Always - + Never for that website - + Never - + + + max %1 + + + + Delete 删除 - + Save 保存 - + Save as... 保存为... - + Save selected - + Save image 保存图片 - + Blacklist 黑名单 - + %n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway? %1 这个图片中的 %n 标签被检测到在黑名单中。你依然想要显示它吗? @@ -4810,43 +4840,48 @@ Please free some space before resuming the download. 全选 - + ... ... - + Add 添加 - + Cancel 取消 - + Ok 确定 - + Options 选项 - + + - No preset selected - + + + + Create a new preset - - + + Name 名称 - + Edit preset @@ -4855,7 +4890,7 @@ Please free some space before resuming the download. 这个来源的设置可更新,但并非针对本版本。 - + An update for this source is available. 这个来源的设置可更新。 @@ -4917,12 +4952,12 @@ Please free some space before resuming the download. 选项 - + Choose a save folder 选择保存的目录 - + An error occurred creating the save folder. diff --git a/languages/English.ts b/languages/English.ts index c5ff2b3af..a7e745916 100644 --- a/languages/English.ts +++ b/languages/English.ts @@ -24,12 +24,12 @@ - + A new version is available: %1 - + Grabber is up to date @@ -120,38 +120,30 @@ - + Choose a save folder - + No image found. - - Api - - - Tag search is impossible with the chosen source (%1). - - - BlacklistFix1 - + This directory does not exist. - + If you want to get the MD5 from the filename, you have to include the %md5% token in it. - + You are about to download information from %n image(s). Are you sure you want to continue? You are about to download information from %n image. Are you sure you want to continue? @@ -160,7 +152,7 @@ - + Blacklist fixer @@ -374,12 +366,12 @@ - + Warning - + You script contains error, are you sure you want to save it? @@ -387,168 +379,168 @@ Image - + <b>Tags:</b> %1<br/><br/> - - + + <b>ID:</b> %1<br/> - + <b>Name:</b> %1<br/> - + <b>Rating:</b> %1<br/> - + <b>Score:</b> %1<br/> - + <b>User:</b> %1<br/><br/> - + <b>Size:</b> %1 x %2<br/> - + <b>Filesize:</b> %1 %2<br/> - + <b>Date:</b> %1 - + 'the 'MM/dd/yyyy' at 'hh:mm - + <i>Unknown</i> - + yes - + no - + Tags - + ID - + MD5 - + Rating - + Score - + Author - + Date - + 'the' MM/dd/yyyy 'at' hh:mm - + Size - + Filesize - + Page - + URL - + Source - + Sample - + Thumbnail - + Parent - + yes (#%1) - + Comments - + Children - + Notes @@ -672,7 +664,7 @@ Page - + No valid source of the site returned result. @@ -733,47 +725,47 @@ QObject - + MM-dd-yyyy HH.mm - + Filename must not be empty! - + Can't validate Javascript expressions. - + Your filename doesn't ends by an extension, symbolized by %ext%! You may not be able to open saved files. - + Your filename is not unique to each image and an image may overwrite a previous one at saving! You should use%md5%, which is unique to each image, to avoid this inconvenience. - + The %%1% token does not exist and will not be replaced. - + Your format contains characters forbidden on Windows! Forbidden characters: * ? " : < > | - + You have chosen to use the %id% token. Know that it is only unique for a selected site. The same ID can identify different images depending on the site. - + Valid filename! @@ -783,59 +775,63 @@ - + image has a "%1" token - + image does not have a "%1" token - - unknown type "%1" (available types: "%2") - - - - - + + + image's %1 does not match - - + + + image's %1 match - + + image is not "%1" - + + image is "%1" - + + An image needs a date to be filtered by age + + + + image's source does not starts with "%1" - + image's source starts with "%1" - + image does not contains "%1" - + image contains "%1" @@ -853,7 +849,7 @@ - + You are about to download information from %n image(s). Are you sure you want to continue? You are about to download information from %n image. Are you sure you want to continue? @@ -862,7 +858,7 @@ - + Rename existing images @@ -1151,12 +1147,12 @@ - + The url you entered is not valid. - + Unable to guess site's type. Are you sure about the url? @@ -1523,115 +1519,125 @@ - + Hash a password - + Please enter your password below.<br/>It will then be hashed using the format "%1". - + Delete a site - + Are you sure you want to delete the site %1? - + Connection... - + Success! - + Failure - + Unable to test + + + Error + + + + + You should at least select one source + + TagContextMenu - + Remove from favorites - + Choose as image - + Add to favorites - + Don't keep for later - + Keep for later - + Don't blacklist - + Blacklist - + Don't ignore - + Ignore - + Copy tag - + Copy all tags - + Open in a new tab - + Open in new a window - + Open in browser @@ -1685,49 +1691,49 @@ TextEdit - + Favorites - - + + Remove - - + + Add - + Kept for later - + Ratings - + Sortings - + Copy - + Cut - + Paste @@ -1777,14 +1783,14 @@ ZoomWindow - - + + Image - + Save @@ -1795,7 +1801,7 @@ - + Save and close @@ -1811,13 +1817,13 @@ - + Save (fav) - + Save and close (fav) @@ -1827,153 +1833,147 @@ - + Reload - + Copy file - + Copy data - + Folder does not exist - + The save folder does not exist yet. Create it? - + Error creating folder. %1 - - + + Saving... (fav) - - + + Saving... - + Saved! (fav) - + Saved! - + Copied! (fav) - + Copied! - + Moved! (fav) - + Moved! - + MD5 already exists (fav) - + MD5 already exists - + Already exists (fav) - + Already exists - + Delete (fav) - + Delete - + Close (fav) - + Close - + File is too big to be displayed. %1 - - An unexpected error occured loading the image (%1 - %2). -%3 - - - - - + + Error - + You did not specified a save folder! Do you want to open the options window? - + You did not specified a save format! Do you want to open the options window? - + Error saving image. - + Save image @@ -1992,7 +1992,7 @@ - + Pause @@ -2003,7 +2003,7 @@ - + Cancel @@ -2083,40 +2083,40 @@ - + Paused - + Resume + - h 'h' m 'm' s 's' + - m 'm' s 's' + - s 's' - + <b>Average speed:</b> %1 %2<br/><br/><b>Elapsed time:</b> %3<br/><b>Remaining time:</b> %4 - + Close @@ -2257,7 +2257,7 @@ - + Choose an image @@ -2403,130 +2403,130 @@ - + No source found - + No source found. Do you have a configuration problem? Try to reinstall the program. - + &Quit - + It seems that the application was not properly closed for its last use. Do you want to restore your last session? - + The Mozilla Firefox addon "Danbooru Downloader" has been detected on your system. Do you want to load its preferences? - + Groups (%1/%2) - + Confirmation - + Are you sure you want to clear your download list? - + This source is not valid. - + The image per page value must be greater or equal to 1. - + The image limit must be greater or equal to 0. - + MM/dd/yyyy - + <b>Name:</b> %1<br/><b>Note:</b> %2 %%<br/><b>Last view:</b> %3 - + Are you sure you want to quit? - + Don't keep for later - + You did not specify a save folder! - + You did not specify a filename! - + Logging in, please wait... - + Downloading pages, please wait... - + Preparing images, please wait... - + Downloading images... - + Error - + An error occured saving the image. %1 Please solve the issue before resuming the download. - - + + Getting images - + %n file(s) downloaded successfully. %n file downloaded successfully. @@ -2534,7 +2534,7 @@ Please solve the issue before resuming the download. - + %n file(s) ignored. %n file ignored. @@ -2542,7 +2542,7 @@ Please solve the issue before resuming the download. - + %n file(s) already existing. %n file already existing. @@ -2550,7 +2550,7 @@ Please solve the issue before resuming the download. - + %n file(s) not found on the server. %n file not found on the server. @@ -2558,7 +2558,7 @@ Please solve the issue before resuming the download. - + %n file(s) skipped. %n file skipped. @@ -2566,7 +2566,7 @@ Please solve the issue before resuming the download. - + %n error(s). %n error. @@ -2574,54 +2574,54 @@ Please solve the issue before resuming the download. - + Errors occured during the images download. Do you want to restart the download of those images? (%1/%2) - + Not enough space on the destination drive "%1". Please free some space before resuming the download. - - - + + + Save link list - - + + Imageboard-Grabber links (*.igl) - + Link list saved successfully! - - + + Error opening file. - - - + + + Load link list - + Link list loaded successfully! - + Loading %n download(s) Loading %n download @@ -2629,7 +2629,7 @@ Please free some space before resuming the download. - + Choose a save folder @@ -2653,8 +2653,8 @@ Please free some space before resuming the download. - - + + Tags @@ -2680,14 +2680,14 @@ Please free some space before resuming the download. - + Filename - - + + Folder @@ -2708,7 +2708,7 @@ Please free some space before resuming the download. - + Add @@ -2744,232 +2744,237 @@ Please free some space before resuming the download. + Search + + + + Site - + Delete all - + Delete selected - + Download - + Download selected - + Move down - + Load - - + + Save - + Move up - + Log - + Clear log - + Open log - + Help - + Tools - + View - + File - - - + + + Kept for later - - - + + + Favorites - - + + Name - + Note - + Last viewed - + Ascending - + Descending - + Wiki - + Destination - + Reset - + Options - + Ctrl+P - + Open destination folder - + Quit - + About Grabber - + About Qt - + New tab - + Close tab - + Blacklist fixer - + Empty folders fixer - + New pool tab - + MD5 list fixer - + Open options folder - + Project website - + Report an issue - + Rename existing images - + Project GitHub - + Restore last closed tab - + Tag loader @@ -3145,13 +3150,13 @@ Please free some space before resuming the download. - + Commands - + Database @@ -3187,12 +3192,12 @@ Please free some space before resuming the download. - + Ignore images containing a blacklisted tag - + <i>Images containing a blacklisted tag will not be displayed in the results if this box is checked. Else, a confirmation will be asked before showing one of these images.</i> @@ -3690,8 +3695,8 @@ Please free some space before resuming the download. - - + + Image @@ -3919,8 +3924,8 @@ Please free some space before resuming the download. - - + + Color @@ -4021,196 +4026,198 @@ Please free some space before resuming the download. - + Hosts - - + + Horizontal margins - - + + Borders - + Images - + Vertical margins - + Show log - + Blacklisted tags - + <i>One line per blacklist. You can put multiple tags on a single line to make "AND" conditions.</i> - + Delay on startup - + s - + Tray icon - + Minimize to tray - + Close to tray - + Enable system tray icon - + Use proxy - + Type - + HTTP - + SOCKS v5 - - + + Host - + Port - + Use system-wide proxy settings - + Add a web service - - + + Tag (after) - - + + Tag (before) - - + + Additional tags: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: the tag<br/><i>%type%</i>: tag type, "general", "artist", "copyright", "character", "model" or "photo_set"<br/><i>%number%</i>: the tag type number (between 0 and 6) - + Start - + End - + Credentials - + + User - + + Password - + Driver - + Choose a save folder - + Choose a save folder for favorites - - + + Edit - - + + Remove - + Choose a color - + Choose a font @@ -4281,92 +4288,99 @@ Please free some space before resuming the download. searchTab - + server offline - + too many tags - + page too far - + HTTPS redirection detected - + An HTTP to HTTPS redirection has been detected for the website %1. Do you want to enable SSL on it? The recommended setting is 'yes'. - + Always - + Never for that website - + Never - + Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway? - + + + max %1 + + + + No result - + Possible reasons: %1 - + + Page %1 of %2 (%3 of %4) - + Delete - + Save - + Save as... - + Save selected - + Save image - + %n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway? %n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway? @@ -4374,7 +4388,7 @@ Please free some space before resuming the download. - + Blacklist @@ -4392,48 +4406,53 @@ Please free some space before resuming the download. - + ... - + Add - + Cancel - + Ok - + Options - + An update for this source is available. - + + - No preset selected - + + + + Create a new preset - - + + Name - + Edit preset @@ -4491,12 +4510,12 @@ Please free some space before resuming the download. - + Choose a save folder - + An error occurred creating the save folder. diff --git a/languages/French.ts b/languages/French.ts index fcee769ff..3d7bf86d4 100644 --- a/languages/French.ts +++ b/languages/French.ts @@ -28,12 +28,12 @@ Russian translation byr Николай Тихонов. - + Grabber is up to date Grabber est à jour - + A new version is available: %1 Une nouvelle version est disponible : %1 @@ -124,12 +124,12 @@ Parcourir - + Choose a save folder Choisir un dossier de sauvegarde - + No image found. Aucune image n'a été trouvée. @@ -137,16 +137,15 @@ Api - Tag search is impossible with the chosen source (%1). - La recherche par tags est impossible avec la source choisie (%1). + La recherche par tags est impossible avec la source choisie (%1). BlacklistFix1 - + Blacklist fixer Réparateur de liste noire @@ -196,17 +195,17 @@ Annuler - + This directory does not exist. Ce dossier n'existe pas. - + If you want to get the MD5 from the filename, you have to include the %md5% token in it. Si vous voulez récupérer le MD5 depuis le nom de fichier, vous devez include le token %md5% dans celui-ci. - + You are about to download information from %n image(s). Are you sure you want to continue? Vous vous apprêtez à télécharger les informations de %n image. Êtes-vous sûr de vouloir continuer ? @@ -470,12 +469,12 @@ Nommage Javascript - + Warning Attention - + You script contains error, are you sure you want to save it? Votre script contient des erreurs, êtes-vous sûr de vouloir l'enregistrer ? @@ -567,168 +566,168 @@ Déplacement depuis <a href="file:///%1">%1</a> vers <a href="file:///%2">%2</a> - + <b>Tags:</b> %1<br/><br/> <b>Tags :</b> %1<br/><br/> - - + + <b>ID:</b> %1<br/> <b>ID :</b> %1<br/> - + <b>Name:</b> %1<br/> - + <b>Rating:</b> %1<br/> <b>Classe :</b> %1<br/> - + <b>Score:</b> %1<br/> <b>Score :</b> %1<br/> - + <b>User:</b> %1<br/><br/> <b>Auteur :</b> %1<br/><br/> - + <b>Size:</b> %1 x %2<br/> <b>Dimensions :</b> %1 x %2<br/> - + <b>Filesize:</b> %1 %2<br/> <b>Taille :</b> %1 %2<br/> - + <b>Date:</b> %1 <b>Date :</b> %1 - + 'the 'MM/dd/yyyy' at 'hh:mm 'le' dd/MM/yyyy 'à' hh:mm - + <i>Unknown</i> <i>Inconnu</i> - + yes oui - + no non - + Tags Tags - + ID ID - + MD5 MD5 - + Rating Classe - + Score Score - + Author Auteur - + Date Date - + 'the' MM/dd/yyyy 'at' hh:mm 'le' dd/MM/yyyy 'à' hh:mm - + Size Dimensions - + Filesize Taille - + Page Page - + URL URL - + Source Source - + Sample - + Thumbnail Miniature - + Parent Parent - + yes (#%1) oui (#%1) - + Comments Commentaires - + Children Enfants - + Notes Notes @@ -852,7 +851,7 @@ Page - + No valid source of the site returned result. Aucune source valide du site n'a retourné de résultat. @@ -973,7 +972,7 @@ <b>Notice :</b> %1 - + MM-dd-yyyy HH.mm dd-MM-yyyy HH.mm @@ -982,42 +981,42 @@ Erreur d'évaluation du Javascript :<br/> - + Filename must not be empty! Le nom de fichier ne doit pas être vide ! - + Can't validate Javascript expressions. Impossible de valider les expressions Javascript. - + Your filename doesn't ends by an extension, symbolized by %ext%! You may not be able to open saved files. Votre nom de fichier ne finit pas par une extension, symbolisée par %ext% ! Vous risquez de ne pas pouvoir ouvrir vos fichiers. - + Your filename is not unique to each image and an image may overwrite a previous one at saving! You should use%md5%, which is unique to each image, to avoid this inconvenience. Votre nom de fichier n'est pas unique à chaque image et une image risque d'en écraser une précédente lors de la sauvegarde ! Vous devriez utiliser le symbole %md5%, unique à chaque image, pour éviter ce désagrément. - + The %%1% token does not exist and will not be replaced. Le symbole %%1% n'existe pas et ne sera pas remplacé. - + Your format contains characters forbidden on Windows! Forbidden characters: * ? " : < > | Votre format contient des caractères interdits sur windows ! Caractères interdits : * ? " : < > | - + You have chosen to use the %id% token. Know that it is only unique for a selected site. The same ID can identify different images depending on the site. Vous avez choisi d'utiliser le symbole %id%. Sachez que celui-ci est unique pour un site choisi. Le même ID pourra identifier des images différentes en fonction du site. - + Valid filename! Format valide ! @@ -1050,59 +1049,67 @@ Gio - + image has a "%1" token - + image does not have a "%1" token - unknown type "%1" (available types: "%2") - type "%1" inconnu (types disponibles : "%2") + type "%1" inconnu (types disponibles : "%2") - - + + + image's %1 does not match le %1 de l'image ne correspond pas - - + + + image's %1 match le %1 de l'image correspond - + + image is not "%1" l'image n'est pas "%1" - + + image is "%1" l'image est "%1" - + + An image needs a date to be filtered by age + + + + image's source does not starts with "%1" la source de l'image ne commence pas par "%1" - + image's source starts with "%1" la source de l'image commence par "%1" - + image does not contains "%1" l'image ne contient pas "%1" - + image contains "%1" l'image contient "%1" @@ -1111,7 +1118,7 @@ RenameExisting1 - + Rename existing images Renommer les images existantes @@ -1176,7 +1183,7 @@ Si vous voulez récupérer le MD5 depuis le nom de fichier, vous devez include le token %md5% dans celui-ci. - + You are about to download information from %n image(s). Are you sure you want to continue? Vous vous apprêtez à télécharger les informations de %n image. Êtes-vous sûr de vouloir continuer ? @@ -1437,12 +1444,12 @@ %v/%m - + The url you entered is not valid. L'url que vous avez entrée n'est pas valide. - + Unable to guess site's type. Are you sure about the url? Impossible de deviner le type du site. Êtes-vous sûr de l'url ? @@ -1843,115 +1850,125 @@ Headers - + Hash a password Hasher un mot de passe - + Please enter your password below.<br/>It will then be hashed using the format "%1". Veuillez entrer votre mot de passe ci-dessous.<br/>Il sera ensuite hashé en utilisant le format "%1". - + Delete a site Supprimer un site - + Are you sure you want to delete the site %1? Êtes-vous sûr de vouloir supprimer le site %1 ? - + Connection... Connexion... - + Success! Succès ! - + Failure Échec - + Unable to test Impossible de tester + + + Error + Erreur + + + + You should at least select one source + + TagContextMenu - + Remove from favorites Retirer des favoris - + Choose as image Choisir comme image - + Add to favorites Ajouter aux favoris - + Don't keep for later Ne pas garder pour plus tard - + Keep for later Garder pour plus tard - + Don't blacklist Retirer de la liste noire - + Blacklist Liste noire - + Don't ignore Ne plus ignorer - + Ignore Ignorer - + Copy tag Copier le tag - + Copy all tags Copier tous les tags - + Open in a new tab Ouvrir dans un nouvel onglet - + Open in new a window Ouvrir dans une nouvelle fenêtre - + Open in browser Ouvrir dans le navigateur @@ -2017,49 +2034,49 @@ TextEdit - + Favorites Favoris - - + + Remove Retirer - - + + Add Ajouter - + Kept for later Gardés pour plus tard - + Ratings Classes - + Sortings Tris - + Copy Copier - + Cut Couper - + Paste Coller @@ -2113,14 +2130,14 @@ ZoomWindow - - + + Image Image - + Save Enregistrer @@ -2131,7 +2148,7 @@ - + Save and close Enregistrer et fermer @@ -2147,13 +2164,13 @@ - + Save (fav) Enregistrer (fav) - + Save and close (fav) Enregistrer et fermer (fav) @@ -2163,156 +2180,155 @@ Dossier de destination (fav) - + Reload Recharger - + Copy file Copier le fichier - + Copy data Copier les données - + Folder does not exist Dossier inexistant - + The save folder does not exist yet. Create it? Le dossier de sauvegarde n'existe pas encore. Le créer ? - + Error creating folder. %1 Erreur lors de la création du dossier. %1 - - + + Saving... (fav) Sauvegarde... (fav) - - + + Saving... Sauvegarde... - + Saved! (fav) Enregistré! (fav) - + Saved! Enregistré! - + Copied! (fav) Copié! (fav) - + Copied! Copié! - + Moved! (fav) Déplacé! (fav) - + Moved! Déplacé! - + MD5 already exists (fav) MD5 déjà existant (fav) - + MD5 already exists MD5 déjà existant - + Already exists (fav) Déjà existant (fav) - + Already exists Déjà existant - + Delete (fav) Supprimer (fav) - + Delete Supprimer - + Close (fav) Fermer (fav) - + Close Fermer - + File is too big to be displayed. %1 Ce fichier est trop gros pour être affiché. %1 - An unexpected error occured loading the image (%1 - %2). %3 - Une erreur non attendue a survenu lors du chargement de l'image (%1 - %2). + Une erreur non attendue a survenu lors du chargement de l'image (%1 - %2). %3 - - + + Error Erreur - + You did not specified a save folder! Do you want to open the options window? Vous n'avez pas précisé de dossier de sauvegarde ! Voulez-vous ouvrir les options ? - + You did not specified a save format! Do you want to open the options window? Vous n'avez pas précisé de format de sauvegarde ! Voulez-vous ouvrir les options ? - + Error saving image. Erreur lors de la sauvegarde de l'image. - + Save image Enregistrer l'image @@ -2321,7 +2337,7 @@ batchWindow - + Pause Pause @@ -2346,7 +2362,7 @@ - + Cancel Annuler @@ -2426,40 +2442,40 @@ Retirer - + Paused En pause - + Resume Reprendre + - h 'h' m 'm' s 's' h 'h' m 'm' s 's' + - m 'm' s 's' m 'm' s 's' + - s 's' s 's' - + <b>Average speed:</b> %1 %2<br/><br/><b>Elapsed time:</b> %3<br/><b>Remaining time:</b> %4 <b>Vitesse moyenne :</b> %1 %2<br/><br/><b>Temps écoulé :</b> %3<br/><b>Temps restant :</b> %4 - + Close Fermer @@ -2703,7 +2719,7 @@ Image - + Choose an image Choisir une image @@ -2862,8 +2878,8 @@ - - + + Tags Tags @@ -2889,14 +2905,14 @@ - + Filename Nom de fichier - - + + Folder Dossier @@ -2917,7 +2933,7 @@ - + Add Ajouter @@ -2932,188 +2948,193 @@ Classe - + + Search + Recherche + + + Delete all Tout effacer - + Delete selected Effacer la séléction - + Download Télécharger - + Download selected Télécharger la séléction - + Load Charger - - + + Save Enregistrer - + Clear log Vider le log - + Open log Ouvrir le log - + Help Aide - + Tools Outils - + View Affichage - + File Fichier - - - + + + Kept for later Gardés pour plus tard - - - + + + Favorites Favoris - - + + Name Nom - + Last viewed Dernière vue - + Ascending Ascendant - + Descending Descendant - + Reset Réinitialiser - + Open destination folder Ouvrir le dossier de destination - + Quit Quitter - + About Grabber À propos de Grabber - + About Qt À propos de Qt - + New tab Nouvel onglet - + Close tab Fermer l'onglet - + Blacklist fixer Réparateur de liste noire - + Empty folders fixer Réparateur de dossiers vides - + New pool tab Nouvel onglet pool - + MD5 list fixer Réparateur de MD5 - + Open options folder Ouvrir le dossier des options - + Project website Site web du projet - + Report an issue Reporter un problème - + Rename existing images Renommer les images existantes - + Project GitHub Projet GitHub - + Restore last closed tab Restaurer le dernier onglet fermé - + Tag loader Chargeur de tags @@ -3138,37 +3159,37 @@ Date - + Site Site - + Move down Descendre - + Move up Monter - + Log Log - + Note Note - + Wiki Wiki - + Destination Destination @@ -3177,22 +3198,22 @@ ... - + Options Options - + Ctrl+P Ctrl+P - + No source found Aucune source trouvée - + No source found. Do you have a configuration problem? Try to reinstall the program. Aucune source n'a été trouvée. Auriez-vous un problème de configuration ? Essayez de réinstaller. @@ -3201,82 +3222,82 @@ Il semblerait que l'application n'ait pas été arrêtée correctement lors de sa dernière utilisation. Voulez-vous la charger sans restaurer votre dernière session ? - + It seems that the application was not properly closed for its last use. Do you want to restore your last session? Il semblerait que l'application n'ait pas été arrêtée correctement lors de sa dernière utilisation. Voulez-vous restaurer votre dernière session ? - + The Mozilla Firefox addon "Danbooru Downloader" has been detected on your system. Do you want to load its preferences? L'extension pour Mozilla Firefox "Danbooru Downloader" a été détéctée sur votre système. Souhaitez-vous en importer les préférences ? - + Groups (%1/%2) Groupes (%1/%2) - + Confirmation Validation - + Are you sure you want to clear your download list? Êtes-vous sûr de vouloir vider votre liste de téléchargement ? - + This source is not valid. Cette source n'est pas valide. - + The image per page value must be greater or equal to 1. La limite d'images par page doit être supérieure ou égale à 1. - + The image limit must be greater or equal to 0. La limite d'images doit être supérieure ou égale à 0. - + MM/dd/yyyy dd/MM/yyyy - + <b>Name:</b> %1<br/><b>Note:</b> %2 %%<br/><b>Last view:</b> %3 <b>Nom :</b> %1<br/><b>Note :</b> %2 %%<br/><b>Dernière vue :</b> %3 - + Are you sure you want to quit? Êtes vous sûr de vouloir quitter ? - + Don't keep for later Ne pas garder pour plus tard - + You did not specify a save folder! Vous n'avez pas précisé de dossier de sauvegarde ! - + You did not specify a filename! Vous n'avez pas précisé de nom de fichier ! - + Logging in, please wait... Connexion aux sources, veuillez patienter... - + Downloading pages, please wait... Téléchargement des pages, veuillez patienter... @@ -3288,12 +3309,12 @@ - + Preparing images, please wait... Préparation des images, veuillez patienter... - + Downloading images... Téléchargement des images en cours... @@ -3308,12 +3329,12 @@ Please solve the issue before resuming the download. Veuillez résoudre le problème avant de reprendre le téléchargement. - + Error Erreur - + An error occured saving the image. %1 Please solve the issue before resuming the download. @@ -3322,13 +3343,13 @@ Please solve the issue before resuming the download. Veuillez résoudre le problème avant de reprendre le téléchargement. - - + + Getting images Récupération des images - + %n file(s) downloaded successfully. %n fichier récupéré avec succès. @@ -3336,7 +3357,7 @@ Veuillez résoudre le problème avant de reprendre le téléchargement. - + %n file(s) ignored. %n fichier ignoré. @@ -3344,7 +3365,7 @@ Veuillez résoudre le problème avant de reprendre le téléchargement. - + %n file(s) already existing. %n fichier déjà existant. @@ -3352,7 +3373,7 @@ Veuillez résoudre le problème avant de reprendre le téléchargement. - + %n file(s) not found on the server. %n fichier non trouvé sur le serveur. @@ -3360,7 +3381,7 @@ Veuillez résoudre le problème avant de reprendre le téléchargement. - + %n file(s) skipped. %n fichier passé. @@ -3368,7 +3389,7 @@ Veuillez résoudre le problème avant de reprendre le téléchargement. - + %n error(s). %n erreur. @@ -3376,59 +3397,59 @@ Veuillez résoudre le problème avant de reprendre le téléchargement. - + Errors occured during the images download. Do you want to restart the download of those images? (%1/%2) Des erreurs sont survenues pendant le téléchargement des images. Voulez vous relancer le téléchargement de celles-ci ? (%1/%2) - + &Quit - + Not enough space on the destination drive "%1". Please free some space before resuming the download. - - - + + + Save link list Enregistrer la liste de liens - - + + Imageboard-Grabber links (*.igl) Liens Imageboard-Grabber (*.igl) - + Link list saved successfully! Liste de liens enregistrée avec succès ! - - + + Error opening file. Erreur lors de l'ouverture du fichier. - - - + + + Load link list Charger une liste de liens - + Link list loaded successfully! Liste de liens chargée avec succès ! - + Loading %n download(s) Chargement de %n téléchargement @@ -3436,7 +3457,7 @@ Please free some space before resuming the download. - + Choose a save folder Choisir un dossier de sauvegarde @@ -3684,13 +3705,13 @@ Please free some space before resuming the download. - + Commands Commandes - + Database Base de données @@ -3730,12 +3751,12 @@ Please free some space before resuming the download. <i>Séparer les tags par des espaces.</i> - + Ignore images containing a blacklisted tag Ignorer les images contenant un tag de la liste noire - + <i>Images containing a blacklisted tag will not be displayed in the results if this box is checked. Else, a confirmation will be asked before showing one of these images.</i> <i>Les images contenant un tag de la liste noire ne seront tout simplement pas affichées dans la liste de résultats si cette case est cochée. Sinon, une confirmation sera demandée avant l'affichage d'une de ces images.</i> @@ -4390,8 +4411,8 @@ Please free some space before resuming the download. - - + + Color Couleur @@ -4575,133 +4596,135 @@ Please free some space before resuming the download. - + Hosts Serveurs - - + + Horizontal margins Marges horizontales - - + + Borders Bordures - + Vertical margins Marges verticales - + Show log Afficher le log - + Blacklisted tags - + <i>One line per blacklist. You can put multiple tags on a single line to make "AND" conditions.</i> - + Delay on startup - + s - + Tray icon - + Minimize to tray - + Close to tray - + Enable system tray icon - + Use proxy Utiliser un proxy - - + + Host Serveur - + Use system-wide proxy settings Utiliser les paramètres proxy système - + Add a web service Ajouter un service web - - + + Tag (after) Tag (après) - - + + Tag (before) Tag (avant) - - + + Additional tags: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: the tag<br/><i>%type%</i>: tag type, "general", "artist", "copyright", "character", "model" or "photo_set"<br/><i>%number%</i>: the tag type number (between 0 and 6) Symboles additionels : <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i> : le tag<br/><i>%type%</i> : type du tag, "general", "artist", "copyright", "character", "model" ou "photo_set"<br/><i>%number%</i> : le numéro du type de tag (varie entre 0 et 6) - + Start Début - + End Fin - + Credentials Identifiants - + + User Utilisateur - + + Password Mot de passe @@ -4711,8 +4734,8 @@ Please free some space before resuming the download. - - + + Image Image @@ -4722,65 +4745,65 @@ Please free some space before resuming the download. % - + Images Images - + Port Port - + Type Type - + HTTP HTTP - + SOCKS v5 SOCKS v5 - + Driver Driver - + Choose a save folder Choisir un dossier de sauvegarde - + Choose a save folder for favorites Choisir un dossier de sauvegarde pour les favoris - - + + Edit Modifier - - + + Remove Retirer - + Choose a color Choisir une couleur - + Choose a font Choisir une fonte @@ -4859,17 +4882,17 @@ Please free some space before resuming the download. Mise à jour des paramètres de l'onglet "%1". - + server offline serveur hors ligne - + too many tags trop de tags - + page too far page trop éloignée @@ -4890,22 +4913,23 @@ Please free some space before resuming the download. une des miniatures est vide (<a href="%1">%1</a>). - + Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway? Certains tags de l'image sont dans la liste blanche : %1. Cependant, certains dans la liste noire : %2. Voulez-vous la télécharger tout de même ? - + No result Pas de résultat - + Possible reasons: %1 Raisons possibles : %1 - + + Page %1 of %2 (%3 of %4) Page %1 de %2 (%3 sur %4) @@ -4946,52 +4970,58 @@ Please free some space before resuming the download. 'le' dd/MM/yyyy 'à' hh:mm - + HTTPS redirection detected - + An HTTP to HTTPS redirection has been detected for the website %1. Do you want to enable SSL on it? The recommended setting is 'yes'. - + Always - + Never for that website - + Never Jamais - + + + max %1 + + + + Delete Supprimer - + Save Enregistrer - + Save as... Enregistrer sous... - + Save selected Enregistrer la sélection - + Save image Enregistrer l'image @@ -5000,12 +5030,12 @@ Please free some space before resuming the download. Mise à jour des cases à cocher. - + Blacklist Liste noire - + %n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway? %n tag figurant dans la liste noire détécté sur cette image : %1. Voulez-vous l'afficher tout de même ? @@ -5038,43 +5068,48 @@ Please free some space before resuming the download. Tout cocher - + ... ... - + Add Ajouter - + Cancel Annuler - + Ok Ok - + Options Options - + + - No preset selected - + + + + Create a new preset Créer un nouveau preset - - + + Name Nom - + Edit preset Modifier un preset @@ -5083,7 +5118,7 @@ Please free some space before resuming the download. Une mise à jour de cette source est disponible, mais pour une autre version du programme. - + An update for this source is available. Une mise à jour de cette source est disponible. @@ -5145,12 +5180,12 @@ Please free some space before resuming the download. Options - + Choose a save folder Choisir un dossier de sauvegarde - + An error occurred creating the save folder. Une erreur est survenue lors de la création du dossier de sauvegarde. diff --git a/languages/Russian.ts b/languages/Russian.ts index a353af6f2..8372107c6 100644 --- a/languages/Russian.ts +++ b/languages/Russian.ts @@ -28,12 +28,12 @@ Перевод на русский: Николай Тихонов. - + Grabber is up to date Установлена последняя версия - + A new version is available: %1 Доступна новая версия: %1 @@ -124,12 +124,12 @@ Изменить - + Choose a save folder Выберите папку для сохранения - + No image found. Изображений не найдено. @@ -137,16 +137,15 @@ Api - Tag search is impossible with the chosen source (%1). - Поиск по тегам невозможен для этого ресурса (%1). + Поиск по тегам невозможен для этого ресурса (%1). BlacklistFix1 - + Blacklist fixer Фиксер черного списка @@ -196,17 +195,17 @@ Отмена - + This directory does not exist. Этой папки не существует. - + If you want to get the MD5 from the filename, you have to include the %md5% token in it. Если вы хотите получить MD5 из имени файла, вы должны включить в него знак % md5%. - + You are about to download information from %n image(s). Are you sure you want to continue? Вы хотите сохранить %n изображение. Продолжить? @@ -472,12 +471,12 @@ Javascript названия - + Warning Предупреждение - + You script contains error, are you sure you want to save it? Ваш скрипт содержит ошибки, вы уверены что хотите сохранить его? @@ -521,168 +520,168 @@ изображение содержит "%1" - + <b>Tags:</b> %1<br/><br/> <b>Теги:</b> %1<br/><br/> - - + + <b>ID:</b> %1<br/> <b>ID :</b> %1<br/> - + <b>Name:</b> %1<br/> - + <b>Rating:</b> %1<br/> <b>Рейтинг:</b> %1<br/> - + <b>Score:</b> %1<br/> <b>Оценка:</b> %1<br/> - + <b>User:</b> %1<br/><br/> <b>Пользователь:</b> %1<br/><br/> - + <b>Size:</b> %1 x %2<br/> <b>Разрешение:</b> %1 x %2<br/> - + <b>Filesize:</b> %1 %2<br/> <b>Размер файла:</b> %1 %2<br/> - + <b>Date:</b> %1 <b>Дата:</b> %1 - + 'the 'MM/dd/yyyy' at 'hh:mm dd/MM/yyyy' в 'hh:mm - + <i>Unknown</i> <i>Неизвестно</i> - + yes да - + no нет - + Tags Теги - + ID ID - + MD5 MD5 - + Rating Рейтинг - + Score Оценка - + Author Автор - + Date Дата - + 'the' MM/dd/yyyy 'at' hh:mm dd/MM/yyyy' в 'hh:mm - + Size Разрешение - + Filesize Размер - + Page Страница - + URL URL - + Source Источник - + Sample Образец - + Thumbnail Превью - + Parent Предок - + yes (#%1) да (#%1) - + Comments Комментарии - + Children Наследник - + Notes Примечания @@ -808,7 +807,7 @@ Page - + No valid source of the site returned result. Ни один из источников сайта не дал результат. @@ -897,7 +896,7 @@ <b>Примечание:</b> %1 - + MM-dd-yyyy HH.mm MM-dd-yyyy HH.mm @@ -906,42 +905,42 @@ Ошибка в определении Javascript: <br/> - + Filename must not be empty! Имя файла не должно быть пустым! - + Can't validate Javascript expressions. Не удается проверить выражения JavaScript. - + Your filename doesn't ends by an extension, symbolized by %ext%! You may not be able to open saved files. Название файла не заканчивается на %ext%! Возможно, вы не сможете открыть скачанные файлы. - + Your filename is not unique to each image and an image may overwrite a previous one at saving! You should use%md5%, which is unique to each image, to avoid this inconvenience. Имена файлов не уникальны, при совпадении новые изображения могут затирать старые! Вам следует использовать переменную %md5% для того чтобы избежать этого. - + The %%1% token does not exist and will not be replaced. Переменная %%1% не существует и не будет заменена. - + Your format contains characters forbidden on Windows! Forbidden characters: * ? " : < > | Ваш формат содержит символы, запрещённые в Windows! Запрещённые символы: * ? " : < > | - + You have chosen to use the %id% token. Know that it is only unique for a selected site. The same ID can identify different images depending on the site. Вы выбрали переменную %id%. Учтите, что она уникальна только внутри сайта. Под тем же ID на другом сайте может быть другое изображение. - + Valid filename! Подходящее имя файла! @@ -974,59 +973,67 @@ ГиБ - + image has a "%1" token - + image does not have a "%1" token - unknown type "%1" (available types: "%2") - неизвестный тип "%1" (доступные типы: "%2") + неизвестный тип "%1" (доступные типы: "%2") - - + + + image's %1 does not match %1 изображения не совпадает - - + + + image's %1 match %1 изображения совпадает - + + image is not "%1" изображение не "%1" - + + image is "%1" изображение "%1" - + + An image needs a date to be filtered by age + + + + image's source does not starts with "%1" источник изображения не начинается с "%1" - + image's source starts with "%1" источник изображения начинается с "%1" - + image does not contains "%1" изображение не содержит "%1" - + image contains "%1" изображение содержит "%1" @@ -1035,7 +1042,7 @@ RenameExisting1 - + Rename existing images Переименовать существующие изображения @@ -1100,7 +1107,7 @@ Если вы хотите получить MD5 из имени файла, вы должны включить в него знак % md5%. - + You are about to download information from %n image(s). Are you sure you want to continue? Вы хотите сохранить %n изображение. Продолжить? @@ -1354,12 +1361,12 @@ %v/%m - + The url you entered is not valid. Введённый адрес недействителен. - + Unable to guess site's type. Are you sure about the url? Невозможно определить тип сайта. Вы уверенны что правильно ввели адрес? @@ -1734,115 +1741,125 @@ Применить - + Hash a password Хешировать пароль - + Please enter your password below.<br/>It will then be hashed using the format "%1". Пожалуйста введите ваш пароль ниже.<br/>Он будет захеширован в формате "%1". - + Delete a site Удалить сайт - + Are you sure you want to delete the site %1? Вы уверенны что хотите удалить %1? - + Connection... - + Success! Успешно! - + Failure Неудача - + Unable to test Не получилось протестировать + + + Error + Ошибка + + + + You should at least select one source + + TagContextMenu - + Remove from favorites Убрать из избранного - + Choose as image Выберите как изображение - + Add to favorites Добавить в избранное - + Don't keep for later Не оставлять на потом - + Keep for later Оставить на потом - + Don't blacklist Убрать из чёрного списка - + Blacklist Черный список - + Don't ignore Не игнорировать - + Ignore Игнорировать - + Copy tag Копировать тег - + Copy all tags Копировать все теги - + Open in a new tab Открыть в новой вкладе - + Open in new a window Открыть в новом окне - + Open in browser Открыть в браузере @@ -1905,49 +1922,49 @@ TextEdit - + Favorites Избранное - - + + Remove Убрать - - + + Add Добавить - + Kept for later На потом - + Ratings Рейтинги - + Sortings Сортировки - + Copy Копировать - + Cut Вырезать - + Paste Вставить @@ -2001,14 +2018,14 @@ ZoomWindow - - + + Image Изображение - + Save Сохранить @@ -2019,7 +2036,7 @@ - + Save and close Сохранить и выйти @@ -2035,13 +2052,13 @@ - + Save (fav) Сохранить (избранное) - + Save and close (fav) Сохранить и закрыть (избранное) @@ -2051,156 +2068,155 @@ Папка для сохранения (избранное) - + Reload - + Copy file Копировать файл - + Copy data Копировать данные - + Folder does not exist Папки не существует - + The save folder does not exist yet. Create it? Папки для сохранения не существует. Создать её? - + Error creating folder. %1 Ошибка при создании папки. %1 - - + + Saving... (fav) Сохранение... (избранное) - - + + Saving... Сохранение... - + Saved! (fav) Сохранено! (избранное) - + Saved! Сохранено! - + Copied! (fav) Скопировано! (Избранное) - + Copied! Скопировано! - + Moved! (fav) Перемещено! (Избранное) - + Moved! Перемещено! - + MD5 already exists (fav) Совпадение MD5(избр) - + MD5 already exists Совпадение MD5 - + Already exists (fav) Уже существует(избр) - + Already exists Уже существует - + Delete (fav) Удалить (избр.) - + Delete Удалить - + Close (fav) Закрыть (избранное) - + Close Закрыть - + File is too big to be displayed. %1 Файл слишколь большой для предпоказа. %1 - An unexpected error occured loading the image (%1 - %2). %3 - Неожиданная ошибка во время загрузки изображения (%1 - %2). + Неожиданная ошибка во время загрузки изображения (%1 - %2). %3 - - + + Error Ошибка - + You did not specified a save folder! Do you want to open the options window? Вы не выбрали папку для сохранения! Хотите открыть окно настроек? - + You did not specified a save format! Do you want to open the options window? Вы не выбрали формат для сохранения! Хотите открыть окно настроек? - + Error saving image. Ошибка сохранения изображения. - + Save image Сохранить изображение @@ -2219,7 +2235,7 @@ - + Pause Пауза @@ -2230,7 +2246,7 @@ - + Cancel Отмена @@ -2310,40 +2326,40 @@ Очистить загрузки - + Paused На паузе - + Resume Возобновить + - h 'h' m 'm' s 's' ч 'ч' м 'м' с 'с' + - m 'm' s 's' м 'м' с 'с' + - s 's' с 'с' - + <b>Average speed:</b> %1 %2<br/><br/><b>Elapsed time:</b> %3<br/><b>Remaining time:</b> %4 <b>Средняя скорость:</b> %1 %2<br/><br/><b>Потрачено времени:</b> %3<br/><b>Осталось ждать:</b> %4 - + Close Закрыть @@ -2587,7 +2603,7 @@ Удалить - + Choose an image Выберите изображение @@ -2742,8 +2758,8 @@ - - + + Tags Теги @@ -2769,14 +2785,14 @@ - + Filename Имя файла - - + + Folder Папка @@ -2797,7 +2813,7 @@ - + Add Добавить @@ -2833,242 +2849,247 @@ + Search + Поиск + + + Site Сайт - + Delete all Очистить список - + Delete selected Удалить из списка - + Download Скачать - + Download selected Скачать выбранное - + Move down Поместить ниже - + Load Загрузить - - + + Save Сохранить - + Move up Поместить выше - + Log Лог - + Clear log Очистить лог - + Open log Открыть лог - + Help Помощь - + Tools Инструменты - + View Просмотр - + File Файл - - - + + + Kept for later Оставлено на потом - - - + + + Favorites Избранное - - + + Name Название - + Note Заметка - + Last viewed Последний просмотр - + Ascending По возрастанию - + Descending По убыванию - + Wiki Вики - + Destination Папка для сохранения - + Reset Сброс - + Options Настройки - + Ctrl+P Ctrl+P - + Open destination folder Открыть папку с загрузками - + Quit Выход - + About Grabber О программе - + About Qt О платформе Qt - + New tab Новая вкладка - + Close tab Закрыть вкладку - + Blacklist fixer Фиксер черного список - + Empty folders fixer Фиксер пустых папок - + New pool tab Новая вкладка пула - + MD5 list fixer Фиксер списка MD5 сумм - + Open options folder Открыть папку с настройками - + Project website Сайт программы - + Report an issue Сообщить об ошибке - + Rename existing images Переименование изображений - + Project GitHub Страница на GitHub - + Restore last closed tab Восстановить закрытую вкладку - + Tag loader Загрузчик тегов - + No source found Источник не найден - + No source found. Do you have a configuration problem? Try to reinstall the program. Источник не найден. У вас проблемы с конфигурацией? Попробуйте переустановить программу. @@ -3077,82 +3098,82 @@ Видимо приложение в прошлый раз было закрыто некорректно. Хотите ли вы начать новый сеанс? - + It seems that the application was not properly closed for its last use. Do you want to restore your last session? Видимо приложение в прошлый раз было закрыто некорректно. Хотите ли вы восстановить сеанс? - + The Mozilla Firefox addon "Danbooru Downloader" has been detected on your system. Do you want to load its preferences? Найден плагин "Danbooru Downloader" для Mozilla Firefox. Хотите загрузить его настройки? - + Groups (%1/%2) Группы (%1/%2) - + Confirmation Подтверждение - + Are you sure you want to clear your download list? Вы уверены, что хотите очистить список загрузок? - + This source is not valid. Этот источник не действителен. - + The image per page value must be greater or equal to 1. Число изображений на страницу должно быть не меньше 1. - + The image limit must be greater or equal to 0. Лимит изображений должен быть равен или больше 0. - + MM/dd/yyyy MM/dd/yyyy - + <b>Name:</b> %1<br/><b>Note:</b> %2 %%<br/><b>Last view:</b> %3 <b>Название:</b> %1<br/><b>Заметка:</b> %2 %%<br/><b>Последний просмотр:</b> %3 - + Are you sure you want to quit? Вы уверены что хотите выйти? - + Don't keep for later Не оставлять на потом - + You did not specify a save folder! Вы не выбрали папку для сохранения! - + You did not specify a filename! Вы не выбрали имя файла! - + Logging in, please wait... Вход в аккаунт, пожалуйста, подождите ... - + Downloading pages, please wait... Загрузка страниц, пожалуйста подождите... @@ -3165,12 +3186,12 @@ - + Preparing images, please wait... Подготовка изображений, пожалуйста подождите... - + Downloading images... Загрузка изображений... @@ -3185,12 +3206,12 @@ Please solve the issue before resuming the download. Пожалуйста, решите эт проблему перед тем, как возобновить загрузку. - + Error Ошибка - + An error occured saving the image. %1 Please solve the issue before resuming the download. @@ -3199,13 +3220,13 @@ Please solve the issue before resuming the download. Пожалуйста, решите эту проблему перед тем как возобновить загрузку. - - + + Getting images Получение изображений - + %n file(s) downloaded successfully. %n файл успешно загружен. @@ -3214,7 +3235,7 @@ Please solve the issue before resuming the download. - + %n file(s) ignored. %n файл проигнорирован. @@ -3223,7 +3244,7 @@ Please solve the issue before resuming the download. - + %n file(s) already existing. %n файл уже существует. @@ -3232,7 +3253,7 @@ Please solve the issue before resuming the download. - + %n file(s) not found on the server. %n файл не найден на сервере. @@ -3241,7 +3262,7 @@ Please solve the issue before resuming the download. - + %n file(s) skipped. %n файл пропущен. @@ -3250,7 +3271,7 @@ Please solve the issue before resuming the download. - + %n error(s). %n ошибка. @@ -3259,59 +3280,59 @@ Please solve the issue before resuming the download. - + Errors occured during the images download. Do you want to restart the download of those images? (%1/%2) Во время загрузки изображений произошли ошибки. Хотите повторить загрузку? (%1/%2) - + &Quit - + Not enough space on the destination drive "%1". Please free some space before resuming the download. - - - + + + Save link list Сохранить список ссылок - - + + Imageboard-Grabber links (*.igl) Список ссылок из программы Imageboard-Grabber(*.igl) - + Link list saved successfully! Список ссылок сохранён! - - + + Error opening file. Ошибка при открытии файла. - - - + + + Load link list Загрузить список ссылок - + Link list loaded successfully! Список ссылок загружен! - + Loading %n download(s) Загружается %n загрузка @@ -3320,7 +3341,7 @@ Please free some space before resuming the download. - + Choose a save folder Выберите папку для сохранения @@ -3546,13 +3567,13 @@ Please free some space before resuming the download. - + Commands Команды - + Database База данных @@ -3592,12 +3613,12 @@ Please free some space before resuming the download. <i>Разделять теги пробелами.</i> - + Ignore images containing a blacklisted tag Игнорировать изображения содержащие теги из черного списка - + <i>Images containing a blacklisted tag will not be displayed in the results if this box is checked. Else, a confirmation will be asked before showing one of these images.</i> <i>Если включено, изображения с тегами из чёрного списка не будут отображаться в результатах, иначе каждый раз вас будут спрашивать о показе таких изображений.</i> @@ -4085,8 +4106,8 @@ Please free some space before resuming the download. - - + + Image Изображение @@ -4274,8 +4295,8 @@ Please free some space before resuming the download. - - + + Color Цвет @@ -4469,196 +4490,198 @@ Please free some space before resuming the download. - + Hosts В режиме поиска по нескольким сайтам - - + + Horizontal margins Горизонтальные поля - - + + Borders Границы - + Images В режиме поиска по одному сайту / Объединённые результаты - + Vertical margins Вертикальные поля - + Show log Показывать лог - + Blacklisted tags - + <i>One line per blacklist. You can put multiple tags on a single line to make "AND" conditions.</i> - + Delay on startup - + s - + Tray icon - + Minimize to tray - + Close to tray - + Enable system tray icon - + Use proxy Использовать прокси - - + + Host Хост - + Port Порт - + Type Тип - + HTTP HTTP - + SOCKS v5 SOCKS v5 - + Use system-wide proxy settings Использовать системные настройки прокси - + Add a web service Добавить веб-сервис - - + + Tag (after) Тег (перед) - - + + Tag (before) Тег (после) - - + + Additional tags: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: the tag<br/><i>%type%</i>: tag type, "general", "artist", "copyright", "character", "model" or "photo_set"<br/><i>%number%</i>: the tag type number (between 0 and 6) Дополнительные теги: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: означает тег<br/><i>%type%</i>:означает тип тега, "general", "artist", "copyright", "character", "model" или "photo_set"<br/><i>%number%</i>: Количество тегов этих типов (от 0 до 6) - + Start Начало - + End Конец - + Credentials Полномочия - + + User Пользователь - + + Password Пароль - + Driver Драйвер - + Choose a save folder Выберите папку для сохранения - + Choose a save folder for favorites Выберите папку для сохранения избранного - - + + Edit - - + + Remove - + Choose a color Выбор цвета - + Choose a font Выбор шрифта @@ -4733,17 +4756,17 @@ Please free some space before resuming the download. searchTab - + server offline сервер недоступен - + too many tags слишком много тегов - + page too far страница слишком далеко @@ -4752,22 +4775,23 @@ Please free some space before resuming the download. одна из миниатюр пустая (<a href="%1">%1</a>). - + Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway? Некоторые теги изображения находятся в белом списке: %1. Также некоторые теги находятся в черном списке: %2. Всё равно хотите сохранить изображение? - + No result Ничего не найдено - + Possible reasons: %1 Возможные причины: %1 - + + Page %1 of %2 (%3 of %4) Страница %1 из %2 (%3 из %4) @@ -4808,62 +4832,68 @@ Please free some space before resuming the download. dd/MM/yyyy' в 'hh:mm - + HTTPS redirection detected - + An HTTP to HTTPS redirection has been detected for the website %1. Do you want to enable SSL on it? The recommended setting is 'yes'. - + Always - + Never for that website - + Never Никогда - + + + max %1 + + + + Delete Удалить - + Save Сохранить - + Save as... Сохранить как... - + Save selected Сохранить выбранное - + Save image Сохранить изображение - + Blacklist Черный список - + %n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway? Изображение: %1 содержит тег %n из чёрного списка. Всё равно показать изображение? @@ -4885,43 +4915,48 @@ Please free some space before resuming the download. Выбрать все - + ... ... - + Add Добавить - + Cancel Отмена - + Ok Ок - + Options Настройки - + + - No preset selected - + + + + Create a new preset Создать шаблон - - + + Name Имя - + Edit preset Изменить шаблон @@ -4930,7 +4965,7 @@ Please free some space before resuming the download. Для этого источника доступно обновление, но для другой версии программы. - + An update for this source is available. Для этого источника доступно обновление. @@ -4992,12 +5027,12 @@ Please free some space before resuming the download. Настройки - + Choose a save folder Выберите папку для сохранения - + An error occurred creating the save folder. Ошибка при создании папки для сохранения. diff --git a/languages/Spanish.ts b/languages/Spanish.ts index 83fc8d8a2..ab4965963 100644 --- a/languages/Spanish.ts +++ b/languages/Spanish.ts @@ -28,12 +28,12 @@ Traducción al español por Eddy Castillo. - + Grabber is up to date Grabber está actualizado - + A new version is available: %1 Hay una nueva versión disponible: %1 @@ -124,12 +124,12 @@ Navegar - + Choose a save folder Elija una carpeta para guardar - + No image found. No se encontró ninguna imagen. @@ -137,16 +137,15 @@ Api - Tag search is impossible with the chosen source (%1). - Es imposible buscar etiquetas con la fuente elegida (%1). + Es imposible buscar etiquetas con la fuente elegida (%1). BlacklistFix1 - + Blacklist fixer Arreglar lista negra @@ -196,17 +195,17 @@ Cancelar - + This directory does not exist. Esta carpeta no existe. - + If you want to get the MD5 from the filename, you have to include the %md5% token in it. Si quiere usar el MD5 en el nombre del archivo, debe incluir el identificador %md5% en él. - + You are about to download information from %n image(s). Are you sure you want to continue? Está a punto de descargar información de %n imagen. ¿Desea continuar? @@ -470,12 +469,12 @@ Renombrado por javascript - + Warning Advertencia - + You script contains error, are you sure you want to save it? Su script contiene errores, ¿desea continuar? @@ -519,168 +518,168 @@ la imagen contiene "%1" - + <b>Tags:</b> %1<br/><br/> <b>Etiquetas:</b> %1<br/><br/> - - + + <b>ID:</b> %1<br/> <b>ID:</b> %1<br/> - + <b>Name:</b> %1<br/> - + <b>Rating:</b> %1<br/> <b>Clasificación:</b> %1<br/> - + <b>Score:</b> %1<br/> <b>Puntaje:</b> %1<br/> - + <b>User:</b> %1<br/><br/> <b>Usuario:</b> %1<br/> - + <b>Size:</b> %1 x %2<br/> <b>Dimensiones:</b> %1 x %2<br/> - + <b>Filesize:</b> %1 %2<br/> <b>Tamaño:</b> %1 %2<br/> - + <b>Date:</b> %1 <b>Fecha:</b> %1 - + 'the 'MM/dd/yyyy' at 'hh:mm 'el 'MM/dd/yyyy' - 'hh:mm - + <i>Unknown</i> <i>Desconocido</i> - + yes - + no no - + Tags Etiquetas - + ID ID - + MD5 MD5 - + Rating Clasificación - + Score Puntaje - + Author Autor - + Date Fecha - + 'the' MM/dd/yyyy 'at' hh:mm 'el' MM/dd/yyyy '-' hh:mm - + Size Dimensiones - + Filesize Tamaño - + Page Página - + URL URL - + Source Fuente - + Sample Muestra - + Thumbnail Miniatura - + Parent Padre - + yes (#%1) sí (#%1) - + Comments Comentarios - + Children Hijo - + Notes Notas @@ -804,7 +803,7 @@ Page - + No valid source of the site returned result. No se obtuvo resultados de ninguna de las fuentes del sitio web. @@ -893,47 +892,47 @@ <b>Aviso:</b> %1 - + MM-dd-yyyy HH.mm MM-dd-yyyy HH.mm - + Filename must not be empty! ¡El nombre de archivo no debe estar vacío! - + Can't validate Javascript expressions. No se pueden validar las expresiones Javascript. - + Your filename doesn't ends by an extension, symbolized by %ext%! You may not be able to open saved files. ¡El nombre de archivo no termina con una extensión, identificada con %ext%! Es posible que no pueda abrir los archivos guardados. - + Your filename is not unique to each image and an image may overwrite a previous one at saving! You should use%md5%, which is unique to each image, to avoid this inconvenience. ¡El nombre de archivo no es único para cada imagen y se pueden sobreescribir al guardarse! Debería usar %md5%, lo cual es único para cada imagen para evitar este inconveniente. - + The %%1% token does not exist and will not be replaced. El identificador %%1% no existe y no será reemplazado. - + Your format contains characters forbidden on Windows! Forbidden characters: * ? " : < > | ¡El formato contiene caracteres prohibidos en Windows! Caracteres prohibidos: * ? " : < > | - + You have chosen to use the %id% token. Know that it is only unique for a selected site. The same ID can identify different images depending on the site. Está utilizando el identificador %id%. Este solo es único para el sitio web seleccionado. La misma ID puede identificar imágenes diferentes dependiendo del sitio web. - + Valid filename! ¡Nombre de archivo válido! @@ -966,59 +965,67 @@ GiB - + image has a "%1" token - + image does not have a "%1" token - unknown type "%1" (available types: "%2") - Tipo desconocido "%1" (tipos disponibles: "%2") + Tipo desconocido "%1" (tipos disponibles: "%2") - - + + + image's %1 does not match %1 de la imagen no coincide - - + + + image's %1 match %1 de la imagen coincide - + + image is not "%1" la imagen no es "%1" - + + image is "%1" la imagen no es "%1" - + + An image needs a date to be filtered by age + + + + image's source does not starts with "%1" la fuente de la imagen no comienza con "%1" - + image's source starts with "%1" la fuente de la imagen no comienza con "%1" - + image does not contains "%1" la imagen no contiene "%1" - + image contains "%1" la imagen contiene "%1" @@ -1027,7 +1034,7 @@ RenameExisting1 - + Rename existing images Renombrar imágenes existentes @@ -1092,7 +1099,7 @@ Si quiere usar el MD5 en el nombre del archivo, debe incluir el identificador %md5% en él. - + You are about to download information from %n image(s). Are you sure you want to continue? Está a punto de descargar información de %n imagen. ¿Desea continuar? @@ -1345,12 +1352,12 @@ %v/%m - + The url you entered is not valid. - + Unable to guess site's type. Are you sure about the url? No se pudo encontrar el tipo del sitio web. ¿La URL es correcta? @@ -1725,115 +1732,125 @@ Aceptar - + Hash a password Cifrar una contraseña - + Please enter your password below.<br/>It will then be hashed using the format "%1". Por favor introduzca su contraseña abajo. </br>Se cifrará usando el formato "%1". - + Delete a site Eliminar un sitio web - + Are you sure you want to delete the site %1? ¿Seguro que quiere eliminar el sitio web %1? - + Connection... - + Success! ¡Éxito! - + Failure Error - + Unable to test No es posible hacer la prueba + + + Error + Error + + + + You should at least select one source + + TagContextMenu - + Remove from favorites Eliminar de favoritos - + Choose as image Elegir como imagen - + Add to favorites Añadir a favoritos - + Don't keep for later No guardar para más tarde - + Keep for later Guardar para más tarde - + Don't blacklist - + Blacklist Lista negra - + Don't ignore No ignorar - + Ignore Ignorar - + Copy tag Copiar etiqueta - + Copy all tags Copiar todas las etiquetas - + Open in a new tab Abrir en una pestaña nueva - + Open in new a window Abrir en una ventana nueva - + Open in browser Abrir en el navegador web @@ -1895,49 +1912,49 @@ TextEdit - + Favorites Favoritos - - + + Remove Eliminar - - + + Add Añadir - + Kept for later Guardar para más tarde - + Ratings Clasificación - + Sortings Ordenar por - + Copy Copiar - + Cut Cortar - + Paste Pegar @@ -1991,14 +2008,14 @@ ZoomWindow - - + + Image Imagen - + Save Guardar @@ -2009,7 +2026,7 @@ - + Save and close Guardar y cerrar @@ -2025,13 +2042,13 @@ - + Save (fav) Guardar (favorito) - + Save and close (fav) Guardar y cerrar (favorito) @@ -2041,155 +2058,154 @@ Carpeta de destino (favorito) - + Reload - + Copy file Copiar archivo - + Copy data Copiar datos - + Folder does not exist La carpeta no existe - + The save folder does not exist yet. Create it? La carpeta para guardar no existe. ¿Desea crearla? - + Error creating folder. %1 Ocurrió un error al crear la carpeta. %1 - - + + Saving... (fav) Guardando... (favorito) - - + + Saving... Guardando... - + Saved! (fav) ¡Guardado! (favorito) - + Saved! ¡Guardado! - + Copied! (fav) ¡Copiado! (favorito) - + Copied! ¡Copiado! - + Moved! (fav) ¡Movido! (favorito) - + Moved! ¡Movido! - + MD5 already exists (fav) - + MD5 already exists - + Already exists (fav) - + Already exists - + Delete (fav) - + Delete Eliminar - + Close (fav) Cerrar (favorito) - + Close Cerrar - + File is too big to be displayed. %1 - An unexpected error occured loading the image (%1 - %2). %3 - Ha ocurrido un error inesperado al cargar la imagen (%1 - %2) + Ha ocurrido un error inesperado al cargar la imagen (%1 - %2) %3 - - + + Error Error - + You did not specified a save folder! Do you want to open the options window? ¡No se especificó una carpeta para guardar! ¿Desea abrir la ventana de opciones? - + You did not specified a save format! Do you want to open the options window? ¡No se especificó un formato de guardado! ¿Desea abrir la ventana de opciones? - + Error saving image. Error al guardar la imagen. - + Save image Guardar imagen @@ -2208,7 +2224,7 @@ - + Pause Pausa @@ -2219,7 +2235,7 @@ - + Cancel Cancelar @@ -2299,40 +2315,40 @@ Eliminar - + Paused Pausado - + Resume Continuar + - h 'h' m 'm' s 's' h 'h' m 'm' s 's' + - m 'm' s 's' m 'm' s 's' + - s 's' s 's' - + <b>Average speed:</b> %1 %2<br/><br/><b>Elapsed time:</b> %3<br/><b>Remaining time:</b> %4 <b>Velocidad promedio:</b> %1 %2<br/><br/><b>Tiempo transcurrido:</b> %3<br/><b>Tiempo faltante:</b> %4 - + Close Cerrar @@ -2576,7 +2592,7 @@ Eliminar - + Choose an image Elegir una imagen @@ -2731,8 +2747,8 @@ - - + + Tags Etiquetas @@ -2758,14 +2774,14 @@ - + Filename Nombre del archivo - - + + Folder Carpeta @@ -2786,7 +2802,7 @@ - + Add Añadir @@ -2822,327 +2838,332 @@ + Search + Buscar + + + Site Sitio web - + Delete all Eliminar todo - + Delete selected Eliminar seleccionado - + Download Descargar - + Download selected Descargar seleccionado - + Move down Mover hacia abajo - + Load Cargar - - + + Save Guardar - + Move up Mover hacia arriba - + Log Registros - + Clear log Limpiar registros - + Open log Abrir registros - + Help Ayuda - + Tools Herramientas - + View Ver - + File Archivo - - - + + + Kept for later Guardado para más tarde - - - + + + Favorites Favoritos - - + + Name Nombre - + Note Nota - + Last viewed Último visto - + Ascending Ascendente - + Descending Descendente - + Wiki Wiki - + Destination Destino - + Reset Reiniciar - + Options Opciones - + Ctrl+P Ctrl+P - + Open destination folder Abrir carpeta de destino - + Quit Cerrar - + About Grabber Acerca de Grabber - + About Qt Acerca de Qt - + New tab Nueva pestaña - + Close tab Cerrar pestaña - + Blacklist fixer Arreglar lista negra - + Empty folders fixer Arreglar carpetas vacías - + New pool tab Nueva pestaña de colecciones - + MD5 list fixer Arreglar lista MD5 - + Open options folder Abrir carpeta de opciones - + Project website Sitio web del proyecto - + Report an issue Reporta un problema - + Rename existing images Renombrar imágenes existentes - + Project GitHub Github del proyecto - + Restore last closed tab - + Tag loader - + No source found No se encontró ninguna fuente - + No source found. Do you have a configuration problem? Try to reinstall the program. No se encontró ninguna fuente. ¿Será algún problema de configuración? Intente reinstalando el programa. - + &Quit - + It seems that the application was not properly closed for its last use. Do you want to restore your last session? Parece que la aplicación no se cerró correctamente la última vez. ¿Desea restaurar la sesión anterior? - + The Mozilla Firefox addon "Danbooru Downloader" has been detected on your system. Do you want to load its preferences? Se detectó el complemento de Firefox "Danbooru Downloader" en el sistema. ¿Desea cargar su configuración? - + Groups (%1/%2) Grupos (%1/%2) - + Confirmation - + Are you sure you want to clear your download list? - + This source is not valid. Esta fuente no es válida. - + The image per page value must be greater or equal to 1. El valor de imágenes por página debe ser mayor o igual que 1. - + The image limit must be greater or equal to 0. El límite de imágenes debe ser mayor o igual que 0. - + MM/dd/yyyy MM/dd/yyyy - + <b>Name:</b> %1<br/><b>Note:</b> %2 %%<br/><b>Last view:</b> %3 <b>Nombre:</b> %1<br/><b>Nota:</b> %2 %%<br/><b>Última vista:</b> %3 - + Are you sure you want to quit? ¿Seguro que desea salir de la aplicación? - + Don't keep for later No guardar para más tarde - + You did not specify a save folder! ¡No se especificó una carpeta para guardar! - + You did not specify a filename! ¡No se especificó un nombre de archivo! - + Logging in, please wait... Iniciando sesión, por favor espere... - + Downloading pages, please wait... Descargando páginas, por favor espere... @@ -3154,12 +3175,12 @@ - + Preparing images, please wait... Preparando las imágenes, por favor espere... - + Downloading images... Descargando imágenes... @@ -3174,12 +3195,12 @@ Please solve the issue before resuming the download. Por favor, resuelva este problema antes de continuar las descarga. - + Error Error - + An error occured saving the image. %1 Please solve the issue before resuming the download. @@ -3188,13 +3209,13 @@ Please solve the issue before resuming the download. Por favor, resuelva este problema antes de continuar las descarga. - - + + Getting images Obteniendo las imágenes - + %n file(s) downloaded successfully. %n archivo descargado correctamente. @@ -3202,7 +3223,7 @@ Por favor, resuelva este problema antes de continuar las descarga. - + %n file(s) ignored. %n archivo ignorado. @@ -3210,7 +3231,7 @@ Por favor, resuelva este problema antes de continuar las descarga. - + %n file(s) already existing. %n archivo ya existe. @@ -3218,7 +3239,7 @@ Por favor, resuelva este problema antes de continuar las descarga. - + %n file(s) not found on the server. %n archivo no se encontró en el servidor. @@ -3226,7 +3247,7 @@ Por favor, resuelva este problema antes de continuar las descarga. - + %n file(s) skipped. %n archivo ignorado. @@ -3234,7 +3255,7 @@ Por favor, resuelva este problema antes de continuar las descarga. - + %n error(s). %n error. @@ -3242,54 +3263,54 @@ Por favor, resuelva este problema antes de continuar las descarga. - + Errors occured during the images download. Do you want to restart the download of those images? (%1/%2) Ocurrieron errores durante la descarga de las imágenes. ¿Desea reiniciar la descarga de esas imágenes? (%1/%2) - + Not enough space on the destination drive "%1". Please free some space before resuming the download. - - - + + + Save link list Guardar lista de enlaces - - + + Imageboard-Grabber links (*.igl) Enlaces en formato Imageboard-Grabber (*.igl) - + Link list saved successfully! ¡Lista de enlaces guardada correctamente! - - + + Error opening file. Error al abrir el archivo. - - - + + + Load link list Cargar lista de enlaces - + Link list loaded successfully! ¡Lista de enlaces cargada correctamente! - + Loading %n download(s) Cargando %n descarga @@ -3297,7 +3318,7 @@ Please free some space before resuming the download. - + Choose a save folder Elige una carpeta para guardar @@ -3517,13 +3538,13 @@ Please free some space before resuming the download. - + Commands Comandos - + Database Base de datos @@ -3563,12 +3584,12 @@ Please free some space before resuming the download. <i>Separe las etiquetas con espacios</i> - + Ignore images containing a blacklisted tag Ignorar las imágenes que contengan una etiqueta de la lista negra - + <i>Images containing a blacklisted tag will not be displayed in the results if this box is checked. Else, a confirmation will be asked before showing one of these images.</i> <i>Cuando esté activado, las imágenes que contengan una etiqueta de la lista negra no se mostrarán. De otra forma, se le preguntará antes de mostrar una de estas imágenes.</i> @@ -4056,8 +4077,8 @@ Please free some space before resuming the download. - - + + Image Imagen @@ -4241,8 +4262,8 @@ Please free some space before resuming the download. - - + + Color Color @@ -4432,196 +4453,198 @@ Please free some space before resuming the download. - + Hosts Servidores - - + + Horizontal margins Márgenes horizontales - - + + Borders Bordes - + Images Imágenes - + Vertical margins Márgenes verticales - + Show log Mostrar registros - + Blacklisted tags - + <i>One line per blacklist. You can put multiple tags on a single line to make "AND" conditions.</i> - + Delay on startup - + s - + Tray icon - + Minimize to tray - + Close to tray - + Enable system tray icon - + Use proxy Usar proxy - - + + Host Servidor - + Port Puerto - + Type Tipo - + HTTP HTTP - + SOCKS v5 SOCKS v5 - + Use system-wide proxy settings Usar la configuración del sistema - + Add a web service - - + + Tag (after) Etiqueta (después) - - + + Tag (before) Etiqueta (antes) - - + + Additional tags: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: the tag<br/><i>%type%</i>: tag type, "general", "artist", "copyright", "character", "model" or "photo_set"<br/><i>%number%</i>: the tag type number (between 0 and 6) Etiquetas adicionales: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: la etiqueta<br/><i>%type%</i>: tipo de etiqueta, "general", "artist", "copyright", "character", "model" o "photo_set"<br/><i>%number%</i>: el número del tipo de etiqueta (entre 0 y 6) - + Start Inicio - + End Final - + Credentials Identificación - + + User Usuario - + + Password Contraseña - + Driver Controlador - + Choose a save folder Elija una carpeta para guardar - + Choose a save folder for favorites Elija una carpeta para guardar los favoritos - - + + Edit - - + + Remove Eliminar - + Choose a color Elija un color - + Choose a font Elija una tipografía @@ -4692,17 +4715,17 @@ Please free some space before resuming the download. searchTab - + server offline servidor fuera de línea - + too many tags demasiadas etiquetas - + page too far página demasiado lejos @@ -4711,22 +4734,23 @@ Please free some space before resuming the download. una de las miniaturas está vacía (<a href="%1">%1</a>). - + Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway? Algunas etiquetas de la imagen se encuentran en la lista blanca: %1. Sin embargo, algunas etiquetas se encuentran en la lista negra: %2. ¿Desea descargarla de todas formas? - + No result Sin resultados - + Possible reasons: %1 Razones posibles: %1 - + + Page %1 of %2 (%3 of %4) Página %1 de %2 (%3 de %4) @@ -4767,62 +4791,68 @@ Please free some space before resuming the download. 'el 'MM/dd/yyyy' - 'hh:mm - + HTTPS redirection detected - + An HTTP to HTTPS redirection has been detected for the website %1. Do you want to enable SSL on it? The recommended setting is 'yes'. - + Always - + Never for that website - + Never Nunca - + + + max %1 + + + + Delete Eliminar - + Save Guardar - + Save as... Guardar como... - + Save selected Guardar seleccionado - + Save image Guardar imagen - + Blacklist Lista negra - + %n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway? se detectó %n etiqueta de esta imagen en la lista negra: %1. ¿Desea mostrarla de todas formas? @@ -4843,48 +4873,53 @@ Please free some space before resuming the download. Seleccionar todo - + ... ... - + Add Añadir - + Cancel Cancelar - + Ok Aceptar - + Options Opciones - + An update for this source is available. Hay una actualización disponible para esta fuente. - + + - No preset selected - + + + + Create a new preset - - + + Name Nombre - + Edit preset @@ -4946,12 +4981,12 @@ Please free some space before resuming the download. Opciones - + Choose a save folder Elige una carpeta para guardar - + An error occurred creating the save folder. diff --git a/languages/YourLanguage.ts b/languages/YourLanguage.ts index a85916a8d..f5b52418b 100644 --- a/languages/YourLanguage.ts +++ b/languages/YourLanguage.ts @@ -24,12 +24,12 @@ - + A new version is available: %1 - + Grabber is up to date @@ -120,29 +120,21 @@ - + Choose a save folder - + No image found. - - Api - - - Tag search is impossible with the chosen source (%1). - - - BlacklistFix1 - + Blacklist fixer @@ -192,17 +184,17 @@ - + This directory does not exist. - + If you want to get the MD5 from the filename, you have to include the %md5% token in it. - + You are about to download information from %n image(s). Are you sure you want to continue? @@ -372,12 +364,12 @@ - + Warning - + You script contains error, are you sure you want to save it? @@ -385,168 +377,168 @@ Image - + <b>Tags:</b> %1<br/><br/> - - + + <b>ID:</b> %1<br/> - + <b>Name:</b> %1<br/> - + <b>Rating:</b> %1<br/> - + <b>Score:</b> %1<br/> - + <b>User:</b> %1<br/><br/> - + <b>Size:</b> %1 x %2<br/> - + <b>Filesize:</b> %1 %2<br/> - + <b>Date:</b> %1 - + 'the 'MM/dd/yyyy' at 'hh:mm - + <i>Unknown</i> - + yes - + no - + Tags - + ID - + MD5 - + Rating - + Score - + Author - + Date - + 'the' MM/dd/yyyy 'at' hh:mm - + Size - + Filesize - + Page - + URL - + Source - + Sample - + Thumbnail - + Parent - + yes (#%1) - + Comments - + Children - + Notes @@ -668,7 +660,7 @@ Page - + No valid source of the site returned result. @@ -729,47 +721,47 @@ QObject - + MM-dd-yyyy HH.mm - + Filename must not be empty! - + Can't validate Javascript expressions. - + Your filename doesn't ends by an extension, symbolized by %ext%! You may not be able to open saved files. - + Your filename is not unique to each image and an image may overwrite a previous one at saving! You should use%md5%, which is unique to each image, to avoid this inconvenience. - + The %%1% token does not exist and will not be replaced. - + Your format contains characters forbidden on Windows! Forbidden characters: * ? " : < > | - + You have chosen to use the %id% token. Know that it is only unique for a selected site. The same ID can identify different images depending on the site. - + Valid filename! @@ -779,59 +771,63 @@ - + image has a "%1" token - + image does not have a "%1" token - - unknown type "%1" (available types: "%2") - - - - - + + + image's %1 does not match - - + + + image's %1 match - + + image is not "%1" - + + image is "%1" - + + An image needs a date to be filtered by age + + + + image's source does not starts with "%1" - + image's source starts with "%1" - + image does not contains "%1" - + image contains "%1" @@ -840,7 +836,7 @@ RenameExisting1 - + Rename existing images @@ -905,7 +901,7 @@ - + You are about to download information from %n image(s). Are you sure you want to continue? @@ -1146,12 +1142,12 @@ - + The url you entered is not valid. - + Unable to guess site's type. Are you sure about the url? @@ -1518,115 +1514,125 @@ - + Hash a password - + Please enter your password below.<br/>It will then be hashed using the format "%1". - + Delete a site - + Are you sure you want to delete the site %1? - + Connection... - + Success! - + Failure - + Unable to test + + + Error + + + + + You should at least select one source + + TagContextMenu - + Remove from favorites - + Choose as image - + Add to favorites - + Don't keep for later - + Keep for later - + Don't blacklist - + Blacklist - + Don't ignore - + Ignore - + Copy tag - + Copy all tags - + Open in a new tab - + Open in new a window - + Open in browser @@ -1679,49 +1685,49 @@ TextEdit - + Favorites - - + + Remove - - + + Add - + Kept for later - + Ratings - + Sortings - + Copy - + Cut - + Paste @@ -1771,14 +1777,14 @@ ZoomWindow - - + + Image - + Save @@ -1789,7 +1795,7 @@ - + Save and close @@ -1805,13 +1811,13 @@ - + Save (fav) - + Save and close (fav) @@ -1821,153 +1827,147 @@ - + Reload - + Copy file - + Copy data - + Folder does not exist - + The save folder does not exist yet. Create it? - + Error creating folder. %1 - - + + Saving... (fav) - - + + Saving... - + Saved! (fav) - + Saved! - + Copied! (fav) - + Copied! - + Moved! (fav) - + Moved! - + MD5 already exists (fav) - + MD5 already exists - + Already exists (fav) - + Already exists - + Delete (fav) - + Delete - + Close (fav) - + Close - + File is too big to be displayed. %1 - - An unexpected error occured loading the image (%1 - %2). -%3 - - - - - + + Error - + You did not specified a save folder! Do you want to open the options window? - + You did not specified a save format! Do you want to open the options window? - + Error saving image. - + Save image @@ -1986,7 +1986,7 @@ - + Pause @@ -1997,7 +1997,7 @@ - + Cancel @@ -2077,40 +2077,40 @@ - + Paused - + Resume + - h 'h' m 'm' s 's' + - m 'm' s 's' + - s 's' - + <b>Average speed:</b> %1 %2<br/><br/><b>Elapsed time:</b> %3<br/><b>Remaining time:</b> %4 - + Close @@ -2251,7 +2251,7 @@ - + Choose an image @@ -2402,8 +2402,8 @@ - - + + Tags @@ -2429,14 +2429,14 @@ - + Filename - - + + Folder @@ -2457,7 +2457,7 @@ - + Add @@ -2493,456 +2493,461 @@ + Search + + + + Site - + Delete all - + Delete selected - + Download - + Download selected - + Move down - + Load - - + + Save - + Move up - + Log - + Clear log - + Open log - + Help - + Tools - + View - + File - - - + + + Kept for later - - - + + + Favorites - - + + Name - + Note - + Last viewed - + Ascending - + Descending - + Wiki - + Destination - + Reset - + Options - + Ctrl+P - + Open destination folder - + Quit - + About Grabber - + About Qt - + New tab - + Close tab - + Blacklist fixer - + Empty folders fixer - + New pool tab - + MD5 list fixer - + Open options folder - + Project website - + Report an issue - + Rename existing images - + Project GitHub - + Restore last closed tab - + Tag loader - + No source found - + No source found. Do you have a configuration problem? Try to reinstall the program. - + &Quit - + It seems that the application was not properly closed for its last use. Do you want to restore your last session? - + The Mozilla Firefox addon "Danbooru Downloader" has been detected on your system. Do you want to load its preferences? - + Groups (%1/%2) - + Confirmation - + Are you sure you want to clear your download list? - + This source is not valid. - + The image per page value must be greater or equal to 1. - + The image limit must be greater or equal to 0. - + MM/dd/yyyy - + <b>Name:</b> %1<br/><b>Note:</b> %2 %%<br/><b>Last view:</b> %3 - + Are you sure you want to quit? - + Don't keep for later - + You did not specify a save folder! - + You did not specify a filename! - + Logging in, please wait... - + Downloading pages, please wait... - + Preparing images, please wait... - + Downloading images... - + Error - + An error occured saving the image. %1 Please solve the issue before resuming the download. - - + + Getting images - + %n file(s) downloaded successfully. - + %n file(s) ignored. - + %n file(s) already existing. - + %n file(s) not found on the server. - + %n file(s) skipped. - + %n error(s). - + Errors occured during the images download. Do you want to restart the download of those images? (%1/%2) - + Not enough space on the destination drive "%1". Please free some space before resuming the download. - - - + + + Save link list - - + + Imageboard-Grabber links (*.igl) - + Link list saved successfully! - - + + Error opening file. - - - + + + Load link list - + Link list loaded successfully! - + Loading %n download(s) - + Choose a save folder @@ -3117,13 +3122,13 @@ Please free some space before resuming the download. - + Commands - + Database @@ -3159,12 +3164,12 @@ Please free some space before resuming the download. - + Ignore images containing a blacklisted tag - + <i>Images containing a blacklisted tag will not be displayed in the results if this box is checked. Else, a confirmation will be asked before showing one of these images.</i> @@ -3662,8 +3667,8 @@ Please free some space before resuming the download. - - + + Image @@ -3891,8 +3896,8 @@ Please free some space before resuming the download. - - + + Color @@ -3993,196 +3998,198 @@ Please free some space before resuming the download. - + Hosts - - + + Horizontal margins - - + + Borders - + Images - + Vertical margins - + Show log - + Blacklisted tags - + <i>One line per blacklist. You can put multiple tags on a single line to make "AND" conditions.</i> - + Delay on startup - + s - + Tray icon - + Minimize to tray - + Close to tray - + Enable system tray icon - + Use proxy - + Type - + HTTP - + SOCKS v5 - - + + Host - + Port - + Use system-wide proxy settings - + Add a web service - - + + Tag (after) - - + + Tag (before) - - + + Additional tags: <i>%tag%</i>, <i>%type%</i>, <i>%number%</i>.<br/><i>%tag%</i>: the tag<br/><i>%type%</i>: tag type, "general", "artist", "copyright", "character", "model" or "photo_set"<br/><i>%number%</i>: the tag type number (between 0 and 6) - + Start - + End - + Credentials - + + User - + + Password - + Driver - + Choose a save folder - + Choose a save folder for favorites - - + + Edit - - + + Remove - + Choose a color - + Choose a font @@ -4253,97 +4260,104 @@ Please free some space before resuming the download. searchTab - + server offline - + too many tags - + page too far - + HTTPS redirection detected - + An HTTP to HTTPS redirection has been detected for the website %1. Do you want to enable SSL on it? The recommended setting is 'yes'. - + Always - + Never for that website - + Never - + Some tags from the image are in the whitelist: %1. However, some tags are in the blacklist: %2. Do you want to download it anyway? - + + + max %1 + + + + No result - + Possible reasons: %1 - + + Page %1 of %2 (%3 of %4) - + Delete - + Save - + Save as... - + Save selected - + Save image - + Blacklist - + %n tag figuring in the blacklist detected in this image: %1. Do you want to display it anyway? @@ -4363,48 +4377,53 @@ Please free some space before resuming the download. - + ... - + Add - + Cancel - + Ok - + Options - + An update for this source is available. - + + - No preset selected - + + + + Create a new preset - - + + Name - + Edit preset @@ -4462,12 +4481,12 @@ Please free some space before resuming the download. - + Choose a save folder - + An error occurred creating the save folder. From be23d914c771aab8efd1b9d82f9ebc851ec2fd06 Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 5 Aug 2018 17:25:33 +0200 Subject: [PATCH 112/112] Version 6.0.4 --- CMakeLists.txt | 2 +- releases/setup.iss | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index fc1611be0..abf0eeda4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,7 +27,7 @@ endif() project(Grabber) set(USE_SSL 1) -add_definitions(-DVERSION="6.0.3") +add_definitions(-DVERSION="6.0.4") add_definitions(-DPROJECT_WEBSITE_URL="https://bionus.github.io/imgbrd-grabber/") add_definitions(-DPROJECT_GITHUB_URL="https://github.com/Bionus/imgbrd-grabber") add_definitions(-DSOURCE_ISSUES_URL="https://raw.githubusercontent.com/wiki/Bionus/imgbrd-grabber/SourceIssues.md") diff --git a/releases/setup.iss b/releases/setup.iss index 7744b169c..828e9dafc 100755 --- a/releases/setup.iss +++ b/releases/setup.iss @@ -18,7 +18,7 @@ #endif #ifndef MyAppVersion -# define MyAppVersion "6.0.3" +# define MyAppVersion "6.0.4" #endif