diff --git a/AnnotationDialog/Dialog.cpp b/AnnotationDialog/Dialog.cpp index 78c32b80..93e6c6bf 100644 --- a/AnnotationDialog/Dialog.cpp +++ b/AnnotationDialog/Dialog.cpp @@ -1,1733 +1,1733 @@ /* Copyright (C) 2003-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Dialog.h" #include "DateEdit.h" #include "DescriptionEdit.h" #include "ImagePreviewWidget.h" #include "ListSelect.h" #include "Logging.h" #include "ResizableFrame.h" #include "ShortCutManager.h" #include "ShowSelectionOnlyManager.h" #include "enums.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_MARBLE +#include "Map/GeoCoordinates.h" #include #include #include -#include "Map/GeoCoordinates.h" #endif #include #include #include #include #include using Utilities::StringSet; /** * \class AnnotationDialog::Dialog * \brief QDialog subclass used for tagging images */ AnnotationDialog::Dialog::Dialog(QWidget *parent) : QDialog(parent) , m_ratingChanged(false) , m_conflictText(i18n("(You have differing descriptions on individual images, setting text here will override them all)")) { Utilities::ShowBusyCursor dummy; ShortCutManager shortCutManager; // The widget stack QWidget *mainWidget = new QWidget(this); QVBoxLayout *layout = new QVBoxLayout(mainWidget); setLayout(layout); layout->addWidget(mainWidget); m_stack = new QStackedWidget(mainWidget); layout->addWidget(m_stack); // The Viewer m_fullScreenPreview = new Viewer::ViewerWidget(Viewer::ViewerWidget::InlineViewer); m_stack->addWidget(m_fullScreenPreview); // The dock widget m_dockWindow = new QMainWindow; m_stack->addWidget(m_dockWindow); m_dockWindow->setDockNestingEnabled(true); // -------------------------------------------------- Dock widgets m_generalDock = createDock(i18n("Label and Dates"), QString::fromLatin1("Label and Dates"), Qt::TopDockWidgetArea, createDateWidget(shortCutManager)); m_previewDock = createDock(i18n("Image Preview"), QString::fromLatin1("Image Preview"), Qt::TopDockWidgetArea, createPreviewWidget()); m_description = new DescriptionEdit(this); m_description->setProperty("WantsFocus", true); m_description->setObjectName(i18n("Description")); m_description->setCheckSpellingEnabled(true); m_description->setTabChangesFocus(true); // this allows tabbing to the next item in the tab order. m_description->setWhatsThis(i18nc("@info:whatsthis", "A descriptive text of the image." "If Use Exif description is enabled under " "Settings|Configure KPhotoAlbum...|General, a description " "embedded in the image Exif information is imported to this field if available.")); m_descriptionDock = createDock(i18n("Description"), QString::fromLatin1("description"), Qt::LeftDockWidgetArea, m_description); shortCutManager.addDock(m_descriptionDock, m_description); connect(m_description, SIGNAL(pageUpDownPressed(QKeyEvent *)), this, SLOT(descriptionPageUpDownPressed(QKeyEvent *))); #ifdef HAVE_MARBLE // -------------------------------------------------- Map representation m_annotationMapContainer = new QWidget(this); QVBoxLayout *annotationMapContainerLayout = new QVBoxLayout(m_annotationMapContainer); m_annotationMap = new Map::MapView(this); annotationMapContainerLayout->addWidget(m_annotationMap); QHBoxLayout *mapLoadingProgressLayout = new QHBoxLayout(); annotationMapContainerLayout->addLayout(mapLoadingProgressLayout); m_mapLoadingProgress = new QProgressBar(this); mapLoadingProgressLayout->addWidget(m_mapLoadingProgress); m_mapLoadingProgress->hide(); m_cancelMapLoadingButton = new QPushButton(i18n("Cancel")); mapLoadingProgressLayout->addWidget(m_cancelMapLoadingButton); m_cancelMapLoadingButton->hide(); connect(m_cancelMapLoadingButton, SIGNAL(clicked()), this, SLOT(setCancelMapLoading())); m_annotationMapContainer->setObjectName(i18n("Map")); m_mapDock = createDock( i18n("Map"), QString::fromLatin1("map"), Qt::LeftDockWidgetArea, m_annotationMapContainer); shortCutManager.addDock(m_mapDock, m_annotationMapContainer); connect(m_mapDock, SIGNAL(visibilityChanged(bool)), this, SLOT(annotationMapVisibilityChanged(bool))); m_mapDock->setWhatsThis(i18nc("@info:whatsthis", "The map widget allows you to view the location of images if GPS coordinates are found in the Exif information.")); #endif // -------------------------------------------------- Categories QList categories = DB::ImageDB::instance()->categoryCollection()->categories(); // Let's first assume we don't have positionable categories m_positionableCategories = false; for (QList::ConstIterator categoryIt = categories.constBegin(); categoryIt != categories.constEnd(); ++categoryIt) { ListSelect *sel = createListSel(*categoryIt); // Create a QMap of all ListSelect instances, so that we can easily // check if a specific (positioned) tag is (still) selected later m_listSelectList[(*categoryIt)->name()] = sel; QDockWidget *dock = createDock((*categoryIt)->name(), (*categoryIt)->name(), Qt::BottomDockWidgetArea, sel); shortCutManager.addDock(dock, sel->lineEdit()); if ((*categoryIt)->isSpecialCategory()) dock->hide(); // Pass the positionable selection to the object sel->setPositionable((*categoryIt)->positionable()); if (sel->positionable()) { connect(sel, SIGNAL(positionableTagSelected(QString, QString)), this, SLOT(positionableTagSelected(QString, QString))); connect(sel, SIGNAL(positionableTagDeselected(QString, QString)), this, SLOT(positionableTagDeselected(QString, QString))); connect(sel, SIGNAL(positionableTagRenamed(QString, QString, QString)), this, SLOT(positionableTagRenamed(QString, QString, QString))); connect(m_preview->preview(), SIGNAL(proposedTagSelected(QString, QString)), sel, SLOT(ensureTagIsSelected(QString, QString))); // We have at least one positionable category m_positionableCategories = true; } } // -------------------------------------------------- The buttons. // don't use default buttons (Ok, Cancel): QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::NoButton); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); QHBoxLayout *lay1 = new QHBoxLayout; layout->addLayout(lay1); m_revertBut = new QPushButton(i18n("Revert This Item")); KAcceleratorManager::setNoAccel(m_revertBut); lay1->addWidget(m_revertBut); m_clearBut = new QPushButton(); KGuiItem::assign(m_clearBut, KGuiItem(i18n("Clear Form"), QApplication::isRightToLeft() ? QString::fromLatin1("clear_left") : QString::fromLatin1("locationbar_erase"))); KAcceleratorManager::setNoAccel(m_clearBut); lay1->addWidget(m_clearBut); QPushButton *optionsBut = new QPushButton(i18n("Options...")); KAcceleratorManager::setNoAccel(optionsBut); lay1->addWidget(optionsBut); lay1->addStretch(1); m_okBut = new QPushButton(i18n("&Done")); lay1->addWidget(m_okBut); m_continueLaterBut = new QPushButton(i18n("Continue &Later")); lay1->addWidget(m_continueLaterBut); QPushButton *cancelBut = new QPushButton(); KGuiItem::assign(cancelBut, KStandardGuiItem::cancel()); lay1->addWidget(cancelBut); // It is unfortunately not possible to ask KAcceleratorManager not to setup the OK and cancel keys. shortCutManager.addTaken(i18nc("@action:button", "&Search")); shortCutManager.addTaken(m_okBut->text()); shortCutManager.addTaken(m_continueLaterBut->text()); shortCutManager.addTaken(cancelBut->text()); connect(m_revertBut, SIGNAL(clicked()), this, SLOT(slotRevert())); connect(m_okBut, SIGNAL(clicked()), this, SLOT(doneTagging())); connect(m_continueLaterBut, SIGNAL(clicked()), this, SLOT(continueLater())); connect(cancelBut, SIGNAL(clicked()), this, SLOT(reject())); connect(m_clearBut, SIGNAL(clicked()), this, SLOT(slotClear())); connect(optionsBut, SIGNAL(clicked()), this, SLOT(slotOptions())); connect(m_preview, SIGNAL(imageRotated(int)), this, SLOT(rotate(int))); connect(m_preview, SIGNAL(indexChanged(int)), this, SLOT(slotIndexChanged(int))); connect(m_preview, SIGNAL(imageDeleted(DB::ImageInfo)), this, SLOT(slotDeleteImage())); connect(m_preview, SIGNAL(copyPrevClicked()), this, SLOT(slotCopyPrevious())); connect(m_preview, SIGNAL(areaVisibilityChanged(bool)), this, SLOT(slotShowAreas(bool))); connect(m_preview->preview(), SIGNAL(areaCreated(ResizableFrame *)), this, SLOT(slotNewArea(ResizableFrame *))); // Disable so no button accept return (which would break with the line edits) m_revertBut->setAutoDefault(false); m_okBut->setAutoDefault(false); m_continueLaterBut->setAutoDefault(false); cancelBut->setAutoDefault(false); m_clearBut->setAutoDefault(false); optionsBut->setAutoDefault(false); m_dockWindowCleanState = m_dockWindow->saveState(); loadWindowLayout(); m_current = -1; setGeometry(Settings::SettingsData::instance()->windowGeometry(Settings::AnnotationDialog)); setupActions(); shortCutManager.setupShortCuts(); // WARNING layout->addWidget(buttonBox) must be last item in layout layout->addWidget(buttonBox); } QDockWidget *AnnotationDialog::Dialog::createDock(const QString &title, const QString &name, Qt::DockWidgetArea location, QWidget *widget) { QDockWidget *dock = new QDockWidget(title); KAcceleratorManager::setNoAccel(dock); dock->setObjectName(name); dock->setAllowedAreas(Qt::AllDockWidgetAreas); dock->setWidget(widget); m_dockWindow->addDockWidget(location, dock); m_dockWidgets.append(dock); return dock; } QWidget *AnnotationDialog::Dialog::createDateWidget(ShortCutManager &shortCutManager) { QWidget *top = new QWidget; QVBoxLayout *lay2 = new QVBoxLayout(top); // Image Label QHBoxLayout *lay3 = new QHBoxLayout; lay2->addLayout(lay3); QLabel *label = new QLabel(i18n("Label: ")); lay3->addWidget(label); m_imageLabel = new KLineEdit; m_imageLabel->setProperty("WantsFocus", true); m_imageLabel->setObjectName(i18n("Label")); lay3->addWidget(m_imageLabel); shortCutManager.addLabel(label); label->setBuddy(m_imageLabel); // Date QHBoxLayout *lay4 = new QHBoxLayout; lay2->addLayout(lay4); label = new QLabel(i18n("Date: ")); lay4->addWidget(label); m_startDate = new ::AnnotationDialog::DateEdit(true); lay4->addWidget(m_startDate, 1); connect(m_startDate, SIGNAL(dateChanged(DB::ImageDate)), this, SLOT(slotStartDateChanged(DB::ImageDate))); shortCutManager.addLabel(label); label->setBuddy(m_startDate); m_endDateLabel = new QLabel(QString::fromLatin1("-")); lay4->addWidget(m_endDateLabel); m_endDate = new ::AnnotationDialog::DateEdit(false); lay4->addWidget(m_endDate, 1); // Time m_timeLabel = new QLabel(i18n("Time: ")); lay4->addWidget(m_timeLabel); m_time = new QTimeEdit; lay4->addWidget(m_time); m_isFuzzyDate = new QCheckBox(i18n("Use Fuzzy Date")); m_isFuzzyDate->setWhatsThis(i18nc("@info", "In KPhotoAlbum, images can either have an exact date and time" ", or a fuzzy date which happened any time during" " a specified time interval. Images produced by digital cameras" " do normally have an exact date." "If you don't know exactly when a photo was taken" " (e.g. if the photo comes from an analog camera), then you should set" " Use Fuzzy Date.")); m_isFuzzyDate->setToolTip(m_isFuzzyDate->whatsThis()); lay4->addWidget(m_isFuzzyDate); lay4->addStretch(1); connect(m_isFuzzyDate, SIGNAL(stateChanged(int)), this, SLOT(slotSetFuzzyDate())); QHBoxLayout *lay8 = new QHBoxLayout; lay2->addLayout(lay8); m_megapixelLabel = new QLabel(i18n("Minimum megapixels:")); lay8->addWidget(m_megapixelLabel); m_megapixel = new QSpinBox; m_megapixel->setRange(0, 99); m_megapixel->setSingleStep(1); m_megapixelLabel->setBuddy(m_megapixel); lay8->addWidget(m_megapixel); lay8->addStretch(1); m_max_megapixelLabel = new QLabel(i18n("Maximum megapixels:")); lay8->addWidget(m_max_megapixelLabel); m_max_megapixel = new QSpinBox; m_max_megapixel->setRange(0, 99); m_max_megapixel->setSingleStep(1); m_max_megapixelLabel->setBuddy(m_max_megapixel); lay8->addWidget(m_max_megapixel); lay8->addStretch(1); QHBoxLayout *lay9 = new QHBoxLayout; lay2->addLayout(lay9); label = new QLabel(i18n("Rating:")); lay9->addWidget(label); m_rating = new KRatingWidget; m_rating->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); lay9->addWidget(m_rating, 0, Qt::AlignCenter); connect(m_rating, SIGNAL(ratingChanged(uint)), this, SLOT(slotRatingChanged(uint))); m_ratingSearchLabel = new QLabel(i18n("Rating search mode:")); lay9->addWidget(m_ratingSearchLabel); m_ratingSearchMode = new KComboBox(lay9); m_ratingSearchMode->addItems(QStringList() << i18n("==") << i18n(">=") << i18n("<=") << i18n("!=")); m_ratingSearchLabel->setBuddy(m_ratingSearchMode); lay9->addWidget(m_ratingSearchMode); // File name search pattern QHBoxLayout *lay10 = new QHBoxLayout; lay2->addLayout(lay10); m_imageFilePatternLabel = new QLabel(i18n("File Name Pattern: ")); lay10->addWidget(m_imageFilePatternLabel); m_imageFilePattern = new KLineEdit; m_imageFilePattern->setObjectName(i18n("File Name Pattern")); lay10->addWidget(m_imageFilePattern); shortCutManager.addLabel(m_imageFilePatternLabel); m_imageFilePatternLabel->setBuddy(m_imageFilePattern); m_searchRAW = new QCheckBox(i18n("Search only for RAW files")); lay2->addWidget(m_searchRAW); lay9->addStretch(1); lay2->addStretch(1); return top; } QWidget *AnnotationDialog::Dialog::createPreviewWidget() { m_preview = new ImagePreviewWidget(); connect(m_preview, &ImagePreviewWidget::togglePreview, this, &Dialog::togglePreview); return m_preview; } void AnnotationDialog::Dialog::slotRevert() { if (m_setup == InputSingleImageConfigMode) load(); } void AnnotationDialog::Dialog::slotIndexChanged(int index) { if (m_setup != InputSingleImageConfigMode) return; if (m_current >= 0) writeToInfo(); m_current = index; load(); } void AnnotationDialog::Dialog::doneTagging() { saveAndClose(); if (Settings::SettingsData::instance()->hasUntaggedCategoryFeatureConfigured()) { for (DB::ImageInfoListIterator it = m_origList.begin(); it != m_origList.end(); ++it) { (*it)->removeCategoryInfo(Settings::SettingsData::instance()->untaggedCategory(), Settings::SettingsData::instance()->untaggedTag()); } } } /* * Copy tags (only tags/categories, not description/label/...) from previous image to the currently showed one */ void AnnotationDialog::Dialog::slotCopyPrevious() { if (m_setup != InputSingleImageConfigMode) return; if (m_current < 1) return; // FIXME: it would be better to compute the "previous image" in a better way, but let's stick with this for now... DB::ImageInfo &old_info = m_editList[m_current - 1]; m_positionableTagCandidates.clear(); m_lastSelectedPositionableTag.first = QString(); m_lastSelectedPositionableTag.second = QString(); Q_FOREACH (ListSelect *ls, m_optionList) { ls->setSelection(old_info.itemsOfCategory(ls->category())); // Also set all positionable tag candidates if (ls->positionable()) { QString category = ls->category(); QSet selectedTags = old_info.itemsOfCategory(category); QSet positionedTagSet = positionedTags(category); // Add the tag to the positionable candiate list, if no area is already associated with it Q_FOREACH (const auto &tag, selectedTags) { if (!positionedTagSet.contains(tag)) { addTagToCandidateList(category, tag); } } // Check all areas for a linked tag in this category that is probably not selected anymore for (ResizableFrame *area : areas()) { QPair tagData = area->tagData(); if (tagData.first == category) { if (!selectedTags.contains(tagData.second)) { // The linked tag is not selected anymore, so remove it area->removeTagData(); } } } } } } void AnnotationDialog::Dialog::load() { // Remove all areas tidyAreas(); // No areas have been changed m_areasChanged = false; // Empty the positionable tag candidate list and the last selected positionable tag m_positionableTagCandidates.clear(); m_lastSelectedPositionableTag = QPair(); DB::ImageInfo &info = m_editList[m_current]; m_startDate->setDate(info.date().start().date()); if (info.date().hasValidTime()) { m_time->show(); m_time->setTime(info.date().start().time()); m_isFuzzyDate->setChecked(false); } else { m_time->hide(); m_isFuzzyDate->setChecked(true); } if (info.date().start().date() == info.date().end().date()) m_endDate->setDate(QDate()); else m_endDate->setDate(info.date().end().date()); m_imageLabel->setText(info.label()); m_description->setPlainText(info.description()); if (m_setup == InputSingleImageConfigMode) m_rating->setRating(qMax(static_cast(0), info.rating())); m_ratingChanged = false; // A category areas have been linked against could have been deleted // or un-marked as positionable in the meantime, so ... QMap categoryIsPositionable; QList positionableCategories; Q_FOREACH (ListSelect *ls, m_optionList) { ls->setSelection(info.itemsOfCategory(ls->category())); ls->rePopulate(); // Get all selected positionable tags and add them to the candidate list if (ls->positionable()) { QSet selectedTags = ls->itemsOn(); Q_FOREACH (const QString &tagName, selectedTags) { addTagToCandidateList(ls->category(), tagName); } } // ... create a list of all categories and their positionability ... categoryIsPositionable[ls->category()] = ls->positionable(); if (ls->positionable()) { positionableCategories << ls->category(); } } // Create all tagged areas QMap> taggedAreas = info.taggedAreas(); QMapIterator> areasInCategory(taggedAreas); while (areasInCategory.hasNext()) { areasInCategory.next(); QString category = areasInCategory.key(); // ... and check if the respective category is actually there yet and still positionable // (operator[] will insert an empty item if the category has been deleted // and is thus missing in the QMap, but the respective key won't be true) if (categoryIsPositionable[category]) { QMapIterator areaData(areasInCategory.value()); while (areaData.hasNext()) { areaData.next(); QString tag = areaData.key(); // Be sure that the corresponding tag is still checked. The category could have // been un-marked as positionable in the meantime and the tag could have been // deselected, without triggering positionableTagDeselected and the area thus // still remaining. If the category is then re-marked as positionable, the area would // show up without the tag being selected. if (m_listSelectList[category]->tagIsChecked(tag)) { m_preview->preview()->createTaggedArea(category, tag, areaData.value(), m_preview->showAreas()); } } } } if (m_setup == InputSingleImageConfigMode) { setWindowTitle(i18nc("@title:window image %1 of %2 images", "Annotations (%1/%2)", m_current + 1, m_origList.count())); m_preview->canCreateAreas( m_setup == InputSingleImageConfigMode && !info.isVideo() && m_positionableCategories); #ifdef HAVE_MARBLE updateMapForCurrentImage(); #endif } m_preview->updatePositionableCategories(positionableCategories); } void AnnotationDialog::Dialog::writeToInfo() { Q_FOREACH (ListSelect *ls, m_optionList) { ls->slotReturn(); } DB::ImageInfo &info = m_editList[m_current]; if (!info.size().isValid()) { // The actual image size has been fetched by ImagePreview, so we can add it to // the database silenty, so that it's saved if the database will be saved. info.setSize(m_preview->preview()->getActualImageSize()); } if (m_time->isHidden()) { if (m_endDate->date().isValid()) info.setDate(DB::ImageDate(QDateTime(m_startDate->date(), QTime(0, 0, 0)), QDateTime(m_endDate->date(), QTime(23, 59, 59)))); else info.setDate(DB::ImageDate(QDateTime(m_startDate->date(), QTime(0, 0, 0)), QDateTime(m_startDate->date(), QTime(23, 59, 59)))); } else info.setDate(DB::ImageDate(QDateTime(m_startDate->date(), m_time->time()))); // Generate a list of all tagged areas QMap> areas = taggedAreas(); info.setLabel(m_imageLabel->text()); info.setDescription(m_description->toPlainText()); Q_FOREACH (ListSelect *ls, m_optionList) { info.setCategoryInfo(ls->category(), ls->itemsOn()); if (ls->positionable()) { info.setPositionedTags(ls->category(), areas[ls->category()]); } } if (m_ratingChanged) { info.setRating(m_rating->rating()); m_ratingChanged = false; } } void AnnotationDialog::Dialog::ShowHideSearch(bool show) { m_megapixel->setVisible(show); m_megapixelLabel->setVisible(show); m_max_megapixel->setVisible(show); m_max_megapixelLabel->setVisible(show); m_searchRAW->setVisible(show); m_imageFilePatternLabel->setVisible(show); m_imageFilePattern->setVisible(show); m_isFuzzyDate->setChecked(show); m_isFuzzyDate->setVisible(!show); slotSetFuzzyDate(); m_ratingSearchMode->setVisible(show); m_ratingSearchLabel->setVisible(show); } QList AnnotationDialog::Dialog::areas() const { return m_preview->preview()->findChildren(); } QMap> AnnotationDialog::Dialog::taggedAreas() const { QMap> taggedAreas; foreach (ResizableFrame *area, areas()) { QPair tagData = area->tagData(); if (!tagData.first.isEmpty()) { taggedAreas[tagData.first][tagData.second] = area->actualCoordinates(); } } return taggedAreas; } int AnnotationDialog::Dialog::configure(DB::ImageInfoList list, bool oneAtATime) { ShowHideSearch(false); if (Settings::SettingsData::instance()->hasUntaggedCategoryFeatureConfigured()) { DB::ImageDB::instance()->categoryCollection()->categoryForName(Settings::SettingsData::instance()->untaggedCategory())->addItem(Settings::SettingsData::instance()->untaggedTag()); } if (oneAtATime) { m_setup = InputSingleImageConfigMode; } else { m_setup = InputMultiImageConfigMode; // Hide the default positionable category selector m_preview->updatePositionableCategories(); } #ifdef HAVE_MARBLE m_mapIsPopulated = false; m_annotationMap->clear(); #endif m_origList = list; m_editList.clear(); for (DB::ImageInfoListConstIterator it = list.constBegin(); it != list.constEnd(); ++it) { m_editList.append(*(*it)); } setup(); if (oneAtATime) { m_current = 0; m_preview->configure(&m_editList, true); load(); } else { m_preview->configure(&m_editList, false); m_preview->canCreateAreas(false); m_startDate->setDate(QDate()); m_endDate->setDate(QDate()); m_time->hide(); m_rating->setRating(0); m_ratingChanged = false; m_areasChanged = false; Q_FOREACH (ListSelect *ls, m_optionList) { setUpCategoryListBoxForMultiImageSelection(ls, list); } m_imageLabel->setText(QString()); m_imageFilePattern->setText(QString()); m_firstDescription = m_editList[0].description(); const bool allTextEqual = std::all_of(m_editList.begin(), m_editList.end(), [=](const DB::ImageInfo &item) -> bool { return item.description() == m_firstDescription; }); if (!allTextEqual) m_firstDescription = m_conflictText; m_description->setPlainText(m_firstDescription); } showHelpDialog(oneAtATime ? InputSingleImageConfigMode : InputMultiImageConfigMode); return exec(); } DB::ImageSearchInfo AnnotationDialog::Dialog::search(DB::ImageSearchInfo *search) { ShowHideSearch(true); #ifdef HAVE_MARBLE m_mapIsPopulated = false; m_annotationMap->clear(); #endif m_setup = SearchMode; if (search) m_oldSearch = *search; setup(); m_preview->setImage(QStandardPaths::locate(QStandardPaths::DataLocation, QString::fromLatin1("pics/search.jpg"))); m_ratingChanged = false; showHelpDialog(SearchMode); int ok = exec(); if (ok == QDialog::Accepted) { const QDate start = m_startDate->date(); const QDate end = m_endDate->date(); m_oldSearch = DB::ImageSearchInfo(DB::ImageDate(start, end), m_imageLabel->text(), m_description->toPlainText(), m_imageFilePattern->text()); Q_FOREACH (const ListSelect *ls, m_optionList) { m_oldSearch.setCategoryMatchText(ls->category(), ls->text()); } //FIXME: for the user to search for 0-rated images, he must first change the rating to anything > 0 //then change back to 0 . if (m_ratingChanged) m_oldSearch.setRating(m_rating->rating()); m_ratingChanged = false; m_oldSearch.setSearchMode(m_ratingSearchMode->currentIndex()); m_oldSearch.setMegaPixel(m_megapixel->value()); m_oldSearch.setMaxMegaPixel(m_max_megapixel->value()); m_oldSearch.setSearchRAW(m_searchRAW->isChecked()); #ifdef HAVE_MARBLE const Map::GeoCoordinates::Pair regionSelection = m_annotationMap->getRegionSelection(); m_oldSearch.setRegionSelection(regionSelection); #endif return m_oldSearch; } else return DB::ImageSearchInfo(); } void AnnotationDialog::Dialog::setup() { // Repopulate the listboxes in case data has changed // An group might for example have been renamed. Q_FOREACH (ListSelect *ls, m_optionList) { ls->populate(); } if (m_setup == SearchMode) { KGuiItem::assign(m_okBut, KGuiItem(i18nc("@action:button", "&Search"), QString::fromLatin1("find"))); m_continueLaterBut->hide(); m_revertBut->hide(); m_clearBut->show(); m_preview->setSearchMode(true); setWindowTitle(i18nc("@title:window title of the 'find images' window", "Search")); loadInfo(m_oldSearch); } else { m_okBut->setText(i18n("Done")); m_continueLaterBut->show(); m_revertBut->setEnabled(m_setup == InputSingleImageConfigMode); m_clearBut->hide(); m_revertBut->show(); m_preview->setSearchMode(false); m_preview->setToggleFullscreenPreviewEnabled(m_setup == InputSingleImageConfigMode); setWindowTitle(i18nc("@title:window", "Annotations")); } Q_FOREACH (ListSelect *ls, m_optionList) { ls->setMode(m_setup); } } void AnnotationDialog::Dialog::slotClear() { loadInfo(DB::ImageSearchInfo()); } void AnnotationDialog::Dialog::loadInfo(const DB::ImageSearchInfo &info) { m_startDate->setDate(info.date().start().date()); m_endDate->setDate(info.date().end().date()); Q_FOREACH (ListSelect *ls, m_optionList) { ls->setText(info.categoryMatchText(ls->category())); } m_imageLabel->setText(info.label()); m_description->setText(info.description()); } void AnnotationDialog::Dialog::slotOptions() { // create menu entries for dock windows QMenu *menu = new QMenu(this); QMenu *dockMenu = m_dockWindow->createPopupMenu(); menu->addMenu(dockMenu) ->setText(i18n("Configure Window Layout...")); QAction *saveCurrent = dockMenu->addAction(i18n("Save Current Window Setup")); QAction *reset = dockMenu->addAction(i18n("Reset layout")); // create SortType entries menu->addSeparator(); QActionGroup *sortTypes = new QActionGroup(menu); QAction *alphaTreeSort = new QAction( SmallIcon(QString::fromLatin1("view-list-tree")), i18n("Sort Alphabetically (Tree)"), sortTypes); QAction *alphaFlatSort = new QAction( SmallIcon(QString::fromLatin1("draw-text")), i18n("Sort Alphabetically (Flat)"), sortTypes); QAction *dateSort = new QAction( SmallIcon(QString::fromLatin1("x-office-calendar")), i18n("Sort by Date"), sortTypes); alphaTreeSort->setCheckable(true); alphaFlatSort->setCheckable(true); dateSort->setCheckable(true); alphaTreeSort->setChecked(Settings::SettingsData::instance()->viewSortType() == Settings::SortAlphaTree); alphaFlatSort->setChecked(Settings::SettingsData::instance()->viewSortType() == Settings::SortAlphaFlat); dateSort->setChecked(Settings::SettingsData::instance()->viewSortType() == Settings::SortLastUse); menu->addActions(sortTypes->actions()); connect(dateSort, SIGNAL(triggered()), m_optionList.at(0), SLOT(slotSortDate())); connect(alphaTreeSort, SIGNAL(triggered()), m_optionList.at(0), SLOT(slotSortAlphaTree())); connect(alphaFlatSort, SIGNAL(triggered()), m_optionList.at(0), SLOT(slotSortAlphaFlat())); // create MatchType entries menu->addSeparator(); QActionGroup *matchTypes = new QActionGroup(menu); QAction *matchFromBeginning = new QAction(i18n("Match Tags from the First Character"), matchTypes); QAction *matchFromWordStart = new QAction(i18n("Match Tags from Word Boundaries"), matchTypes); QAction *matchAnywhere = new QAction(i18n("Match Tags Anywhere"), matchTypes); matchFromBeginning->setCheckable(true); matchFromWordStart->setCheckable(true); matchAnywhere->setCheckable(true); // TODO add StatusTip text? // set current state: matchFromBeginning->setChecked(Settings::SettingsData::instance()->matchType() == AnnotationDialog::MatchFromBeginning); matchFromWordStart->setChecked(Settings::SettingsData::instance()->matchType() == AnnotationDialog::MatchFromWordStart); matchAnywhere->setChecked(Settings::SettingsData::instance()->matchType() == AnnotationDialog::MatchAnywhere); // add MatchType actions to menu: menu->addActions(matchTypes->actions()); // create toggle-show-selected entry# if (m_setup != SearchMode) { menu->addSeparator(); QAction *showSelectedOnly = new QAction( SmallIcon(QString::fromLatin1("view-filter")), i18n("Show Only Selected Ctrl+S"), menu); showSelectedOnly->setCheckable(true); showSelectedOnly->setChecked(ShowSelectionOnlyManager::instance().selectionIsLimited()); menu->addAction(showSelectedOnly); connect(showSelectedOnly, SIGNAL(triggered()), &ShowSelectionOnlyManager::instance(), SLOT(toggle())); } // execute menu & handle response: QAction *res = menu->exec(QCursor::pos()); if (res == saveCurrent) slotSaveWindowSetup(); else if (res == reset) slotResetLayout(); else if (res == matchFromBeginning) Settings::SettingsData::instance()->setMatchType(AnnotationDialog::MatchFromBeginning); else if (res == matchFromWordStart) Settings::SettingsData::instance()->setMatchType(AnnotationDialog::MatchFromWordStart); else if (res == matchAnywhere) Settings::SettingsData::instance()->setMatchType(AnnotationDialog::MatchAnywhere); } int AnnotationDialog::Dialog::exec() { m_stack->setCurrentWidget(m_dockWindow); showTornOfWindows(); this->setFocus(); // Set temporary focus before show() is called so that extra cursor is not shown on any "random" input widget show(); // We need to call show before we call setupFocus() otherwise the widget will not yet all have been moved in place. setupFocus(); const int ret = QDialog::exec(); hideTornOfWindows(); return ret; } void AnnotationDialog::Dialog::slotSaveWindowSetup() { const QByteArray data = m_dockWindow->saveState(); QFile file(QString::fromLatin1("%1/layout.dat").arg(Settings::SettingsData::instance()->imageDirectory())); if (!file.open(QIODevice::WriteOnly)) { KMessageBox::sorry(this, i18n("

Could not save the window layout.

" "File %1 could not be opened because of the following error: %2", file.fileName(), file.errorString())); } else if (!(file.write(data) && file.flush())) { KMessageBox::sorry(this, i18n("

Could not save the window layout.

" "File %1 could not be written because of the following error: %2", file.fileName(), file.errorString())); } file.close(); } void AnnotationDialog::Dialog::closeEvent(QCloseEvent *e) { e->ignore(); reject(); } void AnnotationDialog::Dialog::hideTornOfWindows() { for (QDockWidget *dock : m_dockWidgets) { if (dock->isFloating()) { qCDebug(AnnotationDialogLog) << "Hiding dock: " << dock->objectName(); dock->hide(); } } } void AnnotationDialog::Dialog::showTornOfWindows() { for (QDockWidget *dock : m_dockWidgets) { if (dock->isFloating()) { qCDebug(AnnotationDialogLog) << "Showing dock: " << dock->objectName(); dock->show(); } } } AnnotationDialog::ListSelect *AnnotationDialog::Dialog::createListSel(const DB::CategoryPtr &category) { ListSelect *sel = new ListSelect(category, m_dockWindow); m_optionList.append(sel); connect(DB::ImageDB::instance()->categoryCollection(), SIGNAL(itemRemoved(DB::Category *, QString)), this, SLOT(slotDeleteOption(DB::Category *, QString))); connect(DB::ImageDB::instance()->categoryCollection(), SIGNAL(itemRenamed(DB::Category *, QString, QString)), this, SLOT(slotRenameOption(DB::Category *, QString, QString))); return sel; } void AnnotationDialog::Dialog::slotDeleteOption(DB::Category *category, const QString &value) { for (QList::Iterator it = m_editList.begin(); it != m_editList.end(); ++it) { (*it).removeCategoryInfo(category->name(), value); } } void AnnotationDialog::Dialog::slotRenameOption(DB::Category *category, const QString &oldValue, const QString &newValue) { for (QList::Iterator it = m_editList.begin(); it != m_editList.end(); ++it) { (*it).renameItem(category->name(), oldValue, newValue); } } void AnnotationDialog::Dialog::reject() { if (m_stack->currentWidget() == m_fullScreenPreview) { togglePreview(); return; } m_fullScreenPreview->stopPlayback(); if (hasChanges()) { int code = KMessageBox::questionYesNo(this, i18n("

Some changes are made to annotations. Do you really want to cancel all recent changes for each affected file?

")); if (code == KMessageBox::No) return; } closeDialog(); } void AnnotationDialog::Dialog::closeDialog() { tidyAreas(); m_accept = QDialog::Rejected; QDialog::reject(); } bool AnnotationDialog::Dialog::hasChanges() { bool changed = false; if (m_setup == InputSingleImageConfigMode) { writeToInfo(); for (int i = 0; i < m_editList.count(); ++i) { changed |= (*(m_origList[i]) != m_editList[i]); } changed |= m_areasChanged; } else if (m_setup == InputMultiImageConfigMode) { changed |= (!m_startDate->date().isNull()); changed |= (!m_endDate->date().isNull()); Q_FOREACH (ListSelect *ls, m_optionList) { StringSet on, partialOn; std::tie(on, partialOn) = selectionForMultiSelect(ls, m_origList); changed |= (on != ls->itemsOn()); changed |= (partialOn != ls->itemsUnchanged()); } changed |= (!m_imageLabel->text().isEmpty()); changed |= (m_description->toPlainText() != m_firstDescription); changed |= m_ratingChanged; } return changed; } void AnnotationDialog::Dialog::rotate(int angle) { if (m_setup == InputMultiImageConfigMode) { // In doneTagging the preview will be queried for its angle. } else { DB::ImageInfo &info = m_editList[m_current]; info.rotate(angle, DB::RotateImageInfoOnly); emit imageRotated(info.fileName()); } } void AnnotationDialog::Dialog::slotSetFuzzyDate() { if (m_isFuzzyDate->isChecked()) { m_time->hide(); m_timeLabel->hide(); m_endDate->show(); m_endDateLabel->show(); } else { m_time->show(); m_timeLabel->show(); m_endDate->hide(); m_endDateLabel->hide(); } } void AnnotationDialog::Dialog::slotDeleteImage() { // CTRL+Del is a common key combination when editing text // TODO: The word right of cursor should be deleted as expected also in date and category fields if (m_setup == SearchMode) return; if (m_setup == InputMultiImageConfigMode) //TODO: probably delete here should mean remove from selection return; DB::ImageInfoPtr info = m_origList[m_current]; m_origList.remove(info); m_editList.removeAll(m_editList.at(m_current)); MainWindow::DirtyIndicator::markDirty(); if (m_origList.count() == 0) { doneTagging(); return; } if (m_current == (int)m_origList.count()) // we deleted the last image m_current--; load(); } void AnnotationDialog::Dialog::showHelpDialog(UsageMode type) { QString doNotShowKey; QString txt; if (type == SearchMode) { doNotShowKey = QString::fromLatin1("image_config_search_show_help"); txt = i18n("

You have just opened the advanced search dialog; to get the most out of it, " "it is suggested that you read the section in the manual on " "advanced searching.

" "

This dialog is also used for typing in information about images; you can find " "extra tips on its usage by reading about " "typing in.

"); } else { doNotShowKey = QString::fromLatin1("image_config_typein_show_help"); txt = i18n("

You have just opened one of the most important windows in KPhotoAlbum; " "it contains lots of functionality which has been optimized for fast usage.

" "

It is strongly recommended that you take 5 minutes to read the " "documentation for this " "dialog

"); } KMessageBox::information(this, txt, QString(), doNotShowKey, KMessageBox::AllowLink); } void AnnotationDialog::Dialog::resizeEvent(QResizeEvent *) { Settings::SettingsData::instance()->setWindowGeometry(Settings::AnnotationDialog, geometry()); } void AnnotationDialog::Dialog::moveEvent(QMoveEvent *) { Settings::SettingsData::instance()->setWindowGeometry(Settings::AnnotationDialog, geometry()); } void AnnotationDialog::Dialog::setupFocus() { QList list = findChildren(); QList orderedList; // Iterate through all widgets in our dialog. for (QObject *obj : list) { QWidget *current = static_cast(obj); if (!current->property("WantsFocus").isValid() || !current->isVisible()) continue; int cx = current->mapToGlobal(QPoint(0, 0)).x(); int cy = current->mapToGlobal(QPoint(0, 0)).y(); bool inserted = false; // Iterate through the ordered list of widgets, and insert the current one, so it is in the right position in the tab chain. for (QList::iterator orderedIt = orderedList.begin(); orderedIt != orderedList.end(); ++orderedIt) { const QWidget *w = *orderedIt; int wx = w->mapToGlobal(QPoint(0, 0)).x(); int wy = w->mapToGlobal(QPoint(0, 0)).y(); if (wy > cy || (wy == cy && wx >= cx)) { orderedList.insert(orderedIt, current); inserted = true; break; } } if (!inserted) orderedList.append(current); } // now setup tab order. QWidget *prev = nullptr; QWidget *first = nullptr; Q_FOREACH (QWidget *widget, orderedList) { if (prev) { setTabOrder(prev, widget); } else { first = widget; } prev = widget; } if (first) { setTabOrder(prev, first); } // Finally set focus on the first list select Q_FOREACH (QWidget *widget, orderedList) { if (widget->property("FocusCandidate").isValid() && widget->isVisible()) { widget->setFocus(); break; } } } void AnnotationDialog::Dialog::slotResetLayout() { m_dockWindow->restoreState(m_dockWindowCleanState); } void AnnotationDialog::Dialog::slotStartDateChanged(const DB::ImageDate &date) { if (date.start() == date.end()) m_endDate->setDate(QDate()); else m_endDate->setDate(date.end().date()); } void AnnotationDialog::Dialog::loadWindowLayout() { QString fileName = QString::fromLatin1("%1/layout.dat").arg(Settings::SettingsData::instance()->imageDirectory()); if (!QFileInfo(fileName).exists()) { // create default layout // label/date/rating in a visual block with description: m_dockWindow->splitDockWidget(m_generalDock, m_descriptionDock, Qt::Vertical); // more space for description: m_dockWindow->resizeDocks({ m_generalDock, m_descriptionDock }, { 60, 100 }, Qt::Vertical); // more space for preview: m_dockWindow->resizeDocks({ m_generalDock, m_descriptionDock, m_previewDock }, { 200, 200, 800 }, Qt::Horizontal); #ifdef HAVE_MARBLE // group the map with the preview m_dockWindow->tabifyDockWidget(m_previewDock, m_mapDock); // make sure the preview tab is active: m_previewDock->raise(); #endif return; } QFile file(fileName); file.open(QIODevice::ReadOnly); QByteArray data = file.readAll(); m_dockWindow->restoreState(data); } void AnnotationDialog::Dialog::setupActions() { m_actions = new KActionCollection(this); QAction *action = nullptr; action = m_actions->addAction(QString::fromLatin1("annotationdialog-sort-alphatree"), m_optionList.at(0), SLOT(slotSortAlphaTree())); action->setText(i18n("Sort Alphabetically (Tree)")); m_actions->setDefaultShortcut(action, Qt::CTRL + Qt::Key_F4); action = m_actions->addAction(QString::fromLatin1("annotationdialog-sort-alphaflat"), m_optionList.at(0), SLOT(slotSortAlphaFlat())); action->setText(i18n("Sort Alphabetically (Flat)")); action = m_actions->addAction(QString::fromLatin1("annotationdialog-sort-MRU"), m_optionList.at(0), SLOT(slotSortDate())); action->setText(i18n("Sort Most Recently Used")); action = m_actions->addAction(QString::fromLatin1("annotationdialog-toggle-sort"), m_optionList.at(0), SLOT(toggleSortType())); action->setText(i18n("Toggle Sorting")); m_actions->setDefaultShortcut(action, Qt::CTRL + Qt::Key_T); action = m_actions->addAction(QString::fromLatin1("annotationdialog-toggle-showing-selected-only"), &ShowSelectionOnlyManager::instance(), SLOT(toggle())); action->setText(i18n("Toggle Showing Selected Items Only")); m_actions->setDefaultShortcut(action, Qt::CTRL + Qt::Key_S); action = m_actions->addAction(QString::fromLatin1("annotationdialog-next-image"), m_preview, SLOT(slotNext())); action->setText(i18n("Annotate Next")); m_actions->setDefaultShortcut(action, Qt::Key_PageDown); action = m_actions->addAction(QString::fromLatin1("annotationdialog-prev-image"), m_preview, SLOT(slotPrev())); action->setText(i18n("Annotate Previous")); m_actions->setDefaultShortcut(action, Qt::Key_PageUp); action = m_actions->addAction(QString::fromLatin1("annotationdialog-OK-dialog"), this, SLOT(doneTagging())); action->setText(i18n("OK dialog")); m_actions->setDefaultShortcut(action, Qt::CTRL + Qt::Key_Return); action = m_actions->addAction(QString::fromLatin1("annotationdialog-delete-image"), this, SLOT(slotDeleteImage())); action->setText(i18n("Delete")); m_actions->setDefaultShortcut(action, Qt::CTRL + Qt::Key_Delete); action = m_actions->addAction(QString::fromLatin1("annotationdialog-copy-previous"), this, SLOT(slotCopyPrevious())); action->setText(i18n("Copy tags from previous image")); m_actions->setDefaultShortcut(action, Qt::ALT + Qt::Key_Insert); action = m_actions->addAction(QString::fromLatin1("annotationdialog-rotate-left"), m_preview, SLOT(rotateLeft())); action->setText(i18n("Rotate counterclockwise")); action = m_actions->addAction(QString::fromLatin1("annotationdialog-rotate-right"), m_preview, SLOT(rotateRight())); action->setText(i18n("Rotate clockwise")); action = m_actions->addAction(QString::fromLatin1("annotationdialog-toggle-viewer"), this, SLOT(togglePreview())); action->setText(i18n("Toggle fullscreen preview")); m_actions->setDefaultShortcut(action, Qt::CTRL + Qt::Key_Space); foreach (QAction *action, m_actions->actions()) { action->setShortcutContext(Qt::WindowShortcut); addAction(action); } // the annotation dialog is created when it's first used; // therefore, its actions are registered well after the MainWindow sets up its actionCollection, // and it has to read the shortcuts here, after they are set up: m_actions->readSettings(); } KActionCollection *AnnotationDialog::Dialog::actions() { return m_actions; } void AnnotationDialog::Dialog::setUpCategoryListBoxForMultiImageSelection(ListSelect *listSel, const DB::ImageInfoList &images) { StringSet on, partialOn; std::tie(on, partialOn) = selectionForMultiSelect(listSel, images); listSel->setSelection(on, partialOn); } std::tuple AnnotationDialog::Dialog::selectionForMultiSelect(ListSelect *listSel, const DB::ImageInfoList &images) { const QString category = listSel->category(); const StringSet allItems = DB::ImageDB::instance()->categoryCollection()->categoryForName(category)->itemsInclCategories().toSet(); StringSet itemsNotSelectedOnAllImages; StringSet itemsOnSomeImages; for (DB::ImageInfoList::ConstIterator imageIt = images.begin(); imageIt != images.end(); ++imageIt) { const StringSet itemsOnThisImage = (*imageIt)->itemsOfCategory(category); itemsNotSelectedOnAllImages += (allItems - itemsOnThisImage); itemsOnSomeImages += itemsOnThisImage; } const StringSet itemsOnAllImages = allItems - itemsNotSelectedOnAllImages; const StringSet itemsPartiallyOn = itemsOnSomeImages - itemsOnAllImages; return std::make_tuple(itemsOnAllImages, itemsPartiallyOn); } void AnnotationDialog::Dialog::slotRatingChanged(unsigned int) { m_ratingChanged = true; } void AnnotationDialog::Dialog::continueLater() { saveAndClose(); } void AnnotationDialog::Dialog::saveAndClose() { tidyAreas(); m_fullScreenPreview->stopPlayback(); if (m_origList.isEmpty()) { // all images are deleted. QDialog::accept(); return; } // I need to check for the changes first, as the case for m_setup == InputSingleImageConfigMode, saves to the m_origList, // and we can thus not check for changes anymore const bool anyChanges = hasChanges(); if (m_setup == InputSingleImageConfigMode) { writeToInfo(); for (int i = 0; i < m_editList.count(); ++i) { *(m_origList[i]) = m_editList[i]; } } else if (m_setup == InputMultiImageConfigMode) { Q_FOREACH (ListSelect *ls, m_optionList) { ls->slotReturn(); } for (DB::ImageInfoListConstIterator it = m_origList.constBegin(); it != m_origList.constEnd(); ++it) { DB::ImageInfoPtr info = *it; if (!m_startDate->date().isNull()) info->setDate(DB::ImageDate(m_startDate->date(), m_endDate->date(), m_time->time())); Q_FOREACH (ListSelect *ls, m_optionList) { info->addCategoryInfo(ls->category(), ls->itemsOn()); info->removeCategoryInfo(ls->category(), ls->itemsOff()); } if (!m_imageLabel->text().isEmpty()) { info->setLabel(m_imageLabel->text()); } if (!m_description->toPlainText().isEmpty() && m_description->toPlainText().compare(m_conflictText)) { info->setDescription(m_description->toPlainText()); } if (m_ratingChanged) { info->setRating(m_rating->rating()); } } m_ratingChanged = false; } m_accept = QDialog::Accepted; if (anyChanges) { MainWindow::DirtyIndicator::markDirty(); } QDialog::accept(); } AnnotationDialog::Dialog::~Dialog() { qDeleteAll(m_optionList); m_optionList.clear(); } void AnnotationDialog::Dialog::togglePreview() { if (m_setup == InputSingleImageConfigMode) { if (m_stack->currentWidget() == m_fullScreenPreview) { m_stack->setCurrentWidget(m_dockWindow); m_fullScreenPreview->stopPlayback(); } else { DB::ImageInfo currentInfo = m_editList[m_current]; m_stack->setCurrentWidget(m_fullScreenPreview); m_fullScreenPreview->load(DB::FileNameList() << currentInfo.fileName()); // compute altered tags by removing existing tags from full set: const QMap> existingAreas = currentInfo.taggedAreas(); QMap> alteredAreas = taggedAreas(); for (auto catIt = existingAreas.constBegin(); catIt != existingAreas.constEnd(); ++catIt) { const QString &categoryName = catIt.key(); const QMap &tags = catIt.value(); for (auto tagIt = tags.cbegin(); tagIt != tags.constEnd(); ++tagIt) { const QString &tagName = tagIt.key(); const QRect &area = tagIt.value(); // remove unchanged areas if (area == alteredAreas[categoryName][tagName]) { alteredAreas[categoryName].remove(tagName); if (alteredAreas[categoryName].empty()) alteredAreas.remove(categoryName); } } } m_fullScreenPreview->addAdditionalTaggedAreas(alteredAreas); } } } void AnnotationDialog::Dialog::tidyAreas() { // Remove all areas marked on the preview image foreach (ResizableFrame *area, areas()) { area->markTidied(); area->deleteLater(); } } void AnnotationDialog::Dialog::slotNewArea(ResizableFrame *area) { area->setDialog(this); } void AnnotationDialog::Dialog::positionableTagSelected(QString category, QString tag) { // Be sure not to propose an already-associated tag QPair tagData = qMakePair(category, tag); foreach (ResizableFrame *area, areas()) { if (area->tagData() == tagData) { return; } } // Set the selected tag as the last selected positionable tag m_lastSelectedPositionableTag = tagData; // Add the tag to the positionable tag candidate list addTagToCandidateList(category, tag); } void AnnotationDialog::Dialog::positionableTagDeselected(QString category, QString tag) { // Remove the tag from the candidate list removeTagFromCandidateList(category, tag); // Search for areas linked against the tag on this image if (m_setup == InputSingleImageConfigMode) { QPair deselectedTag = QPair(category, tag); foreach (ResizableFrame *area, areas()) { if (area->tagData() == deselectedTag) { area->removeTagData(); m_areasChanged = true; // Only one area can be associated with the tag, so we can return here return; } } } // Removal of tagged areas in InputMultiImageConfigMode is done in DB::ImageInfo::removeCategoryInfo } void AnnotationDialog::Dialog::addTagToCandidateList(QString category, QString tag) { m_positionableTagCandidates << QPair(category, tag); } void AnnotationDialog::Dialog::removeTagFromCandidateList(QString category, QString tag) { // Is the deselected tag the last selected positionable tag? if (m_lastSelectedPositionableTag.first == category && m_lastSelectedPositionableTag.second == tag) { m_lastSelectedPositionableTag = QPair(); } // Remove the tag from the candidate list m_positionableTagCandidates.removeAll(QPair(category, tag)); // When a positionable tag is entered via the AreaTagSelectDialog, it's added to this // list twice, so we use removeAll here to be sure to also wipe duplicate entries. } QPair AnnotationDialog::Dialog::lastSelectedPositionableTag() const { return m_lastSelectedPositionableTag; } QList> AnnotationDialog::Dialog::positionableTagCandidates() const { return m_positionableTagCandidates; } void AnnotationDialog::Dialog::slotShowAreas(bool showAreas) { foreach (ResizableFrame *area, areas()) { area->setVisible(showAreas); } } void AnnotationDialog::Dialog::positionableTagRenamed(QString category, QString oldTag, QString newTag) { // Is the renamed tag the last selected positionable tag? if (m_lastSelectedPositionableTag.first == category && m_lastSelectedPositionableTag.second == oldTag) { m_lastSelectedPositionableTag.second = newTag; } // Check the candidate list for the tag QPair oldTagData = QPair(category, oldTag); if (m_positionableTagCandidates.contains(oldTagData)) { // The tag is in the list, so update it m_positionableTagCandidates.removeAt(m_positionableTagCandidates.indexOf(oldTagData)); m_positionableTagCandidates << QPair(category, newTag); } // Check if an area on the current image contains the changed or proposed tag foreach (ResizableFrame *area, areas()) { if (area->tagData() == oldTagData) { area->setTagData(category, newTag); } } } void AnnotationDialog::Dialog::descriptionPageUpDownPressed(QKeyEvent *event) { if (event->key() == Qt::Key_PageUp) { m_actions->action(QString::fromLatin1("annotationdialog-prev-image"))->trigger(); } else if (event->key() == Qt::Key_PageDown) { m_actions->action(QString::fromLatin1("annotationdialog-next-image"))->trigger(); } } void AnnotationDialog::Dialog::checkProposedTagData( QPair tagData, ResizableFrame *areaToExclude) const { foreach (ResizableFrame *area, areas()) { if (area != areaToExclude && area->proposedTagData() == tagData && area->tagData().first.isEmpty()) { area->removeProposedTagData(); } } } void AnnotationDialog::Dialog::areaChanged() { m_areasChanged = true; } /** * @brief positionableTagValid checks whether a given tag can still be associated to an area. * This checks for empty and duplicate tags. * @return */ bool AnnotationDialog::Dialog::positionableTagAvailable(const QString &category, const QString &tag) const { if (category.isEmpty() || tag.isEmpty()) return false; // does any area already have that tag? foreach (const ResizableFrame *area, areas()) { const auto tagData = area->tagData(); if (tagData.first == category && tagData.second == tag) return false; } return true; } /** * @brief Generates a set of positionable tags currently used on the image * @param category * @return */ QSet AnnotationDialog::Dialog::positionedTags(const QString &category) const { QSet tags; foreach (const ResizableFrame *area, areas()) { const auto tagData = area->tagData(); if (tagData.first == category) tags += tagData.second; } return tags; } AnnotationDialog::ListSelect *AnnotationDialog::Dialog::listSelectForCategory(const QString &category) { return m_listSelectList.value(category, nullptr); } #ifdef HAVE_MARBLE void AnnotationDialog::Dialog::updateMapForCurrentImage() { if (m_setup != InputSingleImageConfigMode) { return; } // we can use the coordinates of the original images here, because the are never changed by the annotation dialog if (m_origList[m_current]->coordinates().hasCoordinates()) { m_annotationMap->setCenter(m_origList[m_current]); m_annotationMap->displayStatus(Map::MapView::MapStatus::ImageHasCoordinates); } else { m_annotationMap->displayStatus(Map::MapView::MapStatus::ImageHasNoCoordinates); } } void AnnotationDialog::Dialog::annotationMapVisibilityChanged(bool visible) { // This populates the map if it's added when the dialog is already open if (visible) { // when the map dockwidget is already visible on show(), the call to // annotationMapVisibilityChanged is executed in the GUI thread. // This ensures that populateMap() doesn't block the GUI in this case: QTimer::singleShot(0, this, SLOT(populateMap())); } else { m_cancelMapLoading = true; } } void AnnotationDialog::Dialog::populateMap() { // populateMap is called every time the map widget gets visible if (m_mapIsPopulated) { return; } m_annotationMap->displayStatus(Map::MapView::MapStatus::Loading); m_cancelMapLoading = false; m_mapLoadingProgress->setMaximum(m_origList.count()); m_mapLoadingProgress->show(); m_cancelMapLoadingButton->show(); int processedImages = 0; int imagesWithCoordinates = 0; // we can use the coordinates of the original images here, because the are never changed by the annotation dialog foreach (const DB::ImageInfoPtr info, m_origList) { processedImages++; m_mapLoadingProgress->setValue(processedImages); // keep things responsive by processing events manually: QApplication::processEvents(); if (info->coordinates().hasCoordinates()) { m_annotationMap->addImage(info); imagesWithCoordinates++; } // m_cancelMapLoading is set to true by clicking the "Cancel" button if (m_cancelMapLoading) { m_annotationMap->clear(); break; } } // at this point either we canceled loading or the map is populated: m_mapIsPopulated = !m_cancelMapLoading; mapLoadingFinished(imagesWithCoordinates > 0, imagesWithCoordinates == processedImages); } void AnnotationDialog::Dialog::setCancelMapLoading() { m_cancelMapLoading = true; } void AnnotationDialog::Dialog::mapLoadingFinished(bool mapHasImages, bool allImagesHaveCoordinates) { m_mapLoadingProgress->hide(); m_cancelMapLoadingButton->hide(); if (m_setup == InputSingleImageConfigMode) { m_annotationMap->displayStatus(Map::MapView::MapStatus::ImageHasNoCoordinates); } else { if (m_setup == SearchMode) { m_annotationMap->displayStatus(Map::MapView::MapStatus::SearchCoordinates); } else { if (mapHasImages) { if (!allImagesHaveCoordinates) { m_annotationMap->displayStatus(Map::MapView::MapStatus::SomeImagesHaveNoCoordinates); } else { m_annotationMap->displayStatus(Map::MapView::MapStatus::ImageHasCoordinates); } } else { m_annotationMap->displayStatus(Map::MapView::MapStatus::NoImagesHaveNoCoordinates); } } } if (m_setup != SearchMode) { m_annotationMap->zoomToMarkers(); updateMapForCurrentImage(); } } #endif // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/AnnotationDialog/Dialog.h b/AnnotationDialog/Dialog.h index b3d6e324..81ecaf1b 100644 --- a/AnnotationDialog/Dialog.h +++ b/AnnotationDialog/Dialog.h @@ -1,247 +1,246 @@ /* Copyright (C) 2003-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ANNOTATIONDIALOG_DIALOG_H #define ANNOTATIONDIALOG_DIALOG_H #include "config-kpa-marble.h" -#include "enums.h" #include "ImagePreviewWidget.h" #include "ListSelect.h" +#include "enums.h" #include #include #include #include #include #include #include #include - class DockWidget; class KActionCollection; class KComboBox; class KLineEdit; class KRatingWidget; class KTextEdit; class QCloseEvent; class QDockWidget; class QMainWindow; class QMoveEvent; class QProgressBar; class QPushButton; class QResizeEvent; class QSplitter; class QStackedWidget; class QTimeEdit; namespace Viewer { class ViewerWidget; } namespace DB { class ImageInfo; } namespace Map { class MapView; } namespace AnnotationDialog { class ImagePreview; class DateEdit; class ShortCutManager; class ResizableFrame; class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent); ~Dialog() override; int configure(DB::ImageInfoList list, bool oneAtATime); DB::ImageSearchInfo search(DB::ImageSearchInfo *search = nullptr); KActionCollection *actions(); QPair lastSelectedPositionableTag() const; QList> positionableTagCandidates() const; void addTagToCandidateList(QString category, QString tag); void removeTagFromCandidateList(QString category, QString tag); void checkProposedTagData(QPair tagData, ResizableFrame *areaToExclude) const; void areaChanged(); bool positionableTagAvailable(const QString &category, const QString &tag) const; QSet positionedTags(const QString &category) const; /** * @return A list of all ResizableFrame objects on the current image */ QList areas() const; /** * @brief taggedAreas creates a map of all the currently tagged areas. * This is different from areas(), which also contains untagged areas. * This is different from \code m_editList[m_current].areas()\endcode, which * does not include newly added (or deleted) areas. * @return a map of currently tagged areas */ QMap> taggedAreas() const; ListSelect *listSelectForCategory(const QString &category); protected slots: void slotRevert(); void slotIndexChanged(int index); void doneTagging(); void continueLater(); void slotClear(); void slotOptions(); void slotSaveWindowSetup(); void slotDeleteOption(DB::Category *, const QString &); void slotRenameOption(DB::Category *, const QString &, const QString &); void reject() override; void rotate(int angle); void slotSetFuzzyDate(); void slotDeleteImage(); void slotResetLayout(); void slotStartDateChanged(const DB::ImageDate &); void slotCopyPrevious(); void slotShowAreas(bool showAreas); void slotRatingChanged(unsigned int); void togglePreview(); void descriptionPageUpDownPressed(QKeyEvent *event); void slotNewArea(ResizableFrame *area); void positionableTagSelected(QString category, QString tag); void positionableTagDeselected(QString category, QString tag); void positionableTagRenamed(QString category, QString oldTag, QString newTag); #ifdef HAVE_MARBLE void setCancelMapLoading(); void annotationMapVisibilityChanged(bool visible); void populateMap(); #endif signals: void imageRotated(const DB::FileName &id); protected: QDockWidget *createDock(const QString &title, const QString &name, Qt::DockWidgetArea location, QWidget *widget); QWidget *createDateWidget(ShortCutManager &shortCutManager); QWidget *createPreviewWidget(); ListSelect *createListSel(const DB::CategoryPtr &category); void load(); void writeToInfo(); void setup(); void loadInfo(const DB::ImageSearchInfo &); int exec() override; void closeEvent(QCloseEvent *) override; void showTornOfWindows(); void hideTornOfWindows(); bool hasChanges(); void showHelpDialog(UsageMode); void resizeEvent(QResizeEvent *) override; void moveEvent(QMoveEvent *) override; void setupFocus(); void closeDialog(); void loadWindowLayout(); void setupActions(); void setUpCategoryListBoxForMultiImageSelection(ListSelect *, const DB::ImageInfoList &images); std::tuple selectionForMultiSelect(ListSelect *, const DB::ImageInfoList &images); void saveAndClose(); void ShowHideSearch(bool show); private: QStackedWidget *m_stack; Viewer::ViewerWidget *m_fullScreenPreview; DB::ImageInfoList m_origList; QList m_editList; int m_current; UsageMode m_setup; QList m_optionList; DB::ImageSearchInfo m_oldSearch; int m_accept; QList m_dockWidgets; // "special" named dockWidgets (used to set default layout): QDockWidget *m_generalDock; QDockWidget *m_previewDock; QDockWidget *m_descriptionDock; // Widgets QMainWindow *m_dockWindow; KLineEdit *m_imageLabel; DateEdit *m_startDate; DateEdit *m_endDate; QLabel *m_endDateLabel; QLabel *m_imageFilePatternLabel; KLineEdit *m_imageFilePattern; ImagePreviewWidget *m_preview; QPushButton *m_revertBut; QPushButton *m_clearBut; QPushButton *m_okBut; QPushButton *m_continueLaterBut; KTextEdit *m_description; QTimeEdit *m_time; QLabel *m_timeLabel; QCheckBox *m_isFuzzyDate; KRatingWidget *m_rating; KComboBox *m_ratingSearchMode; QLabel *m_ratingSearchLabel; bool m_ratingChanged; QSpinBox *m_megapixel; QLabel *m_megapixelLabel; QSpinBox *m_max_megapixel; QLabel *m_max_megapixelLabel; QCheckBox *m_searchRAW; QString m_conflictText; QString m_firstDescription; KActionCollection *m_actions; /** Clean state of the dock window. * * Used in slotResetLayout(). */ QByteArray m_dockWindowCleanState; void tidyAreas(); QPair m_lastSelectedPositionableTag; QList> m_positionableTagCandidates; QMap m_listSelectList; bool m_positionableCategories; bool m_areasChanged; #ifdef HAVE_MARBLE QDockWidget *m_mapDock; QWidget *m_annotationMapContainer; Map::MapView *m_annotationMap; void updateMapForCurrentImage(); QProgressBar *m_mapLoadingProgress; QPushButton *m_cancelMapLoadingButton; void mapLoadingFinished(bool mapHasImages, bool allImagesHaveCoordinates); bool m_cancelMapLoading; bool m_mapIsPopulated; #endif }; } #endif /* ANNOTATIONDIALOG_DIALOG_H */ // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/Browser/OverviewPage.cpp b/Browser/OverviewPage.cpp index fb902a7a..1431acb9 100644 --- a/Browser/OverviewPage.cpp +++ b/Browser/OverviewPage.cpp @@ -1,341 +1,341 @@ /* Copyright (C) 2003-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "OverviewPage.h" #include "BrowserWidget.h" #include "CategoryPage.h" #include "ImageViewPage.h" #include "enums.h" #include #ifdef HAVE_MARBLE #include "GeoPositionPage.h" #endif #include #include #include #include #include #include #include #include #include #include #include const int THUMBNAILSIZE = 70; AnnotationDialog::Dialog *Browser::OverviewPage::s_config = nullptr; Browser::OverviewPage::OverviewPage(const Breadcrumb &breadcrumb, const DB::ImageSearchInfo &info, BrowserWidget *browser) : BrowserPage(info, browser) , m_breadcrumb(breadcrumb) { //updateImageCount(); } int Browser::OverviewPage::rowCount(const QModelIndex &parent) const { if (parent != QModelIndex()) return 0; return categories().count() + #ifdef HAVE_MARBLE 1 + #endif 4; // Exiv search + Search info + Untagged Images + Show Image } QVariant Browser::OverviewPage::data(const QModelIndex &index, int role) const { if (role == ValueRole) return index.row(); const int row = index.row(); if (isCategoryIndex(row)) return categoryInfo(row, role); #ifdef HAVE_MARBLE else if (isGeoPositionIndex(row)) return geoPositionInfo(role); #endif else if (isExivIndex(row)) return exivInfo(role); else if (isSearchIndex(row)) return searchInfo(role); else if (isUntaggedImagesIndex(row)) return untaggedImagesInfo(role); else if (isImageIndex(row)) return imageInfo(role); return QVariant(); } bool Browser::OverviewPage::isCategoryIndex(int row) const { return row < categories().count() && row >= 0; } bool Browser::OverviewPage::isGeoPositionIndex(int row) const { #ifdef HAVE_MARBLE return row == categories().count(); #else Q_UNUSED(row); return false; #endif } bool Browser::OverviewPage::isExivIndex(int row) const { int exivRow = categories().count(); - #ifdef HAVE_MARBLE - exivRow++; - #endif +#ifdef HAVE_MARBLE + exivRow++; +#endif return row == exivRow; } bool Browser::OverviewPage::isSearchIndex(int row) const { return rowCount() - 3 == row; } bool Browser::OverviewPage::isUntaggedImagesIndex(int row) const { return rowCount() - 2 == row; } bool Browser::OverviewPage::isImageIndex(int row) const { return rowCount() - 1 == row; } QList Browser::OverviewPage::categories() const { return DB::ImageDB::instance()->categoryCollection()->categories(); } QVariant Browser::OverviewPage::categoryInfo(int row, int role) const { if (role == Qt::DisplayRole) return categories()[row]->name(); else if (role == Qt::DecorationRole) return categories()[row]->icon(THUMBNAILSIZE); return QVariant(); } QVariant Browser::OverviewPage::geoPositionInfo(int role) const { if (role == Qt::DisplayRole) return i18n("Geo Position"); else if (role == Qt::DecorationRole) { return QIcon::fromTheme(QString::fromLatin1("globe")).pixmap(THUMBNAILSIZE); } return QVariant(); } QVariant Browser::OverviewPage::exivInfo(int role) const { if (role == Qt::DisplayRole) return i18n("Exif Info"); else if (role == Qt::DecorationRole) { return QIcon::fromTheme(QString::fromLatin1("document-properties")).pixmap(THUMBNAILSIZE); } return QVariant(); } QVariant Browser::OverviewPage::searchInfo(int role) const { if (role == Qt::DisplayRole) return i18nc("@action Search button in the browser view.", "Search"); else if (role == Qt::DecorationRole) return QIcon::fromTheme(QString::fromLatin1("system-search")).pixmap(THUMBNAILSIZE); return QVariant(); } QVariant Browser::OverviewPage::untaggedImagesInfo(int role) const { if (role == Qt::DisplayRole) return i18n("Untagged Images"); else if (role == Qt::DecorationRole) return QIcon::fromTheme(QString::fromUtf8("archive-insert")).pixmap(THUMBNAILSIZE); return QVariant(); } QVariant Browser::OverviewPage::imageInfo(int role) const { if (role == Qt::DisplayRole) return i18n("Show Thumbnails"); else if (role == Qt::DecorationRole) { QIcon icon = QIcon::fromTheme(QString::fromUtf8("view-preview")); QPixmap pixmap = icon.pixmap(THUMBNAILSIZE); // workaround for QListView in Qt 5.5: // On Qt5.5 if the last item in the list view has no DecorationRole, then // the whole list view "collapses" to the size of text-only items, // cutting off the existing thumbnails. // This can be triggered by an incomplete icon theme. if (pixmap.isNull()) { pixmap = QPixmap(THUMBNAILSIZE, THUMBNAILSIZE); pixmap.fill(Qt::transparent); } return pixmap; } return QVariant(); } Browser::BrowserPage *Browser::OverviewPage::activateChild(const QModelIndex &index) { const int row = index.row(); if (isCategoryIndex(row)) return new Browser::CategoryPage(categories()[row], BrowserPage::searchInfo(), browser()); #ifdef HAVE_MARBLE else if (isGeoPositionIndex(row)) return new Browser::GeoPositionPage(BrowserPage::searchInfo(), browser()); #endif else if (isExivIndex(row)) return activateExivAction(); else if (isSearchIndex(row)) return activateSearchAction(); else if (isUntaggedImagesIndex(row)) { return activateUntaggedImagesAction(); } else if (isImageIndex(row)) return new ImageViewPage(BrowserPage::searchInfo(), browser()); return nullptr; } void Browser::OverviewPage::activate() { updateImageCount(); browser()->setModel(this); } Qt::ItemFlags Browser::OverviewPage::flags(const QModelIndex &index) const { if (isCategoryIndex(index.row()) && !m_rowHasSubcategories[index.row()]) return QAbstractListModel::flags(index) & ~Qt::ItemIsEnabled; else return QAbstractListModel::flags(index); } bool Browser::OverviewPage::isSearchable() const { return true; } Browser::BrowserPage *Browser::OverviewPage::activateExivAction() { QPointer dialog = new Exif::SearchDialog(browser()); { Utilities::ShowBusyCursor undoTheBusyWhileShowingTheDialog(Qt::ArrowCursor); if (dialog->exec() == QDialog::Rejected) { delete dialog; return nullptr; } // Dialog can be deleted by its parent in event loop while in exec() if (dialog.isNull()) return nullptr; } Exif::SearchInfo result = dialog->info(); DB::ImageSearchInfo info = BrowserPage::searchInfo(); info.addExifSearchInfo(dialog->info()); delete dialog; if (DB::ImageDB::instance()->count(info).total() == 0) { KMessageBox::information(browser(), i18n("Search did not match any images or videos."), i18n("Empty Search Result")); return nullptr; } return new OverviewPage(Breadcrumb(i18n("Exif Search")), info, browser()); } Browser::BrowserPage *Browser::OverviewPage::activateSearchAction() { if (!s_config) s_config = new AnnotationDialog::Dialog(browser()); Utilities::ShowBusyCursor undoTheBusyWhileShowingTheDialog(Qt::ArrowCursor); DB::ImageSearchInfo tmpInfo = BrowserPage::searchInfo(); DB::ImageSearchInfo info = s_config->search(&tmpInfo); // PENDING(blackie) why take the address? if (info.isNull()) return nullptr; if (DB::ImageDB::instance()->count(info).total() == 0) { KMessageBox::information(browser(), i18n("Search did not match any images or videos."), i18n("Empty Search Result")); return nullptr; } return new OverviewPage(Breadcrumb(i18nc("Breadcrumb denoting that we 'browsed' to a search result.", "search")), info, browser()); } Browser::Breadcrumb Browser::OverviewPage::breadcrumb() const { return m_breadcrumb; } bool Browser::OverviewPage::showDuringMovement() const { return true; } void Browser::OverviewPage::updateImageCount() { QElapsedTimer timer; timer.start(); int row = 0; for (const DB::CategoryPtr &category : categories()) { QMap items = DB::ImageDB::instance()->classify(BrowserPage::searchInfo(), category->name(), DB::anyMediaType, DB::ClassificationMode::PartialCount); m_rowHasSubcategories[row] = items.count() > 1; ++row; } qCDebug(TimingLog) << "Browser::Overview::updateImageCount(): " << timer.elapsed() << "ms."; } Browser::BrowserPage *Browser::OverviewPage::activateUntaggedImagesAction() { if (Settings::SettingsData::instance()->hasUntaggedCategoryFeatureConfigured()) { DB::ImageSearchInfo info = BrowserPage::searchInfo(); info.addAnd(Settings::SettingsData::instance()->untaggedCategory(), Settings::SettingsData::instance()->untaggedTag()); return new ImageViewPage(info, browser()); } else { // Note: the same dialog text is used in MainWindow::Window::slotMarkUntagged(), // so if it is changed, be sure to also change it there! KMessageBox::information(browser(), i18n("

You have not yet configured which tag to use for indicating untagged images.

" "

Please follow these steps to do so:" "

  • In the menu bar choose Settings
  • " "
  • From there choose Configure KPhotoAlbum
  • " "
  • Now choose the Categories icon
  • " "
  • Now configure section Untagged Images

"), i18n("Feature has not been configured")); return nullptr; } } // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/DB/ImageInfo.h b/DB/ImageInfo.h index 368caa95..fa0634c5 100644 --- a/DB/ImageInfo.h +++ b/DB/ImageInfo.h @@ -1,248 +1,248 @@ /* Copyright (C) 2003-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef IMAGEINFO_H #define IMAGEINFO_H #include "config-kpa-marble.h" #include "CategoryPtr.h" #include "ExifMode.h" #include "FileName.h" #include "ImageDate.h" -#include "Utilities/StringSet.h" #include "MD5.h" +#include "Utilities/StringSet.h" #ifdef HAVE_MARBLE #include #endif #include #include #include #include #include #include namespace Plugins { class ImageInfo; } namespace XMLDB { class Database; } namespace DB { enum PathType { RelativeToImageRoot, AbsolutePath }; enum RotationMode { RotateImageInfoAndAreas, RotateImageInfoOnly }; using Utilities::StringSet; class MemberMap; enum MediaType { Image = 0x01, Video = 0x02 }; const MediaType anyMediaType = MediaType(Image | Video); typedef unsigned int StackID; class ImageInfo : public QSharedData { public: ImageInfo(); explicit ImageInfo(const DB::FileName &fileName, MediaType type = Image, bool readExifInfo = true, bool storeExifInfo = true); ImageInfo(const DB::FileName &fileName, const QString &label, const QString &description, const ImageDate &date, int angle, const MD5 &md5sum, const QSize &size, MediaType type, short rating = -1, StackID stackId = 0, unsigned int stackOrder = 0); ImageInfo(const ImageInfo &other); FileName fileName() const; void setFileName(const DB::FileName &relativeFileName); void setLabel(const QString &); QString label() const; void setDescription(const QString &); QString description() const; void setDate(const ImageDate &); ImageDate date() const; ImageDate &date(); void readExif(const DB::FileName &fullPath, DB::ExifMode mode); void rotate(int degrees, RotationMode mode = RotateImageInfoAndAreas); int angle() const; void setAngle(int angle); short rating() const; void setRating(short rating); bool isStacked() const { return m_stackId != 0; } StackID stackId() const; unsigned int stackOrder() const; void setStackOrder(const unsigned int stackOrder); void setVideoLength(int seconds); int videoLength() const; void setCategoryInfo(const QString &key, const StringSet &value); void addCategoryInfo(const QString &category, const StringSet &values); /** * Enable a tag within a category for this image. * Optionally, the tag's position can be given (for positionable categories). * @param category the category name * @param value the tag name * @param area the image region that the tag applies to. */ void addCategoryInfo(const QString &category, const QString &value, const QRect &area = QRect()); void clearAllCategoryInfo(); void removeCategoryInfo(const QString &category, const StringSet &values); void removeCategoryInfo(const QString &category, const QString &value); /** * Set the tagged areas for the image. * It is assumed that the positioned tags have already been set to the ImageInfo * using one of the functions setCategoryInfo or addCategoryInfo. * * @param category the category name. * @param positionedTags a mapping of tag names to image areas. */ void setPositionedTags(const QString &category, const QMap &positionedTags); bool hasCategoryInfo(const QString &key, const QString &value) const; bool hasCategoryInfo(const QString &key, const StringSet &values) const; QStringList availableCategories() const; StringSet itemsOfCategory(const QString &category) const; void renameItem(const QString &key, const QString &oldValue, const QString &newValue); void renameCategory(const QString &oldName, const QString &newName); bool operator!=(const ImageInfo &other) const; bool operator==(const ImageInfo &other) const; ImageInfo &operator=(const ImageInfo &other); static bool imageOnDisk(const DB::FileName &fileName); const MD5 &MD5Sum() const { return m_md5sum; } void setMD5Sum(const MD5 &sum, bool storeEXIF = true); void setLocked(bool); bool isLocked() const; bool isNull() const { return m_null; } QSize size() const; void setSize(const QSize &size); MediaType mediaType() const; void setMediaType(MediaType type) { if (type != m_type) m_dirty = true; m_type = type; } bool isVideo() const; void createFolderCategoryItem(DB::CategoryPtr, DB::MemberMap &memberMap); void copyExtraData(const ImageInfo &from, bool copyAngle = true); void removeExtraData(); /** * Merge another ImageInfo into this one. * The other ImageInfo is not altered in any way or removed. */ void merge(const ImageInfo &other); QMap> taggedAreas() const; /** * Return the area associated with a tag. * @param category the category name * @param tag the tag name * @return the associated area, or QRect() if no association exists. */ QRect areaForTag(QString category, QString tag) const; void setIsMatched(bool isMatched); bool isMatched() const; void setMatchGeneration(int matchGeneration); int matchGeneration() const; #ifdef HAVE_MARBLE Map::GeoCoordinates coordinates() const; #endif protected: void setIsNull(bool b) { m_null = b; } bool isDirty() const { return m_dirty; } void setIsDirty(bool b) { m_dirty = b; } bool updateDateInformation(int mode) const; void setStackId(const StackID stackId); friend class XMLDB::Database; private: DB::FileName m_fileName; QString m_label; QString m_description; ImageDate m_date; QMap m_categoryInfomation; QMap> m_taggedAreas; int m_angle; enum OnDisk { YesOnDisk, NoNotOnDisk, Unchecked }; mutable OnDisk m_imageOnDisk; MD5 m_md5sum; bool m_null; QSize m_size; MediaType m_type; short m_rating; StackID m_stackId; unsigned int m_stackOrder; int m_videoLength; bool m_isMatched; int m_matchGeneration; #ifdef HAVE_MARBLE mutable Map::GeoCoordinates m_coordinates; mutable bool m_coordsIsSet = false; #endif // Cache information bool m_locked; // Will be set to true after every change bool m_dirty; }; } #endif /* IMAGEINFO_H */ // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/DB/ImageSearchInfo.cpp b/DB/ImageSearchInfo.cpp index bf4fac5d..259e4d48 100644 --- a/DB/ImageSearchInfo.cpp +++ b/DB/ImageSearchInfo.cpp @@ -1,665 +1,664 @@ /* Copyright (C) 2003-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ImageSearchInfo.h" #include "AndCategoryMatcher.h" #include "CategoryMatcher.h" #include "ContainerCategoryMatcher.h" #include "ExactCategoryMatcher.h" #include "ImageDB.h" #include "Logging.h" #include "NegationCategoryMatcher.h" #include "NoTagCategoryMatcher.h" #include "OrCategoryMatcher.h" #include "ValueCategoryMatcher.h" #include #include #include #include #include #include #include using namespace DB; static QAtomicInt s_matchGeneration; static int nextGeneration() { return s_matchGeneration++; } ImageSearchInfo::ImageSearchInfo(const ImageDate &date, const QString &label, const QString &description) : m_date(date) , m_label(label) , m_description(description) , m_rating(-1) , m_megapixel(0) , m_max_megapixel(0) , m_ratingSearchMode(0) , m_searchRAW(false) , m_isNull(false) , m_isCacheable(true) , m_compiled(false) , m_matchGeneration(nextGeneration()) { } ImageSearchInfo::ImageSearchInfo(const ImageDate &date, const QString &label, const QString &description, const QString &fnPattern) : m_date(date) , m_label(label) , m_description(description) , m_fnPattern(fnPattern) , m_rating(-1) , m_megapixel(0) , m_max_megapixel(0) , m_ratingSearchMode(0) , m_searchRAW(false) , m_isNull(false) , m_isCacheable(true) , m_compiled(false) , m_matchGeneration(nextGeneration()) { } QString ImageSearchInfo::label() const { return m_label; } QRegExp ImageSearchInfo::fnPattern() const { return m_fnPattern; } QString ImageSearchInfo::description() const { return m_description; } void ImageSearchInfo::checkIfNull() { if (m_compiled || isNull()) return; if (m_date.isNull() && m_label.isEmpty() && m_description.isEmpty() && m_rating == -1 && m_megapixel == 0 && m_exifSearchInfo.isNull() && m_categoryMatchText.isEmpty() #ifdef HAVE_KGEOMAP && !m_regionSelection.first.hasCoordinates() && !m_regionSelection.second.hasCoordinates() #endif ) { m_isNull = true; } } ImageSearchInfo::ImageSearchInfo() : m_rating(-1) , m_megapixel(0) , m_max_megapixel(0) , m_ratingSearchMode(0) , m_searchRAW(false) , m_isNull(true) , m_isCacheable(true) , m_compiled(false) , m_matchGeneration(nextGeneration()) { } bool ImageSearchInfo::isNull() const { return m_isNull; } bool ImageSearchInfo::isCacheable() const { return m_isCacheable; } void ImageSearchInfo::setCacheable(bool cacheable) { m_isCacheable = cacheable; } bool ImageSearchInfo::match(ImageInfoPtr info) const { if (m_isNull) return true; if (m_isCacheable && info->matchGeneration() == m_matchGeneration) return info->isMatched(); bool ok = doMatch(info); if (m_isCacheable) { info->setMatchGeneration(m_matchGeneration); info->setIsMatched(ok); } return ok; } bool ImageSearchInfo::doMatch(ImageInfoPtr info) const { if (!m_compiled) compile(); // -------------------------------------------------- Rating //ok = ok && (_rating == -1 ) || ( _rating == info->rating() ); if (m_rating != -1) { switch (m_ratingSearchMode) { case 1: // Image rating at least selected if (m_rating > info->rating()) return false; break; case 2: // Image rating less than selected if (m_rating < info->rating()) return false; break; case 3: // Image rating not equal if (m_rating == info->rating()) return false; break; default: if (m_rating != info->rating()) return false; break; } } // -------------------------------------------------- Resolution if (m_megapixel && (m_megapixel * 1000000 > info->size().width() * info->size().height())) return false; if (m_max_megapixel && m_max_megapixel < m_megapixel && (m_max_megapixel * 1000000 < info->size().width() * info->size().height())) return false; // -------------------------------------------------- Date QDateTime actualStart = info->date().start(); QDateTime actualEnd = info->date().end(); if (m_date.start().isValid()) { if (actualEnd < m_date.start() || (m_date.end().isValid() && actualStart > m_date.end())) return false; } else if (m_date.end().isValid() && actualStart > m_date.end()) { return false; } // -------------------------------------------------- Label if (m_label.isEmpty() && info->label().indexOf(m_label) == -1) return false; // -------------------------------------------------- RAW if (m_searchRAW && !ImageManager::RAWImageDecoder::isRAW(info->fileName())) return false; - #ifdef HAVE_MARBLE // Search for GPS Position if (m_usingRegionSelection) { if (!info->coordinates().hasCoordinates()) return false; float infoLat = info->coordinates().lat(); if (m_regionSelectionMinLat > infoLat || m_regionSelectionMaxLat < infoLat) return false; float infoLon = info->coordinates().lon(); if (m_regionSelectionMinLon > infoLon || m_regionSelectionMaxLon < infoLon) return false; } #endif // -------------------------------------------------- File name pattern if (!m_fnPattern.isEmpty() && m_fnPattern.indexIn(info->fileName().relative()) == -1) return false; // -------------------------------------------------- Options // alreadyMatched map is used to make it possible to search for // Jesper & None QMap alreadyMatched; for (CategoryMatcher *optionMatcher : m_categoryMatchers) { if (!optionMatcher->eval(info, alreadyMatched)) return false; } // -------------------------------------------------- Text if (!m_description.isEmpty()) { const QString &txt(info->description()); QStringList list = m_description.split(QChar::fromLatin1(' '), QString::SkipEmptyParts); Q_FOREACH (const QString &word, list) { if (txt.indexOf(word, 0, Qt::CaseInsensitive) == -1) return false; } } // -------------------------------------------------- EXIF if (!m_exifSearchInfo.matches(info->fileName())) return false; return true; } QString ImageSearchInfo::categoryMatchText(const QString &name) const { return m_categoryMatchText[name]; } void ImageSearchInfo::setCategoryMatchText(const QString &name, const QString &value) { if (value.isEmpty()) { m_categoryMatchText.remove(name); } else { m_categoryMatchText[name] = value; } m_isNull = false; m_compiled = false; m_matchGeneration = nextGeneration(); } void ImageSearchInfo::addAnd(const QString &category, const QString &value) { // Escape literal "&"s in value by doubling it QString escapedValue = value; escapedValue.replace(QString::fromUtf8("&"), QString::fromUtf8("&&")); QString val = categoryMatchText(category); if (!val.isEmpty()) val += QString::fromLatin1(" & ") + escapedValue; else val = escapedValue; setCategoryMatchText(category, val); m_isNull = false; m_compiled = false; m_matchGeneration = nextGeneration(); } void ImageSearchInfo::setRating(short rating) { m_rating = rating; m_isNull = false; m_compiled = false; m_matchGeneration = nextGeneration(); } void ImageSearchInfo::setMegaPixel(short megapixel) { m_megapixel = megapixel; m_matchGeneration = nextGeneration(); } void ImageSearchInfo::setMaxMegaPixel(short max_megapixel) { m_max_megapixel = max_megapixel; m_matchGeneration = nextGeneration(); } void ImageSearchInfo::setSearchMode(int index) { m_ratingSearchMode = index; m_matchGeneration = nextGeneration(); } void ImageSearchInfo::setSearchRAW(bool searchRAW) { m_searchRAW = searchRAW; m_matchGeneration = nextGeneration(); } QString ImageSearchInfo::toString() const { QString res; bool first = true; for (QMap::ConstIterator it = m_categoryMatchText.begin(); it != m_categoryMatchText.end(); ++it) { if (!it.value().isEmpty()) { if (first) first = false; else res += QString::fromLatin1(" / "); QString txt = it.value(); if (txt == ImageDB::NONE()) txt = i18nc("As in No persons, no locations etc. I do realize that translators may have problem with this, " "but I need some how to indicate the category, and users may create their own categories, so this is " "the best I can do - Jesper.", "No %1", it.key()); if (txt.contains(QString::fromLatin1("|"))) txt.replace(QString::fromLatin1("&"), QString::fromLatin1(" %1 ").arg(i18n("and"))); else txt.replace(QString::fromLatin1("&"), QString::fromLatin1(" / ")); txt.replace(QString::fromLatin1("|"), QString::fromLatin1(" %1 ").arg(i18n("or"))); txt.replace(QString::fromLatin1("!"), QString::fromLatin1(" %1 ").arg(i18n("not"))); txt.replace(ImageDB::NONE(), i18nc("As in no other persons, or no other locations. " "I do realize that translators may have problem with this, " "but I need some how to indicate the category, and users may create their own categories, so this is " "the best I can do - Jesper.", "No other %1", it.key())); res += txt.simplified(); } } return res; } void ImageSearchInfo::debug() { for (QMap::Iterator it = m_categoryMatchText.begin(); it != m_categoryMatchText.end(); ++it) { qCDebug(DBCategoryMatcherLog) << it.key() << ", " << it.value(); } } // PENDING(blackie) move this into the Options class instead of having it here. void ImageSearchInfo::saveLock() const { KConfigGroup config = KSharedConfig::openConfig()->group(Settings::SettingsData::instance()->groupForDatabase("Privacy Settings")); config.writeEntry(QString::fromLatin1("label"), m_label); config.writeEntry(QString::fromLatin1("description"), m_description); config.writeEntry(QString::fromLatin1("categories"), m_categoryMatchText.keys()); for (QMap::ConstIterator it = m_categoryMatchText.begin(); it != m_categoryMatchText.end(); ++it) { config.writeEntry(it.key(), it.value()); } config.sync(); } ImageSearchInfo ImageSearchInfo::loadLock() { KConfigGroup config = KSharedConfig::openConfig()->group(Settings::SettingsData::instance()->groupForDatabase("Privacy Settings")); ImageSearchInfo info; info.m_label = config.readEntry("label"); info.m_description = config.readEntry("description"); QStringList categories = config.readEntry(QString::fromLatin1("categories"), QStringList()); for (QStringList::ConstIterator it = categories.constBegin(); it != categories.constEnd(); ++it) { info.setCategoryMatchText(*it, config.readEntry(*it, QString())); } return info; } ImageSearchInfo::ImageSearchInfo(const ImageSearchInfo &other) { m_date = other.m_date; m_categoryMatchText = other.m_categoryMatchText; m_label = other.m_label; m_description = other.m_description; m_fnPattern = other.m_fnPattern; m_isNull = other.m_isNull; m_compiled = false; m_rating = other.m_rating; m_ratingSearchMode = other.m_ratingSearchMode; m_megapixel = other.m_megapixel; m_max_megapixel = other.m_max_megapixel; m_searchRAW = other.m_searchRAW; m_exifSearchInfo = other.m_exifSearchInfo; m_matchGeneration = other.m_matchGeneration; m_isCacheable = other.m_isCacheable; #ifdef HAVE_MARBLE m_regionSelection = other.m_regionSelection; #endif } void ImageSearchInfo::compile() const { m_exifSearchInfo.search(); #ifdef HAVE_MARBLE // Prepare Search for GPS Position m_usingRegionSelection = m_regionSelection.first.hasCoordinates() && m_regionSelection.second.hasCoordinates(); if (m_usingRegionSelection) { using std::max; using std::min; m_regionSelectionMinLat = min(m_regionSelection.first.lat(), m_regionSelection.second.lat()); m_regionSelectionMaxLat = max(m_regionSelection.first.lat(), m_regionSelection.second.lat()); m_regionSelectionMinLon = min(m_regionSelection.first.lon(), m_regionSelection.second.lon()); m_regionSelectionMaxLon = max(m_regionSelection.first.lon(), m_regionSelection.second.lon()); } #endif deleteMatchers(); for (QMap::ConstIterator it = m_categoryMatchText.begin(); it != m_categoryMatchText.end(); ++it) { QString category = it.key(); QString matchText = it.value(); QStringList orParts = matchText.split(QString::fromLatin1("|"), QString::SkipEmptyParts); DB::ContainerCategoryMatcher *orMatcher = new DB::OrCategoryMatcher; Q_FOREACH (QString orPart, orParts) { // Split by " & ", not only by "&", so that the doubled "&"s won't be used as a split point QStringList andParts = orPart.split(QString::fromLatin1(" & "), QString::SkipEmptyParts); DB::ContainerCategoryMatcher *andMatcher; bool exactMatch = false; bool negate = false; andMatcher = new DB::AndCategoryMatcher; Q_FOREACH (QString str, andParts) { static QRegExp regexp(QString::fromLatin1("^\\s*!\\s*(.*)$")); if (regexp.exactMatch(str)) { // str is preceded with NOT negate = true; str = regexp.cap(1); } str = str.trimmed(); CategoryMatcher *valueMatcher; if (str == ImageDB::NONE()) { // mark AND-group as containing a "No other" condition exactMatch = true; continue; } else { valueMatcher = new DB::ValueCategoryMatcher(category, str); if (negate) valueMatcher = new DB::NegationCategoryMatcher(valueMatcher); } andMatcher->addElement(valueMatcher); } if (exactMatch) { DB::CategoryMatcher *exactMatcher = nullptr; // if andMatcher has exactMatch set, but no CategoryMatchers, then // matching "category / None" is what we want: if (andMatcher->mp_elements.count() == 0) { exactMatcher = new DB::NoTagCategoryMatcher(category); } else { ExactCategoryMatcher *noOtherMatcher = new ExactCategoryMatcher(category); if (andMatcher->mp_elements.count() == 1) noOtherMatcher->setMatcher(andMatcher->mp_elements[0]); else noOtherMatcher->setMatcher(andMatcher); exactMatcher = noOtherMatcher; } if (negate) exactMatcher = new DB::NegationCategoryMatcher(exactMatcher); orMatcher->addElement(exactMatcher); } else if (andMatcher->mp_elements.count() == 1) orMatcher->addElement(andMatcher->mp_elements[0]); else if (andMatcher->mp_elements.count() > 1) orMatcher->addElement(andMatcher); } CategoryMatcher *matcher = nullptr; if (orMatcher->mp_elements.count() == 1) matcher = orMatcher->mp_elements[0]; else if (orMatcher->mp_elements.count() > 1) matcher = orMatcher; if (matcher) { m_categoryMatchers.append(matcher); if (DBCategoryMatcherLog().isDebugEnabled()) { qCDebug(DBCategoryMatcherLog) << "Matching text '" << matchText << "' in category " << category << ":"; matcher->debug(0); qCDebug(DBCategoryMatcherLog) << "."; } } } m_compiled = true; } ImageSearchInfo::~ImageSearchInfo() { deleteMatchers(); } void ImageSearchInfo::debugMatcher() const { if (!m_compiled) compile(); qCDebug(DBCategoryMatcherLog, "And:"); for (CategoryMatcher *optionMatcher : m_categoryMatchers) { optionMatcher->debug(1); } } QList> ImageSearchInfo::query() const { if (!m_compiled) compile(); // Combine _optionMachers to one list of lists in Disjunctive // Normal Form and return it. QList::Iterator it = m_categoryMatchers.begin(); QList> result; if (it == m_categoryMatchers.end()) return result; result = convertMatcher(*it); ++it; for (; it != m_categoryMatchers.end(); ++it) { QList> current = convertMatcher(*it); QList> oldResult = result; result.clear(); for (QList resultIt : oldResult) { for (QList currentIt : current) { QList tmp; tmp += resultIt; tmp += currentIt; result.append(tmp); } } } return result; } Utilities::StringSet ImageSearchInfo::findAlreadyMatched(const QString &group) const { Utilities::StringSet result; QString str = categoryMatchText(group); if (str.contains(QString::fromLatin1("|"))) { return result; } QStringList list = str.split(QString::fromLatin1("&"), QString::SkipEmptyParts); Q_FOREACH (QString part, list) { QString nm = part.trimmed(); if (!nm.contains(QString::fromLatin1("!"))) result.insert(nm); } return result; } void ImageSearchInfo::deleteMatchers() const { qDeleteAll(m_categoryMatchers); m_categoryMatchers.clear(); } QList ImageSearchInfo::extractAndMatcher(CategoryMatcher *matcher) const { QList result; AndCategoryMatcher *andMatcher; SimpleCategoryMatcher *simpleMatcher; if ((andMatcher = dynamic_cast(matcher))) { for (CategoryMatcher *child : andMatcher->mp_elements) { SimpleCategoryMatcher *simpleMatcher = dynamic_cast(child); Q_ASSERT(simpleMatcher); result.append(simpleMatcher); } } else if ((simpleMatcher = dynamic_cast(matcher))) result.append(simpleMatcher); else Q_ASSERT(false); return result; } /** Convert matcher to Disjunctive Normal Form. * * @return OR-list of AND-lists. (e.g. OR(AND(a,b),AND(c,d))) */ QList> ImageSearchInfo::convertMatcher(CategoryMatcher *item) const { QList> result; OrCategoryMatcher *orMacther; if ((orMacther = dynamic_cast(item))) { for (CategoryMatcher *child : orMacther->mp_elements) { result.append(extractAndMatcher(child)); } } else result.append(extractAndMatcher(item)); return result; } short ImageSearchInfo::rating() const { return m_rating; } ImageDate ImageSearchInfo::date() const { return m_date; } void ImageSearchInfo::addExifSearchInfo(const Exif::SearchInfo info) { m_exifSearchInfo = info; m_isNull = false; } void DB::ImageSearchInfo::renameCategory(const QString &oldName, const QString &newName) { m_categoryMatchText[newName] = m_categoryMatchText[oldName]; m_categoryMatchText.remove(oldName); m_compiled = false; } #ifdef HAVE_MARBLE Map::GeoCoordinates::Pair ImageSearchInfo::regionSelection() const { return m_regionSelection; } -void ImageSearchInfo::setRegionSelection(const Map::GeoCoordinates::Pair& actRegionSelection) +void ImageSearchInfo::setRegionSelection(const Map::GeoCoordinates::Pair &actRegionSelection) { m_regionSelection = actRegionSelection; m_compiled = false; if (m_regionSelection.first.hasCoordinates() && m_regionSelection.second.hasCoordinates()) { m_isNull = false; } } #endif // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/DB/ImageSearchInfo.h b/DB/ImageSearchInfo.h index 537a8d76..9279213a 100644 --- a/DB/ImageSearchInfo.h +++ b/DB/ImageSearchInfo.h @@ -1,146 +1,146 @@ /* Copyright (C) 2003-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef IMAGESEARCHINFO_H #define IMAGESEARCHINFO_H -#include #include "ImageDate.h" #include "ImageInfoPtr.h" +#include #include #ifdef HAVE_MARBLE #include #endif #include #include #include namespace DB { class SimpleCategoryMatcher; class ImageInfo; class CategoryMatcher; class ImageSearchInfo { public: ImageSearchInfo(); ~ImageSearchInfo(); ImageSearchInfo(const ImageDate &date, const QString &label, const QString &description); ImageSearchInfo(const ImageDate &date, const QString &label, const QString &description, const QString &fnPattern); ImageSearchInfo(const ImageSearchInfo &other); ImageDate date() const; QString categoryMatchText(const QString &name) const; void setCategoryMatchText(const QString &name, const QString &value); void renameCategory(const QString &oldName, const QString &newName); QString label() const; QRegExp fnPattern() const; QString description() const; /** * @brief checkIfNull evaluates whether the filter is indeed empty and * sets isNull() to \c true if that is the case. * You only need to call this if you re-use an existing ImageSearchInfo * and set/reset search parameters. * @see ThumbnailView::toggleRatingFilter */ void checkIfNull(); bool isNull() const; bool match(ImageInfoPtr) const; QList> query() const; void addAnd(const QString &category, const QString &value); short rating() const; void setRating(short rating); QString toString() const; void setMegaPixel(short megapixel); void setMaxMegaPixel(short maxmegapixel); void setSearchRAW(bool m_searchRAW); void setSearchMode(int index); void saveLock() const; static ImageSearchInfo loadLock(); void debug(); void debugMatcher() const; Utilities::StringSet findAlreadyMatched(const QString &group) const; void addExifSearchInfo(const Exif::SearchInfo info); // By default, an ImageSearchInfo is cacheable, but only one search // is cached per image. For a search that's only going to be // performed once, don't try to cache the result. void setCacheable(bool cacheable); bool isCacheable() const; #ifdef HAVE_MARBLE Map::GeoCoordinates::Pair regionSelection() const; void setRegionSelection(const Map::GeoCoordinates::Pair &actRegionSelection); #endif protected: void compile() const; void deleteMatchers() const; QList extractAndMatcher(CategoryMatcher *andMatcher) const; QList> convertMatcher(CategoryMatcher *) const; private: ImageDate m_date; QMap m_categoryMatchText; QString m_label; QString m_description; QRegExp m_fnPattern; short m_rating; short m_megapixel; short m_max_megapixel; int m_ratingSearchMode; bool m_searchRAW; bool m_isNull; bool m_isCacheable; mutable bool m_compiled; mutable QList m_categoryMatchers; Exif::SearchInfo m_exifSearchInfo; int m_matchGeneration; bool doMatch(ImageInfoPtr) const; #ifdef HAVE_MARBLE Map::GeoCoordinates::Pair m_regionSelection; mutable bool m_usingRegionSelection = false; mutable float m_regionSelectionMinLat; mutable float m_regionSelectionMaxLat; mutable float m_regionSelectionMinLon; mutable float m_regionSelectionMaxLon; #endif // When adding new instance variable, please notice that this class as an explicit written copy constructor. }; } #endif /* IMAGESEARCHINFO_H */ // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/MainWindow/FeatureDialog.cpp b/MainWindow/FeatureDialog.cpp index ba4c9ed1..98c266ed 100644 --- a/MainWindow/FeatureDialog.cpp +++ b/MainWindow/FeatureDialog.cpp @@ -1,220 +1,220 @@ /* Copyright (C) 2003-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +#include "FeatureDialog.h" #include #include -#include "FeatureDialog.h" #include #include #include #include #include #include #include #include #include #include #include using namespace MainWindow; FeatureDialog::FeatureDialog(QWidget *parent) : QDialog(parent) { setWindowTitle(i18nc("@title:window", "Feature Status")); QTextBrowser *browser = new QTextBrowser(this); QString text = i18n("

Overview

" "

Below you may see the list of compile- and runtime features KPhotoAlbum has, and their status:

" "%1", featureString()); text += i18n("

What can I do if I miss a feature?

" "

If you compiled KPhotoAlbum yourself, then please review the sections below to learn what to install " "to get the feature in question. If on the other hand you installed KPhotoAlbum from a binary package, please tell " "whoever made the package about this defect, eventually including the information from the section below.

" "

In case you are missing a feature and you did not compile KPhotoAlbum yourself, please do consider doing so. " "It really is not that hard. If you need help compiling KPhotoAlbum, feel free to ask on the " "KPhotoAlbum mailing list

" "

The steps to compile KPhotoAlbum can be seen on " "the KPhotoAlbum home page. If you have never compiled a KDE application, then please ensure that " "you have the developer packages installed, in most distributions they go under names like kdelibs-devel

"); text += i18n("

Plug-ins support

" "

KPhotoAlbum has a plug-in system with lots of extensions. You may among other things find plug-ins for:" "

    " "
  • Writing images to cds or dvd's
  • " "
  • Adjusting timestamps on your images
  • " "
  • Making a calendar featuring your images
  • " "
  • Uploading your images to flickr
  • " "
  • Upload your images to facebook
  • " "

" "

The plug-in library is called KIPI, and may be downloaded from the " "KDE Userbase Wiki

"); text += i18n("

SQLite database support

" "

KPhotoAlbum allows you to search using a certain number of Exif tags. For this KPhotoAlbum " "needs an SQLite database. " "In addition the Qt package for SQLite (e.g. qt-sql-sqlite) must be installed.

"); text += i18n("

Map view for geotagged images

" "

If KPhotoAlbum has been built with support for Marble, " "KPhotoAlbum can show images with GPS information on a map." "

"); text += i18n("

Video support

" "

KPhotoAlbum relies on Qt's Phonon architecture for displaying videos; this in turn relies on GStreamer. " "If this feature is not enabled for you, have a look at the " "KPhotoAlbum wiki article on video support.

"); QStringList mimeTypes = supportedVideoMimeTypes(); mimeTypes.sort(); if (mimeTypes.isEmpty()) text += i18n("

No video mime types found, which indicates that either Qt was compiled without phonon support, or there were missing codecs

"); else text += i18n("

Phonon is capable of playing movies of these mime types:

  • %1

", mimeTypes.join(QString::fromLatin1("
  • "))); text += i18n("

    Video thumbnail support

    " "

    KPhotoAlbum can use ffmpeg to extract thumbnails from videos. These thumbnails are used to preview " "videos in the thumbnail viewer.

    "); text += i18n("

    Video metadata support

    " "

    KPhotoAlbum can use ffprobe to extract length information from videos." "

    " "

    Correct length information is necessary for correct rendering of video thumbnails.

    "); browser->setText(text); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(browser); this->setLayout(layout); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); buttonBox->button(QDialogButtonBox::Ok)->setShortcut(Qt::CTRL | Qt::Key_Return); layout->addWidget(buttonBox); connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); } QSize FeatureDialog::sizeHint() const { return QSize(800, 600); } bool MainWindow::FeatureDialog::hasKIPISupport() { #ifdef HASKIPI return true; #else return false; #endif } bool MainWindow::FeatureDialog::hasEXIV2DBSupport() { return Exif::Database::isAvailable(); } bool MainWindow::FeatureDialog::hasGeoMapSupport() { #ifdef HAVE_MARBLE return true; #else return false; #endif } QString FeatureDialog::ffmpegBinary() { QString ffmpeg = QStandardPaths::findExecutable(QString::fromLatin1("ffmpeg")); return ffmpeg; } QString FeatureDialog::ffprobeBinary() { QString ffprobe = QStandardPaths::findExecutable(QString::fromLatin1("ffprobe")); return ffprobe; } bool FeatureDialog::hasVideoThumbnailer() { return !ffmpegBinary().isEmpty(); } bool FeatureDialog::hasVideoProber() { return !ffprobeBinary().isEmpty(); } bool MainWindow::FeatureDialog::hasAllFeaturesAvailable() { // Only answer those that are compile time tests, otherwise we will pay a penalty each time we start up. return hasKIPISupport() && hasEXIV2DBSupport() && hasGeoMapSupport() && hasVideoThumbnailer() && hasVideoProber(); } struct Data { Data() {} Data(const QString &title, const QString tag, bool featureFound) : title(title) , tag(tag) , featureFound(featureFound) { } QString title; QString tag; bool featureFound; }; QString MainWindow::FeatureDialog::featureString() { QList features; features << Data(i18n("Plug-ins available"), QString::fromLatin1("#kipi"), hasKIPISupport()); features << Data(i18n("SQLite database support (used for Exif searches)"), QString::fromLatin1("#database"), hasEXIV2DBSupport()); features << Data(i18n("Map view for geotagged images."), QString::fromLatin1("#geomap"), hasGeoMapSupport()); features << Data(i18n("Video support"), QString::fromLatin1("#video"), !supportedVideoMimeTypes().isEmpty()); features << Data(i18n("Video thumbnail support"), QString::fromLatin1("#videoPreview"), hasVideoThumbnailer()); features << Data(i18n("Video metadata support"), QString::fromLatin1("#videoInfo"), hasVideoProber()); QString result = QString::fromLatin1("

    "); const QString red = QString::fromLatin1("%1"); const QString yes = i18nc("Feature available", "Yes"); const QString no = red.arg(i18nc("Feature not available", "No")); const QString formatString = QString::fromLatin1(""); for (QList::ConstIterator featureIt = features.constBegin(); featureIt != features.constEnd(); ++featureIt) { result += formatString .arg((*featureIt).tag) .arg((*featureIt).title) .arg((*featureIt).featureFound ? yes : no); } result += QString::fromLatin1("
    %2%3

    "); return result; } QStringList MainWindow::FeatureDialog::supportedVideoMimeTypes() { return Phonon::BackendCapabilities::availableMimeTypes(); } // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/Map/GeoCoordinates.h b/Map/GeoCoordinates.h index 280e906e..c2532619 100644 --- a/Map/GeoCoordinates.h +++ b/Map/GeoCoordinates.h @@ -1,63 +1,62 @@ -/* Copyright (C) 2018 The KPhotoAlbum Development Team +/* Copyright (C) 2018-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef GEOCOORDINATES_H #define GEOCOORDINATES_H -#include #include +#include #include namespace Map { class GeoCoordinates { public: bool hasCoordinates() const; double lon() const; double lat() const; double alt() const; bool hasAltitude() const; void setLatLon(const double lat, const double lon); void setAlt(const double alt); typedef QPair Pair; static Pair makePair(const double lat1, const double lon1, const double lat2, const double lon2); operator QString() const; private: // Variables double m_lat; double m_lon; double m_alt; bool m_hasCoordinates = false; bool m_hasAlt = false; - }; } Q_DECLARE_METATYPE(Map::GeoCoordinates::Pair) #endif // GEOCOORDINATES_H // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/Map/MapView.cpp b/Map/MapView.cpp index 6efe63cb..8f140db3 100644 --- a/Map/MapView.cpp +++ b/Map/MapView.cpp @@ -1,338 +1,338 @@ /* Copyright (C) 2014-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ // Local includes #include "MapView.h" -#include "Logging.h" #include "ImageManager/ThumbnailCache.h" +#include "Logging.h" // Marble includes #include #include #include // Qt includes +#include +#include #include #include #include #include #include -#include -#include // KDE includes #include #include #include #include #include -namespace { +namespace +{ const QString MAPVIEW_FLOATER_VISIBLE_CONFIG_PREFIX = QStringLiteral("MarbleFloaterVisible "); -const QStringList MAPVIEW_RENDER_POSITION({QStringLiteral("HOVERS_ABOVE_SURFACE")}); +const QStringList MAPVIEW_RENDER_POSITION({ QStringLiteral("HOVERS_ABOVE_SURFACE") }); } Map::MapView::MapView(QWidget *parent, UsageType type) : QWidget(parent) { if (type == MapViewWindow) { setWindowFlags(Qt::Window); setAttribute(Qt::WA_DeleteOnClose); } QVBoxLayout *layout = new QVBoxLayout(this); m_statusLabel = new QLabel; m_statusLabel->setAlignment(Qt::AlignCenter); m_statusLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_statusLabel->hide(); layout->addWidget(m_statusLabel); m_mapWidget = new Marble::MarbleWidget; m_mapWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_mapWidget->setProjection(Marble::Mercator); m_mapWidget->setMapThemeId(QStringLiteral("earth/openstreetmap/openstreetmap.dgml")); #ifdef MARBLE_HAS_regionSelected_NEW connect(m_mapWidget, &Marble::MarbleWidget::regionSelected, this, &Map::MapView::updateRegionSelection); #else connect(m_mapWidget, &Marble::MarbleWidget::regionSelected, this, &Map::MapView::updateRegionSelectionOld); #endif m_mapWidget->addLayer(this); layout->addWidget(m_mapWidget); m_mapWidget->show(); QHBoxLayout *controlLayout = new QHBoxLayout; layout->addLayout(controlLayout); // KPA's control buttons m_kpaButtons = new QWidget; QHBoxLayout *kpaButtonsLayout = new QHBoxLayout(m_kpaButtons); controlLayout->addWidget(m_kpaButtons); QPushButton *saveButton = new QPushButton; saveButton->setFlat(true); saveButton->setIcon(QPixmap(SmallIcon(QStringLiteral("media-floppy")))); saveButton->setToolTip(i18n("Save the current map settings")); kpaButtonsLayout->addWidget(saveButton); connect(saveButton, &QPushButton::clicked, this, &MapView::saveSettings); m_setLastCenterButton = new QPushButton; m_setLastCenterButton->setFlat(true); m_setLastCenterButton->setIcon(QPixmap(SmallIcon(QStringLiteral("go-first")))); m_setLastCenterButton->setToolTip(i18n("Go to last map position")); kpaButtonsLayout->addWidget(m_setLastCenterButton); connect(m_setLastCenterButton, &QPushButton::clicked, this, &MapView::setLastCenter); QPushButton *showThumbnails = new QPushButton; showThumbnails->setFlat(true); showThumbnails->setIcon(QPixmap(SmallIcon(QStringLiteral("view-preview")))); showThumbnails->setToolTip(i18n("Show thumbnails")); kpaButtonsLayout->addWidget(showThumbnails); m_showThumbnails = true; showThumbnails->setCheckable(true); showThumbnails->setChecked(true); connect(showThumbnails, &QPushButton::clicked, this, &MapView::setShowThumbnails); // Marble floater control buttons m_floaters = new QWidget; QHBoxLayout *floatersLayout = new QHBoxLayout(m_floaters); controlLayout->addStretch(); controlLayout->addWidget(m_floaters); KSharedConfigPtr config = KSharedConfig::openConfig(); KConfigGroup group = config->group(QStringLiteral("MapView")); for (const Marble::RenderPlugin *plugin : m_mapWidget->renderPlugins()) { if (plugin->renderType() != Marble::RenderPlugin::PanelRenderType) { continue; } QPushButton *button = new QPushButton; button->setCheckable(true); button->setFlat(true); button->setChecked(plugin->action()->isChecked()); button->setToolTip(plugin->description()); const QString name = plugin->name(); button->setProperty("floater", name); QPixmap icon = plugin->action()->icon().pixmap(QSize(20, 20)); if (icon.isNull()) { icon = QPixmap(20, 20); icon.fill(Qt::white); } button->setIcon(icon); connect(plugin->action(), &QAction::toggled, button, &QPushButton::setChecked); connect(button, &QPushButton::toggled, plugin->action(), &QAction::setChecked); floatersLayout->addWidget(button); const QString value = group.readEntry(MAPVIEW_FLOATER_VISIBLE_CONFIG_PREFIX + name); - if (! value.isEmpty()) { + if (!value.isEmpty()) { button->setChecked(value == QStringLiteral("true") ? true : false); } } m_pin = QPixmap(QStandardPaths::locate(QStandardPaths::DataLocation, QStringLiteral("pics/pin.png"))); } void Map::MapView::clear() { m_images.clear(); m_markersBox.clear(); m_regionSelected = false; } void Map::MapView::addImage(DB::ImageInfoPtr image) { qCDebug(MapLog) << "Adding image" << image->label(); m_images.append(image); // Update the viewport for zoomToMarkers() if (m_markersBox.isEmpty()) { m_markersBox.setEast(image->coordinates().lon(), Marble::GeoDataCoordinates::Degree); m_markersBox.setWest(image->coordinates().lon(), Marble::GeoDataCoordinates::Degree); m_markersBox.setNorth(image->coordinates().lat(), Marble::GeoDataCoordinates::Degree); m_markersBox.setSouth(image->coordinates().lat(), Marble::GeoDataCoordinates::Degree); } else { if (m_markersBox.east(Marble::GeoDataCoordinates::Degree) < image->coordinates().lon()) { m_markersBox.setEast(image->coordinates().lon(), Marble::GeoDataCoordinates::Degree); } if (m_markersBox.west(Marble::GeoDataCoordinates::Degree) > image->coordinates().lon()) { m_markersBox.setWest(image->coordinates().lon(), Marble::GeoDataCoordinates::Degree); } if (m_markersBox.north(Marble::GeoDataCoordinates::Degree) < image->coordinates().lat()) { m_markersBox.setNorth(image->coordinates().lat(), Marble::GeoDataCoordinates::Degree); } if (m_markersBox.south(Marble::GeoDataCoordinates::Degree) > image->coordinates().lat()) { m_markersBox.setSouth(image->coordinates().lat(), Marble::GeoDataCoordinates::Degree); } } } void Map::MapView::zoomToMarkers() { m_mapWidget->centerOn(m_markersBox); } void Map::MapView::setCenter(const DB::ImageInfoPtr image) { m_lastCenter = image->coordinates(); setLastCenter(); } void Map::MapView::saveSettings() { KSharedConfigPtr config = KSharedConfig::openConfig(); KConfigGroup group = config->group(QStringLiteral("MapView")); for (const QPushButton *button : m_floaters->findChildren()) { group.writeEntry(MAPVIEW_FLOATER_VISIBLE_CONFIG_PREFIX - + button->property("floater").toString(), button->isChecked()); + + button->property("floater").toString(), + button->isChecked()); } config->sync(); QMessageBox::information(this, i18n("Map view"), i18n("Settings saved!")); } void Map::MapView::setShowThumbnails(bool state) { m_showThumbnails = state; m_mapWidget->reloadMap(); } void Map::MapView::displayStatus(MapStatus status) { switch (status) { case MapStatus::Loading: m_statusLabel->setText(i18n("Loading coordinates from the images ...")); m_statusLabel->show(); m_mapWidget->hide(); m_regionSelected = false; m_setLastCenterButton->setEnabled(false); break; case MapStatus::ImageHasCoordinates: m_statusLabel->hide(); m_regionSelected = false; m_mapWidget->show(); m_setLastCenterButton->show(); m_setLastCenterButton->setEnabled(true); break; case MapStatus::ImageHasNoCoordinates: m_statusLabel->setText(i18n("This image does not contain geographic coordinates.")); m_statusLabel->show(); m_mapWidget->hide(); m_setLastCenterButton->show(); m_setLastCenterButton->setEnabled(false); break; case MapStatus::SomeImagesHaveNoCoordinates: m_statusLabel->setText(i18n("Some of the selected images do not contain geographic " "coordinates.")); m_statusLabel->show(); m_regionSelected = false; m_mapWidget->show(); m_setLastCenterButton->show(); m_setLastCenterButton->setEnabled(true); break; case MapStatus::SearchCoordinates: m_statusLabel->setText(i18n("Search for geographic coordinates.")); m_statusLabel->show(); m_mapWidget->show(); m_mapWidget->centerOn(0.0, 0.0); m_setLastCenterButton->hide(); break; case MapStatus::NoImagesHaveNoCoordinates: m_statusLabel->setText(i18n("None of the selected images contain geographic " "coordinates.")); m_statusLabel->show(); m_mapWidget->hide(); m_setLastCenterButton->show(); m_setLastCenterButton->setEnabled(false); break; } emit displayStatusChanged(status); } void Map::MapView::setLastCenter() { m_mapWidget->centerOn(m_lastCenter.lon(), m_lastCenter.lat()); } void Map::MapView::updateRegionSelection(const Marble::GeoDataLatLonBox &selection) { m_regionSelected = true; m_regionSelection = selection; emit signalRegionSelectionChanged(); } #ifndef MARBLE_HAS_regionSelected_NEW void Map::MapView::updateRegionSelectionOld(const QList &selection) { - Q_ASSERT(selection.length()==4); + Q_ASSERT(selection.length() == 4); // see also: https://cgit.kde.org/marble.git/commit/?id=ec1f7f554e9f6ca248b4a3b01dbf08507870687e - Marble::GeoDataLatLonBox sel {selection.at(1),selection.at(3),selection.at(2),selection.at(0), Marble::GeoDataCoordinates::Degree }; + Marble::GeoDataLatLonBox sel { selection.at(1), selection.at(3), selection.at(2), selection.at(0), Marble::GeoDataCoordinates::Degree }; updateRegionSelection(sel); } #endif Map::GeoCoordinates::Pair Map::MapView::getRegionSelection() const { return GeoCoordinates::makePair(m_regionSelection.west(Marble::GeoDataCoordinates::Degree), m_regionSelection.north(Marble::GeoDataCoordinates::Degree), m_regionSelection.east(Marble::GeoDataCoordinates::Degree), m_regionSelection.south(Marble::GeoDataCoordinates::Degree)); } bool Map::MapView::regionSelected() const { return m_regionSelected; } QStringList Map::MapView::renderPosition() const { // we only ever paint on the same layer: return MAPVIEW_RENDER_POSITION; } bool Map::MapView::render(Marble::GeoPainter *painter, Marble::ViewportParams *, const QString &renderPos, Marble::GeoSceneLayer *) { Q_ASSERT(renderPos == renderPosition().first()); - for (const DB::ImageInfoPtr &image: m_images) { + for (const DB::ImageInfoPtr &image : m_images) { const Marble::GeoDataCoordinates pos(image->coordinates().lon(), image->coordinates().lat(), image->coordinates().alt(), Marble::GeoDataCoordinates::Degree); if (m_showThumbnails) { // FIXME(l3u) Maybe we should cache the scaled thumbnails? - painter->drawPixmap(pos, ImageManager::ThumbnailCache::instance()->lookup( - image->fileName()).scaled(QSize(40, 40), - Qt::KeepAspectRatio)); + painter->drawPixmap(pos, ImageManager::ThumbnailCache::instance()->lookup(image->fileName()).scaled(QSize(40, 40), Qt::KeepAspectRatio)); } else { painter->drawPixmap(pos, m_pin); } } return true; } // vi:expandtab:tabstop=4 shiftwidth=4: diff --git a/Map/MapView.h b/Map/MapView.h index b701bddc..75a299b5 100644 --- a/Map/MapView.h +++ b/Map/MapView.h @@ -1,183 +1,182 @@ -/* Copyright (C) 2014-2018 The KPhotoAlbum Development Team +/* Copyright (C) 2014-2019 The KPhotoAlbum Development Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef MAPVIEW_H #define MAPVIEW_H // Local includes #include "config-kpa-marble.h" -#include "GeoCoordinates.h" #include "DB/ImageInfo.h" #include "DB/ImageInfoPtr.h" +#include "GeoCoordinates.h" // Marble includes -#include #include #include +#include // Qt includes #include -#include #include +#include // Marble classes namespace Marble { class MarbleWidget; } // Local includes +#include "GeoCoordinates.h" #include #include -#include "GeoCoordinates.h" // Qt classes class QLabel; class QPushButton; namespace Map { class MapView - : public QWidget - , public Marble::LayerInterface + : public QWidget, + public Marble::LayerInterface { Q_OBJECT public: /** * UsageType: determines whether the widget is used as a standalone widget * or within another widget (e.g. the AnnotationDialog). * @see Viewer::ViewerWidget::UsageType */ enum UsageType { InlineMapView, MapViewWindow }; /** * MapStatus: determines the visibility and text of the status label and the visibility of the * map, depending on the availability of coordinates of the image(s) that are displayed. */ enum MapStatus { Loading, ImageHasCoordinates, ImageHasNoCoordinates, NoImagesHaveNoCoordinates, SomeImagesHaveNoCoordinates, SearchCoordinates }; explicit MapView(QWidget *parent = nullptr, UsageType type = InlineMapView); ~MapView() override = default; /** * Removes all images from the map. */ void clear(); /** * Add an image to the map. */ void addImage(DB::ImageInfoPtr image); /** * Sets the map's zoom so that all images on the map are visible. * If no images have been added, the zoom is not altered. */ void zoomToMarkers(); /** * Sets the state of the "Show Thumbnails" button on the map's control widget. */ void setShowThumbnails(bool state); /** * This sets the status label text and it's visibility, as well as the visibilty of the map * itself to the state indicated by the given MapStatus. */ void displayStatus(MapStatus status); GeoCoordinates::Pair getRegionSelection() const; bool regionSelected() const; // LayerInterface: /** * @brief renderPosition tells the LayerManager what layers we (currently) want to paint on. * Part of the LayerInterface; called by the LayerManager. * @return */ QStringList renderPosition() const override; /** * @brief Render all markers onto the marbleWidget. * Part of the LayerInterface; called by the LayerManager. * @param painter the painter used by the LayerManager * @param viewport * @param renderPos the layer name * @param layer always \c nullptr * @return \c true (return value is discarded by LayerManager::renderLayers()) */ bool render(Marble::GeoPainter *painter, Marble::ViewportParams *, const QString &renderPos, Marble::GeoSceneLayer *) override; Q_SIGNALS: void signalRegionSelectionChanged(); void displayStatusChanged(MapStatus); public slots: /** * Centers the map on the coordinates of the given image. */ void setCenter(const DB::ImageInfoPtr image); private slots: void saveSettings(); void setLastCenter(); void updateRegionSelection(const Marble::GeoDataLatLonBox &selection); #ifndef MARBLE_HAS_regionSelected_NEW // remove once we don't care about Marble v17.12.3 and older anymore void updateRegionSelectionOld(const QList &selection); #endif private: // Variables Marble::MarbleWidget *m_mapWidget; QLabel *m_statusLabel; QPushButton *m_setLastCenterButton; GeoCoordinates m_lastCenter; QWidget *m_kpaButtons; QWidget *m_floaters; // FIXME(jzarl): dirty hack to get it working // if this should work efficiently with a large number of images, // some spatially aware data structure probably needs to be used // (e.g. binning images by location) QList m_images; Marble::GeoDataLatLonBox m_markersBox; bool m_showThumbnails; QPixmap m_pin; Marble::GeoDataLatLonBox m_regionSelection; bool m_regionSelected = false; - }; } #endif // MAPVIEW_H // vi:expandtab:tabstop=4 shiftwidth=4: